@kosdev-code/kos-ui-sdk 2.1.18 → 2.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -1,83 +1,83 @@
1
- "use strict";var Dh=Object.defineProperty;var xh=(t,e,s)=>e in t?Dh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var l=(t,e,s)=>(xh(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("loglevel"),M=require("mobx"),b=require("robot3"),je=require("date-fns"),T=require("@emotion/react/jsx-runtime"),Vn=require("@emotion/styled"),ha=require("react-dom"),Qe=require("@emotion/react"),g=require("react"),Gn=require("mobx-react-lite"),Ah=require("@use-gesture/react"),kr="method",fa="topic",kt="url",As="request-id",Lr="response-id",Yn="status",Ne="dst-addr",pa="src-addr",Oe="type",Wn="ordered",Qn="tracker",ga="Content-Type",ma="Cache-Control",ya="requestId",ba=process.env.KOS_LOGIN_URL||"http://localhost",va=process.env.KOS_APP_PORT||"8080",Rh=`${ba}:${va}`,ir="{MODEL_ID}";var Rs=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(Rs||{}),wa=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(wa||{});const Zn="/kos/model/ready/";D.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const z=globalThis.kos.subscriptions,Ph=()=>Symbol("eventKey");function Xn(t){return z[t]&&Object.getOwnPropertySymbols(z[t]).length>0}function C(t,e){const s=Ph();return z[t]||(D.debug(`Initializing subscription for ${t}`),z[t]={}),D.debug(`Subscribing to ${t} with id ${s.toString()}`),z[t][s]=e,{count:z[t]?Object.getOwnPropertySymbols(z[t]).length:0,unsubscribe:()=>(D.debug(`Unsubscribing from ${t} with id ${s.toString()}`),z[t]&&z[t][s]&&delete z[t][s],z[t]&&Object.getOwnPropertySymbols(z[t]).length===0&&delete z[t],{count:z[t]?Object.getOwnPropertySymbols(z[t]).length:0})}}function V(t,e,s={}){if(!z[t]||Object.getOwnPropertySymbols(z[t]).length===0)return D.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(z[t]).length;return Object.getOwnPropertySymbols(z[t]).forEach(n=>{if(s.sync){const o=s.sync;D.debug(`Performing sync publish for ${t} with sync id ${o}`),z[t][n]({body:e,headers:s}).then(i=>{D.debug(`Response recieved for ${o}, publishing back to source.`),V(o,i)})}else D.debug(`Performing async publish for ${t}`),z[t][n]({body:e,headers:s})}),{eventType:t,subscribers:r}}function kh(){D.warn("Resetting event bus"),Object.keys(z).forEach(t=>delete z[t])}function Ea(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function Jn(t,e){return new Promise((s,r)=>{let n=null;const o=Ea(t,i=>{n&&clearTimeout(n),s(i)});e&&(n=setTimeout(()=>{o(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const Lh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:Xn,once:Ea,publish:V,reset:kh,subscribe:C,waitFor:Jn},Symbol.toStringTag,{value:"Module"}));function Fr(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function Nr(t,e){return new Promise((s,r)=>{let n=null;const o=Fr(t,i=>{n&&clearTimeout(n),s(i)});e&&(n=setTimeout(()=>{o(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function Ma(t,e){const s=t.map(r=>Nr(r,e));return Promise.all(s)}function Ta(t,e){return new Promise((s,r)=>{const n=[];let o=null,i=!1;const a=()=>{n.forEach(c=>c()),o&&clearTimeout(o)};t.forEach(c=>{const u=Fr(c,d=>{i||(i=!0,a(),s({eventType:c,data:d}))});n.push(u)}),e&&(o=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function Sa(t,e,s){return C(t,n=>{n&&e(n)&&s(n)}).unsubscribe}function _a(t,e,s){return C(t,n=>{if(n){const o=e(n);s(o)}}).unsubscribe}function Ia(t,e,s){let r=null;const n=C(t,o=>{r&&clearTimeout(r),r=setTimeout(()=>{s(o)},e)});return()=>{r&&clearTimeout(r),n.unsubscribe()}}function Oa(t,e,s){let r=0,n=null;const o=C(t,i=>{const a=Date.now(),c=a-r;c>=e?(r=a,s(i)):n||(n=setTimeout(()=>{r=Date.now(),s(i),n=null},e-c))});return()=>{n&&clearTimeout(n),o.unsubscribe()}}function $a(t,e,s){let r=[],n=null;const o=()=>{r.length>0&&(s([...r]),r=[])},i=C(t,a=>{a&&(r.push(a),n||(n=setTimeout(()=>{o(),n=null},e)))});return()=>{n&&(clearTimeout(n),o()),i.unsubscribe()}}function eo(t,e=1){const s=[];return C(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(n=>r(n)),C(t,r))}}function Ca(t,e){const s=t.map(r=>C(r,n=>{n&&e(r,n)}));return()=>{s.forEach(r=>r.unsubscribe())}}function Da(t,e){let s=t;const r=[],n=new Set;return Object.values(e).forEach(o=>{Object.keys(o).forEach(i=>{n.add(i)})}),n.forEach(o=>{const{unsubscribe:i}=C(o,a=>{const c=e[s];c&&c[o]&&(s=c[o](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(o=>o())}}}function xa(t,e,s,r){const n=Nr(e,r);return V(t,s),n}async function*Aa(t){const e=[],s=[],r=C(t,n=>{n&&(s.length>0?s.shift()(n):e.push(n))});try{for(;;)e.length>0?yield e.shift():yield await new Promise(n=>{s.push(n)})}finally{r.unsubscribe()}}const Fh={once:Fr,waitFor:Nr,waitForAll:Ma,race:Ta,filter:Sa,map:_a,debounce:Ia,throttle:Oa,buffer:$a,replay:eo,merge:Ca,stateMachine:Da,request:xa,eventIterator:Aa},Nh=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:Fh,buffer:$a,debounce:Ia,eventIterator:Aa,filter:Sa,map:_a,merge:Ca,once:Fr,race:Ta,replay:eo,request:xa,stateMachine:Da,throttle:Oa,waitFor:Nr,waitForAll:Ma},Symbol.toStringTag,{value:"Module"}));async function Ur(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:n,timeout:o}=e,i=Jn(t,o),a=await s(),c=r?r(a):a;return n&&n(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(c),100)})])}function Ra(t,e,s){const{getCurrentState:r,transformState:n}=s;let o=!1;const i=C(t,a=>{a&&(o=!0,e(a))});return Promise.resolve(r()).then(a=>{const c=n?n(a):a;o||e(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function Pa(t,e){let s;const r=new Set,n=async()=>{try{typeof e=="string"?s=await(await fetch(e)).json():s=await e(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};C(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let o=!1;const i=()=>{o||(o=!0,n())};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 n(),s}}}async function to(t,e){if(typeof t=="string")return Ur(t,e);const s=t,{getCurrentState:r,shouldUseFetchedState:n,timeout:o}=e,i=await r(),a=e.transformState?e.transformState(i):i;if(n&&n(a))return a;const c=s.map(d=>Jn(d,o)),u=await Promise.all(c);return u[u.length-1]}function ka(t,e,s){const{fetchMissedEvents:r,checkInterval:n=3e4,deduplicateById:o}=s,i=new Set,a=C(t,async u=>{if(u){if(o){const d=o(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await e(u)}}),c=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(o){const f=o(h);i.has(f)||(i.add(f),await e(h))}else await e(h)}catch(u){console.error("Failed to fetch missed events:",u)}},n);return()=>{a.unsubscribe(),clearInterval(c)}}function La(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:n,fetchInitialState:o,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await Ur(e,{getCurrentState:o,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 o();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 C(e,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),C(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&C(r,()=>{a.state="error",u()}),n&&C(n,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const Uh={waitForOrGetState:Ur,subscribeWithInitialState:Ra,createStatefulEventStream:Pa,waitForAllWithState:to,createResilientEventHandler:ka,createConnectionStateManager:La},jh=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Uh,createConnectionStateManager:La,createResilientEventHandler:ka,createStatefulEventStream:Pa,subscribeWithInitialState:Ra,waitForAllWithState:to,waitForOrGetState:Ur},Symbol.toStringTag,{value:"Module"})),Bh=(t,e=0)=>{if(!+t)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=e<0?0:e,n=["bytes","KB","MB","GB","TB"],o=Math.floor(Math.log(t)/Math.log(s)),i=parseFloat((t/Math.pow(s,o)).toFixed(r)),a=n[o];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function so(t){let e="pending",s;const r=t.then(o=>{e="success",s=o},o=>{e="error",s=o});return{read:()=>{switch(e){case"pending":throw r;case"error":throw s;default:return s}}}}function ot(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function Hh(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const n=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,n)})})}function Kh(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((n,o)=>n===r[o])}const ro=(t,e)=>{const s=t.map(o=>o.id);return e.map(o=>o.id).filter(o=>!s.includes(o))},Fa=t=>t,Na=t=>t,qh=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=Fa,idMapper:n=Na})=>o=>{const i=o.map(n),c=ro(i,t.data).map(r).filter(Boolean);t.removeAll(c);const u=i.map(d=>{const h=t.getModel(d.id);return h&&s?s(d,h):e(d)}).filter(Boolean);t.addAll(u)},zh=({container:t,onAddItem:e,onRemoveItem:s=Fa,idMapper:r=Na})=>n=>{const o=n.map(r);ro(o,t.models).forEach(s),o.forEach(e)},Vh=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=n=>n})=>n=>{const o=n.map(r);ro(o,t).forEach(s),o.forEach(e)},Gh=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},Ei=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Mi=[{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 Ua(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=Mi.length;s++){const r=Mi[s];if(Math.abs(e)<r.amount)return Ei.format(Math.round(e),r.name);e/=r.amount}return Ei.format(Math.round(e),"years")}const no=t=>t%4===0&&t%100!==0||t%400===0,oo=(t,e)=>[31,no(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],ja=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,oo(s.getFullYear(),s.getMonth()))),s},Ba=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},Mt="en-US",Ha={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"}},Ka={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"}},qa=(t,{dateStyle:e="short",locales:s=Mt}={dateStyle:"short",locales:Mt})=>{const r=e==="short"?Ha.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},za=(t,{locales:e=Mt,timeStyle:s="short"}={locales:Mt,timeStyle:"short"})=>{const r=Ka[s];return new Intl.DateTimeFormat(e,r).format(t)},Va=(t,{dateStyle:e="short",locales:s=Mt,timeStyle:r="short"}={dateStyle:"short",locales:Mt,timeStyle:"short"})=>{const n={...e&&Ha[e],...r&&Ka[r]};return new Intl.DateTimeFormat(s,n).format(t)},Yh=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Ba,addMonthsToDate:ja,formatDate:qa,formatDateSince:Ua,formatDateTime:Va,formatTime:za,getDaysInMonth:oo,isLeapYear:no},Symbol.toStringTag,{value:"Module"}));function Ga(t,e,s=300){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,n)},s)}}const te="canvas-renderer",an=new Map,Ti=new Map,cn=new Map,ln=new Map,Ps=(t,e)=>{Ya[t]=e},Ya={indexExtension:{registerIndexExtension:(t,e)=>{const s=ln.get(t)||{};Object.assign(s,e),ln.set(t,e)},loadIndexExtensions:t=>ln.get(t)||{}},loader:{registerLoader:(t,e)=>{Ti.set(t,e)},executeLoader:async(t,e)=>{const s=Ti.get(t);if(s)return await s(e)}},propertyMapper:{registerPropertyMapper:(t,e)=>{cn.set(t,e)},hasMapper:t=>cn.has(t),executeMapper:(t,e,s)=>{const r=cn.get(t);return r?r(e,s):""}},dataMapper:{registerDataMapper:(t,e)=>{const s=an.get(t)||[];s.push(e),an.set(t,s)},executeMapper:async(t,e,s)=>{const r=an.get(t);if(!r)return{};const n={};for(const o of r){const i=await o(e,s);Object.assign(n,i)}return n}},canvas:{registerRenderer:(t,e)=>{if(!$[te]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}$[te].register(t,e)}}},$=Ya,Wh=async({context:t,extension:e})=>{const s=await $.loader.executeLoader(e,{});return t==null||t.set(e,s),s},Qh=async({extension:t,contextData:e,data:s})=>await $.dataMapper.executeMapper(t,s,e),Zh=async({extension:t,contextData:e,data:s})=>await $.propertyMapper.executeMapper(t,s,e),Xh=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Qh,executeLoaderExtension:Wh,executePropertyMapperExtension:Zh},Symbol.toStringTag,{value:"Module"})),Jh="Extensions";class ef{constructor(){l(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}const me=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),Wa="studio.tools.preview",tf="studio.relax.store.validation",Qa="studio.log.debug",Za="studio.log.info",sf={profiles:[Wa]};var da;const rf=((da=globalThis.getKosConfig)==null?void 0:da.call(globalThis))||JSON.stringify(sf),Xa=JSON.parse(rf);globalThis.kosConfig=Xa;const io=Xa,Ja=()=>io.profiles||[],_n=t=>Ja().includes(t),nf=()=>io.logging||!1,of=()=>{const t=_n(Qa),e=_n(Za);return t?"DEBUG":e?"INFO":void 0},ec=()=>{const t=me(),e=of(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},tc=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",sc=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",rc="ws-log",af=D.methodFactory,nc=tc(),cf=sc();D.methodFactory=function(t,e,s){const r=af(t,e,s);return function(...n){var c;const o=s?String(s):"",i=o?`[${String(o).substring(o.lastIndexOf(":")+1)}] | `:"[root] | ",a=n.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!==rc||nc&&cf)&&globalThis.kosLog(`UI: ${i}${a}`)}};let oc=ec();D.setLevel(oc);window.setKosLogLevel=t=>{oc=t,D.setLevel(t)};const ar=D.getLogger(rc);window.enableKosMessageLog=()=>{ar.setLevel(D.levels.INFO)};window.disableKosMessageLog=()=>{ar.setLevel(D.levels.ERROR)};nc?window.enableKosMessageLog():window.disableKosMessageLog();const lf=["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(";"),uf=["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(";"),Hs=t=>e=>{D.getLevel()<=t&&e()},m={...D,ifDebug:Hs(D.levels.DEBUG),ifInfo:Hs(D.levels.INFO),ifWarn:Hs(D.levels.WARN),ifError:Hs(D.levels.ERROR),getLogger:t=>D.getLogger(`kos::${t}`),getLoggers:()=>D.getLoggers(),createLogger:({name:t,group:e})=>{var o,i,a,c;const s=`${e?`${e}:`:"kos"}::${t}`,r=D.getLogger(s);let n=(i=(o=globalThis.kos.logOverrides)==null?void 0:o.find(u=>u.name===s))==null?void 0:i.level;return n?r.setLevel(n):(n=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:c.level,n&&r.setLevel(n)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");ar.info(`%c⬆ ${e}`,lf)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");ar.info(`%c⬇ ${e}`,uf)}},ic="featureFlagResolver",Ks=new Map;Ps(ic,{register:(t,e)=>{var s;Ks.has(t)||Ks.set(t,[]),(s=Ks.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Ks.get(t);if(!s)return[];const r=s.map(a=>a(e)),o=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(o)).reduce((a,c)=>(a[c]=!0,a),{});return cc.updateFlags(i),Object.keys(i)}});const df="kos.loader.featureFlag";class ac{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new ac;const cc=window.KosFeatureFlags,lc=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,n=o=>{const i=(o+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${n(0)}${n(8)}${n(4)}`},uc=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return lc(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},dc=(t,e)=>getComputedStyle(t).getPropertyValue(e),hf=(t,e)=>uc(dc(t,e)),ff=(t,e)=>{const s={...t};return s.id&&delete s.id,s},In=(t,e,s=ff)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})},ee=Symbol("SubscriptionHandlers"),N=Symbol("DependencyModels"),ls=Symbol("FutureService"),Be=Symbol("ChildModels"),us=Symbol("ParentModel"),ds=Symbol("LogConfig"),er=Symbol("ReferenceConfig"),ao=Symbol("KosModelSymbol"),et=Symbol("ModelEffects"),He=Symbol("CompanionParentModel"),co=Symbol("FutureContainerSetup"),lo=Symbol("MultipleFutureContainerSetup"),hs=Symbol("FutureAliases"),uo=Symbol("TroubleAwareSetup"),ho=Symbol("LoggerSetup"),fo=Symbol("ContainerAwareSetup"),ks=Symbol("StateMachineSetup"),wt=Symbol("StateEntryHandlers"),fs=Symbol("StateExitHandlers"),pf=Symbol("StateActionHandlers"),gf=m.createLogger({group:"decorators",name:"fsm-injection"});function hc(t){const e=t[ks];if(!e)return;const{config:s,options:r}=e;vf(t,s,r),wf(t,r);const n=bf(t);mf(t,s,r,n),yf(t,s,r)}function mf(t,e,s,r){t.transition=Tf(t,e,s,r.entry,r.exit),t.canTransition=xf(t,e,s),t.isInState=Af(t,s)}function yf(t,e,s){Ef(t),Mf(t,e,s)}function bf(t){const e=t.constructor.prototype[wt]||new Map,s=t.constructor.prototype[fs]||new Map;return{entry:e,exit:s}}function vf(t,e,s){t._fsmConfig=e,t._fsmOptions=s}function wf(t,e){const{stateProperty:s,trackHistory:r}=e,n=t._fsmConfig;t[s]=n.initial,t._fsmInitialized=!0,t.isTransitioning=!1,r&&(t.stateHistory=[{state:n.initial,timestamp:new Date}])}function Ef(t){Object.defineProperty(t,"isFsmInitialized",{get(){return this._fsmInitialized},enumerable:!0,configurable:!0})}function Mf(t,e,s){const{stateProperty:r}=s;Object.defineProperty(t,"allowedTransitions",{get(){if(!this._fsmInitialized)return[];const n=this[r],o=this._fsmConfig.states[n];return o!=null&&o.on?Object.keys(o.on):[]},enumerable:!0,configurable:!0})}function Tf(t,e,s,r,n){const{stateProperty:o,throwOnInvalid:i}=s;return function(a){if(!this._fsmInitialized){Sf(e.initializeAt,i);return}const c=this[o],u=_f(c,a,this._fsmConfig,i);u&&Of(this,c,u,a,o,r,n,s)}}function Sf(t,e){const s=`Cannot transition: FSM not initialized. Waiting for ${t} lifecycle phase.`;if(e)throw new Error(s);console.warn(s)}function _f(t,e,s,r){var i;const n=s.states[t],o=(i=n==null?void 0:n.on)==null?void 0:i[e];if(!o){If(t,e,r);return}return o}function If(t,e,s){const r=`Invalid transition: Event "${e}" not allowed from state "${t}"`;if(s)throw new Error(r);console.warn(r)}function Of(t,e,s,r,n,o,i,a){t.isTransitioning=!0;try{$f(t,e,i),t[n]=s,Df(t,s,r,a),Cf(t,s,o)}finally{t.isTransitioning=!1}}function $f(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function Cf(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function Df(t,e,s,r){r.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date,event:s})}function xf(t,e,s){const{stateProperty:r}=s;return function(n){var a;if(!this._fsmInitialized)return!1;const o=this[r],i=this._fsmConfig.states[o];return((a=i==null?void 0:i.on)==null?void 0:a[n])!==void 0}}function Af(t,e){const{stateProperty:s}=e;return function(r){return this._fsmInitialized?this[s]===r:!1}}function fc(t,e){const s=t[ks];if(!s)return;const{config:r,options:n}=s,{stateProperty:o}=n;r.initializeAt===e&&(t._fsmInitialized||(Rf(t,o,r.initial),t._fsmInitialized=!0,Pf(t,r.initial,n),kf(t,r.initial),gf.debug(`FSM initialized for model ${t.id} at lifecycle ${e} with initial state "${r.initial}"`)))}function Rf(t,e,s){t[e]=s}function Pf(t,e,s){s.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date})}function kf(t,e){const r=(t.constructor.prototype[wt]||new Map).get(e);r&&typeof t[r]=="function"&&t[r]()}const $e=(t,e)=>{t[Be]=t[Be]||{},t[Be][e]=!0},it=t=>`{PROP_${String(t)}}`,Lf=t=>`{PROP_${String(t)}}`,Ff=it("kosParentId"),jr=t=>e=>{e[us]=e[us]||{};const s=(t==null?void 0:t.parentId)||Ff;e[us]={parentId:s}};function Nf(t){return e=>{const s=(t==null?void 0:t.mode)||"decorator",r=(t==null?void 0:t.parentProperty)||"companionParent",n=(t==null?void 0:t.excludeProperties)||[],o=t==null?void 0:t.lifecycle;return jr()(e),e.prototype[He]={mode:s,parentProperty:r,excludeProperties:n,lifecycle:o},e}}function pc(t){return e=>{const s=t!=null&&t.legacy?"_models":(t==null?void 0:t.containerProperty)||"container",r=(t==null?void 0:t.includeMethods)!==!1,n=(t==null?void 0:t.includeGetters)!==!1,o=(t==null?void 0:t.modelsProperty)||"models",i=(t==null?void 0:t.containerOptions)||{};return e.prototype[fo]={containerProperty:s,includeMethods:r,includeGetters:n,modelsProperty:o,containerOptions:i,legacy:(t==null?void 0:t.legacy)||!1},e}}function Uf(t,e,s){const r=s.value;s.value=function(...n){const o=Y.getContext(this.id);return n.push(o),r.apply(this,n)}}const Br=Symbol("KosExecutionContext");function po(t){return t&&typeof t=="object"&&Br in t}function jf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[co]={mode:s,handlerProperty:r},e}}function Bf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[lo]={mode:s,handlerProperty:r},e}}var x=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(x||{});const Hf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:x},Symbol.toStringTag,{value:"Module"})),Re=Symbol("HttpRouteHandlers"),Si="__httpBrowserRouter";function Hr(t){return function(s){return function(r,n,o){r[Re]=r[Re]||[];const i={method:t,path:s,handler:n};return r[Re].push(i),r[N]=r[N]||{},r[N][Si]||(r[N][Si]={modelType:"browser-router-model",lifecycle:x.INIT}),o}}}const gc=Hr("GET"),Ls=Hr("POST"),Kf=Hr("PUT"),mc=Hr("DELETE"),qf=mc;function cr(t){return!!(t!=null&&t[Re])&&t[Re].length>0}function yc(t){return(t==null?void 0:t[Re])||[]}const zf=({group:t}={group:""})=>e=>{e[ds]=e[ds]||{},e[ds]={group:t}};class bc{static create({modelId:e,modelTypeName:s,component:r}){const n=[r??"kos",s,e].filter(Boolean).join(".");return m.createLogger({name:n})}}function vc(t){return e=>{const s=(t==null?void 0:t.loggerProperty)||"logger",r=t==null?void 0:t.loggerContext;e.prototype[ho]={loggerProperty:s,loggerContext:r};const n=()=>{var i;return(i=e.prototype[ao])==null?void 0:i.type};let o;return Object.defineProperty(e.prototype,s,{get(){if(!o){const i=n();o=bc.create({modelTypeName:r||i,component:"kos-model"})}return o},enumerable:!1,configurable:!1}),e}}function wc(t){return(e,s,r)=>{e[et]=e[et]||{},e[et][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Vf=t=>(e,s)=>{e[er]=e[er]||{},e[er][s]=t},un=m.createLogger({name:"resolve-parameters"}),Ee=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((n,o)=>(n[o]=Ee({value:r[o],modelId:e,modelData:s}),n),{});else if(typeof r=="string"){const n=new RegExp("{PROP_(.+?)}","g");let o=r!=null&&r.includes(ir)?r.replace(ir,e):r;if(s){let i=!1;const a=/^{PROP_.+?}$/.test(o);if(o=o.replace(n,(c,u)=>{if(Object.getOwnPropertyNames(s).includes(u)||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(u)){const h=s[u];return h?(un.debug(`Resolved ${c} to ${h}`),h):(un[a?"debug":"warn"](`Property ${u} is falsy${a?"":" in composite string"}, marking for undefined return`),i=!0,c)}return un[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),c}),i)return}return o}else return r;return r},tt=Symbol("ServiceRequestHandlers"),_i=new WeakMap;function Gf(t){return(e,s,r)=>{var a;e[tt]=e[tt]||{};const n=r.value,o={...t,handlerMethod:s,originalHandler:n},i=`${((a=t.method)==null?void 0:a.toUpperCase())||"GET"}:${String(t.path)}`;if(e[tt][i]=o,!t.lifecycle){const c=function(...u){const d=u[u.length-1],h=async f=>{const p=_i.get(c);if(!p)throw new Error("Service request metadata not found for method");try{const{default:y}=await Promise.resolve().then(()=>Zc),w=Ee({value:p.path,modelId:this.id,modelData:this}),E={...typeof p.pathParams=="function"?p.pathParams(this):p.pathParams||{},...(f==null?void 0:f.pathParams)||{}},S={...typeof p.queryParams=="function"?p.queryParams(this):p.queryParams||{},...(f==null?void 0:f.queryParams)||{}},L=(f==null?void 0:f.body)||(typeof p.body=="function"?p.body(this):p.body),P={};Object.keys(E).length>0&&(P.path=E),Object.keys(S).length>0&&(P.query=S);const O=(p.method||"get").toLowerCase(),_=y,[K,q]=O==="get"?await _.get(w,P):O==="post"?await _.post(w,P,L):O==="put"?await _.put(w,P,L):O==="delete"?await _.delete(w,P,L):await _.get(w,P);if(K){if(p.errorHandler)switch(p.errorHandler.strategy){case"log":return console.error(`Service request error: ${K}`),p.errorHandler.onError&&p.errorHandler.onError(new Error(K),this),[null,p.errorHandler.defaultValue];case"ignore":return[null,p.errorHandler.defaultValue];case"default":return[null,p.errorHandler.defaultValue];case"throw":default:return[K,null]}return[K,null]}let J=q;return p.transform&&(J=p.transform(q)),[null,J]}catch(y){return[y.message||"Unknown error",null]}};if(po(d))return d.$request=h,n.apply(this,u);{const f={[Br]:!0,$request:h};return n.apply(this,[...u,f])}};_i.set(c,o),r.value=c}return r}}var Ec=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(Ec||{}),ue=(t=>(t.IMMEDIATE="immediate",t.SINGLE="single",t.TTL="ttl",t.PERMANENT="permanent",t.MANUAL="manual",t))(ue||{}),Je=(t=>(t.ALL="all",t.AFTER_REQUEST="after-request",t.AFTER_RESPONSE="after-response",t.NONE="none",t))(Je||{});const Yf=m.createLogger({name:"kos-state-machine"});function Wf(t,e){return s=>(s.prototype[ks]={config:{...t,initializeAt:t.initializeAt||x.READY},options:{stateProperty:(e==null?void 0:e.stateProperty)||"currentState",trackHistory:(e==null?void 0:e.trackHistory)||!1,throwOnInvalid:(e==null?void 0:e.throwOnInvalid)!==!1}},s)}function Qf(t){return(e,s)=>{e[wt]||(e[wt]=new Map),e[wt].set(t,s)}}function Zf(t){return(e,s)=>{e[fs]||(e[fs]=new Map),e[fs].set(t,s)}}function Xf(t){return(e,s,r)=>{const n=r.value;return r.value=function(...o){var u,d;if(!this.isFsmInitialized)return n.apply(this,o);const a=this.currentState;if(!t.allowedStates.includes(a)){const h=`Method ${String(s)} cannot be called from state "${a}". Allowed states: ${t.allowedStates.join(", ")}`;if(t.throwOnInvalid!==void 0?t.throwOnInvalid:((d=(u=this[ks])==null?void 0:u.options)==null?void 0:d.throwOnInvalid)!==!1)throw new Error(h);Yf.warn(h);return}return n.apply(this,o)},r}}function Jf(t){return e=>{const s=(t==null?void 0:t.pathProperty)||"path";return e.prototype[uo]={pathProperty:s},e.prototype[N]=e.prototype[N]||{},e.prototype[N].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},e}}const Lt=({modelType:t,id:e,options:s,lifecycle:r})=>(n,o)=>{n[N]=n[N]||{},n[N][o]={modelType:t,id:e,options:s,lifecycle:r||x.INIT}};class Mc{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=_o.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=W(()=>{var n,o;(e.endState||e.progress)&&((o=(n=this.container)==null?void 0:n.onFutureUpdate)==null||o.call(n,e))});this.disposers.set(s||e.id,r)}removeFuture(e){var s;this.futures.delete(e||this.context),(s=this.disposers.get(e||this.context))==null||s(),this.disposers.delete(e||this.context)}getFuture(e){return this.futures.get(e||this.context)}get futureMap(){return this.futures}}class Kr{constructor(e){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=W(()=>{var r,n;(e.endState||e.progress)&&((n=(r=this.container)==null?void 0:r.onFutureUpdate)==null||n.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw m.error(e),e}}}const Tc=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},Sc=Symbol("KosObservableData");class _c{constructor(){l(this,"map");l(this,"_revision",1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return s==="_revision"||e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var n;return this.map.has(s),this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(n=this.atomMap.get(s))==null||n.reportChanged(),!0},ownKeys:()=>[...Array.from(this.map.keys()),"_revision"]});this.map=M.observable.map(new Map),M.makeObservable(this,{_revision:M.observable})}setValue(e,s){const r=this.map.has(e);this.map.set(e,s),r||M.action(()=>{this._revision++})()}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return this._revision,Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}_c.prototype[Sc]=!0;function ep(t,e){return new Proxy(t,{construct:(s,r)=>{const n=new t(...r);return n.setValues(e),n.proxy}})}const _e=t=>{const e=ep(_c,t);return new e(t)};function tp(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class go{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=_e(),this.generateIndex(),M.autorun(()=>{this._container.revision&&this.generateIndex()}),M.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(e,s,r=this._map,n=this.data){const o=r.get(e)||new Set;o.add(s),r.set(e,o),n[e]=Array.from(o)}resolveIndex(e,s){this.data.keys.filter(n=>!Object.keys(s).includes(n)).forEach(n=>{delete this.data[n],this._map.delete(n)}),Object.keys(s).forEach(n=>{const o=s[n],i=this.data[n]||[];if(tp(o,i))m.debug(`KosContainerIndex - Index ${n} is the same`);else{this.data[n]=o;const a=e.get(n)||new Set;this._map.set(n,a)}})}generateIndex(){M.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const n=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(n)?n.forEach(o=>{this.addItemToIndex(o,r,e,s)}):typeof n=="string"||typeof n=="number"?this.addItemToIndex(String(n),r,e,s):typeof n=="boolean"&&this.addItemToIndex(String(n),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function sp(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>M.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const Gt=m.createLogger({name:"kos-container-model"});class Ce{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?$.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const n=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((o,i)=>(o[i]=void 0,o),{}):{};this._index=M.observable.map(n),this.idx=_e(),this._parentId=e==null?void 0:e.parentId,M.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new go({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(e,s){this._data.set(e.id||"",e),e.id&&this._parentId&&Y.setParentContext(e.id,this._parentId),s||this.increment();const r=this._disposerMap.get(e.id);r&&(r(),this._disposerMap.delete(e.id));const n=Object.entries(this._optionsMap||{}),o=Object.values(this._optionsMap||{}),i=new Map(n.map(([d,h])=>[h,d])),a=d=>{var f,p;o.includes(d.name)&&((f=this.index.get(i.get(d.name)))==null||f.refresh());const h=n.filter(([,y])=>typeof y=="function");for(const[y]of h)(p=this.index.get(y))==null||p.refresh()},c=sp(e,a,o.filter(d=>typeof d=="string")),u=M.observe(e,a);this._disposerMap.set(e.id||"",()=>[u,...c].forEach(d=>d()))}removeModel(e,s){this._data.delete(e),s||this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Gt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(Gt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Gt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(e=>{const s=e.id;st(e).then(()=>{Gt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Gt.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}var v=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(v||{}),F=(t=>(t.CREATE="create",t.INITIALIZE="init",t.LOAD="load",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.RESET="go_offline",t.UNLOAD="unload",t.FAILED="failed",t.GO_ACTIVE="go_active",t.GO_INACTIVE="go_inactive",t.TIMEOUT="timeout",t))(F||{});const de=async t=>{if(t.id){const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},st=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(t)},rp=async t=>{if(await I.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(F.UNLOAD,v.UNLOADED)},np=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(t),m.debug(`reload model initiated for model ${t.id}, model ready: ${lr(t)} - ${Date.now()} `),await de(t),m.debug(`reload model complete for model ${t.id}, model ready: ${lr(t)} - ${Date.now()} `)},op=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},Ic=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Ie=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Oc=(t,e)=>{if(!t)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(t).filter(n=>Object.keys(e).every(o=>n[o]===e[o]))},ip=(t,e)=>Oc(t,e)[0],ap=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},$c=t=>{if(!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},cp=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},On=(t,e)=>{const s=I.getInstance().modelManager.getModelById(t);if(!s){m.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(n=>e(n.modelData))},Te=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,lr=t=>{const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},lp=m.createLogger({name:"kos-model-factory"}),ps={byModelType:t=>I.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=ps.byModelType(e);if(!r)throw lp.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},ie={Factory:{create:t=>e=>(s,r)=>(r&&Y.setParentContext(e,r),ps.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&Y.setParentContext(t,s),ps.getModelInstance(t,t,e))},Model:{instance:t=>e=>ps.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Ii=window.KosRegistry.coreModels,dn=window.KosRegistry.preloadModels,hn=window.KosRegistry.companionModels,qs=window.KosRegistry.models,A={model:{registerLegacyModel:t=>(e,s)=>(Ii.set(e,s),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(dn.includes(e)||dn.push(e),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=fn(e)?e.registration():e;return qs.set(r.type,r),fn(e)&&e.relatedModels.forEach(n=>qs.set(n.type,n.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],fn(e)&&e.relatedModels.forEach(n=>I.getInstance().modelManager.registry.models[n.type]=n.registration().registration))),s&&A.model.preloadModel(t)(r.type),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},get:t=>qs.get(t),getAll:()=>Array.from(qs.entries()),getPreloadModels:()=>dn,getLegacyModels:()=>Array.from(Ii.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=hn.get(e)||[];return r.push(s),hn.set(e,r),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(hn.entries())}},Cc=A.model.registerLegacyModel,Dc=A.model.register,up=A.companion.register,dp=A.model.preloadModel,mo=t=>typeof t.updateModel=="function",fn=t=>t.registration!==void 0&&typeof t.registration=="function";class xc{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=Te(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){A.model.register({})(this.registration()),this.registerRelatedModels()}}class ye extends xc{constructor(e){super({...e,singleton:!1,factory:ie.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=Ie(e);if(!r)throw new Error("Model not found with id "+e);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const n=s(r);if(this.guard(n)){if(mo(n))n.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return n}else throw new Error("Model is not of type "+this.type)}})},options:r=>({build:()=>{const n=s(r);if(this.guard(n))return n;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 Se extends xc{constructor(e){super({...e,singleton:!0,factory:ie.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=Ie(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 n=e(r);if(this.guard(n)){if(mo(n))n.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return n}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(n).modelTypeId}`)}})},options:r=>({build:()=>{const n=e(r);if(this.guard(n))return n;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(n).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const $n=m.createLogger({group:"decorators",name:"kos-model"});function hp(t,e,s){var o;const r=(o=t[us])==null?void 0:o.parentId;if(!r)return;const n=Ee({value:r,modelData:s,modelId:e});n&&typeof n=="string"&&Y.setParentContext(e,n)}function fp(t){const e=t[ls];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function pp(t,e){const s=t[N]||{};Object.entries(s).forEach(([r,n])=>{const o=Ee({value:n.id||n.modelType,modelData:t,modelId:e}),i=Object.entries((n==null?void 0:n.options)||{}).reduce((a,[c,u])=>(a[c]=Ee({value:u,modelData:t,modelId:e}),a),{});if(typeof o=="string"){if(!n.lazy){const a=I.getInstance().modelManager.createModelInstance(n.modelType,o,i);t[r]=a.data}I.getInstance().modelManager.addDependency(e,o)}})}function gp(t){const e=t[co];if(!e)return;const{mode:s,handlerProperty:r}=e,n=new Kr(t);t[r]=n,s==="full"&&(Object.defineProperty(t,"future",{get(){return n.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){var o;return((o=n.future)==null?void 0:o.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var o;return((o=n.future)==null?void 0:o.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return n.future?!n.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var o;return((o=n.future)==null?void 0:o.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{n.future&&await n.future.cancelFuture()})}function mp(t){const e=t[lo];if(!e)return;const{mode:s,handlerProperty:r}=e,n=new Mc(t);t[r]=n,Object.defineProperty(t,"future",{get(){return n.future},enumerable:!0,configurable:!0});const o=t[hs];o instanceof Map&&o.forEach(i=>{const a=`${i}Future`;Object.defineProperty(t,a,{get(){return n.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(t,`${i}Progress`,{get(){const c=n.futureMap.get(i);return(c==null?void 0:c.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}Status`,{get(){const c=n.futureMap.get(i);return(c==null?void 0:c.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsRunning`,{get(){const c=n.futureMap.get(i);return c?!c.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsCancelled`,{get(){const c=n.futureMap.get(i);return(c==null?void 0:c.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const c=n.futureMap.get(i);c&&await c.cancelFuture()})}),s==="full"&&(Object.defineProperty(t,"progress",{get(){var i;return((i=n.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var i;return((i=n.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return n.future?!n.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var i;return((i=n.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{n.future&&await n.future.cancelFuture()})}function yp(t){const e=t[uo];if(!e)return;const{pathProperty:s}=e;Object.defineProperty(t,"troubles",{get(){const r=this[s];if(r==null){const n=`@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(n):console.warn(n),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((n,o)=>o.rank-n.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troublesByType",{get(){return this.troubles.reduce(Tc,{})},enumerable:!0,configurable:!0})}function bp(t,e){const s=t[fo];if(!s)return;const{containerProperty:r,includeMethods:n,includeGetters:o,modelsProperty:i,containerOptions:a,legacy:c}=s,u={...a,parentId:a.parentId||e},d=new Ce(u);t[r]=d,t[Be]||(t[Be]={}),t[Be][r]=d,n&&(t.getModel=h=>d.getModel(h),t.addModel=h=>{d.addModel(h)},t.removeModel=h=>{d.removeModel(h)}),o&&(Object.defineProperty(t,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(t,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function vp(t,e){const s=t.constructor.prototype[He];if(!s)return;const{mode:r,parentProperty:n,excludeProperties:o}=s,i=e[n];if(!i){$n.warn(`Companion decorator configured but no parent model found at '${n}'`);return}if(t.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 y=i.constructor.prototype[ee]||{};return Object.values(y).some(w=>{const E=w==null?void 0:w.handler;return E===i[p]||E===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||c.includes(p)||o.includes(p)||u(p)||p in t,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 y=i[p];typeof y=="function"?t[p]=(...w)=>y.apply(i,w):Object.defineProperty(t,p,{get:()=>i[p],set:w=>{i[p]=w},enumerable:!0,configurable:!0})}catch(y){$n.debug(`Skipping companion proxy for property ${p}:`,y)}}function wp(t){try{return M.makeAutoObservable(t)}catch(e){return $n.error("Failed to make observable:",e),t}}const Ep={construct(t,e){var c;const[s,r={}]=e,n=Y.createContext(s);hp(t,s,r);const i=!!t.prototype[ho]?null:m.createLogger({name:t.prototype.modelTypeId,group:((c=t[ds])==null?void 0:c.group)??"kos-model"}),a=new t(s,r,{logger:i,kosContext:n});return fp(a),gp(a),mp(a),yp(a),bp(a,s),vp(a,r),hc(a),pp(a,s),wp(a)}};function R(t){return e=>{var o,i;const s=e,r=typeof t=="string"?{modelTypeId:t,autoRegister:!1}:{autoRegister:!1,...t};s.prototype.modelTypeId=r.modelTypeId,s.prototype[ao]=!0,(o=s.prototype)[ee]??(o[ee]={}),(i=s.prototype)[N]??(i[N]={}),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const n=new Proxy(s,Ep);if(r.singleton!==void 0){let a;r.singleton?a=new Se({class:n,type:r.modelTypeId}):a=new ye({class:n,type:r.modelTypeId}),Object.defineProperty(n,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return n}}const Mp=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>n=>{n[ee]=n[ee]||{},Array.isArray(t)?t.forEach(o=>{n[ee][o]={websocket:s,handler:e,condition:r}}):n[ee][t]={websocket:s,handler:Ga(n,M.action(e),200),condition:r}};function Ac(t,e,s){const r={};if(!t.endsWith("/*"))return r;const n=t.slice(0,-2);if(e.startsWith(n)){const o=e.slice(n.length+1),i=s||"path";r[i]=o}return r}function Rc(t){return t.endsWith("/*")}function B(t){return(e,s,r)=>{const n=Tp(t,r);Ip(e,t.topic,n),t.replay&&Op(t.topic,t.replay.bufferSize)}}function Tp(t,e){const{condition:s=(_,K)=>!0,transform:r=_=>_,websocket:n=!1,fos:o=!1,bridge:i=!1,skipParse:a=!1,lifecycle:c,destinationAddress:u,debounce:d,throttle:h,buffer:f,filter:p,once:y,wildcardName:w,flow:E,requiresBaseline:S}=t,L=e.value,P=Sp(L,{debounce:d,throttle:h,buffer:f,once:y}),O=_p(p,s);return{websocket:n,fos:o,bridge:i,handler:P,condition:O,transform:r,lifecycle:c,skipParse:a,destinationAddress:u,wildcardName:w,flow:E,requiresBaseline:S}}function Sp(t,e){var o,i;let s=t;const r=typeof e.debounce=="number"?e.debounce:(o=e.debounce)==null?void 0:o.delay,n=typeof e.throttle=="number"?e.throttle:(i=e.throttle)==null?void 0:i.interval;return r&&r>0?s=$p(s,e.debounce):n&&n>0?s=Ap(s,e.throttle):e.buffer?s=Rp(async function(c){for(const u of c)await s.call(this,u)},e.buffer):e.once&&(s=Pp(s)),s}function _p(t,e){return t?(s,r,n)=>t(n)?e(s,r,n):!1:e}function Ip(t,e,s){t[ee]=t[ee]||{},Array.isArray(e)?e.forEach(r=>{t[ee][r]=s}):t[ee][e]=s}function Op(t,e){kp(t,e)}function $p(t,e){const s=typeof e=="number"?e:e.delay;return Cp(e)==="discard"?Dp(t,s):xp(t,s)}function Cp(t){return(typeof t=="object"?t.discardIntermediate:!1)?"discard":"accumulate"}function Dp(t,e){let s=null;return function(r){s&&clearTimeout(s),s=setTimeout(()=>{t.call(this,r),s=null},e)}}function xp(t,e){let s=null,r=[];return function(n){r.push(n),s&&clearTimeout(s),s=setTimeout(()=>{const o=[...r];r=[],t.call(this,o),s=null},e)}}function Ap(t,e){const s=typeof e=="number"?e:e.interval,r=typeof e=="object"?e.discardIntermediate:!1;let n=0,o=null,i=[],a=!1;const c=function(){if(i.length>0){const u=[...i];i=[],t.call(this,u)}};return function(u){const d=Date.now(),h=d-n;r?h>=s?(n=d,t.call(this,u)):o||(o=setTimeout(()=>{n=Date.now(),t.call(this,u),o=null},s-h)):(i.push(u),h>=s?(n=d,c.call(this)):a||(a=!0,o=setTimeout(()=>{n=Date.now(),c.call(this),o=null,a=!1},s-h)))}}function Rp(t,e){const s=[];let r=null;const n=e.maxSize||1e3,o=i=>{s.length>0&&(t.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=n){r&&(clearTimeout(r),r=null),o(this);return}r||(r=setTimeout(()=>{o(this),r=null},e.time))}}function Pp(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function kp(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{eo(r,e)})}const pn=new Map,Pc={addToDeletionQueue:(t,e)=>{const s=pn.get(t)||[];s.push(e),pn.set(t,s)},cancelDeletion:t=>{const e=pn.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},Lp=m.createLogger({name:"kos-dependency-manager"});class Fp{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(e,s){Pc.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(e)||r.push(e),this._usedByCache.set(s,r);const n=this._usesCache.get(e)||[];n.includes(s)||n.push(s),this._usesCache.set(e,n)}remove(e,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(o=>o!==e));const n=this._usesCache.get(e)||[];this._usesCache.set(e,n.filter(o=>o!==s))}canDestroy(e){const s=this._usedByCache.get(e);return s!=null&&s.length?(Lp.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}const Oi=m.createLogger({name:"kos-model-cache"});class Np{constructor(e=[]){l(this,"_modelsById",M.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).map(e=>e).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?(Oi.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Oi.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const kc=t=>typeof t=="function",zs=m.createLogger({name:"kos-companion-instantiator"});class Up{constructor(e,s,r){this.registry=e,this.cache=s,this.createModel=r}createCompanionModels(e,s,r){const n=this.getCompanionDefinitions(e.modelTypeName);r!==void 0&&zs.debug(`Creating ${r} lifecycle companions for ${e.modelTypeName} [${e.modelId}]`);for(const o of n){const i=this.resolveCompanionType(o,e,s,r);i&&this.shouldCreateCompanion(i.lifecycle,r)&&this.instantiateCompanion(i.type,e,s,r)}}getCompanionDefinitions(e){var s;return((s=this.registry.companionModels)==null?void 0:s[e])||[]}resolveCompanionType(e,s,r,n){return kc(e.type)?this.resolveFactoryCompanion(e,s,r,n):this.resolveStringCompanion(e)}resolveFactoryCompanion(e,s,r,n){const o=e.type(s.modelData,r);if(!o)return zs.debug(`Companion factory returned undefined for ${s.modelTypeName} at ${n||"INIT"} phase`),null;const i=this.extractLifecycleFromType(o);return{type:o,lifecycle:i}}resolveStringCompanion(e){return{type:e.type,lifecycle:e.lifecycle}}extractLifecycleFromType(e){const s=this.registry.models[e];if(!(s!=null&&s.class))return;const r=s.class.prototype[He];return r==null?void 0:r.lifecycle}shouldCreateCompanion(e,s){return s!==void 0?e===s:e===void 0}instantiateCompanion(e,s,r,n){const o=this.generateCompanionId(e,s.modelId);if(this.companionAlreadyExists(o,e,s.modelTypeName))return;const i=this.createCompanionInstance(e,o,s,r);i&&(this.attachCompanionToParent(i,s),zs.debug(`Created ${n||"INIT"} companion ${e} for ${s.modelTypeName} [${s.modelId}]`))}generateCompanionId(e,s){return`${e}-${s}`}companionAlreadyExists(e,s,r){return this.cache.hasModel(e)?(zs.debug(`Companion ${s} already exists for ${r}`),!0):!1}createCompanionInstance(e,s,r,n){const o=this.createModel(e,s,{data:n,companionParent:r.modelData,kosParentId:r.modelId});return(o==null?void 0:o.model)||null}attachCompanionToParent(e,s){e[He]=s,s.addCompanionModel(e)}}function Lc(t,e){return`${Zn}${t}${e?`/${e}`:`/${t}`}`}function Fc(t){return`${Zn}${t}`}function gn(t){const e=[];return new Promise((s,r)=>{for(const{condition:n,onMatch:o}of t){const i=M.when(n,()=>{e.forEach(a=>a());try{o==null||o(),s()}catch(a){r(a)}});e.push(i)}})}const Nc=5e3;class jp extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const Uc=(t,e,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{m.error(`Model ${e.modelId} - ${e.modelTypeName} - ${s} timed out after ${t}ms`),a(new jp(`${e.modelId} - ${e.modelTypeName} - ${s}`,e))},t)}),cancel:()=>{r&&clearTimeout(r)}}},jc=t=>t.fsm.transitionTo(F.GO_ACTIVE,v.ACTIVE),Bc=t=>t.whenReady(),Hc=t=>t.fsm.transitionTo(F.LOAD,v.LOADED),Bp=t=>t.fsm.transitionTo(F.UNLOAD,v.UNLOADED),Kc=t=>t.fsm.transitionTo(F.INITIALIZE,v.INITIALIZED);var yo=(t=>(t.ACTIVE="active",t.READY="ready",t.LOAD="load",t.UNLOAD="unload",t.INIT="init",t))(yo||{});const tr={active:jc,ready:Bc,load:Hc,init:Kc},qc=(t,e)=>{const s=e.id||e.modelType,r=Ee({value:s,modelData:t.modelData,modelId:t.modelId});m.debug(`activating dependent model ${e.modelType} with id ${r}`);const n=Object.keys((e==null?void 0:e.options)||{}).reduce((i,a)=>{const c=e.options[a];return i[a]=Ee({value:c,modelData:t.modelData,modelId:t.modelId}),i},{});return{dependentModel:I.getInstance().modelManager.createModelInstance(e.modelType,r,n),dataModelId:r}},zc=(t,e=x.READY)=>{var n;const s=((n=t.modelData)==null?void 0:n[N])||{};return Object.keys(s).length===0?(m.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(o=>s[o].lifecycle===e).map(o=>{const i=s[o],{dependentModel:a,dataModelId:c}=qc(t,i);t.modelData[o]=a.data,m.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const u=async(f,p,y)=>{var w;await((w=f.whenReady)==null?void 0:w.call(f)),m.debug(`dependent model ${p} with id ${y} - READY`)},{promise:d,cancel:h}=Uc(Nc,t,t.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(o=>!!o)},Vc=async(t,e,s,r)=>{if(m.debug(`Execute lifecycle with ${e.length} models`),e.length===0){m.debug(`${t.modelId} has no children. Returning`);return}if(!s){m.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const n=e.map(a=>{let c;return tr[s]&&a?c=tr[s](a):(a||m.error("model is undefined. This shouldn't happen"),tr[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(n.map(a=>{var d;const{promise:c,cancel:u}=Uc(Nc,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 ${t.modelId} had ${i.length} failed child models on ${r}`)},Gc=async(t,e,s)=>{await Vc(t,t.getChildren().filter(r=>!!r),e,s)},Wt=async(t,e)=>{const r=(await Promise.allSettled(zc(t,e))).filter(n=>n.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))},Hp=t=>typeof t.toJSON=="function",gs=t=>t[N]!==void 0,bo=t=>t.revision!==void 0&&t.index!==void 0,Yc=t=>{if(t){if(gs(t))return t;if(bo(t))return t.data;if(t instanceof Map||t instanceof M.ObservableMap||t instanceof Set)return Array.from(t.values()).filter(gs);if(Array.isArray(t))return t.filter(gs)}};function Kp(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,n,o;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(n=(r=t.companionManager)==null?void 0:r.all())==null?void 0:n.map(i=>i.modelTypeName),children:(o=t.getChildren)==null?void 0:o.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),qp(t.modelData,t.modelTypeName,t.modelId,t)}function qp(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const n=((a=r.getChildren)==null?void 0:a.call(r))||[],o=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[N]||{};return{id:s,type:e,companions:{count:o.length,data:o.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:n.length,data:n.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const n={};for(const o of Object.keys(t))if(!(o.startsWith("_")||typeof t[o]=="function"))try{const i=t[o];gs(i)?n[`[KOS Model] ${o}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:bo(i)?n[`[KOS Container] ${o}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?n[o]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?n[o]=JSON.parse(JSON.stringify(i)):n[o]=i}catch{n[o]="[unreadable]"}return n}})}class zp{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{Y.setParentContext(r.modelId,this.model.modelId)}catch(n){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,n)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[Be])||{};return Object.keys(e).map(r=>Yc(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class Vp{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Gp{constructor(e,s,r,n){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=n}setup(){var s;const e=((s=this.modelData)==null?void 0:s[et])||{};for(const r of Object.keys(e)){const{value:n,dependencies:o,options:i}=e[r],a=n.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},u=o?M.reaction(()=>o(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Yp=m.createLogger({name:"model-active-machine"}),Wp=t=>{const e=b.createMachine(v.INACTIVE,{[v.FAILED]:b.state(b.transition(F.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:b.state(b.transition(F.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:b.invoke(()=>(t.activeStatus=v.ACTIVATING,t.activate()),b.transition("done",v.ACTIVE,b.action(()=>{t.activeStatus=v.ACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED}))),[v.ACTIVE]:b.state(b.transition(F.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:b.invoke(()=>(t.activeStatus=v.DEACTIVATING,t.deactivate()),b.transition("done",v.INACTIVE,b.action(()=>{t.activeStatus=v.INACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED})))});return{service:b.interpret(e,r=>Yp.debug(r.machine.current)),machine:e}},$i=m.createLogger({name:"model-online-machine"}),Qp=t=>{const e=b.createMachine(v.OFFLINE,{[v.ONLINE]:b.state(b.transition(F.GO_OFFLINE,v.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:b.state(b.transition(F.GO_ONLINE,v.ONLINE,b.action(async()=>{$i.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=v.ONLINE,await t.fsm.transitionTo(F.INITIALIZE,v.INITIALIZED)})))}),s=b.interpret(e,r=>$i.debug(r.machine.current));return{machine:e,service:s}},Zp=t=>{var r;const e=Wp(t).service,s=Qp(t).service;return b.createMachine(v.CREATING,{[v.CREATING]:b.state(b.transition(F.CREATE,v.CREATED)),[v.CREATED]:b.state(b.immediate(v.INITIALIZING)),[v.INITIALIZING]:b.invoke(()=>(X(()=>{t.status=v.INITIALIZING}),t.init()),b.transition("done",v.INITIALIZED,b.action(()=>{t.status=v.INITIALIZED})),b.transition("error",v.FAILED,b.action(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=v.FAILED}))),[v.INITIALIZED]:b.state(b.immediate(v.LOADING)),[v.LOADING]:b.invoke(()=>(X(()=>{t.status=v.LOADING}),t.load()),b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.LOADED]:b.state(b.immediate(v.READYING),b.transition(F.UNLOAD,v.UNLOADING)),[v.RESETTING]:b.invoke(()=>{var n;return X(()=>{t.status=v.RESETTING}),(n=t.unload)==null||n.call(t),t.load()},b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED}))),[v.READYING]:b.invoke(()=>(X(()=>{t.status=v.READYING}),t.ready()),b.transition("done",v.READY,b.action(()=>{X(()=>{t.status=v.READY}),s.send(F.GO_ONLINE)})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.READY]:b.state(b.transition(F.UNLOAD,v.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(F.RESET,v.RESETTING),b.transition(F.GO_ONLINE,v.READY,b.action(()=>{s.send(F.GO_ONLINE)})),b.transition(F.GO_OFFLINE,v.READY,b.action(()=>{s.send(F.GO_OFFLINE)})),b.transition(F.GO_ACTIVE,v.READY,b.action(()=>{e.send(F.GO_ACTIVE)})),b.transition(F.GO_INACTIVE,v.READY,b.action(()=>{e.send(F.GO_INACTIVE)}))),[v.UNLOADED]:b.state(),[v.FAILED]:b.state()})},Xp=m.createLogger({name:"kos-model-lifecycle"}),Jp=t=>({service:b.interpret(Zp(t),s=>Xp.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class eg{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=Jp(e);this.service=r.service,this.service.send(F.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,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 ${e} toward target ${s}`),new Promise((o,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),o())}),this.service.send(e)}).finally(()=>{var o;(o=this.disposer)==null||o.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[v.ACTIVE,v.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const Wc="browser-router-model";class vo{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!cr(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const n=this.model[r];if(n&&typeof n=="object"&&"use"in n&&typeof n.use=="function"){e=n;break}}if(e||(e=(s=Ie(Wc))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return cr(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=yc(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const o=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,o)}let n;for(;(n=s.exec(e))!==null;){const o=n[1];if(o in this.model){const i=this.model[o];r=r.replace(n[0],String(i))}else this.logger.warn(`Property '${o}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const n=async(o,i)=>{var a;try{await s.call(this.model,o,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,n),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(o=>o.method===e&&o.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function tg(t,e){if(!cr(t))return;const s=Ie(Wc);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new vo(t,e).setRouter(s.model)}class sg{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const n=this.queue.length,o=this.filterEventsByStrategy(e,s,r),i=n-o.length;this.log.warn(`Processing ${o.length}/${n} offline message(s) with strategy: ${e}`);for(const a of o)try{a.handler()}catch(c){this.log.error(`Error while processing offline message for topic ${a.topic}:`,c)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${o.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case Je.ALL:return[...this.queue];case Je.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(n=>n.receivedAt>=s);case Je.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(n=>n.receivedAt>=r);case Je.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(o=>o.receivedAt),n={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(n.afterRequest=this.queue.filter(o=>o.receivedAt>=e).length),s!==void 0&&(n.afterResponse=this.queue.filter(o=>o.receivedAt>=s).length),n}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class rg{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(F.GO_ONLINE,v.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(F.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}const Qc=()=>({isMock:!1,URL:exports.BASE_URL}),ng=m.createLogger({name:"kos-service-request"}),og="errUnknown";async function Vs(t,e,s,r,n){const o=r!=null&&r.path?Object.keys(r.path).reduce((h,f)=>String(h).replace(`{${f}}`,r==null?void 0:r.path[f]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${h}=${r.query[h]}`).join("&"):"",a=`${Qc().URL}${o}${i?`?${encodeURIComponent(i)}`:""}`;ng.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};n&&(c.body=JSON.stringify(n));const u=await exports.kosFetch(a,c);return u.status<200||u.status>=400?[`${u.statusText||og}`,null]:[null,(await u.json()).data]}function wo(){return{get:(t,e,s)=>Vs(t,"get",s,e),post:(t,e,s,r)=>Vs(t,"post",r,e,s),put:(t,e,s,r)=>Vs(t,"put",r,e,s),delete:(t,e,s,r)=>Vs(t,"delete",r,e,s)}}const De=wo(),Zc=Object.freeze(Object.defineProperty({__proto__:null,default:De},Symbol.toStringTag,{value:"Module"})),We=m.createLogger({name:"kos-service-request-manager",group:"Model"});function ig(t,e){return!t.condition||t.condition(e)}function ag(t,e){return Ee({value:t.path,modelId:e.id,modelData:e})}function cg(t,e){if(t.pathParams)return Ee({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function lg(t,e){if(t.queryParams)return Ee({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function ug(t,e){if(t.body)return Ee({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function dg(t){return(t||"get").toLowerCase()}function Ci(t,e){return`${e.toUpperCase()}:${t}`}function Xc(t){return t==null}function hg(t,e,s,r){r&&Xc(t)&&We.warn(`Required field '${e}' is missing in response for ${s}`)}function fg(t,e){return Xc(t)&&e!==void 0?e:t}class pg{constructor(e,s){l(this,"model");l(this,"responseStore");l(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[tt]||{};Object.values(s).forEach(r=>{const n=r.lifecycle;this.handlers.has(n)||this.handlers.set(n,[]),this.handlers.get(n).push(r)}),Object.keys(s).length>0&&We.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(We.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return ig(e,this.model)?!0:(We.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),[n,o]=await this.performRequest(s),i=this.captureResponseTiming();return{requestContext:s,error:n,response:o,requestedAt:r.requestedAt,receivedAt:i.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=ag(e,this.model),r=cg(e,this.model),n=lg(e,this.model),o=ug(e,this.model),i=dg(e.method);return{resolvedPath:s,method:i,pathParams:r,queryParams:n,body:o}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,n,o){const i=s.cache||{retention:ue.SINGLE},a=Ci(r,s.method||"get");this.responseStore.set(a,e,i,n,o),await s.originalHandler.call(this.model,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,n){const o=De;switch(s){case"get":return await o.get(e,r);case"post":return await o.post(e,r,n);case"put":return await o.put(e,r,n);case"delete":return await o.delete(e,r,n);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(n=>{const o=this.getNestedValue(e,n.from),i=n.transform?this.applyTransform(o,n.transform):o;hg(i,n.from,s.path,n.required||!1);const a=fg(i,n.default);r[n.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,n)=>r==null?void 0:r[n],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return We.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(n=>{const o=s.mappings&&s.mappings.length>0?this.applyMappings(n,s):n,i=s.idExtractor?s.idExtractor(o):o.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(o):a.instance(i).options(o).build()}):r.map(n=>s.mappings&&s.mappings.length>0?this.applyMappings(n,s):n):(We.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s){const r=s.errorHandler||{strategy:"throw"};switch(r.onError&&r.onError(e,this.model),r.strategy){case"throw":throw e;case"log":We.error(`Service request failed for ${s.path}:`,e.message);break;case"ignore":break;case"default":if(r.defaultValue!==void 0){const n=Ci(s.path,s.method||"get");this.responseStore.set(n,r.defaultValue,s.cache||{retention:ue.SINGLE})}break}}}class gg{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(e,r=>{if(!this.subscription.closed&&r!==void 0){const n=this.subscription.resolvers.shift();n?n(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function Di(t){return new gg(t)}const Jc=({path:t,requestId:e,method:s,destinationAddress:r})=>{let n=`${kr}:${s}
1
+ "use strict";var xh=Object.defineProperty;var Ah=(t,e,s)=>e in t?xh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var l=(t,e,s)=>(Ah(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("loglevel"),M=require("mobx"),b=require("robot3"),je=require("date-fns"),T=require("@emotion/react/jsx-runtime"),Gn=require("@emotion/styled"),fa=require("react-dom"),Qe=require("@emotion/react"),g=require("react"),Yn=require("mobx-react-lite"),Rh=require("@use-gesture/react"),Lr="method",pa="topic",kt="url",Rs="request-id",Fr="response-id",Wn="status",Ne="dst-addr",ga="src-addr",Oe="type",Qn="ordered",Zn="tracker",ma="Content-Type",ya="Cache-Control",ba="requestId",va=process.env.KOS_LOGIN_URL||"http://localhost",wa=process.env.KOS_APP_PORT||"8080",Ph=`${va}:${wa}`,ar="{MODEL_ID}";var Ps=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(Ps||{}),Ea=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(Ea||{});const Xn="/kos/model/ready/";D.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const z=globalThis.kos.subscriptions,kh=()=>Symbol("eventKey");function Jn(t){return z[t]&&Object.getOwnPropertySymbols(z[t]).length>0}function C(t,e){const s=kh();return z[t]||(D.debug(`Initializing subscription for ${t}`),z[t]={}),D.debug(`Subscribing to ${t} with id ${s.toString()}`),z[t][s]=e,{count:z[t]?Object.getOwnPropertySymbols(z[t]).length:0,unsubscribe:()=>(D.debug(`Unsubscribing from ${t} with id ${s.toString()}`),z[t]&&z[t][s]&&delete z[t][s],z[t]&&Object.getOwnPropertySymbols(z[t]).length===0&&delete z[t],{count:z[t]?Object.getOwnPropertySymbols(z[t]).length:0})}}function V(t,e,s={}){if(!z[t]||Object.getOwnPropertySymbols(z[t]).length===0)return D.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(z[t]).length;return Object.getOwnPropertySymbols(z[t]).forEach(n=>{if(s.sync){const o=s.sync;D.debug(`Performing sync publish for ${t} with sync id ${o}`),z[t][n]({body:e,headers:s}).then(i=>{D.debug(`Response recieved for ${o}, publishing back to source.`),V(o,i)})}else D.debug(`Performing async publish for ${t}`),z[t][n]({body:e,headers:s})}),{eventType:t,subscribers:r}}function Lh(){D.warn("Resetting event bus"),Object.keys(z).forEach(t=>delete z[t])}function Ma(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function eo(t,e){return new Promise((s,r)=>{let n=null;const o=Ma(t,i=>{n&&clearTimeout(n),s(i)});e&&(n=setTimeout(()=>{o(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const Fh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:Jn,once:Ma,publish:V,reset:Lh,subscribe:C,waitFor:eo},Symbol.toStringTag,{value:"Module"}));function Nr(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function Ur(t,e){return new Promise((s,r)=>{let n=null;const o=Nr(t,i=>{n&&clearTimeout(n),s(i)});e&&(n=setTimeout(()=>{o(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function Ta(t,e){const s=t.map(r=>Ur(r,e));return Promise.all(s)}function Sa(t,e){return new Promise((s,r)=>{const n=[];let o=null,i=!1;const a=()=>{n.forEach(c=>c()),o&&clearTimeout(o)};t.forEach(c=>{const u=Nr(c,d=>{i||(i=!0,a(),s({eventType:c,data:d}))});n.push(u)}),e&&(o=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function _a(t,e,s){return C(t,n=>{n&&e(n)&&s(n)}).unsubscribe}function Ia(t,e,s){return C(t,n=>{if(n){const o=e(n);s(o)}}).unsubscribe}function Oa(t,e,s){let r=null;const n=C(t,o=>{r&&clearTimeout(r),r=setTimeout(()=>{s(o)},e)});return()=>{r&&clearTimeout(r),n.unsubscribe()}}function $a(t,e,s){let r=0,n=null;const o=C(t,i=>{const a=Date.now(),c=a-r;c>=e?(r=a,s(i)):n||(n=setTimeout(()=>{r=Date.now(),s(i),n=null},e-c))});return()=>{n&&clearTimeout(n),o.unsubscribe()}}function Ca(t,e,s){let r=[],n=null;const o=()=>{r.length>0&&(s([...r]),r=[])},i=C(t,a=>{a&&(r.push(a),n||(n=setTimeout(()=>{o(),n=null},e)))});return()=>{n&&(clearTimeout(n),o()),i.unsubscribe()}}function to(t,e=1){const s=[];return C(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(n=>r(n)),C(t,r))}}function Da(t,e){const s=t.map(r=>C(r,n=>{n&&e(r,n)}));return()=>{s.forEach(r=>r.unsubscribe())}}function xa(t,e){let s=t;const r=[],n=new Set;return Object.values(e).forEach(o=>{Object.keys(o).forEach(i=>{n.add(i)})}),n.forEach(o=>{const{unsubscribe:i}=C(o,a=>{const c=e[s];c&&c[o]&&(s=c[o](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(o=>o())}}}function Aa(t,e,s,r){const n=Ur(e,r);return V(t,s),n}async function*Ra(t){const e=[],s=[],r=C(t,n=>{n&&(s.length>0?s.shift()(n):e.push(n))});try{for(;;)e.length>0?yield e.shift():yield await new Promise(n=>{s.push(n)})}finally{r.unsubscribe()}}const Nh={once:Nr,waitFor:Ur,waitForAll:Ta,race:Sa,filter:_a,map:Ia,debounce:Oa,throttle:$a,buffer:Ca,replay:to,merge:Da,stateMachine:xa,request:Aa,eventIterator:Ra},Uh=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:Nh,buffer:Ca,debounce:Oa,eventIterator:Ra,filter:_a,map:Ia,merge:Da,once:Nr,race:Sa,replay:to,request:Aa,stateMachine:xa,throttle:$a,waitFor:Ur,waitForAll:Ta},Symbol.toStringTag,{value:"Module"}));async function jr(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:n,timeout:o}=e,i=eo(t,o),a=await s(),c=r?r(a):a;return n&&n(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(c),100)})])}function Pa(t,e,s){const{getCurrentState:r,transformState:n}=s;let o=!1;const i=C(t,a=>{a&&(o=!0,e(a))});return Promise.resolve(r()).then(a=>{const c=n?n(a):a;o||e(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function ka(t,e){let s;const r=new Set,n=async()=>{try{typeof e=="string"?s=await(await fetch(e)).json():s=await e(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};C(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let o=!1;const i=()=>{o||(o=!0,n())};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 n(),s}}}async function so(t,e){if(typeof t=="string")return jr(t,e);const s=t,{getCurrentState:r,shouldUseFetchedState:n,timeout:o}=e,i=await r(),a=e.transformState?e.transformState(i):i;if(n&&n(a))return a;const c=s.map(d=>eo(d,o)),u=await Promise.all(c);return u[u.length-1]}function La(t,e,s){const{fetchMissedEvents:r,checkInterval:n=3e4,deduplicateById:o}=s,i=new Set,a=C(t,async u=>{if(u){if(o){const d=o(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await e(u)}}),c=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(o){const f=o(h);i.has(f)||(i.add(f),await e(h))}else await e(h)}catch(u){console.error("Failed to fetch missed events:",u)}},n);return()=>{a.unsubscribe(),clearInterval(c)}}function Fa(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:n,fetchInitialState:o,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await jr(e,{getCurrentState:o,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 o();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 C(e,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),C(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&C(r,()=>{a.state="error",u()}),n&&C(n,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const jh={waitForOrGetState:jr,subscribeWithInitialState:Pa,createStatefulEventStream:ka,waitForAllWithState:so,createResilientEventHandler:La,createConnectionStateManager:Fa},Bh=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:jh,createConnectionStateManager:Fa,createResilientEventHandler:La,createStatefulEventStream:ka,subscribeWithInitialState:Pa,waitForAllWithState:so,waitForOrGetState:jr},Symbol.toStringTag,{value:"Module"})),Hh=(t,e=0)=>{if(!+t)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=e<0?0:e,n=["bytes","KB","MB","GB","TB"],o=Math.floor(Math.log(t)/Math.log(s)),i=parseFloat((t/Math.pow(s,o)).toFixed(r)),a=n[o];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function ro(t){let e="pending",s;const r=t.then(o=>{e="success",s=o},o=>{e="error",s=o});return{read:()=>{switch(e){case"pending":throw r;case"error":throw s;default:return s}}}}function ot(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function Kh(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const n=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,n)})})}function qh(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((n,o)=>n===r[o])}const no=(t,e)=>{const s=t.map(o=>o.id);return e.map(o=>o.id).filter(o=>!s.includes(o))},Na=t=>t,Ua=t=>t,zh=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=Na,idMapper:n=Ua})=>o=>{const i=o.map(n),c=no(i,t.data).map(r).filter(Boolean);t.removeAll(c);const u=i.map(d=>{const h=t.getModel(d.id);return h&&s?s(d,h):e(d)}).filter(Boolean);t.addAll(u)},Vh=({container:t,onAddItem:e,onRemoveItem:s=Na,idMapper:r=Ua})=>n=>{const o=n.map(r);no(o,t.models).forEach(s),o.forEach(e)},Gh=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=n=>n})=>n=>{const o=n.map(r);no(o,t).forEach(s),o.forEach(e)},Yh=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},Mi=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Ti=[{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 ja(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=Ti.length;s++){const r=Ti[s];if(Math.abs(e)<r.amount)return Mi.format(Math.round(e),r.name);e/=r.amount}return Mi.format(Math.round(e),"years")}const oo=t=>t%4===0&&t%100!==0||t%400===0,io=(t,e)=>[31,oo(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Ba=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,io(s.getFullYear(),s.getMonth()))),s},Ha=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},Mt="en-US",Ka={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"}},qa={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"}},za=(t,{dateStyle:e="short",locales:s=Mt}={dateStyle:"short",locales:Mt})=>{const r=e==="short"?Ka.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},Va=(t,{locales:e=Mt,timeStyle:s="short"}={locales:Mt,timeStyle:"short"})=>{const r=qa[s];return new Intl.DateTimeFormat(e,r).format(t)},Ga=(t,{dateStyle:e="short",locales:s=Mt,timeStyle:r="short"}={dateStyle:"short",locales:Mt,timeStyle:"short"})=>{const n={...e&&Ka[e],...r&&qa[r]};return new Intl.DateTimeFormat(s,n).format(t)},Wh=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Ha,addMonthsToDate:Ba,formatDate:za,formatDateSince:ja,formatDateTime:Ga,formatTime:Va,getDaysInMonth:io,isLeapYear:oo},Symbol.toStringTag,{value:"Module"}));function Ya(t,e,s=300){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,n)},s)}}const te="canvas-renderer",cn=new Map,Si=new Map,ln=new Map,un=new Map,ks=(t,e)=>{Wa[t]=e},Wa={indexExtension:{registerIndexExtension:(t,e)=>{const s=un.get(t)||{};Object.assign(s,e),un.set(t,e)},loadIndexExtensions:t=>un.get(t)||{}},loader:{registerLoader:(t,e)=>{Si.set(t,e)},executeLoader:async(t,e)=>{const s=Si.get(t);if(s)return await s(e)}},propertyMapper:{registerPropertyMapper:(t,e)=>{ln.set(t,e)},hasMapper:t=>ln.has(t),executeMapper:(t,e,s)=>{const r=ln.get(t);return r?r(e,s):""}},dataMapper:{registerDataMapper:(t,e)=>{const s=cn.get(t)||[];s.push(e),cn.set(t,s)},executeMapper:async(t,e,s)=>{const r=cn.get(t);if(!r)return{};const n={};for(const o of r){const i=await o(e,s);Object.assign(n,i)}return n}},canvas:{registerRenderer:(t,e)=>{if(!$[te]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}$[te].register(t,e)}}},$=Wa,Qh=async({context:t,extension:e})=>{const s=await $.loader.executeLoader(e,{});return t==null||t.set(e,s),s},Zh=async({extension:t,contextData:e,data:s})=>await $.dataMapper.executeMapper(t,s,e),Xh=async({extension:t,contextData:e,data:s})=>await $.propertyMapper.executeMapper(t,s,e),Jh=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Zh,executeLoaderExtension:Qh,executePropertyMapperExtension:Xh},Symbol.toStringTag,{value:"Module"})),ef="Extensions";class tf{constructor(){l(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}const me=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),Qa="studio.tools.preview",sf="studio.relax.store.validation",Za="studio.log.debug",Xa="studio.log.info",rf={profiles:[Qa]};var ha;const nf=((ha=globalThis.getKosConfig)==null?void 0:ha.call(globalThis))||JSON.stringify(rf),Ja=JSON.parse(nf);globalThis.kosConfig=Ja;const ao=Ja,ec=()=>ao.profiles||[],In=t=>ec().includes(t),of=()=>ao.logging||!1,af=()=>{const t=In(Za),e=In(Xa);return t?"DEBUG":e?"INFO":void 0},tc=()=>{const t=me(),e=af(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},sc=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",rc=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",nc="ws-log",cf=D.methodFactory,oc=sc(),lf=rc();D.methodFactory=function(t,e,s){const r=cf(t,e,s);return function(...n){var c;const o=s?String(s):"",i=o?`[${String(o).substring(o.lastIndexOf(":")+1)}] | `:"[root] | ",a=n.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!==nc||oc&&lf)&&globalThis.kosLog(`UI: ${i}${a}`)}};let ic=tc();D.setLevel(ic);window.setKosLogLevel=t=>{ic=t,D.setLevel(t)};const cr=D.getLogger(nc);window.enableKosMessageLog=()=>{cr.setLevel(D.levels.INFO)};window.disableKosMessageLog=()=>{cr.setLevel(D.levels.ERROR)};oc?window.enableKosMessageLog():window.disableKosMessageLog();const uf=["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(";"),df=["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=t=>e=>{D.getLevel()<=t&&e()},m={...D,ifDebug:Ks(D.levels.DEBUG),ifInfo:Ks(D.levels.INFO),ifWarn:Ks(D.levels.WARN),ifError:Ks(D.levels.ERROR),getLogger:t=>D.getLogger(`kos::${t}`),getLoggers:()=>D.getLoggers(),createLogger:({name:t,group:e})=>{var o,i,a,c;const s=`${e?`${e}:`:"kos"}::${t}`,r=D.getLogger(s);let n=(i=(o=globalThis.kos.logOverrides)==null?void 0:o.find(u=>u.name===s))==null?void 0:i.level;return n?r.setLevel(n):(n=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:c.level,n&&r.setLevel(n)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");cr.info(`%c⬆ ${e}`,uf)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");cr.info(`%c⬇ ${e}`,df)}},ac="featureFlagResolver",qs=new Map;ks(ac,{register:(t,e)=>{var s;qs.has(t)||qs.set(t,[]),(s=qs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=qs.get(t);if(!s)return[];const r=s.map(a=>a(e)),o=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(o)).reduce((a,c)=>(a[c]=!0,a),{});return lc.updateFlags(i),Object.keys(i)}});const hf="kos.loader.featureFlag";class cc{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new cc;const lc=window.KosFeatureFlags,uc=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,n=o=>{const i=(o+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${n(0)}${n(8)}${n(4)}`},dc=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return uc(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},hc=(t,e)=>getComputedStyle(t).getPropertyValue(e),ff=(t,e)=>dc(hc(t,e)),pf=(t,e)=>{const s={...t};return s.id&&delete s.id,s},On=(t,e,s=pf)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})},ee=Symbol("SubscriptionHandlers"),N=Symbol("DependencyModels"),us=Symbol("FutureService"),Be=Symbol("ChildModels"),ds=Symbol("ParentModel"),hs=Symbol("LogConfig"),tr=Symbol("ReferenceConfig"),co=Symbol("KosModelSymbol"),et=Symbol("ModelEffects"),He=Symbol("CompanionParentModel"),lo=Symbol("FutureContainerSetup"),uo=Symbol("MultipleFutureContainerSetup"),fs=Symbol("FutureAliases"),ho=Symbol("TroubleAwareSetup"),fo=Symbol("LoggerSetup"),po=Symbol("ContainerAwareSetup"),Ls=Symbol("StateMachineSetup"),wt=Symbol("StateEntryHandlers"),ps=Symbol("StateExitHandlers"),gf=Symbol("StateActionHandlers"),mf=m.createLogger({group:"decorators",name:"fsm-injection"});function fc(t){const e=t[Ls];if(!e)return;const{config:s,options:r}=e;wf(t,s,r),Ef(t,r);const n=vf(t);yf(t,s,r,n),bf(t,s,r)}function yf(t,e,s,r){t.transition=Sf(t,e,s,r.entry,r.exit),t.canTransition=Af(t,e,s),t.isInState=Rf(t,s)}function bf(t,e,s){Mf(t),Tf(t,e,s)}function vf(t){const e=t.constructor.prototype[wt]||new Map,s=t.constructor.prototype[ps]||new Map;return{entry:e,exit:s}}function wf(t,e,s){t._fsmConfig=e,t._fsmOptions=s}function Ef(t,e){const{stateProperty:s,trackHistory:r}=e,n=t._fsmConfig;t[s]=n.initial,t._fsmInitialized=!0,t.isTransitioning=!1,r&&(t.stateHistory=[{state:n.initial,timestamp:new Date}])}function Mf(t){Object.defineProperty(t,"isFsmInitialized",{get(){return this._fsmInitialized},enumerable:!0,configurable:!0})}function Tf(t,e,s){const{stateProperty:r}=s;Object.defineProperty(t,"allowedTransitions",{get(){if(!this._fsmInitialized)return[];const n=this[r],o=this._fsmConfig.states[n];return o!=null&&o.on?Object.keys(o.on):[]},enumerable:!0,configurable:!0})}function Sf(t,e,s,r,n){const{stateProperty:o,throwOnInvalid:i}=s;return function(a){if(!this._fsmInitialized){_f(e.initializeAt,i);return}const c=this[o],u=If(c,a,this._fsmConfig,i);u&&$f(this,c,u,a,o,r,n,s)}}function _f(t,e){const s=`Cannot transition: FSM not initialized. Waiting for ${t} lifecycle phase.`;if(e)throw new Error(s);console.warn(s)}function If(t,e,s,r){var i;const n=s.states[t],o=(i=n==null?void 0:n.on)==null?void 0:i[e];if(!o){Of(t,e,r);return}return o}function Of(t,e,s){const r=`Invalid transition: Event "${e}" not allowed from state "${t}"`;if(s)throw new Error(r);console.warn(r)}function $f(t,e,s,r,n,o,i,a){t.isTransitioning=!0;try{Cf(t,e,i),t[n]=s,xf(t,s,r,a),Df(t,s,o)}finally{t.isTransitioning=!1}}function Cf(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function Df(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function xf(t,e,s,r){r.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date,event:s})}function Af(t,e,s){const{stateProperty:r}=s;return function(n){var a;if(!this._fsmInitialized)return!1;const o=this[r],i=this._fsmConfig.states[o];return((a=i==null?void 0:i.on)==null?void 0:a[n])!==void 0}}function Rf(t,e){const{stateProperty:s}=e;return function(r){return this._fsmInitialized?this[s]===r:!1}}function pc(t,e){const s=t[Ls];if(!s)return;const{config:r,options:n}=s,{stateProperty:o}=n;r.initializeAt===e&&(t._fsmInitialized||(Pf(t,o,r.initial),t._fsmInitialized=!0,kf(t,r.initial,n),Lf(t,r.initial),mf.debug(`FSM initialized for model ${t.id} at lifecycle ${e} with initial state "${r.initial}"`)))}function Pf(t,e,s){t[e]=s}function kf(t,e,s){s.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date})}function Lf(t,e){const r=(t.constructor.prototype[wt]||new Map).get(e);r&&typeof t[r]=="function"&&t[r]()}const $e=(t,e)=>{t[Be]=t[Be]||{},t[Be][e]=!0},it=t=>`{PROP_${String(t)}}`,Ff=t=>`{PROP_${String(t)}}`,Nf=it("kosParentId"),Br=t=>e=>{e[ds]=e[ds]||{};const s=(t==null?void 0:t.parentId)||Nf;e[ds]={parentId:s}};function Uf(t){return e=>{const s=(t==null?void 0:t.mode)||"decorator",r=(t==null?void 0:t.parentProperty)||"companionParent",n=(t==null?void 0:t.excludeProperties)||[],o=t==null?void 0:t.lifecycle;return Br()(e),e.prototype[He]={mode:s,parentProperty:r,excludeProperties:n,lifecycle:o},e}}function gc(t){return e=>{const s=t!=null&&t.legacy?"_models":(t==null?void 0:t.containerProperty)||"container",r=(t==null?void 0:t.includeMethods)!==!1,n=(t==null?void 0:t.includeGetters)!==!1,o=(t==null?void 0:t.modelsProperty)||"models",i=(t==null?void 0:t.containerOptions)||{};return e.prototype[po]={containerProperty:s,includeMethods:r,includeGetters:n,modelsProperty:o,containerOptions:i,legacy:(t==null?void 0:t.legacy)||!1},e}}function jf(t,e,s){const r=s.value;s.value=function(...n){const o=Y.getContext(this.id);return n.push(o),r.apply(this,n)}}const Hr=Symbol("KosExecutionContext");function go(t){return t&&typeof t=="object"&&Hr in t}function Bf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[lo]={mode:s,handlerProperty:r},e}}function Hf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[uo]={mode:s,handlerProperty:r},e}}var x=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(x||{});const Kf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:x},Symbol.toStringTag,{value:"Module"})),Re=Symbol("HttpRouteHandlers"),_i="__httpBrowserRouter";function Kr(t){return function(s){return function(r,n,o){r[Re]=r[Re]||[];const i={method:t,path:s,handler:n};return r[Re].push(i),r[N]=r[N]||{},r[N][_i]||(r[N][_i]={modelType:"browser-router-model",lifecycle:x.INIT}),o}}}const mc=Kr("GET"),Fs=Kr("POST"),qf=Kr("PUT"),yc=Kr("DELETE"),zf=yc;function lr(t){return!!(t!=null&&t[Re])&&t[Re].length>0}function bc(t){return(t==null?void 0:t[Re])||[]}const Vf=({group:t}={group:""})=>e=>{e[hs]=e[hs]||{},e[hs]={group:t}};class vc{static create({modelId:e,modelTypeName:s,component:r}){const n=[r??"kos",s,e].filter(Boolean).join(".");return m.createLogger({name:n})}}function wc(t){return e=>{const s=(t==null?void 0:t.loggerProperty)||"logger",r=t==null?void 0:t.loggerContext;e.prototype[fo]={loggerProperty:s,loggerContext:r};const n=()=>{var i;return(i=e.prototype[co])==null?void 0:i.type};let o;return Object.defineProperty(e.prototype,s,{get(){if(!o){const i=n();o=vc.create({modelTypeName:r||i,component:"kos-model"})}return o},enumerable:!1,configurable:!1}),e}}function Ec(t){return(e,s,r)=>{e[et]=e[et]||{},e[et][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Gf=t=>(e,s)=>{e[tr]=e[tr]||{},e[tr][s]=t},dn=m.createLogger({name:"resolve-parameters"}),Ee=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((n,o)=>(n[o]=Ee({value:r[o],modelId:e,modelData:s}),n),{});else if(typeof r=="string"){const n=new RegExp("{PROP_(.+?)}","g");let o=r!=null&&r.includes(ar)?r.replace(ar,e):r;if(s){let i=!1;const a=/^{PROP_.+?}$/.test(o);if(o=o.replace(n,(c,u)=>{if(Object.getOwnPropertyNames(s).includes(u)||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(u)){const h=s[u];return h?(dn.debug(`Resolved ${c} to ${h}`),h):(dn[a?"debug":"warn"](`Property ${u} is falsy${a?"":" in composite string"}, marking for undefined return`),i=!0,c)}return dn[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),c}),i)return}return o}else return r;return r},tt=Symbol("ServiceRequestHandlers"),Ii=new WeakMap;function Yf(t){return(e,s,r)=>{var a;e[tt]=e[tt]||{};const n=r.value,o={...t,handlerMethod:s,originalHandler:n},i=`${((a=t.method)==null?void 0:a.toUpperCase())||"GET"}:${String(t.path)}`;if(e[tt][i]=o,!t.lifecycle){const c=function(...u){const d=u[u.length-1],h=async f=>{const p=Ii.get(c);if(!p)throw new Error("Service request metadata not found for method");try{const{default:y}=await Promise.resolve().then(()=>Xc),w=Ee({value:p.path,modelId:this.id,modelData:this}),E={...typeof p.pathParams=="function"?p.pathParams(this):p.pathParams||{},...(f==null?void 0:f.pathParams)||{}},S={...typeof p.queryParams=="function"?p.queryParams(this):p.queryParams||{},...(f==null?void 0:f.queryParams)||{}},L=(f==null?void 0:f.body)||(typeof p.body=="function"?p.body(this):p.body),P={};Object.keys(E).length>0&&(P.path=E),Object.keys(S).length>0&&(P.query=S);const O=(p.method||"get").toLowerCase(),_=y,[K,q]=O==="get"?await _.get(w,P):O==="post"?await _.post(w,P,L):O==="put"?await _.put(w,P,L):O==="delete"?await _.delete(w,P,L):await _.get(w,P);if(K){if(p.errorHandler)switch(p.errorHandler.strategy){case"log":return console.error(`Service request error: ${K}`),p.errorHandler.onError&&p.errorHandler.onError(new Error(K),this),[null,p.errorHandler.defaultValue];case"ignore":return[null,p.errorHandler.defaultValue];case"default":return[null,p.errorHandler.defaultValue];case"throw":default:return[K,null]}return[K,null]}let J=q;return p.transform&&(J=p.transform(q)),[null,J]}catch(y){return[y.message||"Unknown error",null]}};if(go(d))return d.$request=h,n.apply(this,u);{const f={[Hr]:!0,$request:h};return n.apply(this,[...u,f])}};Ii.set(c,o),r.value=c}return r}}var Mc=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(Mc||{}),ue=(t=>(t.IMMEDIATE="immediate",t.SINGLE="single",t.TTL="ttl",t.PERMANENT="permanent",t.MANUAL="manual",t))(ue||{}),Je=(t=>(t.ALL="all",t.AFTER_REQUEST="after-request",t.AFTER_RESPONSE="after-response",t.NONE="none",t))(Je||{});const Wf=m.createLogger({name:"kos-state-machine"});function Qf(t,e){return s=>(s.prototype[Ls]={config:{...t,initializeAt:t.initializeAt||x.READY},options:{stateProperty:(e==null?void 0:e.stateProperty)||"currentState",trackHistory:(e==null?void 0:e.trackHistory)||!1,throwOnInvalid:(e==null?void 0:e.throwOnInvalid)!==!1}},s)}function Zf(t){return(e,s)=>{e[wt]||(e[wt]=new Map),e[wt].set(t,s)}}function Xf(t){return(e,s)=>{e[ps]||(e[ps]=new Map),e[ps].set(t,s)}}function Jf(t){return(e,s,r)=>{const n=r.value;return r.value=function(...o){var u,d;if(!this.isFsmInitialized)return n.apply(this,o);const a=this.currentState;if(!t.allowedStates.includes(a)){const h=`Method ${String(s)} cannot be called from state "${a}". Allowed states: ${t.allowedStates.join(", ")}`;if(t.throwOnInvalid!==void 0?t.throwOnInvalid:((d=(u=this[Ls])==null?void 0:u.options)==null?void 0:d.throwOnInvalid)!==!1)throw new Error(h);Wf.warn(h);return}return n.apply(this,o)},r}}function ep(t){return e=>{const s=(t==null?void 0:t.pathProperty)||"path";return e.prototype[ho]={pathProperty:s},e.prototype[N]=e.prototype[N]||{},e.prototype[N].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},e}}const Lt=({modelType:t,id:e,options:s,lifecycle:r})=>(n,o)=>{n[N]=n[N]||{},n[N][o]={modelType:t,id:e,options:s,lifecycle:r||x.INIT}};class Tc{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=Io.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=W(()=>{var n,o;(e.endState||e.progress)&&((o=(n=this.container)==null?void 0:n.onFutureUpdate)==null||o.call(n,e))});this.disposers.set(s||e.id,r)}removeFuture(e){var s;this.futures.delete(e||this.context),(s=this.disposers.get(e||this.context))==null||s(),this.disposers.delete(e||this.context)}getFuture(e){return this.futures.get(e||this.context)}get futureMap(){return this.futures}}class qr{constructor(e){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=W(()=>{var r,n;(e.endState||e.progress)&&((n=(r=this.container)==null?void 0:r.onFutureUpdate)==null||n.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw m.error(e),e}}}const Sc=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},_c=Symbol("KosObservableData"),Gt=Symbol("revision");var hT;class Ic{constructor(){l(this,"map");l(this,hT,1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return s===Gt||e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var n;return this.map.has(s),this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(n=this.atomMap.get(s))==null||n.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=M.observable.map(new Map),M.makeObservable(this,{[Gt]:M.observable})}setValue(e,s){const r=this.map.has(e);this.map.set(e,s),r||M.action(()=>{this[Gt]++})()}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return this[Gt],Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}hT=Gt;Ic.prototype[_c]=!0;function tp(t,e){return new Proxy(t,{construct:(s,r)=>{const n=new t(...r);return n.setValues(e),n.proxy}})}const _e=t=>{const e=tp(Ic,t);return new e(t)};function sp(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class mo{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=_e(),this.generateIndex(),M.autorun(()=>{this._container.revision&&this.generateIndex()}),M.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(e,s,r=this._map,n=this.data){const o=r.get(e)||new Set;o.add(s),r.set(e,o),n[e]=Array.from(o)}resolveIndex(e,s){this.data.keys.filter(n=>!Object.keys(s).includes(n)).forEach(n=>{delete this.data[n],this._map.delete(n)}),Object.keys(s).forEach(n=>{const o=s[n],i=this.data[n]||[];if(sp(o,i))m.debug(`KosContainerIndex - Index ${n} is the same`);else{this.data[n]=o;const a=e.get(n)||new Set;this._map.set(n,a)}})}generateIndex(){M.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const n=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(n)?n.forEach(o=>{this.addItemToIndex(o,r,e,s)}):typeof n=="string"||typeof n=="number"?this.addItemToIndex(String(n),r,e,s):typeof n=="boolean"&&this.addItemToIndex(String(n),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function rp(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>M.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const Yt=m.createLogger({name:"kos-container-model"});class Ce{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?$.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const n=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((o,i)=>(o[i]=void 0,o),{}):{};this._index=M.observable.map(n),this.idx=_e(),this._parentId=e==null?void 0:e.parentId,M.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new mo({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(e,s){this._data.set(e.id||"",e),e.id&&this._parentId&&Y.setParentContext(e.id,this._parentId),s||this.increment();const r=this._disposerMap.get(e.id);r&&(r(),this._disposerMap.delete(e.id));const n=Object.entries(this._optionsMap||{}),o=Object.values(this._optionsMap||{}),i=new Map(n.map(([d,h])=>[h,d])),a=d=>{var f,p;o.includes(d.name)&&((f=this.index.get(i.get(d.name)))==null||f.refresh());const h=n.filter(([,y])=>typeof y=="function");for(const[y]of h)(p=this.index.get(y))==null||p.refresh()},c=rp(e,a,o.filter(d=>typeof d=="string")),u=M.observe(e,a);this._disposerMap.set(e.id||"",()=>[u,...c].forEach(d=>d()))}removeModel(e,s){this._data.delete(e),s||this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Yt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(Yt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Yt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(e=>{const s=e.id;st(e).then(()=>{Yt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Yt.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}var v=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(v||{}),F=(t=>(t.CREATE="create",t.INITIALIZE="init",t.LOAD="load",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.RESET="go_offline",t.UNLOAD="unload",t.FAILED="failed",t.GO_ACTIVE="go_active",t.GO_INACTIVE="go_inactive",t.TIMEOUT="timeout",t))(F||{});const de=async t=>{if(t.id){const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},st=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(t)},np=async t=>{if(await I.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(F.UNLOAD,v.UNLOADED)},op=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(t),m.debug(`reload model initiated for model ${t.id}, model ready: ${ur(t)} - ${Date.now()} `),await de(t),m.debug(`reload model complete for model ${t.id}, model ready: ${ur(t)} - ${Date.now()} `)},ip=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},Oc=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Ie=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},$c=(t,e)=>{if(!t)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(t).filter(n=>Object.keys(e).every(o=>n[o]===e[o]))},ap=(t,e)=>$c(t,e)[0],cp=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},Cc=t=>{if(!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},lp=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},$n=(t,e)=>{const s=I.getInstance().modelManager.getModelById(t);if(!s){m.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(n=>e(n.modelData))},Te=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,ur=t=>{const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},up=m.createLogger({name:"kos-model-factory"}),gs={byModelType:t=>I.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=gs.byModelType(e);if(!r)throw up.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},ie={Factory:{create:t=>e=>(s,r)=>(r&&Y.setParentContext(e,r),gs.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&Y.setParentContext(t,s),gs.getModelInstance(t,t,e))},Model:{instance:t=>e=>gs.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Oi=window.KosRegistry.coreModels,hn=window.KosRegistry.preloadModels,fn=window.KosRegistry.companionModels,zs=window.KosRegistry.models,A={model:{registerLegacyModel:t=>(e,s)=>(Oi.set(e,s),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(hn.includes(e)||hn.push(e),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=pn(e)?e.registration():e;return zs.set(r.type,r),pn(e)&&e.relatedModels.forEach(n=>zs.set(n.type,n.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],pn(e)&&e.relatedModels.forEach(n=>I.getInstance().modelManager.registry.models[n.type]=n.registration().registration))),s&&A.model.preloadModel(t)(r.type),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},get:t=>zs.get(t),getAll:()=>Array.from(zs.entries()),getPreloadModels:()=>hn,getLegacyModels:()=>Array.from(Oi.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=fn.get(e)||[];return r.push(s),fn.set(e,r),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(fn.entries())}},Dc=A.model.registerLegacyModel,xc=A.model.register,dp=A.companion.register,hp=A.model.preloadModel,yo=t=>typeof t.updateModel=="function",pn=t=>t.registration!==void 0&&typeof t.registration=="function";class Ac{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=Te(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){A.model.register({})(this.registration()),this.registerRelatedModels()}}class ye extends Ac{constructor(e){super({...e,singleton:!1,factory:ie.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=Ie(e);if(!r)throw new Error("Model not found with id "+e);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const n=s(r);if(this.guard(n)){if(yo(n))n.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return n}else throw new Error("Model is not of type "+this.type)}})},options:r=>({build:()=>{const n=s(r);if(this.guard(n))return n;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 Se extends Ac{constructor(e){super({...e,singleton:!0,factory:ie.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=Ie(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 n=e(r);if(this.guard(n)){if(yo(n))n.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return n}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(n).modelTypeId}`)}})},options:r=>({build:()=>{const n=e(r);if(this.guard(n))return n;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(n).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const Cn=m.createLogger({group:"decorators",name:"kos-model"});function fp(t,e,s){var o;const r=(o=t[ds])==null?void 0:o.parentId;if(!r)return;const n=Ee({value:r,modelData:s,modelId:e});n&&typeof n=="string"&&Y.setParentContext(e,n)}function pp(t){const e=t[us];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function gp(t,e){const s=t[N]||{};Object.entries(s).forEach(([r,n])=>{const o=Ee({value:n.id||n.modelType,modelData:t,modelId:e}),i=Object.entries((n==null?void 0:n.options)||{}).reduce((a,[c,u])=>(a[c]=Ee({value:u,modelData:t,modelId:e}),a),{});if(typeof o=="string"){if(!n.lazy){const a=I.getInstance().modelManager.createModelInstance(n.modelType,o,i);t[r]=a.data}I.getInstance().modelManager.addDependency(e,o)}})}function mp(t){const e=t[lo];if(!e)return;const{mode:s,handlerProperty:r}=e,n=new qr(t);t[r]=n,s==="full"&&(Object.defineProperty(t,"future",{get(){return n.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){var o;return((o=n.future)==null?void 0:o.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var o;return((o=n.future)==null?void 0:o.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return n.future?!n.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var o;return((o=n.future)==null?void 0:o.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{n.future&&await n.future.cancelFuture()})}function yp(t){const e=t[uo];if(!e)return;const{mode:s,handlerProperty:r}=e,n=new Tc(t);t[r]=n,Object.defineProperty(t,"future",{get(){return n.future},enumerable:!0,configurable:!0});const o=t[fs];o instanceof Map&&o.forEach(i=>{const a=`${i}Future`;Object.defineProperty(t,a,{get(){return n.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(t,`${i}Progress`,{get(){const c=n.futureMap.get(i);return(c==null?void 0:c.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}Status`,{get(){const c=n.futureMap.get(i);return(c==null?void 0:c.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsRunning`,{get(){const c=n.futureMap.get(i);return c?!c.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsCancelled`,{get(){const c=n.futureMap.get(i);return(c==null?void 0:c.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const c=n.futureMap.get(i);c&&await c.cancelFuture()})}),s==="full"&&(Object.defineProperty(t,"progress",{get(){var i;return((i=n.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var i;return((i=n.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return n.future?!n.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var i;return((i=n.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{n.future&&await n.future.cancelFuture()})}function bp(t){const e=t[ho];if(!e)return;const{pathProperty:s}=e;Object.defineProperty(t,"troubles",{get(){const r=this[s];if(r==null){const n=`@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(n):console.warn(n),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((n,o)=>o.rank-n.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troublesByType",{get(){return this.troubles.reduce(Sc,{})},enumerable:!0,configurable:!0})}function vp(t,e){const s=t[po];if(!s)return;const{containerProperty:r,includeMethods:n,includeGetters:o,modelsProperty:i,containerOptions:a,legacy:c}=s,u={...a,parentId:a.parentId||e},d=new Ce(u);t[r]=d,t[Be]||(t[Be]={}),t[Be][r]=d,n&&(t.getModel=h=>d.getModel(h),t.addModel=h=>{d.addModel(h)},t.removeModel=h=>{d.removeModel(h)}),o&&(Object.defineProperty(t,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(t,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function wp(t,e){const s=t.constructor.prototype[He];if(!s)return;const{mode:r,parentProperty:n,excludeProperties:o}=s,i=e[n];if(!i){Cn.warn(`Companion decorator configured but no parent model found at '${n}'`);return}if(t.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 y=i.constructor.prototype[ee]||{};return Object.values(y).some(w=>{const E=w==null?void 0:w.handler;return E===i[p]||E===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||c.includes(p)||o.includes(p)||u(p)||p in t,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 y=i[p];typeof y=="function"?t[p]=(...w)=>y.apply(i,w):Object.defineProperty(t,p,{get:()=>i[p],set:w=>{i[p]=w},enumerable:!0,configurable:!0})}catch(y){Cn.debug(`Skipping companion proxy for property ${p}:`,y)}}function Ep(t){try{return M.makeAutoObservable(t)}catch(e){return Cn.error("Failed to make observable:",e),t}}const Mp={construct(t,e){var c;const[s,r={}]=e,n=Y.createContext(s);fp(t,s,r);const i=!!t.prototype[fo]?null:m.createLogger({name:t.prototype.modelTypeId,group:((c=t[hs])==null?void 0:c.group)??"kos-model"}),a=new t(s,r,{logger:i,kosContext:n});return pp(a),mp(a),yp(a),bp(a),vp(a,s),wp(a,r),fc(a),gp(a,s),Ep(a)}};function R(t){return e=>{var o,i;const s=e,r=typeof t=="string"?{modelTypeId:t,autoRegister:!1}:{autoRegister:!1,...t};s.prototype.modelTypeId=r.modelTypeId,s.prototype[co]=!0,(o=s.prototype)[ee]??(o[ee]={}),(i=s.prototype)[N]??(i[N]={}),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const n=new Proxy(s,Mp);if(r.singleton!==void 0){let a;r.singleton?a=new Se({class:n,type:r.modelTypeId}):a=new ye({class:n,type:r.modelTypeId}),Object.defineProperty(n,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return n}}const Tp=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>n=>{n[ee]=n[ee]||{},Array.isArray(t)?t.forEach(o=>{n[ee][o]={websocket:s,handler:e,condition:r}}):n[ee][t]={websocket:s,handler:Ya(n,M.action(e),200),condition:r}};function Rc(t,e,s){const r={};if(!t.endsWith("/*"))return r;const n=t.slice(0,-2);if(e.startsWith(n)){const o=e.slice(n.length+1),i=s||"path";r[i]=o}return r}function Pc(t){return t.endsWith("/*")}function B(t){return(e,s,r)=>{const n=Sp(t,r);Op(e,t.topic,n),t.replay&&$p(t.topic,t.replay.bufferSize)}}function Sp(t,e){const{condition:s=(_,K)=>!0,transform:r=_=>_,websocket:n=!1,fos:o=!1,bridge:i=!1,skipParse:a=!1,lifecycle:c,destinationAddress:u,debounce:d,throttle:h,buffer:f,filter:p,once:y,wildcardName:w,flow:E,requiresBaseline:S}=t,L=e.value,P=_p(L,{debounce:d,throttle:h,buffer:f,once:y}),O=Ip(p,s);return{websocket:n,fos:o,bridge:i,handler:P,condition:O,transform:r,lifecycle:c,skipParse:a,destinationAddress:u,wildcardName:w,flow:E,requiresBaseline:S}}function _p(t,e){var o,i;let s=t;const r=typeof e.debounce=="number"?e.debounce:(o=e.debounce)==null?void 0:o.delay,n=typeof e.throttle=="number"?e.throttle:(i=e.throttle)==null?void 0:i.interval;return r&&r>0?s=Cp(s,e.debounce):n&&n>0?s=Rp(s,e.throttle):e.buffer?s=Pp(async function(c){for(const u of c)await s.call(this,u)},e.buffer):e.once&&(s=kp(s)),s}function Ip(t,e){return t?(s,r,n)=>t(n)?e(s,r,n):!1:e}function Op(t,e,s){t[ee]=t[ee]||{},Array.isArray(e)?e.forEach(r=>{t[ee][r]=s}):t[ee][e]=s}function $p(t,e){Lp(t,e)}function Cp(t,e){const s=typeof e=="number"?e:e.delay;return Dp(e)==="discard"?xp(t,s):Ap(t,s)}function Dp(t){return(typeof t=="object"?t.discardIntermediate:!1)?"discard":"accumulate"}function xp(t,e){let s=null;return function(r){s&&clearTimeout(s),s=setTimeout(()=>{t.call(this,r),s=null},e)}}function Ap(t,e){let s=null,r=[];return function(n){r.push(n),s&&clearTimeout(s),s=setTimeout(()=>{const o=[...r];r=[],t.call(this,o),s=null},e)}}function Rp(t,e){const s=typeof e=="number"?e:e.interval,r=typeof e=="object"?e.discardIntermediate:!1;let n=0,o=null,i=[],a=!1;const c=function(){if(i.length>0){const u=[...i];i=[],t.call(this,u)}};return function(u){const d=Date.now(),h=d-n;r?h>=s?(n=d,t.call(this,u)):o||(o=setTimeout(()=>{n=Date.now(),t.call(this,u),o=null},s-h)):(i.push(u),h>=s?(n=d,c.call(this)):a||(a=!0,o=setTimeout(()=>{n=Date.now(),c.call(this),o=null,a=!1},s-h)))}}function Pp(t,e){const s=[];let r=null;const n=e.maxSize||1e3,o=i=>{s.length>0&&(t.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=n){r&&(clearTimeout(r),r=null),o(this);return}r||(r=setTimeout(()=>{o(this),r=null},e.time))}}function kp(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function Lp(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{to(r,e)})}const gn=new Map,kc={addToDeletionQueue:(t,e)=>{const s=gn.get(t)||[];s.push(e),gn.set(t,s)},cancelDeletion:t=>{const e=gn.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},Fp=m.createLogger({name:"kos-dependency-manager"});class Np{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(e,s){kc.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(e)||r.push(e),this._usedByCache.set(s,r);const n=this._usesCache.get(e)||[];n.includes(s)||n.push(s),this._usesCache.set(e,n)}remove(e,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(o=>o!==e));const n=this._usesCache.get(e)||[];this._usesCache.set(e,n.filter(o=>o!==s))}canDestroy(e){const s=this._usedByCache.get(e);return s!=null&&s.length?(Fp.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}const $i=m.createLogger({name:"kos-model-cache"});class Up{constructor(e=[]){l(this,"_modelsById",M.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).map(e=>e).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?($i.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>($i.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const Lc=t=>typeof t=="function",Vs=m.createLogger({name:"kos-companion-instantiator"});class jp{constructor(e,s,r){this.registry=e,this.cache=s,this.createModel=r}createCompanionModels(e,s,r){const n=this.getCompanionDefinitions(e.modelTypeName);r!==void 0&&Vs.debug(`Creating ${r} lifecycle companions for ${e.modelTypeName} [${e.modelId}]`);for(const o of n){const i=this.resolveCompanionType(o,e,s,r);i&&this.shouldCreateCompanion(i.lifecycle,r)&&this.instantiateCompanion(i.type,e,s,r)}}getCompanionDefinitions(e){var s;return((s=this.registry.companionModels)==null?void 0:s[e])||[]}resolveCompanionType(e,s,r,n){return Lc(e.type)?this.resolveFactoryCompanion(e,s,r,n):this.resolveStringCompanion(e)}resolveFactoryCompanion(e,s,r,n){const o=e.type(s.modelData,r);if(!o)return Vs.debug(`Companion factory returned undefined for ${s.modelTypeName} at ${n||"INIT"} phase`),null;const i=this.extractLifecycleFromType(o);return{type:o,lifecycle:i}}resolveStringCompanion(e){return{type:e.type,lifecycle:e.lifecycle}}extractLifecycleFromType(e){const s=this.registry.models[e];if(!(s!=null&&s.class))return;const r=s.class.prototype[He];return r==null?void 0:r.lifecycle}shouldCreateCompanion(e,s){return s!==void 0?e===s:e===void 0}instantiateCompanion(e,s,r,n){const o=this.generateCompanionId(e,s.modelId);if(this.companionAlreadyExists(o,e,s.modelTypeName))return;const i=this.createCompanionInstance(e,o,s,r);i&&(this.attachCompanionToParent(i,s),Vs.debug(`Created ${n||"INIT"} companion ${e} for ${s.modelTypeName} [${s.modelId}]`))}generateCompanionId(e,s){return`${e}-${s}`}companionAlreadyExists(e,s,r){return this.cache.hasModel(e)?(Vs.debug(`Companion ${s} already exists for ${r}`),!0):!1}createCompanionInstance(e,s,r,n){const o=this.createModel(e,s,{data:n,companionParent:r.modelData,kosParentId:r.modelId});return(o==null?void 0:o.model)||null}attachCompanionToParent(e,s){e[He]=s,s.addCompanionModel(e)}}function Fc(t,e){return`${Xn}${t}${e?`/${e}`:`/${t}`}`}function Nc(t){return`${Xn}${t}`}function mn(t){const e=[];return new Promise((s,r)=>{for(const{condition:n,onMatch:o}of t){const i=M.when(n,()=>{e.forEach(a=>a());try{o==null||o(),s()}catch(a){r(a)}});e.push(i)}})}const Uc=5e3;class Bp extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const jc=(t,e,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{m.error(`Model ${e.modelId} - ${e.modelTypeName} - ${s} timed out after ${t}ms`),a(new Bp(`${e.modelId} - ${e.modelTypeName} - ${s}`,e))},t)}),cancel:()=>{r&&clearTimeout(r)}}},Bc=t=>t.fsm.transitionTo(F.GO_ACTIVE,v.ACTIVE),Hc=t=>t.whenReady(),Kc=t=>t.fsm.transitionTo(F.LOAD,v.LOADED),Hp=t=>t.fsm.transitionTo(F.UNLOAD,v.UNLOADED),qc=t=>t.fsm.transitionTo(F.INITIALIZE,v.INITIALIZED);var bo=(t=>(t.ACTIVE="active",t.READY="ready",t.LOAD="load",t.UNLOAD="unload",t.INIT="init",t))(bo||{});const sr={active:Bc,ready:Hc,load:Kc,init:qc},zc=(t,e)=>{const s=e.id||e.modelType,r=Ee({value:s,modelData:t.modelData,modelId:t.modelId});m.debug(`activating dependent model ${e.modelType} with id ${r}`);const n=Object.keys((e==null?void 0:e.options)||{}).reduce((i,a)=>{const c=e.options[a];return i[a]=Ee({value:c,modelData:t.modelData,modelId:t.modelId}),i},{});return{dependentModel:I.getInstance().modelManager.createModelInstance(e.modelType,r,n),dataModelId:r}},Vc=(t,e=x.READY)=>{var n;const s=((n=t.modelData)==null?void 0:n[N])||{};return Object.keys(s).length===0?(m.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(o=>s[o].lifecycle===e).map(o=>{const i=s[o],{dependentModel:a,dataModelId:c}=zc(t,i);t.modelData[o]=a.data,m.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const u=async(f,p,y)=>{var w;await((w=f.whenReady)==null?void 0:w.call(f)),m.debug(`dependent model ${p} with id ${y} - READY`)},{promise:d,cancel:h}=jc(Uc,t,t.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(o=>!!o)},Gc=async(t,e,s,r)=>{if(m.debug(`Execute lifecycle with ${e.length} models`),e.length===0){m.debug(`${t.modelId} has no children. Returning`);return}if(!s){m.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const n=e.map(a=>{let c;return sr[s]&&a?c=sr[s](a):(a||m.error("model is undefined. This shouldn't happen"),sr[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(n.map(a=>{var d;const{promise:c,cancel:u}=jc(Uc,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 ${t.modelId} had ${i.length} failed child models on ${r}`)},Yc=async(t,e,s)=>{await Gc(t,t.getChildren().filter(r=>!!r),e,s)},Qt=async(t,e)=>{const r=(await Promise.allSettled(Vc(t,e))).filter(n=>n.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))},Kp=t=>typeof t.toJSON=="function",ms=t=>t[N]!==void 0,vo=t=>t.revision!==void 0&&t.index!==void 0,Wc=t=>{if(t){if(ms(t))return t;if(vo(t))return t.data;if(t instanceof Map||t instanceof M.ObservableMap||t instanceof Set)return Array.from(t.values()).filter(ms);if(Array.isArray(t))return t.filter(ms)}};function qp(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,n,o;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(n=(r=t.companionManager)==null?void 0:r.all())==null?void 0:n.map(i=>i.modelTypeName),children:(o=t.getChildren)==null?void 0:o.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),zp(t.modelData,t.modelTypeName,t.modelId,t)}function zp(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const n=((a=r.getChildren)==null?void 0:a.call(r))||[],o=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[N]||{};return{id:s,type:e,companions:{count:o.length,data:o.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:n.length,data:n.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const n={};for(const o of Object.keys(t))if(!(o.startsWith("_")||typeof t[o]=="function"))try{const i=t[o];ms(i)?n[`[KOS Model] ${o}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:vo(i)?n[`[KOS Container] ${o}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?n[o]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?n[o]=JSON.parse(JSON.stringify(i)):n[o]=i}catch{n[o]="[unreadable]"}return n}})}class Vp{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{Y.setParentContext(r.modelId,this.model.modelId)}catch(n){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,n)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[Be])||{};return Object.keys(e).map(r=>Wc(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class Gp{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Yp{constructor(e,s,r,n){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=n}setup(){var s;const e=((s=this.modelData)==null?void 0:s[et])||{};for(const r of Object.keys(e)){const{value:n,dependencies:o,options:i}=e[r],a=n.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},u=o?M.reaction(()=>o(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Wp=m.createLogger({name:"model-active-machine"}),Qp=t=>{const e=b.createMachine(v.INACTIVE,{[v.FAILED]:b.state(b.transition(F.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:b.state(b.transition(F.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:b.invoke(()=>(t.activeStatus=v.ACTIVATING,t.activate()),b.transition("done",v.ACTIVE,b.action(()=>{t.activeStatus=v.ACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED}))),[v.ACTIVE]:b.state(b.transition(F.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:b.invoke(()=>(t.activeStatus=v.DEACTIVATING,t.deactivate()),b.transition("done",v.INACTIVE,b.action(()=>{t.activeStatus=v.INACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED})))});return{service:b.interpret(e,r=>Wp.debug(r.machine.current)),machine:e}},Ci=m.createLogger({name:"model-online-machine"}),Zp=t=>{const e=b.createMachine(v.OFFLINE,{[v.ONLINE]:b.state(b.transition(F.GO_OFFLINE,v.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:b.state(b.transition(F.GO_ONLINE,v.ONLINE,b.action(async()=>{Ci.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=v.ONLINE,await t.fsm.transitionTo(F.INITIALIZE,v.INITIALIZED)})))}),s=b.interpret(e,r=>Ci.debug(r.machine.current));return{machine:e,service:s}},Xp=t=>{var r;const e=Qp(t).service,s=Zp(t).service;return b.createMachine(v.CREATING,{[v.CREATING]:b.state(b.transition(F.CREATE,v.CREATED)),[v.CREATED]:b.state(b.immediate(v.INITIALIZING)),[v.INITIALIZING]:b.invoke(()=>(X(()=>{t.status=v.INITIALIZING}),t.init()),b.transition("done",v.INITIALIZED,b.action(()=>{t.status=v.INITIALIZED})),b.transition("error",v.FAILED,b.action(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=v.FAILED}))),[v.INITIALIZED]:b.state(b.immediate(v.LOADING)),[v.LOADING]:b.invoke(()=>(X(()=>{t.status=v.LOADING}),t.load()),b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.LOADED]:b.state(b.immediate(v.READYING),b.transition(F.UNLOAD,v.UNLOADING)),[v.RESETTING]:b.invoke(()=>{var n;return X(()=>{t.status=v.RESETTING}),(n=t.unload)==null||n.call(t),t.load()},b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED}))),[v.READYING]:b.invoke(()=>(X(()=>{t.status=v.READYING}),t.ready()),b.transition("done",v.READY,b.action(()=>{X(()=>{t.status=v.READY}),s.send(F.GO_ONLINE)})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.READY]:b.state(b.transition(F.UNLOAD,v.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(F.RESET,v.RESETTING),b.transition(F.GO_ONLINE,v.READY,b.action(()=>{s.send(F.GO_ONLINE)})),b.transition(F.GO_OFFLINE,v.READY,b.action(()=>{s.send(F.GO_OFFLINE)})),b.transition(F.GO_ACTIVE,v.READY,b.action(()=>{e.send(F.GO_ACTIVE)})),b.transition(F.GO_INACTIVE,v.READY,b.action(()=>{e.send(F.GO_INACTIVE)}))),[v.UNLOADED]:b.state(),[v.FAILED]:b.state()})},Jp=m.createLogger({name:"kos-model-lifecycle"}),eg=t=>({service:b.interpret(Xp(t),s=>Jp.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class tg{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=eg(e);this.service=r.service,this.service.send(F.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,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 ${e} toward target ${s}`),new Promise((o,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),o())}),this.service.send(e)}).finally(()=>{var o;(o=this.disposer)==null||o.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[v.ACTIVE,v.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const Qc="browser-router-model";class wo{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!lr(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const n=this.model[r];if(n&&typeof n=="object"&&"use"in n&&typeof n.use=="function"){e=n;break}}if(e||(e=(s=Ie(Qc))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return lr(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=bc(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const o=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,o)}let n;for(;(n=s.exec(e))!==null;){const o=n[1];if(o in this.model){const i=this.model[o];r=r.replace(n[0],String(i))}else this.logger.warn(`Property '${o}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const n=async(o,i)=>{var a;try{await s.call(this.model,o,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,n),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(o=>o.method===e&&o.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function sg(t,e){if(!lr(t))return;const s=Ie(Qc);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new wo(t,e).setRouter(s.model)}class rg{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const n=this.queue.length,o=this.filterEventsByStrategy(e,s,r),i=n-o.length;this.log.warn(`Processing ${o.length}/${n} offline message(s) with strategy: ${e}`);for(const a of o)try{a.handler()}catch(c){this.log.error(`Error while processing offline message for topic ${a.topic}:`,c)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${o.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case Je.ALL:return[...this.queue];case Je.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(n=>n.receivedAt>=s);case Je.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(n=>n.receivedAt>=r);case Je.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(o=>o.receivedAt),n={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(n.afterRequest=this.queue.filter(o=>o.receivedAt>=e).length),s!==void 0&&(n.afterResponse=this.queue.filter(o=>o.receivedAt>=s).length),n}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class ng{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(F.GO_ONLINE,v.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(F.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}const Zc=()=>({isMock:!1,URL:exports.BASE_URL}),og=m.createLogger({name:"kos-service-request"}),ig="errUnknown";async function Gs(t,e,s,r,n){const o=r!=null&&r.path?Object.keys(r.path).reduce((h,f)=>String(h).replace(`{${f}}`,r==null?void 0:r.path[f]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${h}=${r.query[h]}`).join("&"):"",a=`${Zc().URL}${o}${i?`?${encodeURIComponent(i)}`:""}`;og.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};n&&(c.body=JSON.stringify(n));const u=await exports.kosFetch(a,c);return u.status<200||u.status>=400?[`${u.statusText||ig}`,null]:[null,(await u.json()).data]}function Eo(){return{get:(t,e,s)=>Gs(t,"get",s,e),post:(t,e,s,r)=>Gs(t,"post",r,e,s),put:(t,e,s,r)=>Gs(t,"put",r,e,s),delete:(t,e,s,r)=>Gs(t,"delete",r,e,s)}}const De=Eo(),Xc=Object.freeze(Object.defineProperty({__proto__:null,default:De},Symbol.toStringTag,{value:"Module"})),We=m.createLogger({name:"kos-service-request-manager",group:"Model"});function ag(t,e){return!t.condition||t.condition(e)}function cg(t,e){return Ee({value:t.path,modelId:e.id,modelData:e})}function lg(t,e){if(t.pathParams)return Ee({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function ug(t,e){if(t.queryParams)return Ee({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function dg(t,e){if(t.body)return Ee({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function hg(t){return(t||"get").toLowerCase()}function Di(t,e){return`${e.toUpperCase()}:${t}`}function Jc(t){return t==null}function fg(t,e,s,r){r&&Jc(t)&&We.warn(`Required field '${e}' is missing in response for ${s}`)}function pg(t,e){return Jc(t)&&e!==void 0?e:t}class gg{constructor(e,s){l(this,"model");l(this,"responseStore");l(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[tt]||{};Object.values(s).forEach(r=>{const n=r.lifecycle;this.handlers.has(n)||this.handlers.set(n,[]),this.handlers.get(n).push(r)}),Object.keys(s).length>0&&We.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(We.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return ag(e,this.model)?!0:(We.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),[n,o]=await this.performRequest(s),i=this.captureResponseTiming();return{requestContext:s,error:n,response:o,requestedAt:r.requestedAt,receivedAt:i.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=cg(e,this.model),r=lg(e,this.model),n=ug(e,this.model),o=dg(e,this.model),i=hg(e.method);return{resolvedPath:s,method:i,pathParams:r,queryParams:n,body:o}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,n,o){const i=s.cache||{retention:ue.SINGLE},a=Di(r,s.method||"get");this.responseStore.set(a,e,i,n,o),await s.originalHandler.call(this.model,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,n){const o=De;switch(s){case"get":return await o.get(e,r);case"post":return await o.post(e,r,n);case"put":return await o.put(e,r,n);case"delete":return await o.delete(e,r,n);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(n=>{const o=this.getNestedValue(e,n.from),i=n.transform?this.applyTransform(o,n.transform):o;fg(i,n.from,s.path,n.required||!1);const a=pg(i,n.default);r[n.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,n)=>r==null?void 0:r[n],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return We.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(n=>{const o=s.mappings&&s.mappings.length>0?this.applyMappings(n,s):n,i=s.idExtractor?s.idExtractor(o):o.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(o):a.instance(i).options(o).build()}):r.map(n=>s.mappings&&s.mappings.length>0?this.applyMappings(n,s):n):(We.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s){const r=s.errorHandler||{strategy:"throw"};switch(r.onError&&r.onError(e,this.model),r.strategy){case"throw":throw e;case"log":We.error(`Service request failed for ${s.path}:`,e.message);break;case"ignore":break;case"default":if(r.defaultValue!==void 0){const n=Di(s.path,s.method||"get");this.responseStore.set(n,r.defaultValue,s.cache||{retention:ue.SINGLE})}break}}}class mg{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(e,r=>{if(!this.subscription.closed&&r!==void 0){const n=this.subscription.resolvers.shift();n?n(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function xi(t){return new mg(t)}const el=({path:t,requestId:e,method:s,destinationAddress:r})=>{let n=`${Lr}:${s}
2
2
  `;return n+=`topic:${t}
3
3
  `,n+=`${kt}:${t}
4
- `,n+=`${As}:${e}
4
+ `,n+=`${Rs}:${e}
5
5
  `,r&&(n+=`${Ne}:${r}
6
6
  `),n+=`${Oe}:kos.studio.request
7
7
  `,n+=`
8
- `,n},el=({path:t,requestId:e,method:s,destinationAddress:r,ordered:n,tracker:o})=>{let i=`${fa}:/http${t}
9
- `;return i+=`${kr}:${s}
8
+ `,n},tl=({path:t,requestId:e,method:s,destinationAddress:r,ordered:n,tracker:o})=>{let i=`${pa}:/http${t}
9
+ `;return i+=`${Lr}:${s}
10
10
  `,i+=`${kt}:${t}
11
- `,i+=`${ya}:${e}
11
+ `,i+=`${ba}:${e}
12
12
  `,r&&(i+=`${Ne}:${r}
13
- `),n&&(i+=`${Wn}:true
14
- `),o&&(i+=`${Qn}:${o}
13
+ `),n&&(i+=`${Qn}:true
14
+ `),o&&(i+=`${Zn}:${o}
15
15
  `),i+=`${Oe}:fos.http.request
16
16
  `,i+=`
17
- `,i},tl=({path:t,requestId:e,method:s,destinationAddress:r,ordered:n,tracker:o,bridge:i,headers:a})=>{let c=`${kr}:${s}
17
+ `,i},sl=({path:t,requestId:e,method:s,destinationAddress:r,ordered:n,tracker:o,bridge:i,headers:a})=>{let c=`${Lr}:${s}
18
18
  `;return c+=`${kt}:${t}
19
- `,c+=`${As}:${e}
19
+ `,c+=`${Rs}:${e}
20
20
  `,r&&(c+=`${Ne}:${r}
21
- `),n&&(c+=`${Wn}:true
22
- `),o&&(c+=`${Qn}:${o}
21
+ `),n&&(c+=`${Qn}:true
22
+ `),o&&(c+=`${Zn}:${o}
23
23
  `),a&&Object.keys(a).forEach(u=>{c+=`${u}:${a[u]}
24
24
  `}),c+=`${Oe}:${i?"fos":"kos"}.http.request
25
25
  `,c+=`
26
- `,c},Ve=(t,e)=>{let s=t;return e&&(s+=e),s};function Qt(t){const e={...t};return{append(s,r){e[s]=r},delete(s){delete e[s]},get(s){return e[s]},forEach(s){Object.keys(e).forEach(r=>s(e[r],r,this))},has(s){return Object.hasOwn(e,s)},set(s,r){e[s]=r},keys(){return Object.keys(e)},values(){return Object.values(e)},entries(){return Object.entries(e)}}}function Zt(t){let e=!1;return window.ReadableStream?new ReadableStream({start(r){function n(){return Promise.resolve({done:e,value:t}).then(({done:o,value:i})=>{if(o){r.close();return}r.enqueue(i),e=!0,n()})}n()}}):t}const sl=({path:t,requestId:e,destinationAddress:s})=>{let r=`topic:${t}
26
+ `,c},Ve=(t,e)=>{let s=t;return e&&(s+=e),s};function Zt(t){const e={...t};return{append(s,r){e[s]=r},delete(s){delete e[s]},get(s){return e[s]},forEach(s){Object.keys(e).forEach(r=>s(e[r],r,this))},has(s){return Object.hasOwn(e,s)},set(s,r){e[s]=r},keys(){return Object.keys(e)},values(){return Object.values(e)},entries(){return Object.entries(e)}}}function Xt(t){let e=!1;return window.ReadableStream?new ReadableStream({start(r){function n(){return Promise.resolve({done:e,value:t}).then(({done:o,value:i})=>{if(o){r.close();return}r.enqueue(i),e=!0,n()})}n()}}):t}const rl=({path:t,requestId:e,destinationAddress:s})=>{let r=`topic:${t}
27
27
  `;return r+=`${kt}:${t}
28
- `,r+=`${As}:${e}
28
+ `,r+=`${Rs}:${e}
29
29
  `,r+=`${Ne}:${s}
30
30
  `,r+=`${Oe}:kos.studio.request
31
31
  `,r+=`
32
- `,r},rl=({requestId:t,destinationAddress:e,requestType:s,headers:r})=>{let n=`${As}:${t}
32
+ `,r},nl=({requestId:t,destinationAddress:e,requestType:s,headers:r})=>{let n=`${Rs}:${t}
33
33
  `;return n+=`${Ne}:${e}
34
34
  `,n+=`${Oe}:${s}
35
35
  `,r&&Object.keys(r).forEach(o=>{n+=`${o}:${r[o]}
36
36
  `}),n+=`
37
- `,n},mg=(t,e)=>{const s=t,r=Ve(rl(e),typeof s=="string"?s:JSON.stringify(s)),n=I.getInstance().transport.socket;n?(m.debug("Sending message",r),n.socket.send(r)):m.error("socket transport is not initialized")},nl=({path:t,responseId:e,status:s,destinationAddress:r})=>{let n=`topic:${t}
37
+ `,n},yg=(t,e)=>{const s=t,r=Ve(nl(e),typeof s=="string"?s:JSON.stringify(s)),n=I.getInstance().transport.socket;n?(m.debug("Sending message",r),n.socket.send(r)):m.error("socket transport is not initialized")},ol=({path:t,responseId:e,status:s,destinationAddress:r})=>{let n=`topic:${t}
38
38
  `;return n+=`${kt}:${t}
39
- `,e&&(n+=`${Lr}:${e}
40
- `),n+=`${Yn}:${s}
39
+ `,e&&(n+=`${Fr}:${e}
40
+ `),n+=`${Wn}:${s}
41
41
  `,n+=`${Ne}:${r}
42
42
  `,n+=`${Oe}:kos.studio.response
43
43
  `,n+=`
44
- `,n},yg=(t,e)=>{const s=t,r=Ve(sl(e),JSON.stringify(s)),n=I.getInstance().transport.socket;n?n.socket.send(r):m.error("socket transport is not initialized")},bg=(t,e)=>{const s=e.responseId?{status:e.status,data:t}:t,r=Ve(nl(e),JSON.stringify(s)),n=I.getInstance().transport.socket;n?n.socket.send(r):m.error("socket transport is not initialized")},ol=({topic:t})=>{let e=`topic:${t}
44
+ `,n},bg=(t,e)=>{const s=t,r=Ve(rl(e),JSON.stringify(s)),n=I.getInstance().transport.socket;n?n.socket.send(r):m.error("socket transport is not initialized")},vg=(t,e)=>{const s=e.responseId?{status:e.status,data:t}:t,r=Ve(ol(e),JSON.stringify(s)),n=I.getInstance().transport.socket;n?n.socket.send(r):m.error("socket transport is not initialized")},il=({topic:t})=>{let e=`topic:${t}
45
45
  `;return e+=`${Oe}:kos.broker.send
46
46
  `,e+=`
47
- `,e},il=({responseId:t,destinationAddress:e,type:s,sourceAddress:r,status:n})=>{let o=`${Lr}:${t}
47
+ `,e},al=({responseId:t,destinationAddress:e,type:s,sourceAddress:r,status:n})=>{let o=`${Fr}:${t}
48
48
  `;return o+=`${Ne}:${e}
49
- `,o+=`${pa}:${r}
49
+ `,o+=`${ga}:${r}
50
50
  `,o+=`${Oe}:${s??"kos.message.request"}
51
- `,o+=`${Yn}:${n}
52
- `,o+=`${ga}:application/json
53
- `,o+=`${ma}:no-cache
51
+ `,o+=`${Wn}:${n}
52
+ `,o+=`${ma}:application/json
53
+ `,o+=`${ya}:no-cache
54
54
  `,o+=`
55
- `,o},al=({topic:t,responseId:e,destinationAddress:s,type:r})=>{let n=`topic:${t}
56
- `;return e&&(n+=`${Lr}:${e}
55
+ `,o},cl=({topic:t,responseId:e,destinationAddress:s,type:r})=>{let n=`topic:${t}
56
+ `;return e&&(n+=`${Fr}:${e}
57
57
  `),n+=`${Ne}:${s}
58
58
  `,n+=`${Oe}:${r??"kos.message.request"}
59
59
  `,n+=`
60
- `,n},vg=({msg:t,options:e})=>{const s=t,r=Ve(ol(e),JSON.stringify(s)),n=I.getInstance().transport.socket;n?n.socket.send(r):m.error("socket transport is not initialized")},cl=({msg:t,options:e})=>{const s=t,r=Ve(al(e),JSON.stringify(s)),n=I.getInstance().transport.socket;n?n.socket.send(r):m.error("socket transport is not initialized")},ll=({msg:t,options:e})=>{const s=t,r=Ve(il(e),JSON.stringify(s)),n=I.getInstance().transport.socket;n?n.socket.send(r):m.error("socket transport is not initialized")},Cn=(t,e)=>{try{return e?t.body??t:JSON.parse(t.body)}catch{return t.body||t}};class wg{constructor(e){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=e,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(e){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of e)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(e,s)}async*processSingleEvent(e){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(e))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(e),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([e]):[e],this.updateProcessingStats([e])}}async*processBatchedEvents(e,s){const r=s.size||100,n=s.window||1e3;let o=[],i=Date.now();const a=async()=>{if(o.length===0)return;const c=[...o];o=[],i=Date.now();const u=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(u.length===0)return;this.config.backpressure&&await this.waitForCapacity();const d=this.config.transform?this.config.transform(u):u;return this.stats.batchesProcessed++,this.updateProcessingStats(u),d};try{for await(const u of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(u);this.eventQueue.length>0;){const d=this.dequeueEvent();d&&o.push(d);const f=Date.now()-i;if(o.length>=r||f>=n){const p=await a();p!==void 0&&(yield p);break}}else{o.push(u);const h=Date.now()-i;if(o.length>=r||h>=n){const f=await a();f!==void 0&&(yield f)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(e){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(e,s);return this.config.filter.historySize&&(this.filterHistory.push(e),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const e=Date.now(),s=Math.floor(e/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[n]of this.rateLimitWindow)n<s-1&&this.rateLimitWindow.delete(n);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const e=Date.now(),n=(Math.floor(e/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-e;n>0&&await new Promise(o=>setTimeout(o,n))}async waitForCapacity(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=e;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const n=this.eventQueue.length-e;if(n<=0)return;let o=[];if(s==="oldest"?o=this.eventQueue.splice(0,n):s==="newest"&&(o=this.eventQueue.splice(-n)),this.stats.eventsDropped+=o.length,this.stats.currentQueueSize=this.eventQueue.length,r&&o.length>0)try{r(o)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(e){if(this.eventQueue.push(e),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const e=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,e}updateProcessingStats(e){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+e.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?e.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(e){return this.activePromises.add(e),e.finally(()=>this.activePromises.delete(e)),e}getStats(){return{...this.stats}}}class Eg extends WebSocket{constructor(e){super(e)}}function xi(t){const e=`
60
+ `,n},wg=({msg:t,options:e})=>{const s=t,r=Ve(il(e),JSON.stringify(s)),n=I.getInstance().transport.socket;n?n.socket.send(r):m.error("socket transport is not initialized")},ll=({msg:t,options:e})=>{const s=t,r=Ve(cl(e),JSON.stringify(s)),n=I.getInstance().transport.socket;n?n.socket.send(r):m.error("socket transport is not initialized")},ul=({msg:t,options:e})=>{const s=t,r=Ve(al(e),JSON.stringify(s)),n=I.getInstance().transport.socket;n?n.socket.send(r):m.error("socket transport is not initialized")},Dn=(t,e)=>{try{return e?t.body??t:JSON.parse(t.body)}catch{return t.body||t}};class Eg{constructor(e){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=e,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(e){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of e)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(e,s)}async*processSingleEvent(e){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(e))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(e),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([e]):[e],this.updateProcessingStats([e])}}async*processBatchedEvents(e,s){const r=s.size||100,n=s.window||1e3;let o=[],i=Date.now();const a=async()=>{if(o.length===0)return;const c=[...o];o=[],i=Date.now();const u=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(u.length===0)return;this.config.backpressure&&await this.waitForCapacity();const d=this.config.transform?this.config.transform(u):u;return this.stats.batchesProcessed++,this.updateProcessingStats(u),d};try{for await(const u of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(u);this.eventQueue.length>0;){const d=this.dequeueEvent();d&&o.push(d);const f=Date.now()-i;if(o.length>=r||f>=n){const p=await a();p!==void 0&&(yield p);break}}else{o.push(u);const h=Date.now()-i;if(o.length>=r||h>=n){const f=await a();f!==void 0&&(yield f)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(e){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(e,s);return this.config.filter.historySize&&(this.filterHistory.push(e),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const e=Date.now(),s=Math.floor(e/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[n]of this.rateLimitWindow)n<s-1&&this.rateLimitWindow.delete(n);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const e=Date.now(),n=(Math.floor(e/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-e;n>0&&await new Promise(o=>setTimeout(o,n))}async waitForCapacity(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=e;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const n=this.eventQueue.length-e;if(n<=0)return;let o=[];if(s==="oldest"?o=this.eventQueue.splice(0,n):s==="newest"&&(o=this.eventQueue.splice(-n)),this.stats.eventsDropped+=o.length,this.stats.currentQueueSize=this.eventQueue.length,r&&o.length>0)try{r(o)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(e){if(this.eventQueue.push(e),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const e=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,e}updateProcessingStats(e){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+e.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?e.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(e){return this.activePromises.add(e),e.finally(()=>this.activePromises.delete(e)),e}getStats(){return{...this.stats}}}class Mg extends WebSocket{constructor(e){super(e)}}function Ai(t){const e=`
61
61
 
62
62
  `,s=`
63
- `,r=/:(.*)/s,[n,o]=t.split(e).map(a=>a.trim());return{headers:n.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:o}}function Mg(t){const e=`
63
+ `,r=/:(.*)/s,[n,o]=t.split(e).map(a=>a.trim());return{headers:n.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:o}}function Tg(t){const e=`
64
64
 
65
65
  `,s=`
66
- `,r=/:(.*)/s,[,n,o]=t.split(e).map(a=>a.trim());return{headers:n.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:o}}class Eo{constructor({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:o,onConnectionLost:i,Transport:a=Eg}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"socket");l(this,"connectionEstablished");l(this,"alias");l(this,"onConnectionEstablished");l(this,"onConnectionLost");l(this,"offlineMessages",[]);l(this,"oldSend");this.host=e,this.port=s,this.protocol=r,this.onConnectionEstablished=o,this.onConnectionLost=i,this.alias=n,this.socket=new a(`${this.protocol}${this.host}:${this.port}/events`),this.socket.onmessage=this.onMessage.bind(this),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.oldSend=this.socket.send,this.connectionEstablished=!1,C("/mock/msg/receive",c=>{var u,d;if(c!=null&&c.body){m.wsReceive(c==null?void 0:c.body);const h={data:c.body};(d=(u=this.socket)==null?void 0:u.onmessage)==null||d.call(u,h)}}),M.makeObservable(this,{connectionEstablished:M.observable})}addOfflineMessage(e){this.offlineMessages.push({msg:e})}processMessageEvent(e){const{data:s}=e;return xi(s)}onMessage(e){try{m.debug("webSocketTransport: onMessage received");const{headers:s,body:r}=this.processMessageEvent(e);m.wsReceive(e.data);const n=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(n){let o=r,i=s;if(n==="kos.sniffer.msg"){const{headers:a,body:c}=Mg(e.data);o=c,i={...s,...a}}V(n,o,i)}}catch(s){m.error("onMessage exception",s.message,s.stack)}}onOpen(e){m.info("websocket connection opened"),this.socket=e.currentTarget,M.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
66
+ `,r=/:(.*)/s,[,n,o]=t.split(e).map(a=>a.trim());return{headers:n.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:o}}class Mo{constructor({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:o,onConnectionLost:i,Transport:a=Mg}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"socket");l(this,"connectionEstablished");l(this,"alias");l(this,"onConnectionEstablished");l(this,"onConnectionLost");l(this,"offlineMessages",[]);l(this,"oldSend");this.host=e,this.port=s,this.protocol=r,this.onConnectionEstablished=o,this.onConnectionLost=i,this.alias=n,this.socket=new a(`${this.protocol}${this.host}:${this.port}/events`),this.socket.onmessage=this.onMessage.bind(this),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.oldSend=this.socket.send,this.connectionEstablished=!1,C("/mock/msg/receive",c=>{var u,d;if(c!=null&&c.body){m.wsReceive(c==null?void 0:c.body);const h={data:c.body};(d=(u=this.socket)==null?void 0:u.onmessage)==null||d.call(u,h)}}),M.makeObservable(this,{connectionEstablished:M.observable})}addOfflineMessage(e){this.offlineMessages.push({msg:e})}processMessageEvent(e){const{data:s}=e;return Ai(s)}onMessage(e){try{m.debug("webSocketTransport: onMessage received");const{headers:s,body:r}=this.processMessageEvent(e);m.wsReceive(e.data);const n=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(n){let o=r,i=s;if(n==="kos.sniffer.msg"){const{headers:a,body:c}=Tg(e.data);o=c,i={...s,...a}}V(n,o,i)}}catch(s){m.error("onMessage exception",s.message,s.stack)}}onOpen(e){m.info("websocket connection opened"),this.socket=e.currentTarget,M.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
67
67
  alias:${this.alias}
68
68
 
69
- `),m.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var n;m.debug(`sending offline message ${r.msg}`),(n=this.socket)==null||n.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),M.runInAction(()=>{this.connectionEstablished=!1}),m.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(e){var s,r;if(m.wsSend(e),window.kosLogEvents){const{headers:n,body:o}=xi(String(e));V(Rs.SEND,{headers:n,body:o})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:n,requestId:o}=window.kosTopicIntercept(e);if(n){e=`mocked:true
69
+ `),m.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var n;m.debug(`sending offline message ${r.msg}`),(n=this.socket)==null||n.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),M.runInAction(()=>{this.connectionEstablished=!1}),m.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(e){var s,r;if(m.wsSend(e),window.kosLogEvents){const{headers:n,body:o}=Ai(String(e));V(Ps.SEND,{headers:n,body:o})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:n,requestId:o}=window.kosTopicIntercept(e);if(n){e=`mocked:true
70
70
  ${e}`;const a={data:`mocked:true
71
- ${n(o)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,e)}else this.oldSend.call(this.socket,e)}}class Tg{constructor(e){l(this,"addEventListener");l(this,"dispatchEvent");l(this,"removeEventListener");l(this,"_onclose");l(this,"_onerror");l(this,"_onmessage");l(this,"_onopen");l(this,"messageQueue",[]);l(this,"isSending",!1);D.debug(`called Bridge Transport with addr ${e}`);const s=this;globalThis.kosWindowWebsocketRecv=r=>{if(s.onmessage){const n={data:r};s.onmessage(n)}},D.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),D.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>D.debug("not implemented"),this.dispatchEvent=()=>D.debug("not implemented"),this.removeEventListener=()=>D.debug("not implemented")}close(){D.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const e=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(e),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(e){this.messageQueue.push(e),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(e){globalThis.kosWindowWebsocketSend(e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage=e}get onopen(){return this._onopen}set onopen(e){this._onopen=e}get onclose(){return this._onclose}set onclose(e){this._onclose=e}get onerror(){return this._onerror}set onerror(e){this._onopen=e}}class Sg extends Eo{constructor({host:s,port:r,alias:n}){super({host:s,port:r,Transport:Tg,alias:n,protocol:"kos://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class _g extends Eo{constructor({host:s,port:r}){super({host:s,port:r,protocol:"ws://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class Ig extends Eo{constructor({host:s,port:r,protocol:n,onConnectionEstablished:o,onConnectionLost:i,alias:a}){super({host:s,port:r,onConnectionEstablished:o,onConnectionLost:i,alias:a,protocol:n});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}window.kosEnableMocks=process.env.KOS_MOCK_WS==="true";window.kosLogEvents=process.env.KOS_LOG_WS==="true";class Dn{static build({host:e,port:s,protocol:r,fos:n,alias:o,onConnectionEstablished:i,onConnectionLost:a}){return m.debug("initializing websocket connection"),m.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),m.warn(`fos: ${n?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!n?(m.warn("Using bridged message transport"),new Sg({host:e,port:s,protocol:r,onConnectionEstablished:i,onConnectionLost:a,alias:o})):n?new _g({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:i,onConnectionLost:a}):new Ig({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:i,onConnectionLost:a})}}const Og=me();Og.fos&&(window.kosUseFos=!0);const Ai=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=Ai?parseInt(Ai):0;const Ye=D.getLogger("web-socket-transport");var ul=(t=>(t.NOT_INITIALIZED="not_initialized",t.INITIALIZED="initialized",t.OFFLINE="OFFLINE",t.ONLINE="ONLINE",t))(ul||{}),ms=(t=>(t.CONNECTED="websocket.connected",t.DISCONNECTED="websocket.disconnected",t.RELOAD="websocket.reload",t))(ms||{});class Tt{constructor({host:e="localhost",port:s=8080,protocol:r="ws://",token:n,initialize:o,alias:i,fos:a}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"_token");l(this,"webSocketSupported",!!globalThis.WebSocket);l(this,"authorized");l(this,"alias");l(this,"socket");l(this,"fosSocket");l(this,"fosPort");l(this,"useFosTransport");this.host=e,this.port=s,this.protocol=r,this._token=n,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!a,this.fosPort=a==null?void 0:a.port,this.socket=void 0,this.fosSocket=void 0;let c=!1;M.makeObservable(this,{authorized:M.observable,socket:M.observable,fosSocket:M.observable,init:M.action,connectionEstablished:M.computed}),M.reaction(()=>this.connectionEstablished,u=>{u&&(Ye.warn("Connection Established"),V("websocket.connected","websocket.connected"),c&&V("websocket.reload","websocket.reload"),c=!0)}),o&&this.init()}get connectionEstablished(){return!this.webSocketSupported||!this.socket||this.useFosTransport&&!this.fosSocket?!1:this.useFosTransport&&this.fosSocket?this.socket.connectionEstablished&&this.fosSocket.connectionEstablished:!this.useFosTransport&&this.socket?this.socket.connectionEstablished:!1}init(){var e,s;if(m.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=Dn.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=Dn.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ye.error("Connection Lost"),V("websocket.disconnected","websocket.disconnected"),this.init()}}),globalThis.kosWindowWebsocketOpen){const r={currentTarget:this.socket.socket};(s=(e=this.socket.socket)==null?void 0:e.onopen)==null||s.call(e,r)}return this}_sendSubscriptionMessage(e,s,r=!1,n=!1,o){var f,p,y,w;Ye.debug(`${s} to topic ${e}`);const i=me(),a=i==null?void 0:i.connId,c=o??a??((f=window==null?void 0:window.kosBridge)==null?void 0:f.call(window,"connId"));Ye.debug(`subscribing with connId ${c}`);const u=c?`dst-addr:${c}
71
+ ${n(o)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,e)}else this.oldSend.call(this.socket,e)}}class Sg{constructor(e){l(this,"addEventListener");l(this,"dispatchEvent");l(this,"removeEventListener");l(this,"_onclose");l(this,"_onerror");l(this,"_onmessage");l(this,"_onopen");l(this,"messageQueue",[]);l(this,"isSending",!1);D.debug(`called Bridge Transport with addr ${e}`);const s=this;globalThis.kosWindowWebsocketRecv=r=>{if(s.onmessage){const n={data:r};s.onmessage(n)}},D.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),D.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>D.debug("not implemented"),this.dispatchEvent=()=>D.debug("not implemented"),this.removeEventListener=()=>D.debug("not implemented")}close(){D.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const e=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(e),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(e){this.messageQueue.push(e),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(e){globalThis.kosWindowWebsocketSend(e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage=e}get onopen(){return this._onopen}set onopen(e){this._onopen=e}get onclose(){return this._onclose}set onclose(e){this._onclose=e}get onerror(){return this._onerror}set onerror(e){this._onopen=e}}class _g extends Mo{constructor({host:s,port:r,alias:n}){super({host:s,port:r,Transport:Sg,alias:n,protocol:"kos://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class Ig extends Mo{constructor({host:s,port:r}){super({host:s,port:r,protocol:"ws://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class Og extends Mo{constructor({host:s,port:r,protocol:n,onConnectionEstablished:o,onConnectionLost:i,alias:a}){super({host:s,port:r,onConnectionEstablished:o,onConnectionLost:i,alias:a,protocol:n});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}window.kosEnableMocks=process.env.KOS_MOCK_WS==="true";window.kosLogEvents=process.env.KOS_LOG_WS==="true";class xn{static build({host:e,port:s,protocol:r,fos:n,alias:o,onConnectionEstablished:i,onConnectionLost:a}){return m.debug("initializing websocket connection"),m.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),m.warn(`fos: ${n?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!n?(m.warn("Using bridged message transport"),new _g({host:e,port:s,protocol:r,onConnectionEstablished:i,onConnectionLost:a,alias:o})):n?new Ig({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:i,onConnectionLost:a}):new Og({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:i,onConnectionLost:a})}}const $g=me();$g.fos&&(window.kosUseFos=!0);const Ri=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=Ri?parseInt(Ri):0;const Ye=D.getLogger("web-socket-transport");var dl=(t=>(t.NOT_INITIALIZED="not_initialized",t.INITIALIZED="initialized",t.OFFLINE="OFFLINE",t.ONLINE="ONLINE",t))(dl||{}),ys=(t=>(t.CONNECTED="websocket.connected",t.DISCONNECTED="websocket.disconnected",t.RELOAD="websocket.reload",t))(ys||{});class Tt{constructor({host:e="localhost",port:s=8080,protocol:r="ws://",token:n,initialize:o,alias:i,fos:a}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"_token");l(this,"webSocketSupported",!!globalThis.WebSocket);l(this,"authorized");l(this,"alias");l(this,"socket");l(this,"fosSocket");l(this,"fosPort");l(this,"useFosTransport");this.host=e,this.port=s,this.protocol=r,this._token=n,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!a,this.fosPort=a==null?void 0:a.port,this.socket=void 0,this.fosSocket=void 0;let c=!1;M.makeObservable(this,{authorized:M.observable,socket:M.observable,fosSocket:M.observable,init:M.action,connectionEstablished:M.computed}),M.reaction(()=>this.connectionEstablished,u=>{u&&(Ye.warn("Connection Established"),V("websocket.connected","websocket.connected"),c&&V("websocket.reload","websocket.reload"),c=!0)}),o&&this.init()}get connectionEstablished(){return!this.webSocketSupported||!this.socket||this.useFosTransport&&!this.fosSocket?!1:this.useFosTransport&&this.fosSocket?this.socket.connectionEstablished&&this.fosSocket.connectionEstablished:!this.useFosTransport&&this.socket?this.socket.connectionEstablished:!1}init(){var e,s;if(m.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=xn.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=xn.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ye.error("Connection Lost"),V("websocket.disconnected","websocket.disconnected"),this.init()}}),globalThis.kosWindowWebsocketOpen){const r={currentTarget:this.socket.socket};(s=(e=this.socket.socket)==null?void 0:e.onopen)==null||s.call(e,r)}return this}_sendSubscriptionMessage(e,s,r=!1,n=!1,o){var f,p,y,w;Ye.debug(`${s} to topic ${e}`);const i=me(),a=i==null?void 0:i.connId,c=o??a??((f=window==null?void 0:window.kosBridge)==null?void 0:f.call(window,"connId"));Ye.debug(`subscribing with connId ${c}`);const u=c?`dst-addr:${c}
72
72
  `:"",d=r?`subscribe:${e}`:n?`type:fos.broker
73
73
  cmd:${s}
74
74
  ${u}topics:${e}
75
75
  `:`${u}type:kos.broker.${s}
76
76
 
77
- ["${e}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(w=E==null?void 0:E.socket)==null||w.send(d)}else{Ye.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(d)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:n,destinationAddress:o}){const{unsubscribe:i,count:a}=C(e,s);return Ye.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,n,o),()=>{const{count:c}=i();Ye.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,n,o)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(Tt,"_instance");class $g{constructor(e,s,r,n,o){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);l(this,"baselineDependencies",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=n,this.log=o}registerAll(e){var n;const s=((n=this.modelData)==null?void 0:n[ee])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(o=>{const i=s[o],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(o);if(this.log.debug(`Resolved topic: ${o} → ${c}`),i.requiresBaseline&&(this.baselineDependencies.set(c,i.requiresBaseline),this.log.debug(`Registered baseline dependency for ${c}: ${i.requiresBaseline.path}`)),i.flow)this.subscribeWithFlowControl(i,c,a);else{const u=this.createHandler(c,i);this.subscribe(i,c,u,a===x.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,n){const o=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Tt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:o});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=C(s,r);n?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var n;try{const o=(n=r==null?void 0:r.headers)==null?void 0:n["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?o===i:!0,c=this.extractWildcardCapture(e,r,s),u=this.isBaselineReady(e);if(!this.model.isReady()||!u){u?this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`):this.log.warn(`Baseline not ready for ${e}. Queuing message.`);const d=()=>{const h=Cn(r,s.skipParse),f=s.transform(h);if(a&&s.condition(f,this.modelData,r))return this.callHandlerWithWildcard(s,f,c,r)};this.offlineQueue.enqueue(d,e,r)}else{const d=Cn(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)}}catch(o){this.log.error(`Error handling subscription for ${e}`,o)}}}extractWildcardCapture(e,s,r){var o;if(!r.wildcardName||!Rc(e))return null;const n=((o=s==null?void 0:s.headers)==null?void 0:o.topic)||"";return Ac(e,n,r.wildcardName)}callHandlerWithWildcard(e,s,r,n){if(r&&Object.keys(r).length>0){const o={...n,wildcardCapture:r};return e.handler.call(this.modelData,s,o,this.modelData)}else return e.handler.call(this.modelData,s,n,this.modelData)}resolvePropKey(e){const s=/.*({PROP_(.+)})/;let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",this.modelId):e;const n=r.match(s);return n&&n[2]in this.modelData&&(r=r.replace(n[1],this.modelData[n[2]])),r}async subscribeWithFlowControl(e,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const n=new wg(e.flow);this.flowControllers.set(s,n);const o=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,o,n),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===x.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(e,s,r,n){const o=new AbortController;try{let i;if(e.websocket){const a=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;Tt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Di(s)}else i=Di(s);return(async()=>{try{for await(const a of n.processEvents(i)){if(o.signal.aborted)break;const c=r(a);c instanceof Promise&&await n.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),o}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var n,o,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c,e,r)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(o=(n=s.flow)==null?void 0:n.errorHandling)!=null&&o.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const n=e.flow.errorHandling.retry;let o=r;for(let i=1;i<=n.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${n.attempts} for handler`),await new Promise(a=>setTimeout(a,n.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){o=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",o),o}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}getResponseStore(){return this.modelData.serviceResponses}isBaselineReady(e){const s=this.baselineDependencies.get(e);if(!s)return!0;const r=this.getResponseStore();if(!r)return this.log.warn(`ServiceResponseStore not found for baseline check on topic: ${e}`),!1;const o=`${(s.method||"get").toUpperCase()}:${s.path}`;return r.has(o)}flushQueueForBaseline(e){const s=this.baselineDependencies.get(e);if(!s){this.log.debug(`No baseline dependency for topic: ${e}`);return}const r=this.getResponseStore();if(!r){this.log.warn("ServiceResponseStore not found, falling back to standard flush"),this.offlineQueue.flush();return}const n=s.method||"get",o=r.getTemporalMetadataByPath(s.path,n);if(!o){this.log.warn(`Baseline temporal metadata not found for ${s.path}, falling back to standard flush`),this.offlineQueue.flush();return}const i=s.replayStrategy||Je.AFTER_REQUEST;this.log.info(`Flushing queue with strategy ${i} for topic: ${e}`),this.log.debug(`Baseline timing - requested: ${o.requestedAt}, received: ${o.receivedAt}`),this.offlineQueue.flushWithStrategy(i,o.requestedAt,o.receivedAt)}}function ht(t,e){const s=`[Model:${e}]`;return{debug:(...r)=>t.debug(s,...r),info:(...r)=>t.info(s,...r),warn:(...r)=>t.warn(s,...r),error:(...r)=>t.error(s,...r)}}function Cg(t){return!!(t!=null&&t[et])&&Object.keys(t[et]).length>0}function Dg(t){return!!(t!=null&&t[ee])&&Object.keys(t[ee]).length>0}function xg(t){return!!(t!=null&&t[Re])&&t[Re].length>0}function Ag(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[tt])&&Object.keys(e[tt]).length>0}function Rg(t){return t.retention===ue.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function Pg(t,e){return t.has(e)}function kg(t){return!t.expiresAt||Date.now()<t.expiresAt}function Ri(t,e,s,r){const n=setTimeout(()=>r(t),e);s.set(t,n)}class Lg{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:ue.SINGLE},n=Date.now(),o=Date.now()){if(this.shouldExtendTTL(e,r))return this.extendExistingTTL(e,r.ttl),!1;const i=this.createCachedResponse(s,e,r,n,o);return this.storeResponse(e,i,r),!0}get(e){const s=this.responses.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.delete(e);return}return s.data}}getByPath(e,s="get"){return this.get(this.makeKey(e,s))}has(e){return this.get(e)!==void 0}delete(e){this.responses.delete(e),this.retentionPolicies.delete(e);const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}clearPath(e){Array.from(this.responses.keys()).filter(r=>this.extractPath(r)===e).forEach(r=>this.delete(r))}clear(){this.cleanupTimers.forEach(e=>clearTimeout(e)),this.responses.clear(),this.retentionPolicies.clear(),this.cleanupTimers.clear()}get size(){return this.responses.size}shouldCleanupAfterHandler(e){const s=this.retentionPolicies.get(e);return(s==null?void 0:s.retention)===ue.IMMEDIATE}shouldExtendTTL(e,s){if(!Rg(s)||!Pg(this.responses,e))return!1;const r=this.responses.get(e);return kg(r)}extendExistingTTL(e,s){const r=this.responses.get(e);r.expiresAt=Date.now()+s,this.resetCleanupTimer(e,s)}resetCleanupTimer(e,s){this.clearTimerIfExists(e),Ri(e,s,this.cleanupTimers,r=>this.delete(r))}clearTimerIfExists(e){const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}createCachedResponse(e,s,r,n,o){return{data:e,timestamp:o,requestedAt:n,receivedAt:o,path:this.extractPath(s),method:this.extractMethod(s),expiresAt:this.calculateExpiresAt(r)}}calculateExpiresAt(e){return e.retention===ue.TTL&&e.ttl?Date.now()+e.ttl:void 0}storeResponse(e,s,r){this.responses.set(e,s),this.retentionPolicies.set(e,r),this.applyRetentionPolicy(e,r)}applyRetentionPolicy(e,s){switch(s.retention){case ue.IMMEDIATE:break;case ue.TTL:s.ttl&&Ri(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case ue.SINGLE:break;case ue.PERMANENT:case ue.MANUAL:break}}makeKey(e,s){return`${s.toUpperCase()}:${e}`}extractPath(e){return e.split(":",2)[1]||e}extractMethod(e){return e.split(":",2)[0]||"get"}getTemporalMetadata(e){const s=this.responses.get(e);if(s)return{requestedAt:s.requestedAt,receivedAt:s.receivedAt}}getTemporalMetadataByPath(e,s="get"){return this.getTemporalMetadata(this.makeKey(e,s))}cleanup(){const e=Date.now();Array.from(this.responses.entries()).filter(([r,n])=>n.expiresAt&&e>n.expiresAt).map(([r])=>r).forEach(r=>this.delete(r))}}class Fg{static createAll(e){const{modelId:s,modelTypeName:r,modelData:n}=e,o=bc.create({modelId:s,modelTypeName:r}),i=new eg(e,ht(o,"fsm")),a=new sg(ht(o,"offline-queue")),c=new Vp(e),u=new zp(e),d=new Lg;n.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(Cg(n)&&(h.effectManager=new Gp(r,s,n,ht(o,"effect"))),Dg(n)){const f=ht(o,"subscription");h.subscriptionManager=new $g(e,n,s,a,f),h.onlineLifecycleManager=new rg(e,ht(o,"online"))}return xg(n)&&(h.httpRouteManager=new vo(n,ht(o,"http-routes"))),Ag(n)&&(h.serviceRequestManager=new pg(n,d)),h}}const U=D.getLogger("kos-model"),Ng="kos.extension.model.loader";class dl{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"serviceResponses");l(this,"serviceRequestManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const n=Fg.createAll(this);this.fsm=n.fsm,this.offlineQueue=n.offlineQueue,this.companionManager=n.companionManager,this.childResolver=n.childResolver,this.serviceResponses=n.serviceResponseStore,n.effectManager&&(this.effectManager=n.effectManager),n.subscriptionManager&&(this.subscriptionManager=n.subscriptionManager),n.httpRouteManager&&(this.httpRouteManager=n.httpRouteManager),n.onlineLifecycleManager&&(this.onlineLifecycleManager=n.onlineLifecycleManager),n.serviceRequestManager&&(this.serviceRequestManager=n.serviceRequestManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,serviceRequestManager:!1,serviceResponses:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Kp(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===v.ACTIVE}isOnline(){return this._onlineStatus===v.ONLINE}isReady(){return this._status===v.READY}async deactivate(){var e,s,r;U.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const n=Y.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,n)),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(n){throw U.debug(`Model ${this.modelId} failed to deactivated`),n}}async activate(){var e,s,r,n;U.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await Wt(this,x.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.ACTIVATE));const o=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,o)),this.initializeStateMachineForLifecycle(x.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(n=this.subscriptionManager)==null||n.registerAll(x.ACTIVATE),this.createLifecycleCompanions(x.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw U.debug(`Model ${this.modelId} failed to activate`),o}}async whenLoaded(){await gn([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{U.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await gn([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{U.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await gn([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{U.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,n;if(this.fsm.current===v.READY){U.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{U.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await Wt(this,x.READY),await Gc(this,yo.READY,x.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.READY));const o=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.ready)==null?void 0:r.call(s,o)),this.offlineQueue.flush(),this.initializeStateMachineForLifecycle(x.READY),(n=this.subscriptionManager)==null||n.registerAll(x.READY),this.createLifecycleCompanions(x.READY),U.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};V(Lc(this.modelTypeName,this.modelId),i),V(Fc(this.modelTypeName),i)}catch(o){throw U.error(o),Error(o)}}async load(){var n,o,i,a,c,u;const e=this[He];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED||this.fsm.current===v.LOADING){U.debug(`Model ${s} with id ${r} already loaded or loading`);return}U.debug(`Loading model ${s} with id ${r}`),await Wt(this,x.LOAD);try{const d=Y.getContext(r),h=`${Ng}.${s}`,f=await $.loader.executeLoader(h,{});f&&(U.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(x.LOAD)),await((i=(o=this.modelData)==null?void 0:o.load)==null?void 0:i.call(o,d)),X(()=>{this.loaded=!0}),U.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(x.LOAD),(a=this.subscriptionManager)==null||a.registerAll(x.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(x.LOAD)}catch(d){throw U.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,n,o,i,a;U.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const c=this.getChildren().map(d=>{var h;return(h=d.unload)==null?void 0:h.call(d)}).filter(d=>!!d);await Promise.allSettled(c);const u=Y.getContext(this.modelId);if(await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,u)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),this.modelData){const d=this.modelData;if(d._fsmInitialized=!1,d._fsmConfig){const h=((n=d._fsmOptions)==null?void 0:n.stateProperty)||"currentState";d[h]=void 0}d.stateHistory&&(d.stateHistory=[])}U.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(o=this.effectManager)==null||o.disposeAll(),(i=this.subscriptionManager)==null||i.disposeAll(),(a=this.httpRouteManager)==null||a.dispose()}catch(c){throw U.debug(`Model ${this.modelId} failed to unload`),c}}async init(){var o,i,a,c;const e=this[He];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,n=Y.getContext(s);U.debug(`Initializing model ${r} with id ${s}`),await Wt(this,x.INIT);try{await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(x.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,n)),this.initialized=!0,U.debug(`Model ${r} with id ${s} initialized`),(c=this.onlineLifecycleManager)==null||c.register(),this.initializeStateMachineForLifecycle(x.INIT),this.registerSubscribers(x.INIT),this.createLifecycleCompanions(x.INIT)}catch(u){throw U.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;U.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&fc(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;U.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(x.ONLINE)}async offline(){var s,r,n;U.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=Y.getContext(this.modelId);await((n=(r=this.modelData)==null?void 0:r.offline)==null?void 0:n.call(r,e))}accept(e){e.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(e){this.companionManager.add(e)}clearCompanionModels(){this.companionManager.clear()}}const Pi=m.createLogger({name:"kos-model-instantiator"});class Ug{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new Up(e,s,this.createModelInstance.bind(this))}createModelInstance(e,s,r={}){const n=this.registry.models[e];if(!n)throw new Error(`No model registered for type ${e}`);const o=n.singleton?e:s;if(this.cache.restoreFromDeleteCache(o),!this.cache.hasModel(o)){Pi.debug(`Creating model instance: ${e} [${o}]`);const a=n.create?n.create({modelTypeId:e,id:o,options:r}):new n.class(o,r),c=new dl({modelTypeName:e,id:o,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(o);if(!i)throw Pi.error(`Model ${e} [${o}] not found in cache`),new Error(`Model ${e} [${o}] not found in cache`);return{model:i,data:i.modelData}}createCompanionModels(e,s,r){this.companionInstantiator.createCompanionModels(e,s,r)}_createCompanionModels(e,s){this.createCompanionModels(e,s)}}let jg=class{constructor(e){this._registry=e}get registry(){return this._registry}getModelTypeRegistry(e){const s=this.registry.models[e];if(!s)throw new Error(`No registration for model type ${e}`);return s}registerModel(e){const s=e.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...e.registration})}registerCompanionModel(e,s){var r,n;(r=this.registry).companionModels??(r.companionModels={}),(n=this.registry.companionModels)[e]??(n[e]=[]),this.registry.companionModels[e].some(o=>o.type===s)||this.registry.companionModels[e].push({type:s})}getModelSubscriptions(e){var s;return((s=this.getModelTypeRegistry(e))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(e){var r;const s=(r=this.getModelTypeRegistry(e))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${e}`);return s}getModelFactory(e){return Ft(e)}};const hl=10,ki=m.createLogger({name:"kos-model-manager"});class fl{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Fp,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=e=>{const s=this.getModelById(e);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=e=>{var r,n;const s=this.getModelById(e);if(s)return((n=(r=s.modelData).toJSON)==null?void 0:n.call(r))||{}},globalThis.kos.kosModelDebug=e=>{var r;const s=this.getModelById(e);if(s)return((r=s.modelData)==null?void 0:r.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(e,s){const r=this.getInstance(s);return r._registry=new jg(e),r.cache=new Np(e.preloadModels),r.instantiator=new Ug(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(ki.debug("Creating new instance of KosModelManager"),new this),(r=globalThis.kos)==null?void 0:r.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(e=>(ki.debug(`preloading ${e}`),typeof e=="string"?this.createModelInstance(e).model:this.createModelInstance(e.modelType,e.modelId,e.options).model))}get models(){return this.cache.models}getModelById(e){return this.cache.getModelById(e)}addModel(e){return this.cache.addModel(e)}removeModel(e){this.cache.removeModel(e.modelId)}hasModel(e){return this.cache.hasModel(e)}getModelsByType(e,s){return Array.from(this.models).filter(r=>r.modelTypeName===e).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(e){return this._registry.getModelSubscriptions(e)}getDataModelBuilder(e){return this._registry.getDataModelBuilder(e)}getModelFactory(e){return Ft(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(F.RESET,v.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),Pc.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),hl)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}createLifecycleCompanions(e,s,r){this.instantiator.createCompanionModels(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var sr=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.RELOADING="reloading",t))(sr||{}),yt=(t=>(t.CREATE="create",t.INITIALIZE="init",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.UNLOAD="unload",t.RELOAD="reload",t))(yt||{});const Bg=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,o=>D.debug(o.machine.current)),r=b.createMachine({creating:b.state(b.transition("create","created")),created:b.state(b.immediate("initializing")),initializing:b.invoke(()=>t.init(),b.transition("done","initialized")),initialized:b.state(b.immediate("loading")),loading:b.invoke(()=>t.load(),b.transition("done","loaded")),loaded:b.state(b.immediate("readying"),b.transition("unload","unloading")),readying:b.invoke(()=>t.ready(),b.transition("done","ready",b.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:b.invoke(()=>t.reload(),b.transition("done","loading")),ready:b.state(b.transition("reload","reloading"),b.transition("unload","unloaded",b.action(t.unload.bind(t))),b.transition("go_online","ready",b.action(()=>{s.send("go_online")})),b.transition("go_offline","ready",b.action(()=>{s.send("go_offline")}))),unloaded:b.state()});return{service:b.interpret(r,o=>D.debug(o.machine.current)),online:s}},Q=m.createLogger({name:"kos-core"}),Hg=()=>{const t=me(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},Kg=()=>{const t=window.location.protocol,e=me(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},qg=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=me(),r=s==null?void 0:s.host;let n;try{n=new URL(r).hostname}catch{}return n??e??t},zg=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=me(),r=s==null?void 0:s.host;let n;try{n=new URL(r).port}catch{}return n??e??t},Vg=(t,e)=>{let s;return{promise:new Promise((o,i)=>{s=setTimeout(()=>{e?m.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):m.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},Li=t=>typeof t.reload=="function",Gg=t=>typeof t.unload=="function";var pl=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(pl||{});class I{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=sr.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(ms.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(yt.GO_ONLINE)}),C(ms.DISCONNECTED,async()=>{this.fsmService.service.send(yt.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(ms.RELOAD,()=>{Q.warn("WebSocket requested reload"),this.fsmService.service.send(yt.RELOAD)}),C("/studio/project/reload",()=>{Q.warn("Project requested reload"),this.fsmService.service.send(yt.RELOAD)});const s=Tt.getInstance(),r=qg(),n=zg(),o=Kg();s.host=r,s.port=Number.parseInt(n),s.protocol=o,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Hg()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Bg(this),this.fsmService.service.send(yt.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var n,o,i,a;const e=Date.now();if(this._reloading){Q.info("reload already in progress");return}this._reloading=!0,Q.warn("reloading KOS Core"),Q.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Li(c.modelData)&&(Q.info(`reloading model ${c.modelId}`),(n=c.unload)==null||n.call(c),await c.modelData.reload(),(o=c.registerSubscribers)==null||o.call(c),Q.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Li(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{Q.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Q.debug("KOS Core going online"),await this._transport.whenReady(),Q.debug("KOS Transport Ready. Calling online() for models"),V("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Q.debug("KOS Core going offline"),V("/kosCore/offline","/kosCore/offline")}async unload(){var n;Q.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Q.debug("unloading KOS Core");const s=this.modelManager;for(const o of s.models)Gg(o.modelData)&&((n=o.unload)==null||n.call(o));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===sr.READY)}async ready(){Q.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(n=>({modelId:n.modelId,model:n,promise:n.whenReady()})),r=(await Promise.allSettled(e.map(n=>{const{promise:o,cancel:i}=Vg(5e3,n.model);Promise.race([n.promise.then(()=>{i()}),o])}))).filter(n=>n.status==="rejected");if(r.length)throw Q.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Q.debug("leaving kos-core ready() ")}get isReady(){return this.status===sr.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Q.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Q.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Q.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Q.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const n=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{$.dataMapper.registerDataMapper(u,p)}):$.dataMapper.registerDataMapper(u,d))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&$.propertyMapper.registerPropertyMapper(u,d)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&$.loader.registerLoader(u,d)}),A.model.getAll().forEach(([,u])=>{e.models={...e.models,...u.registration}}),e.models={...e.models,...A.model.getLegacyModels()},A.companion.getAll().forEach(([u,d])=>{e.companionModels={...e.companionModels},e.companionModels[u]=e.companionModels[u]||[];for(const h of d){let f;if(typeof h=="string"){const p=e.models[h];if(p!=null&&p.class){const y=p.class.prototype[He];f=y==null?void 0:y.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),A.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const o=fl.create(e,s);return n.modelManager=o,n}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function xn(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function Yg(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function Wg(t){return await t.arrayBuffer()}function Qg(t,e){return new Blob([t],{type:e})}async function Zg(t){const e={},s=[],r=[];t.forEach((n,o)=>{r.push([o,n])});for(const[n,o]of r)if(o instanceof File){const i=await o.arrayBuffer();s.push({name:n,filename:o.name,type:o.type,data:xn(i)})}else e[n]=o.toString();return{fields:e,files:s}}function Xg(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function Jg(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:xn(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await Wg(t);return{data:xn(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await Zg(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Gs=m.createLogger({name:"kos-fetch"}),em=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,tm=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),sm=t=>t!=null&&t.studio?Jc:t!=null&&t.fos?el:tl,rm=async(t,e)=>{const s=I.getInstance().transport;await s.whenReady();const r=ot(),n=new URL(t),o=`${n.pathname}${n.search}`;Gs.debug(`path: ${o}`);const i=(e==null?void 0:e.timeout)||em,a=sm(e),c=await Jg(e==null?void 0:e.body),u={};c.contentType&&(u["content-type"]=c.contentType),c.encoding&&(u["content-encoding"]=c.encoding);const d=Ve(a({path:o,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...u}}),c.data);return new Promise(h=>{let f=null,p=null;if(e!=null&&e.signal){if(e.signal.aborted){h({headers:Qt({}),status:0,ok:!1,json:async()=>null,body:Zt(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}});return}e.signal.addEventListener("abort",()=>{p&&clearTimeout(p),f&&f(),h({headers:Qt({}),status:0,ok:!1,json:async()=>null,body:Zt(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})})}p=setTimeout(()=>{Gs.error(`Timeout occurred - url: ${t}`),f&&f(),h({headers:Qt({}),status:404,ok:!1,json:async()=>null,body:Zt(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i);const y=C(r,E=>{p&&clearTimeout(p);const S=(E==null?void 0:E.headers)||{},L=S["content-type"]||"text/plain",P=S["content-encoding"],O=(E==null?void 0:E.body)||"";let _=O;if(P==="base64"&&O)try{_=Yg(O)}catch(q){Gs.error("Failed to decode base64 response",q)}const K={headers:Qt(S),status:S.status&&parseInt(S.status)||200,ok:S.status==="200",json:async()=>{try{if(typeof _=="string")return _.length?JSON.parse(_):null;{const J=new TextDecoder().decode(_);return J.length?JSON.parse(J):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof _=="string"?_:new TextDecoder().decode(_),arrayBuffer:async()=>_ instanceof ArrayBuffer?_:new TextEncoder().encode(_).buffer,blob:async()=>_ instanceof ArrayBuffer?Qg(_,L):new Blob([_],{type:L}),formData:async()=>{const q=new FormData;if(L==="multipart/form-data"&&typeof _=="string")try{const J=JSON.parse(_);J.fields&&Object.entries(J.fields).forEach(([zt,Vt])=>{q.append(zt,Vt)}),J.files&&Gs.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return q},body:e!=null&&e.stream?Xg(async q=>{if(_ instanceof ArrayBuffer)q.enqueue(new Uint8Array(_));else{const J=new TextEncoder;q.enqueue(J.encode(_))}q.close()}):Zt(typeof _=="string"?_:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};y.unsubscribe(),tm().then(()=>h(K))});f=y.unsubscribe;const w=e!=null&&e.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${e}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=rm;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const nm=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class om{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){nm.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(n=>{var o;(o=n.accept)==null||o.call(n,this)}))}}class gl{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const im=async(t,e)=>{const s=new gl;e.forEach(n=>s.use(n));const r={data:t,result:{}};return await s.execute(r),r.result},Ft=t=>({type:t,build:(e,s)=>I.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=I.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),am=t=>{I.getInstance().modelManager.registerModel(t)},cm=(t,e)=>{I.getInstance().modelManager.registerCompanionModel(t,e)},Fi="/kos/ui/internal/heartbeat/",lm=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:n})=>{const o=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=o.subscribeTopic({topic:`${Fi}${t}`,callback:()=>{a=performance.now()}}),u=r??3e3,d=window.setInterval(()=>{let w=performance.now()-a;w=w/1e3,w>u/1e3&&i.abort()},u),h=n??2e3,f=window.setInterval(()=>{cl({msg:{},options:{topic:`${Fi}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},y=()=>{p(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:p}},ml=(...t)=>e=>t.reduce((s,r)=>r(s),e),um={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function dm(t,e){let s=1;const r={...um,...e},{maxAttempts:n,baseDelayMs:o,backoffFactor:i}=r;let a=o;for(;s<=n;)try{return await t()}catch(c){if(m.error(`Attempt ${s} failed: ${c}`),s<n)a=o*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw c}throw new Error("All attempts failed")}const hm=m.createLogger({name:"kos-service-request"}),ae=t=>({isMock:!1,URL:exports.BASE_URL}),fm=(t,e,s)=>async({id:r,tracker:n,urlOverride:o,ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d})=>{const h={method:"DELETE"};t&&(h.destinationAddress=t),n&&(h.tracker=n),Nt(h,{ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d});const f=await s(o||`${e}/${r}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},Nt=(t,{ordered:e,studio:s,fos:r,destinationAddress:n,bridge:o,timeout:i})=>(i&&(t.timeout=i),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),o&&(t.bridge=o),(n||n==="")&&(t.destinationAddress=n),t),pm=(t,e,s)=>async({urlOverride:r,ordered:n,studio:o,fos:i,bridge:a,timeout:c,destinationAddress:u})=>{const d={method:"GET"};t&&(d.destinationAddress=t),Nt(d,{timeout:c,ordered:n,studio:o,fos:i,bridge:a,destinationAddress:u});const f=await s(r||e,d);if(!f.ok){let y;try{y=await f.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${f.status}`,y)}return await f.json()},gm=(t,e,s)=>async({urlOverride:r,ordered:n,studio:o,fos:i,bridge:a,tracker:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),c&&(h.tracker=c),Nt(h,{timeout:u,ordered:n,studio:o,fos:i,bridge:a,destinationAddress:d});const f=r||e;hm.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},mm=(t,e,s)=>async({urlOverride:r,id:n,ordered:o,studio:i,fos:a,bridge:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),Nt(h,{timeout:u,ordered:o,studio:i,fos:a,bridge:c,destinationAddress:d});const f=r||`${e}/${n}`,p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class ge extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Ni=(t,e,s)=>async({model:r,urlOverride:n,ordered:o,tracker:i,studio:a,fos:c,bridge:u,timeout:d,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(f.destinationAddress=t),i&&(f.tracker=i),Nt(f,{timeout:d,ordered:o,studio:a,fos:c,bridge:u,destinationAddress:h});const p=await s(n||e,f);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},Ui=(t="POST",e,s,r)=>async({model:n,id:o,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,destinationAddress:f})=>{const p={method:t};n&&(p.body=JSON.stringify(n)),e&&(p.destinationAddress=e),Nt(p,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,destinationAddress:f});const y=await r(i||`${s}/${o}`,p);if(!y.ok){let E;try{E=await y.json()}catch{}throw new ge(`There was a problem modifying the model; returned status ${y.status}`,E)}return await y.json()},ne={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:n,addModelPath:o,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:pm(t,s||e,c),getModelById:mm(t,r||e,c),getOne:gm(t,r||e,c),addModel:Ni(t,o||e,c),deleteModel:fm(t,n||e,c),modifyModel:Ui("POST",t,i||e,c),putModel:Ui("PUT",t,i||e,c),postModel:Ni(t,o||e,c)}}};function ym(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function bm(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function vm(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function wm(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function Em(t){const e=t.serviceResponses;e&&e.clear()}const Mm=ot(),yl=()=>`kos-${Mm}`,Tm=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(yl()),Mo=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:n}=C(t,i=>{D.debug(`recieved response for refId ${t}: ${i}`),n(),clearTimeout(o);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),o=setTimeout(()=>{n(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),Sm=async(t,e,s)=>{const r=Mo(s),n=await Promise.allSettled([t(e),r]);if(n[0].status==="fulfilled"){if(n[1].status==="rejected")throw Error(n[1].reason);if(n[0].value){if(n[1].value.error)throw Error(n[1].value.error);return n[0].value.data=n[1].value,n[0].value}}else throw Error(n[0].reason)},_m=async({topic:t,msg:e,requestId:s})=>{const r=s??ot(),n=Mo(r);V(t,e,{sync:r});const o=await n;if(o.error)throw Error(o.error);return o},he=new Map;class bl{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){X(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=Ie(this._parent))==null?void 0:e.model}get companionModels(){const e=Ie(this._id);return e!=null&&e.model?$c(e.model):[]}get(e){var s,r;if(this._context.has(e))return this._context.get(e);if(this.companionModels.length>0){const n=this.companionModels.find(o=>{var i;return!o.id||!he.has(o.id)?!1:(i=he.get(o.id))==null?void 0:i.context.has(e)});if(n)return(s=he.get(n.id))==null?void 0:s.get(e)}if(this._parent)return(r=he.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const Y={createContext:(t,e)=>{const s=he.get(t)??new bl(t);if(e){if(!he.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return he.set(t,s),s},getContext:t=>he.get(t),deleteContext:t=>{he.delete(t)},setParentContext:(t,e)=>{var s;if(!he.has(e))throw new Error(`Parent context ${e} does not exist`);(s=he.get(t))==null||s.setParent(e)},rootContext:()=>he.get("root")};Y.createContext("root");const Im=t=>Y.getContext(t.id),mn=m.createLogger({name:"kos-data-container"});class To{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,n)=>(r[n]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=_e(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new go({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}get revision(){return this._revision}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s))})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=M.isObservable(e)?e:M.observable.object(e),n=this._disposerMap.get(e.id);n&&(n(),this._disposerMap.delete(e.id)),this._data.set(r.id||"",r),s||this.increment();const o=M.observe(r,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(r.id||"",o)}removeModel(e){this._data.delete(e),this.increment();const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}updateModel(e){const s=M.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(mn.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(mn.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return mn.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class Om{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ie.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return Te(this.type)}}class $m{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ie.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return Te(this.type)}}class vl{constructor(){l(this,"_token");M.makeAutoObservable(this),C("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class wl{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const n=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:n})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(n=>!(n.method===e&&n.path===s)),this.openApiRoutes=this.openApiRoutes.filter(n=>!(n.method===e&&n.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:n,params:o}=this.extractPathParams(e.path),i={...e,params:o,query:n};for(const c of this.routes){const u=this.matchRoute(c.path,r);if(c.method===e.method&&u){i.params=u;let d=0;const h=async()=>{if(d<c.middlewares.length){const f=c.middlewares[d++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),n=this.parseQueryParams(r);for(const o of this.routes){const i=this.matchRoute(o.path,s);if(i)return{path:s,query:n,params:i}}return{path:s,query:n,params:{}}}matchRoute(e,s){const r=e.split("/").filter(Boolean),n=s.split("/").filter(Boolean);if(r.length!==n.length)return null;const o={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))o[r[i].slice(1)]=decodeURIComponent(n[i]);else if(r[i]!==n[i])return null;return o}parseQueryParams(e){return e?e.split("&").reduce((s,r)=>{const[n,o]=r.split("=").map(decodeURIComponent);return s[n]=o??"",s},{}):{}}}const El=m.createLogger({name:"intent-service"}),Cm=t=>{Xn(`/kos/intent/${t.type}`)?V(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):El.info(`No subscribers for intent ${t.type}. Intent not sent.`)},Dm=async t=>new Promise(e=>{const{type:s,options:r}=t;if(Xn(`/kos/intent/${t.type}`)){const n=ot(),{unsubscribe:o}=C(n,a=>{clearTimeout(i),o(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=n),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{o(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);V(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:n})}else El.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Ae=m.createLogger({name:"app-startup-service"});async function Ml(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:n=!1}=e;if(t.length===0)return Ae.warn("No app IDs provided to waitForAppsToStart"),!0;Ae.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const o=t.map(c=>`/kos/app/started/${c}`),i=await to(o,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>Zc),[u,d]=await c.get("/api/kos/apps/started");return u?(Ae.error("Error fetching started apps:",u),[]):d}catch(c){Ae.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(u=>{const d=c.find(h=>h.appId===u);return!(!d||!d.started||n&&!d.postStarted)}),timeout:s}),a=t.filter(c=>{const u=i.find(d=>d.appId===c);return!!(!u||!u.started||n&&!u.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(Ae.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return Ae.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(o){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Ae.error(i,o),r)throw new Error(`${i} - ${o instanceof Error?o.message:String(o)}`);return!1}}async function xm(t,e={}){return Ml([t],e)}async function Am(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const n=await r.json(),o=(n==null?void 0:n.data)??[];t.forEach(i=>{const a=o.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){Ae.error("Failed to check app startup status:",r),t.forEach(n=>s[n]=!1)}return s}async function Rm(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return Ae.error("Failed to fetch started apps:",t),[]}}const An=M.when,So=M.computed,X=M.runInAction,W=M.autorun,Tl=M.reaction,_o=M.observable,Io="Not Assigned",Pm="kos.trouble.added",km="kos.trouble.removed";var ve=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(ve||{}),ys=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(ys||{});const Sl=m.createLogger({name:"config-bean-service",group:"Services"}),Oo=exports.BASE_URL,_l=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:Lm,getOne:Fm}=ne.build({destinationAddress:"",basePath:`${Oo}/kos/config/`}),Il=async(t,e,s="/api/kos/config")=>(Sl.debug(`sending modify request for ConfigBean: ${t}`),Lm({model:e,urlOverride:`${Oo}${s}/${t}`})),Ol=async(t,e="/api/kos/config")=>(Sl.debug(`sending get request for ConfigBean: ${t}`),await Fm({urlOverride:`${Oo}${e}/details/${t}/15`})),$o=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",qr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function $l(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Cl(t,e="",s={}){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const n=e?`${e}.${r}`:r;typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])?Cl(t[r],n,s):s[n]=t[r]}return s}const Dl=(t,e)=>{const s=t.details[0].bean||$l(t.details[0].scopes),r=Cl(s);M.runInAction(()=>{const n={...r};e.props.setValues(n)})},xl=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let n=s.currentValue,o=s.previousValue;typeof n=="string"&&$o(n)&&(n=n.toLowerCase()=="true",o=(o==null?void 0:o.toLowerCase())=="true"),typeof n=="string"&&qr(n)&&(n=Number(n),o=Number(o)),e.props[r]=n,e.prevProps[r]=o})})},Al=t=>Object.fromEntries(t.props.entries),Nm=t=>e=>s=>t.build(e,s);var Um=Object.defineProperty,jm=Object.getOwnPropertyDescriptor,Rl=(t,e,s,r)=>{for(var n=r>1?void 0:r?jm(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Um(e,s,n),n};function Bm(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Co="config-bean-model",Ys=m.getLogger(Co),Hm=it("path");let ur=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=Il,getConfigBean:r=Ol}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=_e(),this.prevProps=_e()}get values(){return this.props.values}async ready(){Ys.debug(`readying config bean ${this.path}`),Ys.debug(`complete readying config bean ${this.path}`)}async load(){Ys.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;Dl(e,this),Ys.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;X(()=>{s&&(this._schema=s)})}}get schemaKeys(){var t;return Object.keys(((t=this._schema)==null?void 0:t.schema)||{})}getSchemaForProperty(t){var s,r;if(this.schemaKeys.includes(t))return(s=this._schema)==null?void 0:s.schema[t];const e=Bm(this.schemaKeys,t);if(e)return(r=this._schema)==null?void 0:r.schema[e]}async updateProperty(t,e){this.props[t]=e,await this.updateConfigBean()}async updateConfigBean(){const t=Al(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){xl(t,this)}};Rl([B({topic:`/kos/config/${Hm}`,websocket:!0})],ur.prototype,"handleConfigBeanUpdated",1);ur=Rl([R(Co)],ur);const ws=new ye({class:ur,type:Co}),zr=({path:t,lazy:e,serviceBasePath:s})=>(r,n)=>{r[N]=r[N]||{},r[N][n]={modelType:ws.type,id:`${ws.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:x.INIT,lazy:e}},{URL:Pl}=ae(),{getOne:Km,getAll:qm}=ne.build({basePath:`${Pl}/api/kos/regions/info`}),kl=async()=>{try{return await Km({})}catch{return}},Ll=async()=>{try{return await qm({urlOverride:`${Pl}/api/kos/regions`})}catch{return}},zm=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:kl,getRegions:Ll},Symbol.toStringTag,{value:"Module"}));var le=(t=>(t[t.family=0]="family",t[t.scale=1]="scale",t[t.offset=2]="offset",t[t.decimals=3]="decimals",t[t.alias=4]="alias",t[t.system=5]="system",t))(le||{});const Fl={s:["time",1,0,0],second:["time",1,0,0],m:["time",1/60,0,0],minute:["time",1/60,0,0],h:["time",1/3600,0,0],hour:["time",1/3600,0,0],day:["time",1/86400,0,0],week:["time",1/604800,0,0],month:["time",1/2628e3,0,0],year:["time",1/31536e3,0,0],default:["time",1/.001,0,0],ms:["time",1/.001,0,0],millisecond:["time",1/.001,0,0],microsecond:["time",1/1e-6,0,0],nanosecond:["time",1/1e-9,0,0],picosecond:["time",1/1e-12,0,0]};function Vm(t,e){const s=e.id,r=e.units.reduce((n,o)=>{const i=[o.measure,o.scale,o.offset,o.decimals,o.alias,s];return n[o.name]=i,o.alias&&(n[o.alias]=i),n},{...Fl});return{...t,...r}}function Gm(t,e){const s=e.id,r=e.units.reduce((n,o)=>{const i=n[o.measure]||{},a=i[s]||{};i[s]=a;const c=[o.measure,o.scale,o.offset,o.decimals,o.alias,s];return a[o.name]=c,Object.hasOwn(o,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),n[o.measure]=i,o.alias&&(n[o.alias]=i),n},{time:{[s]:{...Fl}}});return Object.keys(r).forEach(n=>{t[n]={...t[n],...r[n]}}),t}function Ym(t,e){const s=e.id,r=e.units.reduce((n,o)=>{const i=n[o.measure]||{};return Object.hasOwn(o,"default")&&(i[s]=o.name),n[o.measure]=i,n},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(n=>{t[n]={...t[n],...r[n]}}),t}var Wm=Object.defineProperty,Qm=Object.getOwnPropertyDescriptor,Do=(t,e,s,r)=>{for(var n=r>1?void 0:r?Qm(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Wm(e,s,n),n};const rr="region-info-model",Yt=m.createLogger({name:"region-info-model"});let Es=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[le.system]}getUnitMeasure(t){const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[le.family]}getDefaultUnitDecimalPlaces(t,e,s){if(!t||!e)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,n=this.measureMap[t];if(!n)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const o=n[e.toLowerCase()];if(!o)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(n).join(", ")}`);const i=o[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${t} and unit system: ${e}. Unit should come from list of units: ${Object.keys(o).join(", ")}`);return i[le.decimals]}getDefaultUnitForMeasure(t,e){if(!t||!e)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[t];if(!s)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[e.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(t,e,s){if(e[le.family]!==s[le.family])throw new Error(`Cannot convert between units of different families: ${e[le.family]} and ${s[le.family]}`);const r=e[le.offset],n=e[le.scale],o=s[le.scale],i=s[le.offset],a=s[le.decimals];return((t-r)/(n/o)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],n=this.unitSystemMap[s];if(!r||!n)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,n)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",n=s.unit||"";let o=this.unitSystemMap[r],i=this.unitSystemMap[n];if(!i&&s.measure&&s.system){const u=this.measureMap[s.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=u[s.system])==null?void 0:a.default,i||Yt.info("Could not find default unit for measure",s.measure)}if(!o&&e.measure&&e.system){const u=this.measureMap[e.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);o=(c=u[e.system])==null?void 0:c.default,o||Yt.info("Could not find default unit for measure",e.measure)}return!o||!i?(Yt.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,o,i)}async init(){Yt.debug("initializing region info")}async load(){Yt.debug("loading region info");const t=await Ll();t&&(this.regions=t.data.map(s=>s.id),this.timeZoneMap=t.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=t.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const e=await kl();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const n={id:r.id,name:r.id};return s[r.id]=n,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(Vm,{}),this.measureMap=e.data.unitSystems.reduce(Gm,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(Ym,{}),this.timeFormats=e.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=e.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var t,e;await((e=(t=this.regionSource).ready)==null?void 0:e.call(t))}};Do([zr({path:"kos:service:region:settings"})],Es.prototype,"regionSource",2);Do([zr({path:"kos:service:region"})],Es.prototype,"region",2);Es=Do([R(rr)],Es);const re={registration:{[rr]:{class:Es,singleton:!0}},type:rr,factory:ie.Singleton.create(rr)},dr=({source:t,defaultSystem:e="si",defaultMeasure:s})=>{let r={system:e,measure:s};return typeof t=="string"?r={...r,unit:t}:r={...r,...t},r},xo=(t,e,s)=>{const{model:r}=Ie(re.type);if(!r)throw new Error("RegionInfo model not found");if(!lr(r))throw new Error("RegionInfo model not ready");const n={system:r.defaultUnitSystem},o=dr({source:e}),i=dr({source:s||n,defaultMeasure:r.getUnitMeasure(o.unit||"")});return r.convert(t,o,i)};function ji(t,e,s){const r=e.toLowerCase().replace(/_/g,"-").replace(/s$/,""),n=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const o=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(n,{style:"unit",unit:r,unitDisplay:o,minimumFractionDigits:a,maximumFractionDigits:i}).format(t)}catch{return e}}const Zm=(t,e,s,r)=>{const n=xo(t,e,s),o=dr({source:e}),{model:i}=Ie(re.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(o.unit||""),c={system:i.defaultUnitSystem},u=dr({source:s||c,defaultMeasure:i.getUnitMeasure(o.unit||"")}),d=i.getDefaultUnitForMeasure(a,u.system),h=i.getDefaultUnitDecimalPlaces(a,u.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:n,unit:d||o.unit||"",display:ji(n,d||o.unit||"",{...f,mode:"long"}),shortDisplay:ji(n,d||o.unit||"",{...f,mode:"short"})}};function Bi({start:t,end:e,count:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(t>=e)throw new Error("Start should be less than end.");const n=(e-t)/(s-1),o=[];for(let i=0;i<s;i++){const a=Math.round(t+i*n);o.push(a.toFixed(r))}return o}function Hi({start:t,end:e,interval:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(t>=e)throw new Error("Start should be less than end.");const n=[];let o=t;for(;o<=e;)n.push(o.toFixed(r)),o+=s;return n[n.length-1]!==e.toString()&&n.push(e.toString()),n}const ft=(t,e)=>s=>!t||!e?s:qr(s)?xo(Number(s),t,e):s,Xm=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Bi(t.options).map(ft(s,r));if(t.options.type==="rangeInterval")return Hi(t.options).map(ft(s,r));if(t.options.type==="list"){const{list:n}=t.options;return n.map(ft(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Bi(t.options.unitSystems[e]).map(ft(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Hi(t.options.unitSystems[e]).map(ft(s,r));if(t.options.type==="unitSystemList"&&e){const{list:n}=t.options.unitSystems[e];return n.map(ft(s,r))}}return[]},Jm=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var ey=Object.defineProperty,ty=Object.getOwnPropertyDescriptor,Ao=(t,e,s,r)=>{for(var n=r>1?void 0:r?ty(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&ey(e,s,n),n};function sy(t){return(t==null?void 0:t.type)==="enum"}function ry(t){switch(t){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return t}}function ny(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return je.format(r,e)}const nr="config-bean-prop-model",pt=m.createLogger({name:"config-bean-prop-model"}),oy=it("path"),iy=it("serviceBasePath");let Ms=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return _l(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(t,e,s)}getDefaultUnitForMeasure(t,e){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(t,e)}get schemaType(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.type?t.type:"String"}get schemaFormat(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.format?ry(t.format):""}get options(){var i;const t=this.regionInfo.defaultUnitSystem,e=this.getConverter(),s=((i=e==null?void 0:e.to)==null?void 0:i.system)??t,r=this.bean.getSchemaForProperty(this.attribute),n=sy(r)?r.values:Xm(r,s,e==null?void 0:e.from,e==null?void 0:e.to),o=n.length>0?n.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,n):this.optionsExpander:o}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,n=(t==null?void 0:t.system)||e,o=t==null?void 0:t.unit;return{measure:r,system:n,unit:o}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),n=this.convertUnit(e.to,t,s);return{backend:r,display:n}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var n,o;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((n=s==null?void 0:s.to)==null?void 0:n.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(o=s==null?void 0:s.to)==null?void 0:o.unit);try{const c=this.getFormatterOptions(s);if(c){let u=String(t);return u=c.formatToParts(Number(t))[0].value,Number(u)}}catch(c){pt.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:n}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,n)}return e||""}async activate(){pt.debug(`activating config bean ${this.id}`)}get displayValue(){const t=this.value;if(typeof t=="boolean")return String(t);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return ny(t,s)}if(!isNaN(t))try{const e=this.getConverter(),s=this.getFormatterOptions(e);if(s){let r=String(t);return r=s.format(Number(t)),r}}catch(e){pt.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(n=>n.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var n;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((n=s==null?void 0:s.to)==null?void 0:n.system)??e;return Jm(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,n;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((n=t==null?void 0:t.to)==null?void 0:n.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var o,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let n=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,u=this.formatter||c;if(u){let d=typeof u=="function"?u(((o=t==null?void 0:t.to)==null?void 0:o.system)||e):u;s&&(d={unit:this.getDefaultUnit(t),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{n=new Intl.NumberFormat(r,{...d})}catch(h){pt.error(`error creating formatter ${d}. Returning the raw value`,h)}}else pt.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return n}getConverter(){var r,n,o,i,a,c,u,d,h,f,p;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const y=(r=this.converter)==null?void 0:r.measure,w=(o=(n=this.converter)==null?void 0:n.to)==null?void 0:o.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,S=y||w||E||e,L=((u=(c=this.converter)==null?void 0:c.to)==null?void 0:u.unit)||this.regionInfo.getDefaultUnitForMeasure(S,((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),P=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(L),O=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:O,...this.converter.from},to:{...this.converter.to,unit:L,system:P},measure:S}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:w===E?s:y}}}}async updateProperty(t){pt.debug(`updating property ${this.attribute} with value ${t}`);let e=t;if(this.getConverter()&&!isNaN(e)){const{backend:n,display:o}=this.getConverterUnits();e=this.regionInfo.convert(Number(e),o,n)}const r=Array.isArray(e)?JSON.stringify(e):String(e);await this.bean.updateProperty(this.attribute,r)}};Ao([Lt({modelType:re.type})],Ms.prototype,"regionInfo",2);Ao([zr({path:oy,serviceBasePath:iy})],Ms.prototype,"bean",2);Ms=Ao([R(nr)],Ms);const at={registration:{[nr]:{class:Ms,singleton:!1}},type:nr,factory:ie.Factory.create(nr)};function ay(t){const{path:e,attribute:s,converter:r,formatter:n,lazy:o,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(u,d)=>{u[N]=u[N]||{},u[N][d]={modelType:at.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:n,optionsExpander:i},lifecycle:x.INIT,lazy:o}}}const Nl="future-model",Ut=Ft(Nl),Vr=m.createLogger({name:"future-service",group:"Services"}),{isMock:cy,URL:Fs}=ae();var Ke=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(Ke||{});const{getAll:ly,modifyModel:uy,addModel:dy,deleteModel:hy,postModel:fy}=ne.build({destinationAddress:"",basePath:`${Fs}/api/future`,mock:cy}),py=async()=>await ly({}),Ul=async(t,e="/api/kos/future")=>(Vr.info(`sending delete request for Future: ${t}`),await hy({id:t,urlOverride:`${Fs}${e}/${t}`})),jl=async(t,e="/api/kos/future")=>(Vr.info("sending add request for Future"),await dy({model:t,urlOverride:`${Fs}${e}`})),gy=async(t,e,s="/api/kos/future")=>(Vr.info(`sending modify request for Future: ${t}`),uy({model:e,id:t,urlOverride:`${Fs}${s}/${t}`})),Bl=async(t,e="/api/kos/future")=>(Vr.info(`sending cancel request for Future: ${t}`),fy({urlOverride:`${Fs}${e}/${t}/cancel`,ordered:!0,model:{}})),Ro=t=>({id:String(t.id),progress:t.progress,remainingTimeMs:t.remainingTimeMs,endState:t.endState,reason:t.reason,clientData:t.clientData,reasonData:t.reasonData,note:t.note,tracker:t.tracker}),Po=(t,e)=>{m.debug(`future dto ${t.id} end state ${t.endState}`),m.debug(`future model ${e.id} end state ${e.endState}`),e.endState?m.debug(`future model ${e.id} is already complete`):(m.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=Ro(t);X(()=>{Object.keys(s).forEach(r=>{r==="id"?(e.futureId=s.id,s.tracker||(e.id=s.id)):r==="tracker"?e.id=s.tracker:e[r]=s[r]})})}))},Hl=t=>e=>s=>t.build(String(e),s),ko=t=>e=>ml(Ro,Hl(t)(e.tracker||e.id))(e);var my=Object.defineProperty,yy=Object.getOwnPropertyDescriptor,Kl=(t,e,s,r)=>{for(var n=r>1?void 0:r?yy(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&my(e,s,n),n};const yn=m.getLogger(Ut.type);let hr=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=Bl,An(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{yn.info(`Future ${this.id} has completed with status ${this.status}`),st(this)})}async load(){yn.debug(`loading Future ${this.id}`)}unload(){yn.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await An(()=>this.futureId!==Io),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[u,d]of Object.entries(e))if(Math.abs(t)>=d){s=u,r=Math.round(t/d);break}const o=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return o.length===3?`${((a=o[1])==null?void 0:a.value)??0} ${((c=o[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),Po(t,this)}};Kl([B({topic:`kos.future/${ir}`})],hr.prototype,"handleFutureUpdated",1);hr=Kl([R(Ut.type)],hr);const ql=hr,zl=wo();var by=Object.defineProperty,vy=Object.getOwnPropertyDescriptor,Vl=(t,e,s,r)=>{for(var n=r>1?void 0:r?vy(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&by(e,s,n),n};const Gl="browser-router-model",wy="kos.http.request",Ey="kos.http.response";let fr=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new wl}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],n=e.headers.url,o=e.headers.method,i=e.headers["request-id"],a={id:i,method:o,path:n,body:t};let c=200;const u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),ll({msg:d,options:{responseId:i,destinationAddress:s,type:Ey,sourceAddress:r,status:c}})},status:function(d){return c=d,this}};if(a.path==="/openapi.json"){u.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,u)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};Vl([B({topic:wy})],fr.prototype,"handleRequest",1);fr=Vl([R(Gl)],fr);const Lo=new Se({class:fr,type:Gl}),Yl="future-container-model",qe=Ft(Yl),Wl=t=>ko(Ut)(t),My=t=>{const e=Wl(t);return qe.build(qe.type,{}).addFutureModel(e),e},Ty=t=>qe.build(qe.type,{}).getFuture(String(t)),rt={buildFutureModel:Wl,initiateFuture:My,getFuture:Ty};var Sy=Object.defineProperty,_y=Object.getOwnPropertyDescriptor,Fo=(t,e,s,r)=>{for(var n=r>1?void 0:r?_y(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Sy(e,s,n),n};const Ws=m.getLogger(qe.type);let Ts=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=Ul,addFuture:n=jl}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=n,this.id=t,this._futures=new Ce,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){Ws.error("error deleting a Future"),Ws.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=ko(Ut)(s);return this.addFutureModel(r),r}}catch(e){throw Ws.error("error creating a Future"),Ws.error(e),e}}handleFutureUpdated(t,e){const s=rt.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),V(r,e.body,e.headers)}};Fo([$e],Ts.prototype,"_futures",2);Fo([B({topic:"kos.future"})],Ts.prototype,"handleFutureUpdated",1);Ts=Fo([R(qe.type)],Ts);const Ql=Ts,{URL:Ns}=ae(),{getOne:Iy,postModel:Oy,deleteModel:Zl}=ne.build({basePath:`${Ns}/api/keyVal`}),Rn=m.createLogger({name:"key-value-service",group:"Services"}),Xl=async(t,e)=>{await Zl({urlOverride:`${Ns}/api/keyVal/${t}/${e}`,id:e})},Jl=async(t,e,s)=>{const r=await Oy({urlOverride:`${Ns}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Rn.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},eu=async(t="studio")=>{Rn.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await Iy({urlOverride:`${Ns}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Rn.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},$y=async t=>{await Zl({urlOverride:`${Ns}/api/keyVal/${t}`,id:""})},Cy=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Xl,deleteKeyValueNamespace:$y,getKeyValue:eu,updateKeyValue:Jl},Symbol.toStringTag,{value:"Module"}));var Dy=Object.defineProperty,xy=Object.getOwnPropertyDescriptor,No=(t,e,s,r)=>{for(var n=r>1?void 0:r?xy(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Dy(e,s,n),n};const tu="key-value-model";let Ss=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=_e(),this.namespace=e.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(t,e){this.logger.debug(`updating studio-state ${t} with value ${e}`),e!==void 0?(await Jl(this.namespace,t,e),this.data[t]=e):(await Xl(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await eu(this.namespace);this.data.setValues(t)}handleStateUpdate(t){t.namespace===this.namespace&&(this.data[t.key]=t.value)}handleStateDelete(t){t.namespace===this.namespace&&(this.data[t.key]=void 0)}};No([B({topic:"/keyVal/set"})],Ss.prototype,"handleStateUpdate",1);No([B({topic:"/keyVal/remove"})],Ss.prototype,"handleStateDelete",1);Ss=No([R(tu)],Ss);const Uo=new ye({class:Ss,type:tu});var fe="INUMBER",jt="IOP1",Bt="IOP2",Ht="IOP3",Pe="IVAR",nt="IVARNAME",St="IFUNCALL",Gr="IFUNDEF",oe="IEXPR",jo="IEXPREVAL",ct="IMEMBER",Yr="IENDSTATEMENT",_t="IARRAY";function k(t,e){this.type=t,this.value=e??0}k.prototype.toString=function(){switch(this.type){case fe:case jt:case Bt:case Ht:case Pe:case nt:case Yr:return this.value;case St:return"CALL "+this.value;case Gr:return"DEF "+this.value;case _t:return"ARRAY "+this.value;case ct:return"."+this.value;default:return"Invalid Instruction"}};function Wr(t){return new k(jt,t)}function Ue(t){return new k(Bt,t)}function su(t){return new k(Ht,t)}function Pn(t,e,s,r,n){for(var o=[],i=[],a,c,u,d,h=0;h<t.length;h++){var f=t[h],p=f.type;if(p===fe||p===nt)Array.isArray(f.value)?o.push.apply(o,Pn(f.value.map(function(y){return new k(fe,y)}).concat(new k(_t,f.value.length)),e,s,r,n)):o.push(f);else if(p===Pe&&n.hasOwnProperty(f.value))f=new k(fe,n[f.value]),o.push(f);else if(p===Bt&&o.length>1)c=o.pop(),a=o.pop(),d=s[f.value],f=new k(fe,d(a.value,c.value)),o.push(f);else if(p===Ht&&o.length>2)u=o.pop(),c=o.pop(),a=o.pop(),f.value==="?"?o.push(a.value?c.value:u.value):(d=r[f.value],f=new k(fe,d(a.value,c.value,u.value)),o.push(f));else if(p===jt&&o.length>0)a=o.pop(),d=e[f.value],f=new k(fe,d(a.value)),o.push(f);else if(p===oe){for(;o.length>0;)i.push(o.shift());i.push(new k(oe,Pn(f.value,e,s,r,n)))}else if(p===ct&&o.length>0)a=o.pop(),o.push(new k(fe,a.value[f.value]));else{for(;o.length>0;)i.push(o.shift());i.push(f)}}for(;o.length>0;)i.push(o.shift());return i}function ru(t,e,s){for(var r=[],n=0;n<t.length;n++){var o=t[n],i=o.type;if(i===Pe&&o.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===jt?u=Wr(c.value):c.type===Bt?u=Ue(c.value):c.type===Ht?u=su(c.value):u=new k(c.type,c.value),r.push(u)}else i===oe?r.push(new k(oe,ru(o.value,e,s))):r.push(o)}return r}function Ze(t,e,s){var r=[],n,o,i,a,c,u;if(Bo(t))return xe(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===fe||p===nt)r.push(f.value);else if(p===Bt)o=r.pop(),n=r.pop(),f.value==="and"?r.push(n?!!Ze(o,e,s):!1):f.value==="or"?r.push(n?!0:!!Ze(o,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(n,Ze(o,e,s),s))):(a=e.binaryOps[f.value],r.push(a(xe(n,s),xe(o,s))));else if(p===Ht)i=r.pop(),o=r.pop(),n=r.pop(),f.value==="?"?r.push(Ze(n?o:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(xe(n,s),xe(o,s),xe(i,s))));else if(p===Pe)if(f.value in e.functions)r.push(e.functions[f.value]);else if(f.value in e.unaryOps&&e.parser.isOperatorEnabled(f.value))r.push(e.unaryOps[f.value]);else{var y=s[f.value];if(y!==void 0)r.push(y);else throw new Error("undefined variable: "+f.value)}else if(p===jt)n=r.pop(),a=e.unaryOps[f.value],r.push(a(xe(n,s)));else if(p===St){for(u=f.value,c=[];u-- >0;)c.unshift(xe(r.pop(),s));if(a=r.pop(),a.apply&&a.call)r.push(a.apply(void 0,c));else throw new Error(a+" is not a function")}else if(p===Gr)r.push(function(){for(var w=r.pop(),E=[],S=f.value;S-- >0;)E.unshift(r.pop());var L=r.pop(),P=function(){for(var O=Object.assign({},s),_=0,K=E.length;_<K;_++)O[E[_]]=arguments[_];return Ze(w,e,O)};return Object.defineProperty(P,"name",{value:L,writable:!1}),s[L]=P,P}());else if(p===oe)r.push(Ay(f,e));else if(p===jo)r.push(f);else if(p===ct)n=r.pop(),r.push(n[f.value]);else if(p===Yr)r.pop();else if(p===_t){for(u=f.value,c=[];u-- >0;)c.unshift(r.pop());r.push(c)}else throw new Error("invalid Expression")}if(r.length>1)throw new Error("invalid Expression (parity)");return r[0]===0?0:xe(r[0],s)}function Ay(t,e,s){return Bo(t)?t:{type:jo,value:function(r){return Ze(t.value,e,r)}}}function Bo(t){return t&&t.type===jo}function xe(t,e){return Bo(t)?t.value(e):t}function Ho(t,e){for(var s=[],r,n,o,i,a,c,u=0;u<t.length;u++){var d=t[u],h=d.type;if(h===fe)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Ki).join(", ")+"]"):s.push(Ki(d.value));else if(h===Bt)n=s.pop(),r=s.pop(),i=d.value,e?i==="^"?s.push("Math.pow("+r+", "+n+")"):i==="and"?s.push("(!!"+r+" && !!"+n+")"):i==="or"?s.push("(!!"+r+" || !!"+n+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+n+")))"):i==="=="?s.push("("+r+" === "+n+")"):i==="!="?s.push("("+r+" !== "+n+")"):i==="["?s.push(r+"[("+n+") | 0]"):s.push("("+r+" "+i+" "+n+")"):i==="["?s.push(r+"["+n+"]"):s.push("("+r+" "+i+" "+n+")");else if(h===Ht)if(o=s.pop(),n=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+n+" : "+o+")");else throw new Error("invalid Expression");else if(h===Pe||h===nt)s.push(d.value);else if(h===jt)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):e?i==="not"?s.push("(!"+r+")"):i==="!"?s.push("fac("+r+")"):s.push(i+"("+r+")"):i==="!"?s.push("("+r+"!)"):s.push("("+i+" "+r+")");else if(h===St){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===Gr){for(n=s.pop(),c=d.value,a=[];c-- >0;)a.unshift(s.pop());r=s.pop(),e?s.push("("+r+" = function("+a.join(", ")+") { return "+n+" })"):s.push("("+r+"("+a.join(", ")+") = "+n+")")}else if(h===ct)r=s.pop(),s.push(r+"."+d.value);else if(h===_t){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===oe)s.push("("+Ho(d.value,e)+")");else if(h!==Yr)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Ki(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function vt(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function Ko(t,e,s){s=s||{};for(var r=!!s.withMembers,n=null,o=0;o<t.length;o++){var i=t[o];i.type===Pe||i.type===nt?!r&&!vt(e,i.value)?e.push(i.value):(n!==null&&(vt(e,n)||e.push(n)),n=i.value):i.type===ct&&r&&n!==null?n+="."+i.value:i.type===oe?Ko(i.value,e,s):n!==null&&(vt(e,n)||e.push(n),n=null)}n!==null&&!vt(e,n)&&e.push(n)}function we(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}we.prototype.simplify=function(t){return t=t||{},new we(Pn(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};we.prototype.substitute=function(t,e){return e instanceof we||(e=this.parser.parse(String(e))),new we(ru(this.tokens,t,e),this.parser)};we.prototype.evaluate=function(t){return t=t||{},Ze(this.tokens,this,t)};we.prototype.toString=function(){return Ho(this.tokens,!1)};we.prototype.symbols=function(t){t=t||{};var e=[];return Ko(this.tokens,e,t),e};we.prototype.variables=function(t){t=t||{};var e=[];Ko(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};we.prototype.toJSFunction=function(t,e){var s=this,r=new Function(t,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+Ho(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var _s="TEOF",j="TOP",Qr="TNUMBER",nu="TSTRING",ke="TPAREN",It="TBRACKET",Zr="TCOMMA",qo="TNAME",zo="TSEMICOLON";function ou(t,e,s){this.type=t,this.value=e,this.index=s}ou.prototype.toString=function(){return this.type+": "+this.value};function G(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}G.prototype.newToken=function(t,e,s){return new ou(t,e,s??this.pos)};G.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};G.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};G.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(_s,"EOF");if(this.isWhitespace()||this.isComment())return this.next();if(this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName())return this.current;this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')};G.prototype.isString=function(){var t=!1,e=this.pos,s=this.expression.charAt(e);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,e+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var n=this.expression.substring(e+1,r);this.current=this.newToken(nu,this.unescape(n),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};G.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(ke,t),this.pos++,!0):!1};G.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(It,t),this.pos++,!0):!1};G.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(Zr,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(zo,";"),this.pos++,!0):!1};G.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(r in this.consts)return this.current=this.newToken(Qr,this.consts[r]),this.pos+=r.length,!0}return!1};G.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(j,r),this.pos+=r.length,!0}return!1};G.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var n=this.expression.substring(t,e);return this.current=this.newToken(qo,n),this.pos+=n.length,!0}return!1};G.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
78
- `||e==="\r")&&(t=!0,this.pos++,!(this.pos>=this.expression.length));)e=this.expression.charAt(this.pos);return t};var Ry=/^[0-9a-f]{4}$/i;G.prototype.unescape=function(t){var e=t.indexOf("\\");if(e<0)return t;for(var s=t.substring(0,e);e>=0;){var r=t.charAt(++e);switch(r){case"'":s+="'";break;case'"':s+='"';break;case"\\":s+="\\";break;case"/":s+="/";break;case"b":s+="\b";break;case"f":s+="\f";break;case"n":s+=`
79
- `;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var n=t.substring(e+1,e+5);Ry.test(n)||this.parseError("Illegal escape sequence: \\u"+n),s+=String.fromCharCode(parseInt(n,16)),e+=4;break;default:throw this.parseError('Illegal escape sequence: "\\'+r+'"')}++e;var o=t.indexOf("\\",e);s+=t.substring(e,o<0?t.length:o),e=o}return s};G.prototype.isComment=function(){var t=this.expression.charAt(this.pos);return t==="/"&&this.expression.charAt(this.pos+1)==="*"?(this.pos=this.expression.indexOf("*/",this.pos)+2,this.pos===1&&(this.pos=this.expression.length),!0):!1};G.prototype.isRadixInteger=function(){var t=this.pos;if(t>=this.expression.length-2||this.expression.charAt(t)!=="0")return!1;++t;var e,s;if(this.expression.charAt(t)==="x")e=16,s=/^[0-9a-f]$/i,++t;else if(this.expression.charAt(t)==="b")e=2,s=/^[01]$/i,++t;else return!1;for(var r=!1,n=t;t<this.expression.length;){var o=this.expression.charAt(t);if(s.test(o))t++,r=!0;else break}return r&&(this.current=this.newToken(Qr,parseInt(this.expression.substring(n,t),e)),this.pos=t),r};G.prototype.isNumber=function(){for(var t=!1,e=this.pos,s=e,r=e,n=!1,o=!1,i;e<this.expression.length&&(i=this.expression.charAt(e),i>="0"&&i<="9"||!n&&i===".");)i==="."?n=!0:o=!0,e++,t=o;if(t&&(r=e),i==="e"||i==="E"){e++;for(var a=!0,c=!1;e<this.expression.length;){if(i=this.expression.charAt(e),a&&(i==="+"||i==="-"))a=!1;else if(i>="0"&&i<="9")c=!0,a=!1;else break;e++}c||(e=r)}return t?(this.current=this.newToken(Qr,parseFloat(this.expression.substring(s,e))),this.pos=e):this.pos=r,t};G.prototype.isOperator=function(){var t=this.pos,e=this.expression.charAt(this.pos);if(e==="+"||e==="-"||e==="*"||e==="/"||e==="%"||e==="^"||e==="?"||e===":"||e===".")this.current=this.newToken(j,e);else if(e==="∙"||e==="•")this.current=this.newToken(j,"*");else if(e===">")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,">="),this.pos++):this.current=this.newToken(j,">");else if(e==="<")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"<="),this.pos++):this.current=this.newToken(j,"<");else if(e==="|")if(this.expression.charAt(this.pos+1)==="|")this.current=this.newToken(j,"||"),this.pos++;else return!1;else if(e==="=")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"=="),this.pos++):this.current=this.newToken(j,e);else if(e==="!")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"!="),this.pos++):this.current=this.newToken(j,e);else return!1;return this.pos++,this.isOperatorEnabled(this.current.value)?!0:(this.pos=t,!1)};G.prototype.isOperatorEnabled=function(t){return this.parser.isOperatorEnabled(t)};G.prototype.getCoordinates=function(){var t=0,e,s=-1;do t++,e=this.pos-s,s=this.expression.indexOf(`
80
- `,s+1);while(s>=0&&s<this.pos);return{line:t,column:e}};G.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)};function H(t,e,s){this.parser=t,this.tokens=e,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}H.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};H.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?vt(e,t.value):typeof e=="function"?e(t):t.value===e};H.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};H.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};H.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};H.prototype.expect=function(t,e){if(!this.accept(t,e)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(e||t))}};H.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.accept(qo)||this.accept(j,s))t.push(new k(Pe,this.current.value));else if(this.accept(Qr))t.push(new k(fe,this.current.value));else if(this.accept(nu))t.push(new k(fe,this.current.value));else if(this.accept(ke,"("))this.parseExpression(t),this.expect(ke,")");else if(this.accept(It,"["))if(this.accept(It,"]"))t.push(new k(_t,0));else{var r=this.parseArrayList(t);t.push(new k(_t,r))}else throw new Error("unexpected "+this.nextToken)};H.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};H.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};H.prototype.parseUntilEndStatement=function(t,e){return this.accept(zo)?(this.nextToken&&this.nextToken.type!==_s&&!(this.nextToken.type===ke&&this.nextToken.value===")")&&e.push(new k(Yr)),this.nextToken.type!==_s&&this.parseExpression(e),t.push(new k(oe,e)),!0):!1};H.prototype.parseArrayList=function(t){for(var e=0;!this.accept(It,"]");)for(this.parseExpression(t),++e;this.accept(Zr);)this.parseExpression(t),++e;return e};H.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(j,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===St){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var n=0,o=e.value+1;n<o;n++){var i=r-n;t[i].type===Pe&&(t[i]=new k(nt,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new k(oe,s)),t.push(new k(Gr,e.value));continue}if(e.type!==Pe&&e.type!==ct)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new k(nt,e.value)),t.push(new k(oe,s)),t.push(Ue("="))}};H.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(j,"?");){var e=[],s=[];this.parseConditionalExpression(e),this.expect(j,":"),this.parseConditionalExpression(s),t.push(new k(oe,e)),t.push(new k(oe,s)),t.push(su("?"))}};H.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(j,"or");){var e=[];this.parseAndExpression(e),t.push(new k(oe,e)),t.push(Ue("or"))}};H.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(j,"and");){var e=[];this.parseComparison(e),t.push(new k(oe,e)),t.push(Ue("and"))}};var Py=["==","!=","<","<=",">=",">","in"];H.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,Py);){var e=this.current;this.parseAddSub(t),t.push(Ue(e.value))}};var ky=["+","-","||"];H.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(j,ky);){var e=this.current;this.parseTerm(t),t.push(Ue(e.value))}};var Ly=["*","/","%"];H.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,Ly);){var e=this.current;this.parseFactor(t),t.push(Ue(e.value))}};H.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.save(),this.accept(j,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===ke&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===zo||this.nextToken.type===Zr||this.nextToken.type===_s||this.nextToken.type===ke&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(Wr(r.value))}else this.parseExponential(t)};H.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(j,"^");)this.parseFactor(t),t.push(Ue("^"))};H.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(j,"!");)t.push(Wr("!"))};H.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.accept(j,s)){var r=this.current;this.parseAtom(t),t.push(Wr(r.value))}else for(this.parseMemberExpression(t);this.accept(ke,"(");)if(this.accept(ke,")"))t.push(new k(St,0));else{var n=this.parseArgumentList(t);t.push(new k(St,n))}};H.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(ke,")");)for(this.parseExpression(t),++e;this.accept(Zr);)this.parseExpression(t),++e;return e};H.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(j,".")||this.accept(It,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(qo),t.push(new k(ct,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(It,"]"),t.push(Ue("["))}else throw new Error("unexpected symbol: "+e.value)}};function Fy(t,e){return Number(t)+Number(e)}function Ny(t,e){return t-e}function Uy(t,e){return t*e}function jy(t,e){return t/e}function By(t,e){return t%e}function Hy(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function Ky(t,e){return t===e}function qy(t,e){return t!==e}function zy(t,e){return t>e}function Vy(t,e){return t<e}function Gy(t,e){return t>=e}function Yy(t,e){return t<=e}function Wy(t,e){return!!(t&&e)}function Qy(t,e){return!!(t||e)}function Zy(t,e){return vt(e,t)}function Xy(t){return(Math.exp(t)-Math.exp(-t))/2}function Jy(t){return(Math.exp(t)+Math.exp(-t))/2}function eb(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function tb(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function sb(t){return Math.log(t+Math.sqrt(t*t-1))}function rb(t){return Math.log((1+t)/(1-t))/2}function qi(t){return Math.log(t)*Math.LOG10E}function nb(t){return-t}function ob(t){return!t}function ib(t){return t<0?Math.ceil(t):Math.floor(t)}function ab(t){return Math.random()*(t||1)}function zi(t){return Vo(t+1)}function cb(t){return isFinite(t)&&t===Math.round(t)}var lb=4.7421875,bn=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function Vo(t){var e,s;if(cb(t)){if(t<=0)return isFinite(t)?1/0:NaN;if(t>171)return 1/0;for(var r=t-2,n=t-1;r>1;)n*=r,r--;return n===0&&(n=1),n}if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*Vo(1-t));if(t>=171.35)return 1/0;if(t>85){var o=t*t,i=o*t,a=i*t,c=a*t;return Math.sqrt(2*Math.PI/t)*Math.pow(t/Math.E,t)*(1+1/(12*t)+1/(288*o)-139/(51840*i)-571/(2488320*a)+163879/(209018880*c)+5246819/(75246796800*c*t))}--t,s=bn[0];for(var u=1;u<bn.length;++u)s+=bn[u]/(t+u);return e=t+lb+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function ub(t){return Array.isArray(t)?t.length:String(t).length}function Vi(){for(var t=0,e=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),n;e<r?(n=e/r,t=t*n*n+1,e=r):r>0?(n=r/e,t+=n*n):t+=r}return e===1/0?1/0:e*Math.sqrt(t)}function Gi(t,e,s){return t?e:s}function db(t,e){return typeof e>"u"||+e==0?Math.round(t):(t=+t,e=-+e,isNaN(t)||!(typeof e=="number"&&e%1===0)?NaN:(t=t.toString().split("e"),t=Math.round(+(t[0]+"e"+(t[1]?+t[1]-e:-e))),t=t.toString().split("e"),+(t[0]+"e"+(t[1]?+t[1]+e:e))))}function hb(t,e,s){return s&&(s[t]=e),e}function fb(t,e){return t[e|0]}function pb(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function gb(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function mb(t,e){if(typeof t!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(e))throw new Error("Second argument to map is not an array");return e.map(function(s,r){return t(s,r)})}function yb(t,e,s){if(typeof t!="function")throw new Error("First argument to fold is not a function");if(!Array.isArray(s))throw new Error("Second argument to fold is not an array");return s.reduce(function(r,n,o){return t(r,n,o)},e)}function bb(t,e){if(typeof t!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(e))throw new Error("Second argument to filter is not an array");return e.filter(function(s,r){return t(s,r)})}function vb(t,e){if(!(Array.isArray(e)||typeof e=="string"))throw new Error("Second argument to indexOf is not a string or array");return e.indexOf(t)}function wb(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function Eb(t){return(t>0)-(t<0)||+t}var Yi=1/3;function Mb(t){return t<0?-Math.pow(-t,Yi):Math.pow(t,Yi)}function Tb(t){return Math.exp(t)-1}function Sb(t){return Math.log(1+t)}function _b(t){return Math.log(t)/Math.LN2}function lt(t){this.options=t||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||Xy,cosh:Math.cosh||Jy,tanh:Math.tanh||eb,asinh:Math.asinh||tb,acosh:Math.acosh||sb,atanh:Math.atanh||rb,sqrt:Math.sqrt,cbrt:Math.cbrt||Mb,log:Math.log,log2:Math.log2||_b,ln:Math.log,lg:Math.log10||qi,log10:Math.log10||qi,expm1:Math.expm1||Tb,log1p:Math.log1p||Sb,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||ib,"-":nb,"+":Number,exp:Math.exp,not:ob,length:ub,"!":zi,sign:Math.sign||Eb},this.binaryOps={"+":Fy,"-":Ny,"*":Uy,"/":jy,"%":By,"^":Math.pow,"||":Hy,"==":Ky,"!=":qy,">":zy,"<":Vy,">=":Gy,"<=":Yy,and:Wy,or:Qy,in:Zy,"=":hb,"[":fb},this.ternaryOps={"?":Gi},this.functions={random:ab,fac:zi,min:gb,max:pb,hypot:Math.hypot||Vi,pyt:Math.hypot||Vi,pow:Math.pow,atan2:Math.atan2,if:Gi,gamma:Vo,roundTo:db,map:mb,fold:yb,filter:bb,indexOf:vb,join:wb},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}lt.prototype.parse=function(t){var e=[],s=new H(this,new G(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect(_s,"EOF"),new we(e,this)};lt.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var iu=new lt;lt.parse=function(t){return iu.parse(t)};lt.evaluate=function(t,e){return iu.parse(t).evaluate(e)};var Wi={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"remainder","^":"power","!":"factorial","<":"comparison",">":"comparison","<=":"comparison",">=":"comparison","==":"comparison","!=":"comparison","||":"concatenate",and:"logical",or:"logical",not:"logical","?":"conditional",":":"conditional","=":"assignment","[":"array","()=":"fndef"};function Ib(t){return Wi.hasOwnProperty(t)?Wi[t]:t}lt.prototype.isOperatorEnabled=function(t){var e=Ib(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var Ob=Object.defineProperty,$b=Object.getOwnPropertyDescriptor,Cb=(t,e,s)=>e in t?Ob(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Db=(t,e,s,r)=>{for(var n=r>1?void 0:r?$b(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n},xb=(t,e,s)=>(Cb(t,e+"",s),s);const Ab="kos-expression-evaluator-model";class Rb{constructor(e,s,r,n){l(this,"name");l(this,"expression");l(this,"expr");l(this,"getContextData",null);l(this,"_lastResult",{value:void 0});this.name=e,this.expression=s,this.expr=r,this.getContextData=n,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(e){this._lastResult=e}evaluate(e){try{return{value:this.expr.evaluate(e),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let pr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"parser");l(this,"_data");l(this,"_expressions",new Map);l(this,"_results");l(this,"_contextRevision",0);this.id=t,this.logger=s.logger,this._data=_e(),this._results=_e(),this.parser=new lt}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(t){this._data.setValues(t),X(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(t,e){this._data[t]=e}updateNestedValue(t,e){const s=t.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${t}" - cannot be empty`);return}let n=this._data;for(const o of s)(n[o]===void 0||n[o]===null)&&(n[o]={}),n=n[o];n[r]=e,this.logger.debug(`Updated nested context value "${t}" to:`,e)}addModelToContext(t,e){this._data[t]=e}addExpression(t,e){try{const s=this.parser.parse(e),r=new Rb(t,e,s,()=>this.data);this._expressions.set(t,r),this.evaluateExpression(t),this.logger.debug(`Added expression "${t}": ${e}`)}catch(s){throw this.logger.error(`Failed to parse expression "${t}"`,s),s}}removeExpression(t){const e=this._expressions.delete(t);return e?(delete this._results[t],this.logger.debug(`Removed expression "${t}"`)):this.logger.warn(`Attempted to remove non-existent expression "${t}". Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpression(t){const e=this._expressions.get(t);return e||this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpressionValue(t){const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return e.result}getCachedExpressionValue(t){const e=this._expressions.get(t);if(e)return e.result}get expressions(){return Array.from(this._expressions.values())}get expressionNames(){return Array.from(this._expressions.keys())}get results(){return this.evaluateAllExpressions(),this._results}evaluateAllExpressions(){Array.from(this._expressions.keys()).forEach(e=>{this._expressions.get(e)&&this.evaluateExpression(e)})}evaluateExpression(t){this.logger.debug(`Evaluating expression: ${String(t)}`);const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${String(t)}" not found`);return}const s=e.evaluate(this.data);this.logger.debug(`Expression "${String(t)}" evaluated to:`,s);const r=e.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(t)}" result changed from`,r,"to",s),e.updateResult(s),this.updateResult(t,s))}updateResult(t,e){this.logger.debug(`ExpressionEvaluator.updateResult called for "${t}":`,e),X(()=>{this._results[t]=e})}createExpression(t){const e=ot();return this.addExpression(e,t),e}};xb(pr,"Registration");pr=Db([R({modelTypeId:Ab,singleton:!1})],pr);const au=pr.Registration,Pb=m.createLogger({name:"kos-log-manager-service",group:"Services"}),kb="/api/kos/logs/overrides",cu=async()=>(Pb.debug("sending GET for kos-log-manager"),await De.get(kb)),Lb=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:cu},Symbol.toStringTag,{value:"Module"}));var Fb=Object.defineProperty,Nb=Object.getOwnPropertyDescriptor,Xr=(t,e,s,r)=>{for(var n=r>1?void 0:r?Nb(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Fb(e,s,n),n};const lu="kos-log-manager-model",Ub="/kos/logs/override/add/*",jb="/kos/logs/override/remove/*",Bb=t=>{if(typeof t=="string")return t;if(typeof t=="number")switch(t){case 0:return"trace";case 1:return"debug";case 2:return"info";case 3:return"warn";case 4:return"error";default:return"info"}return"info"};let Ot=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new To}updateModel(t){}resolveLoggers(){const t=m.getLoggers(),s=Object.entries(t).map(([r,n])=>({name:r,level:Bb(n.getLevel())})).reduce((r,{name:n,level:o})=>(r[n]={name:n,level:o},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const n=m.getLoggers()[r.name];if(!n){this.logger.debug(`Logger ${r.name} not found`);return}n.setLevel(t.level)});const s=m.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const n=m.getLoggers()[r.name];n||this.logger.debug(`Logger ${r.name} not found`),n==null||n.resetLevel()});const s=m.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await cu();if(t){this.logger.error("Failed to load log overrides",t);return}const s=(e==null?void 0:e.filter(r=>{var n;return((n=r.type)==null?void 0:n.toUpperCase())==="UI"}).map(r=>({name:r.name??"",type:r.type??"",level:r.level??"info",id:r.name||""})))??[];this._overrides.addAll(s),s.forEach(r=>{this.setLogLevels(r)})}};Xr([gc("/api/kos/ui/loggers")],Ot.prototype,"getAllLoggers",1);Xr([B({topic:Ub,websocket:!0,wildcardName:"nodeType"})],Ot.prototype,"handleOverrideAdded",1);Xr([B({topic:jb,websocket:!0,wildcardName:"nodeType"})],Ot.prototype,"handleOverrideRemoved",1);Ot=Xr([R(lu)],Ot);const uu=new Se({class:Ot,type:lu}),{URL:Us}=ae(),{postModel:Go,getOne:Hb}=ne.build({basePath:`${Us}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const du=async t=>{const e=await Go({model:t,urlOverride:`${Us}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},hu=async t=>{const e=await Go({model:t,urlOverride:`${Us}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},fu=async t=>{const e=await Go({model:{},urlOverride:`${Us}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},pu=async()=>{const t=await Hb({urlOverride:`${Us}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},Kb=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:pu,setDate:hu,setTime:du,setTimezone:fu},Symbol.toStringTag,{value:"Module"}));var qb=Object.defineProperty,zb=Object.getOwnPropertyDescriptor,Jr=(t,e,s,r)=>{for(var n=r>1?void 0:r?zb(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&qb(e,s,n),n};const Xt="kos-time-model",Vb="/kos/time/time",Gb="/kos/time/day",Yb="/kos/time/timezone";let $t=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await du(t)}async updateSystemDate(t){await hu(t)}async updateSystemTimezone(t){await fu(t)}handleTimeChange(){V(ys.TIME_CHANGE,{})}handleDayChange(){V(ys.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),V(ys.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await pu();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};Jr([B({topic:Vb,websocket:!0})],$t.prototype,"handleTimeChange",1);Jr([B({topic:Gb,websocket:!0})],$t.prototype,"handleDayChange",1);Jr([B({topic:Yb,websocket:!0})],$t.prototype,"handleTimeZoneChange",1);$t=Jr([R(Xt)],$t);const gr={registration:{[Xt]:{class:$t,singleton:!0}},type:Xt,predicate:Te(Xt),factory:ie.Singleton.create(Xt)};var Wb=Object.defineProperty,Qb=Object.getOwnPropertyDescriptor,gu=(t,e,s,r)=>{for(var n=r>1?void 0:r?Qb(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Wb(e,s,n),n};const mu="log-block-container-model";let mr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t,sortKey:"blockNum"})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};gu([$e],mr.prototype,"_models",2);mr=gu([R(mu)],mr);const Zb=m.createLogger({name:"log-stream-container-service",group:"Services"}),yu=()=>{var r;const t=me(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},Kt=yu(),Xb="/api/kos/logs/node/{nodeId}/streams",bu=async()=>(Zb.debug("sending GET for log-stream-container"),await De.get(Xb,{path:{nodeId:"primary"}},{destinationAddress:Kt})),vu=async(t,e="primary")=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:Kt})},wu=async t=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:Kt})},Jb=async()=>{await De.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:Kt})},Eu=async t=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:Kt}),Mu=async(t,e)=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:Kt}),ev=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Jb,getKosConnectionId:yu,getLogStreamBlock:Mu,getLogStreamBlocks:Eu,getLogStreams:bu,subscribeToLogStream:vu,unsubscribeFromLogStream:wu},Symbol.toStringTag,{value:"Module"}));var tv=Object.getOwnPropertyDescriptor,sv=(t,e,s,r)=>{for(var n=r>1?void 0:r?tv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const Tu="log-block-model";let kn=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await Mu(this.stream,this.blockNum);if(t){this.logger.error(`Failed to get log block ${this.blockNum}`);return}e&&this.addLines(e.lines,!0)}updateModel(t){this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount}addLines(t,e){const s=e?[]:this.lines;this.lines=[...s,...t],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};kn=sv([R(Tu)],kn);const Is=new ye({class:kn,type:Tu}),en=new ye({class:mr,type:mu});en.addRelatedModel(Is);var rv=Object.defineProperty,nv=Object.getOwnPropertyDescriptor,Su=(t,e,s,r)=>{for(var n=r>1?void 0:r?nv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&rv(e,s,n),n};const _u="log-stream-model";let yr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"_blocks");l(this,"name");l(this,"currentBlockId");l(this,"isResetting");l(this,"generatorInstance");l(this,"shouldStop",!1);this.id=t,this.logger=s.logger,this.currentBlockId="",this.name=e.name,this.nodeId=e.nodeId,this.isResetting=!0,this._blocks=en.instance(`${t}-blocks`).options({}).build()}get firstLineNum(){const t=this.populated[0];return t?t.startLineNum:0}get currentBlock(){const t=this.currentBlockId;return this._blocks.getModel(t)}get populated(){return this._blocks.data.filter(t=>t.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((t,e)=>t+e.lineCount,0)}accept(t){t.visit(this)}updateBlock(t){var r;let e=this._blocks.models.getModel(`${t.stream}-block-${t.blockNum}`);const s={nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)};e||(e=Is.instance(`${t.stream}-block-${t.blockNum}`).options(s).build(),this._blocks.addModel(e)),e&&e.updateModel(s),(!this.currentBlock||t.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}addBlock(t){var s;const e=Is.instance(`${t.stream}-block-${t.blockNum}`).options({nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)}).build();this._blocks.addModel(e),(!this.currentBlock||t.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}removeBlock(t){this._blocks.models.removeModel(`${this.name}-block-${t}`)}async subscribe(){await vu(this.name)}async unsubscribe(){await wu(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const e of this._blocks.models.data)e.lines=[];const t=this._blocks.data[this._blocks.data.length-1];t&&await t.syncLines(),this.isResetting=!1}async init(){this.logger.debug(`initializing log-stream ${this.id}`)}async load(){this.logger.debug(`loading log-stream ${this.id}`);const[t,e]=await Eu(this.name);if(t){this.logger.error(`Error loading log stream: ${t}`);return}if(e)for(const r of e)this.addBlock(r);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const r=this._blocks.data[this._blocks.data.length-2];r&&await r.syncLines()}}start(){return this.shouldStop=!1,this.generatorInstance=this.streamLogs(),this.generatorInstance}stop(){var t;this.shouldStop=!0,(t=this.generatorInstance)==null||t.next(),console.log("Requested generator stop.")}async*streamLogs(){const t=[];let e=null,s=0,r=this.currentBlockId;const n=Tl(()=>{const o=this.currentBlock;return o?{blockId:this.currentBlockId,lineCount:o.lines.length}:null},o=>{const i=this.currentBlock;if(i)if(r!==(o==null?void 0:o.blockId))r=o==null?void 0:o.blockId,s=0,t.push(...i.lines);else{const a=i.lines.slice(s);t.push(...a),s+=a.length}e&&(e(),e=null)},{fireImmediately:!0});try{for(const o of this.populated.filter(i=>i!==this.currentBlock))for(const i of o.lines)yield i;for(;;)for(t.length===0&&await new Promise(o=>e=o);t.length>0;)yield t.shift()}finally{n()}}};Su([$e],yr.prototype,"_blocks",2);yr=Su([R(_u)],yr);const bs=new ye({class:yr,type:_u});var ov=Object.defineProperty,iv=Object.getOwnPropertyDescriptor,ut=(t,e,s,r)=>{for(var n=r>1?void 0:r?iv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&ov(e,s,n),n};const Iu="log-stream-container-model",av="/kos/logs/subscription/addBlock/*",cv="/kos/logs/subscription/updateBlock/*",lv="/kos/logs/subscription/removeBlock/*",uv="/kos/logs/subscription/lines/*",Ou="/kos/logs/streams/add/*";let Le=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t}),this.selectedStream=void 0}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}updateModel(t){}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}updateSelectedStream(t){this.selectedStream=t}handleStreamAdded(t){this.logger.debug(`Received topic: ${Ou}`);const e=t.stream,s=bs.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.addBlock(t)}handleRemoveBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.removeBlock(t.blockNum)}handleUpdateBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.updateBlock(t)}handleLogLine(t,e){var n;this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&((n=r.currentBlock)==null||n.addLines(t.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(t){const e=bs.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(e),await e.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[t,e]=await bu();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=bs.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};ut([$e],Le.prototype,"_models",2);ut([B({topic:[Ou],websocket:!0})],Le.prototype,"handleStreamAdded",1);ut([B({topic:[av],websocket:!0})],Le.prototype,"handleAddBlock",1);ut([B({topic:[lv],websocket:!0})],Le.prototype,"handleRemoveBlock",1);ut([B({topic:[cv],websocket:!0})],Le.prototype,"handleUpdateBlock",1);ut([B({topic:[uv],websocket:!0})],Le.prototype,"handleLogLine",1);Le=ut([R(Iu)],Le);const js=new Se({class:Le,type:Iu});js.addRelatedModel(bs);js.addRelatedModel(en);js.addRelatedModel(Is);const dv=t=>t.rank!==void 0,hv=t=>t.visibleRole!==void 0,fv=t=>t.color!==void 0,pv=t=>{const e=t.info;return dv(e)?e.rank:0},gv=t=>{const e=t.info;return fv(e)?e.color:"orange"},mv=t=>{const e=t.info;return hv(e)?e.visibleRole:"TECHNICIAN"},{URL:tn}=ae(),{getAll:yv,postModel:$u}=ne.build({basePath:`${tn}/api/kos/troubles`}),Cu=async t=>await yv({urlOverride:`${tn}${t}`}),Du=async(t,e="/api/kos/troubles",s)=>{try{const r=await $u({model:{},urlOverride:`${tn}${e}/resolve/${t}`,tracker:s});return r!=null&&r.data&&rt.initiateFuture(r.data),r.data}catch{const n={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve trouble"};return rt.initiateFuture(n),n}},bv=async(t,e="/api/kos/troubles",s)=>{try{const r=await $u({model:t,urlOverride:`${tn}${e}/resolve/`,tracker:s});return r!=null&&r.data&&rt.initiateFuture(r.data),r.data}catch{const n={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve troubles"};return rt.initiateFuture(n),n}},vv=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:bv,getTroubles:Cu,resolveTrouble:Du},Symbol.toStringTag,{value:"Module"})),br="troubleDataMapper",Qs=new Map;Ps(br,{register:(t,e)=>{var s;Qs.has(t)||Qs.set(t,[]),(s=Qs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Qs.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:m.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const Bs="troubleMapper",Zs=new Map;Ps(Bs,{register:(t,e)=>{var s;Zs.has(t)||Zs.set(t,[]),(s=Zs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Zs.get(t);if(!s)return[];const r=s.map(i=>i(e)),o=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(o))}});$[Bs].register("nozzle",async t=>[t.data.nozzlePath]);$[Bs].register("path",async t=>[t.data.path]);const wv=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(o=>$[Bs].execute(o,t));return(await Promise.allSettled(r)).forEach(o=>{o.status==="fulfilled"&&o.value.forEach(i=>e.add(i))}),Array.from(e)},xu=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>$[br].execute(i,t)),r=$[br].execute(t.type,t);s.push(r);const o=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...t.data,...o}};class Ev{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class Mv{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class gt{static getHandler(e){switch(e){case"ResolvableTrouble":return new Ev;case"BlockPumpTrouble":return new Mv;default:return}}}var Tv=Object.defineProperty,Sv=Object.getOwnPropertyDescriptor,Au=(t,e,s,r)=>{for(var n=r>1?void 0:r?Sv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Tv(e,s,n),n};const Jt="trouble-model";function Xs(t){return typeof t.shouldDefer=="boolean"}let vr=class{constructor(t,{resolvable:e,tags:s,info:r,id:n,clientData:o,rank:i,ifaces:a,type:c,group:u,createTime:d,role:h,color:f,servicePath:p,...y},w){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"servicePath");l(this,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=w.logger,this.type=c,this._troubleId=n,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=f,this.tags=s,this.info=r,this.group=u,this.servicePath=p??"/api/kos/troubles",this.createTime=d,this.clientData=o,this.data={},Object.assign(this.data,y),this.futureHandler=new Kr(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=gt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:gt.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=gt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:gt.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=gt.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=gt.getHandler(this.type))==null?void 0:t.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await xu(this)}get deferredCompanion(){const t=On(this.id,e=>Xs(e));if(t&&Xs(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=On(this.id,e=>Xs(e));return t&&Xs(t.modelData)?t.modelData.shouldDefer:!1}clearDefer(){var t;(t=this.deferredCompanion)==null||t.clearDefer()}defer(){var t;(t=this.deferredCompanion)==null||t.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(t){var e;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(e=this.deferredCompanion)==null||e.defer();return}return await Du(this._troubleId,this.servicePath,t)}};Au([di()],vr.prototype,"resolve",1);vr=Au([R(Jt)],vr);const Os={registration:{[Jt]:{class:vr,singleton:!1}},type:Jt,predicate:Te(Jt),factory:ie.Factory.create(Jt)};var Ru=Object.defineProperty,_v=Object.getOwnPropertyDescriptor,Iv=(t,e,s)=>e in t?Ru(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Yo=(t,e,s,r)=>{for(var n=r>1?void 0:r?_v(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Ru(e,s,n),n},Ov=(t,e,s)=>(Iv(t,e+"",s),s);function Qi(t){return $.propertyMapper.hasMapper(ve.TroubleRank)?$.propertyMapper.executeMapper(ve.TroubleRank,t):pv(t)}function Zi(t){return($.propertyMapper.hasMapper(ve.TroubleColor)?$.propertyMapper.executeMapper(ve.TroubleColor,t):gv(t)).toLowerCase()}function Xi(t){return($.propertyMapper.hasMapper(ve.TroubleRole)?$.propertyMapper.executeMapper(ve.TroubleRole,t):mv(t)).toLowerCase()}const $v="trouble-container-model";class pe{}l(pe,"INDEX_TROUBLES_BY_IFACE","byIface"),l(pe,"INDEX_TROUBLES_BY_TYPE","byType"),l(pe,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(pe,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(pe,"SORT_KEY_RANK","rank"),l(pe,"TROUBLES_DEFERRED","true");let Ct=class{constructor(t,e){l(this,"id");l(this,"servicePath","/api/kos/troubles");this.id=t,this.servicePath=e.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");const t=await Cu(this.servicePath);try{t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:Qi(e),color:Zi(e),role:Xi(e),id:String(e.id)},r=Os.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw this.logger.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&st(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:Qi(t),color:Zi(t),role:Xi(t),id:String(t.id)};if(e.role==="NONE")return;const s=Os.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};Ov(Ct,"Registration");Yo([B({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],Ct.prototype,"handleTroubleRemoved",1);Yo([B({topic:"/kos/trouble/add",websocket:!0})],Ct.prototype,"handleTroubleAdded",1);Ct=Yo([R({modelTypeId:$v,singleton:!0}),vc(),pc({containerProperty:"troubles",containerOptions:{indexMap:{[pe.INDEX_TROUBLES_BY_IFACE]:wv,[pe.INDEX_TROUBLES_BY_TYPE]:"type",[pe.INDEX_TROUBLES_BY_GROUP]:"group",[pe.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:pe.SORT_KEY_RANK}})],Ct);const Dt=Ct.Registration,{URL:Pu}=ae(),{getAll:Cv}=ne.build({basePath:`${Pu}/api/kos/ota`}),Ji=m.createLogger({name:"ota-service",group:"Services"}),Dv=async()=>{Ji.debug("sending GET request to /api/kos/ota/artifacts");const t=await Cv({urlOverride:`${Pu}/api/kos/ota/artifacts`});return Ji.debug("getArtifacts - response:",t),t==null?void 0:t.data};var xv=Object.defineProperty,Av=Object.getOwnPropertyDescriptor,sn=(t,e,s,r)=>{for(var n=r>1?void 0:r?Av(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&xv(e,s,n),n};const ku="ota-model",Rv=t=>{let e=null;for(const s in t){const r=t[s],n=r.lastUpdateTime;(!e||e.lastUpdateTime<n)&&(e=r)}return e},vn=t=>{const e=t.artifactInfo,s=Rv(t.requests),r=(e==null?void 0:e.identifier)||(s==null?void 0:s.kabId);if(!r)return;let n;switch(t.status){case"INSTALLED":n="ready";break;case"INVALID":n="error";break;case"MISSING":n=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":n="pending"}const o=e===void 0;return{id:r,manifest:o,label:e==null?void 0:e.version,name:e==null?void 0:e.name,status:n,error:n==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:n==="error"?s==null?void 0:s.errorCount:0,progress:n==="downloading"&&s&&!o?s.currentSize/(e==null?void 0:e.size)*100:void 0,size:e==null?void 0:e.size}};let xt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new To);l(this,"troubleContainer");this.id=t,this.logger=s.logger}get downloadInProgressTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:e[0]}get updatePendingTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:e[0]}get pausedDueToErrorsTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:e[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var t;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(t=this.updatePendingTrouble)==null||t.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const t=await Dv();t&&t.forEach(e=>{const s=vn(e);s&&this.data.addModel(s)})}catch(t){this.logger.error(`loading ota ${this.id} - error:`,t)}}async handleAllArtifacts(t){this.logger.debug("handleAllArtifacts:",t),await this.data.clear();try{t.forEach(e=>{const s=vn(e);s&&this.data.addModel(s)})}catch(e){this.logger.error(`handleAllArtifacts ${this.id} - error:`,e)}}handleChangedArtifacts(t){this.logger.debug("handleChangedArtifacts:",t);try{t.forEach(e=>{const s=vn(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};sn([Lt({modelType:Dt.type})],xt.prototype,"troubleContainer",2);sn([B({topic:"/kos/ota/artifacts/all",websocket:!0})],xt.prototype,"handleAllArtifacts",1);sn([B({topic:"/kos/ota/artifacts/changed",websocket:!0})],xt.prototype,"handleChangedArtifacts",1);xt=sn([R(ku)],xt);const wr=new Se({class:xt,type:ku});function Pv(t){let e;const s=async(...r)=>{e&&e.abort(),e=new AbortController;const n=e;try{return await t(...r,n.signal)}finally{e===n&&(e=void 0)}};return s.cancel=()=>{e&&(e.abort(),e=void 0)},s.getController=()=>e,s.isActive=()=>!!e,s}const wn=m.createLogger({name:"software-info-service",group:"Services"}),Wo=async t=>{wn.debug("sending GET for software-info");const[e,s]=await zl.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(wn.debug("Request was aborted"),new ge("Request was aborted")):(wn.error("Failed to fetch software-info",e),new ge("Failed to fetch software-info"));return s},kv=Pv(Wo),Lv=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Wo,getSoftwareInfosWithCancel:kv},Symbol.toStringTag,{value:"Module"}));var Fv=Object.getOwnPropertyDescriptor,Nv=(t,e,s,r)=>{for(var n=r>1?void 0:r?Fv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const es="software-info-model";let Ln=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=t,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(t,e){return t.reduce((s,r)=>(s[r[e]]=[...s[r[e]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const t=await Wo(),e=(t==null?void 0:t.nodes)||{};X(()=>{const r=Object.keys(e).map(n=>e[n][0]).map(n=>({nodeName:n.nodeType,kosVersion:n.kosVersion,group:this.groupBy(n.artifacts,"group")}));this.nodes=r})}catch(t){t instanceof ge&&this.logger.error("Failed to fetch software-info",t)}}};Ln=Nv([R(es)],Ln);const Er={registration:{[es]:{class:Ln,singleton:!1}},type:es,predicate:Te(es),factory:ie.Factory.create(es)},{URL:Lu}=ae(),{getOne:Uv}=ne.build({basePath:`${Lu}/api/kos/state`}),jv=m.createLogger({name:"state-bean-service",group:"Services"}),Fu=async({path:t})=>(jv.debug("sending GET for state-bean"),await Uv({urlOverride:`${Lu}/api/kos/state/${t}`})),Bv=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Fu},Symbol.toStringTag,{value:"Module"}));var Hv=Object.defineProperty,Kv=Object.getOwnPropertyDescriptor,Nu=(t,e,s,r)=>{for(var n=r>1?void 0:r?Kv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Hv(e,s,n),n};const ts="state-bean-model",qv=it("path");let Mr=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=t,this.logger=s.logger,this.props=_o.map(new Map),In(e,this)}updateModel(t){In(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&$o(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&qr(r)&&(r=Number(r)),this.props.set(e,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(t){Object.entries(t).forEach(([e,s])=>{this.props.set(e,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const t=await Fu({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};Nu([B({topic:`/kos/state/${qv}`,websocket:!0})],Mr.prototype,"handleConfigBeanUpdated",1);Mr=Nu([R(ts)],Mr);const $s={registration:{[ts]:{class:Mr,singleton:!1}},type:ts,predicate:Te(ts),factory:ie.Factory.create(ts)};var zv=Object.defineProperty,Vv=Object.getOwnPropertyDescriptor,Uu=(t,e,s,r)=>{for(var n=r>1?void 0:r?Vv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&zv(e,s,n),n};const ss="state-prop-model",ea=it("path");let Tr=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=t,this.logger=s.logger,this.path=e.path,this.attribute=e.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var t;return((t=this.value)==null?void 0:t.toString())??""}};Uu([Lt({modelType:$s.type,id:`state-bean-${ea}`,options:{path:ea}})],Tr.prototype,"stateBean",2);Tr=Uu([R(ss)],Tr);const Qo={registration:{[ss]:{class:Tr,singleton:!1}},type:ss,predicate:Te(ss),factory:ie.Factory.create(ss)},{URL:Gv}=ae(),{getAll:Yv}=ne.build({basePath:`${Gv}/api/state-prop`}),Wv=m.createLogger({name:"state-prop-service",group:"Services"}),Qv=async()=>(Wv.debug("sending GET for state-prop"),await Yv({})),Zv=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Qv},Symbol.toStringTag,{value:"Module"})),{URL:Zo}=ae(),{getOne:ju}=ne.build({basePath:`${Zo}/api/translation`}),vs=m.createLogger({name:"translation-service",group:"Services"}),Xv=()=>{const t=window.location.origin,e=me();return(e==null?void 0:e.host)||t},Bu=async(t,e)=>{vs.debug(`Loading translations from: ${t}`);const s=e??Xv();try{const r=await fetch(`${s}${t}`);return r.status!==200?(vs.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw vs.error("Error fetching translations",r),r}},Jv=async()=>{vs.debug("Getting system localization descriptor");const t=await ju({urlOverride:`${Zo}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get localization descriptor ${t==null?void 0:t.status}`);return t.data},Hu=t=>async()=>{vs.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await ju({urlOverride:`${Zo}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},Ku="langResolver";var ew=Object.getOwnPropertyDescriptor,tw=(t,e,s,r)=>{for(var n=r>1?void 0:r?ew(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const rs="translation-model";function sw(t){const e=typeof t=="string",s=e?!1:!!(t!=null&&t.data)&&typeof(t==null?void 0:t.data)!="string",r=e?t:t==null?void 0:t.defaultValue,n=e||t==null?void 0:t.context,o=e?void 0:s?t==null?void 0:t.data:t;return{isBasicOptions:e,defaultValue:r,context:n,data:o}}function qu(t,e=""){return Object.keys(t).reduce((s,r)=>{const n=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])){const o=qu(t[r],n);return{...s,...o}}else return{...s,[n]:t[r]}},{})}function zu(t,e){const s={...t};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(typeof e[r]=="object"&&e[r]!==null&&typeof t[r]=="object"&&t[r]!==null?s[r]=zu(t[r],e[r]):s[r]=e[r]);return s}const Fn=(t,e)=>{const s=/__(.*?)__/g,r=t.replace(s,(n,o)=>Object.prototype.hasOwnProperty.call(e||{},o.trim())?e==null?void 0:e[o.trim()]:n);return r===t?r:s.test(r)?Fn(r,e):r},Js=(t,e,s)=>{const r=/{{(.*?)}}/g,o=Fn(t,e).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return Fn(o,e)},ta=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let Nn=class{constructor(t,e,s){l(this,"id");l(this,"namespace");l(this,"descriptor");l(this,"defaultLocale");l(this,"currentLocale");l(this,"bundleResolver");l(this,"data");l(this,"logger");l(this,"resolver");l(this,"disposer");l(this,"context");l(this,"rootUrl");this.id=t,this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.currentLocale||"en",this.namespace=e.namespace,this.descriptor=e.descriptor,this.rootUrl=e.rootUrl,this.data={},this.resolver=e.resolver||s.kosContext.get(Ku),this.bundleResolver=e.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(t){const e=this.descriptor[t];if(!t||!e)return[this.defaultLocale];if(!this.defaultLocale&&!e.fallbacks)return[t];let s=e.fallbacks||[this.defaultLocale];return s.includes(t)||(s=[t,...s]),s}async loadTranslations(){const t=this.getTranslationLocales(this.currentLocale).reverse(),e=t.map(r=>{if(this.bundleResolver){const n=Y.getContext(this.id);return this.bundleResolver(this.namespace,r,n)}try{const n=this.resolver(this.namespace,r);return Bu(n,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);X(()=>{const r=s.reduce((n,o,i)=>(o.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,o.value),o.value&&(n=zu(n,o.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),n),{});this.data=qu(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=ta(this.namespace,t);if(e!==this.namespace){const r=this.context.getModel(e);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(t,e){if(!t)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:n}=sw(e),{namespace:o,key:i}=ta(this.namespace,t),a=`${i}_${r}`;if(o!==this.namespace){const c=this.context.getModel(o);return c?c.resolveKey(i,e):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>Js(u,this.data,n)):Js(this.data[a],this.data,n)}if(this.data[i]){const c=this.data[i];return Array.isArray(c)?c.map(u=>Js(u,this.data,n)):Js(this.data[i],this.data,n)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=M.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};Nn=tw([jr(),R(rs)],Nn);const Sr={registration:{[rs]:{class:Nn,singleton:!1}},type:rs,predicate:Te(rs),factory:ie.Factory.create(rs)};var rw=Object.defineProperty,nw=Object.getOwnPropertyDescriptor,Vu=(t,e,s,r)=>{for(var n=r>1?void 0:r?nw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&rw(e,s,n),n};const ns="translation-container-model",ow=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function iw(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error("namespace "+t+" not found in descriptor");const r=s.basePath,n=s.locales[e].file;return ow([r,n])}let _r=class{constructor(t,e,s){l(this,"id");l(this,"lang");l(this,"rootUrl");l(this,"descriptor");l(this,"_defaultNamespace");l(this,"resolver");l(this,"logger");l(this,"descriptorUrl");l(this,"namespaces",[]);l(this,"_models");this.id=t,this.lang=e.lang||"en",this.descriptor=e.descriptor,this._defaultNamespace=e.defaultNamespace,this.descriptorUrl=e.descriptorUrl,this.rootUrl=e.rootUrl,this.resolver=e.resolver||iw.bind(this),s.kosContext.set(Ku,this.resolver),this.logger=s.logger,this._models=new Ce({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(t){return this.logger.debug("getting model "+t),this._models.getModel("translation-"+t)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const t of this.namespaces){const e=this.resolveNamespace(t);await de(e)}}resolveNamespace(t){var s;if((s=this.descriptor.namespaces)==null?void 0:s[t]){const r=Object.keys(this.descriptor.namespaces[t].locales)[0],n=this.descriptor.namespaces[t].locales[r].defaultLocale,o=Sr.factory("translation-"+t)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:n,descriptor:this.descriptor.namespaces[t].locales,resolver:this.resolver});return this.addModel(o),this.namespaces.includes(t)||X(()=>{this.namespaces.push(t)}),o}else{this.logger.warn("namespace "+t+" not found in descriptor");const r=Sr.factory("translation-"+t)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug("initializing translation-container container "+this.id)}async load(){this.logger.debug("loading translation-container container "+this.id)}};Vu([$e],_r.prototype,"_models",2);_r=Vu([R(ns)],_r);const Fe={registration:{[ns]:{class:_r,singleton:!0}},type:ns,predicate:Te(ns),factory:ie.Singleton.create(ns)},aw={set(t,e){const s=Y.getContext(Fe.type);s&&s.set(t,e)},get(t){const e=Y.getContext(Fe.type);return e==null?void 0:e.get(t)}},Gu={async init(t){const e=Fe.factory(t);return await de(e),{translations:e}}};function cw(t){return(t==null?void 0:t.troubles)!==void 0&&(t==null?void 0:t.troubles)instanceof Array&&(t==null?void 0:t.troublesByType)!==void 0&&typeof(t==null?void 0:t.troublesByType)=="object"}const Yu="kos-ws-event",Xo=Ft(Yu);var lw=Object.defineProperty,uw=Object.getOwnPropertyDescriptor,Jo=(t,e,s,r)=>{for(var n=r>1?void 0:r?uw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&lw(e,s,n),n};const dw=({headers:t,body:e})=>Object.entries(t).map(([r,n])=>`${r}:${n}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){m.debug("kos event received");const{body:r,headers:n}=e.body,o=n["request-id"]||n["response-id"],i=n["request-id"]||n["response-id"]||n.topic||n.type;if(i){let a=i;if(o)a=`${a}-${s?"send":"receive"}`;else{const u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const c={msgId:a,content:r,headers:n,timestamp:Date.now(),raw:dw({headers:n,body:r}),direction:s?"send":"receive",mocked:!!n.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};Jo([B({topic:[Rs.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Jo([B({topic:[Rs.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Jo([R(Xo.type)],exports.WsEventModel);const sa=me(),hw=sa.debug==="true"||sa.debug===!0,fw="/api/system/canvas",Wu=async(t,e)=>{const s=e||fw,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:hw?"false":"true"},body:t})},pw=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Wu},Symbol.toStringTag,{value:"Module"}));function ra(t,e,s){{const r=t.filter((n,o)=>o%4!==3);return btoa(String.fromCharCode(...r))}}var gw=Object.defineProperty,mw=Object.getOwnPropertyDescriptor,Qu=(t,e,s,r)=>{for(var n=r>1?void 0:r?mw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&gw(e,s,n),n};const Zu="canvas-renderer-model";function En(t){return typeof t.onDone=="function"}let Ir=class{constructor(t,e,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);l(this,"_clearOnComplete");l(this,"isStreaming",!1);l(this,"renderLoopId",null);l(this,"sendIntervalId",null);l(this,"timeoutId",null);l(this,"apiPath");l(this,"endpointName");l(this,"width",50);l(this,"height",30);l(this,"fps",10);l(this,"durationMs",null);l(this,"_onFrame",null);this.id=t,this.logger=s.logger,this.width=e.width??50,this.height=e.height??30,this.fps=e.fps??10,this.durationMs=e.durationMs??null,this.apiPath=e.apiPath??"/api/system/canvas",this.endpointName=e.endpoint}set onFrame(t){this._onFrame=t}set renderer(t){var e,s;this._renderer&&(this.stopStreaming(),(s=(e=this._renderer).dispose)==null||s.call(e)),this._renderer=t,this.isStreaming&&this.startStreaming()}setClearOnComplete(t){this._clearOnComplete=t}sendDataFrame(t,e){Wu(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=ra(t);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,n=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)n[i]=255;const o=ra(n);this.logger.debug(`Sending clear frame: ${t}x${e}, apiPath: ${this.apiPath}`),this.sendDataFrame(o,this.apiPath),(s=this._onFrame)==null||s.call(this,o)}}isOneShotDone(){var t,e;return En(this._renderer)&&((e=(t=this._renderer).isOneShot)==null?void 0:e.call(t))===!0&&this._renderer.isOneShotDone}startStreaming(){var t,e,s,r;{if(!this._renderer)return;if(!this.apiPath){this.logger.error(`No endpoint configured for canvas renderer ${this.id}`);return}this.isStreaming=!0,this._renderer.reset(),(e=(t=this._renderer).play)==null||e.call(t);const n=En(this._renderer);En(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),V("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((d=(u=this._renderer)==null?void 0:u.isOneShot)==null?void 0:d.call(u))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const o=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(o&&this._onFrame&&this.handleFrame(o),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,u;const a=(u=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:u.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!n&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(t,e)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),e.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(t,e)=>{this.startStreaming(),e.send({status:"OK"})})}};Qu([Lt({modelType:Lo.type})],Ir.prototype,"router",2);Ir=Qu([R(Zu)],Ir);const ei=new ye({class:Ir,type:Zu});class Xu{constructor({src:e}){l(this,"video");l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);l(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=e,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(e,s){this.canvas.width=e,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,e,s)}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}onDone(e){this.doneCallback=e}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}}class yw{constructor(){l(this,"canvas");l(this,"gl");l(this,"lastWidth",0);l(this,"lastHeight",0);l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl");if(!e)throw new Error("WebGL not supported");this.gl=e}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(e*s*4);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const n=new Uint8ClampedArray(r.length);for(let o=0;o<s;o++){const i=o*e*4,a=(s-1-o)*e*4;n.set(r.subarray(i,i+e*4),a)}return n}}class bw extends yw{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,n=`
77
+ ["${e}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(w=E==null?void 0:E.socket)==null||w.send(d)}else{Ye.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(d)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:n,destinationAddress:o}){const{unsubscribe:i,count:a}=C(e,s);return Ye.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,n,o),()=>{const{count:c}=i();Ye.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,n,o)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(Tt,"_instance");class Cg{constructor(e,s,r,n,o){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);l(this,"baselineDependencies",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=n,this.log=o}registerAll(e){var n;const s=((n=this.modelData)==null?void 0:n[ee])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(o=>{const i=s[o],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(o);if(this.log.debug(`Resolved topic: ${o} → ${c}`),i.requiresBaseline&&(this.baselineDependencies.set(c,i.requiresBaseline),this.log.debug(`Registered baseline dependency for ${c}: ${i.requiresBaseline.path}`)),i.flow)this.subscribeWithFlowControl(i,c,a);else{const u=this.createHandler(c,i);this.subscribe(i,c,u,a===x.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,n){const o=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Tt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:o});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=C(s,r);n?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var n;try{const o=(n=r==null?void 0:r.headers)==null?void 0:n["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?o===i:!0,c=this.extractWildcardCapture(e,r,s),u=this.isBaselineReady(e);if(!this.model.isReady()||!u){u?this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`):this.log.warn(`Baseline not ready for ${e}. Queuing message.`);const d=()=>{const h=Dn(r,s.skipParse),f=s.transform(h);if(a&&s.condition(f,this.modelData,r))return this.callHandlerWithWildcard(s,f,c,r)};this.offlineQueue.enqueue(d,e,r)}else{const d=Dn(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)}}catch(o){this.log.error(`Error handling subscription for ${e}`,o)}}}extractWildcardCapture(e,s,r){var o;if(!r.wildcardName||!Pc(e))return null;const n=((o=s==null?void 0:s.headers)==null?void 0:o.topic)||"";return Rc(e,n,r.wildcardName)}callHandlerWithWildcard(e,s,r,n){if(r&&Object.keys(r).length>0){const o={...n,wildcardCapture:r};return e.handler.call(this.modelData,s,o,this.modelData)}else return e.handler.call(this.modelData,s,n,this.modelData)}resolvePropKey(e){const s=/.*({PROP_(.+)})/;let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",this.modelId):e;const n=r.match(s);return n&&n[2]in this.modelData&&(r=r.replace(n[1],this.modelData[n[2]])),r}async subscribeWithFlowControl(e,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const n=new Eg(e.flow);this.flowControllers.set(s,n);const o=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,o,n),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===x.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(e,s,r,n){const o=new AbortController;try{let i;if(e.websocket){const a=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;Tt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=xi(s)}else i=xi(s);return(async()=>{try{for await(const a of n.processEvents(i)){if(o.signal.aborted)break;const c=r(a);c instanceof Promise&&await n.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),o}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var n,o,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c,e,r)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(o=(n=s.flow)==null?void 0:n.errorHandling)!=null&&o.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const n=e.flow.errorHandling.retry;let o=r;for(let i=1;i<=n.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${n.attempts} for handler`),await new Promise(a=>setTimeout(a,n.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){o=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",o),o}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}getResponseStore(){return this.modelData.serviceResponses}isBaselineReady(e){const s=this.baselineDependencies.get(e);if(!s)return!0;const r=this.getResponseStore();if(!r)return this.log.warn(`ServiceResponseStore not found for baseline check on topic: ${e}`),!1;const o=`${(s.method||"get").toUpperCase()}:${s.path}`;return r.has(o)}flushQueueForBaseline(e){const s=this.baselineDependencies.get(e);if(!s){this.log.debug(`No baseline dependency for topic: ${e}`);return}const r=this.getResponseStore();if(!r){this.log.warn("ServiceResponseStore not found, falling back to standard flush"),this.offlineQueue.flush();return}const n=s.method||"get",o=r.getTemporalMetadataByPath(s.path,n);if(!o){this.log.warn(`Baseline temporal metadata not found for ${s.path}, falling back to standard flush`),this.offlineQueue.flush();return}const i=s.replayStrategy||Je.AFTER_REQUEST;this.log.info(`Flushing queue with strategy ${i} for topic: ${e}`),this.log.debug(`Baseline timing - requested: ${o.requestedAt}, received: ${o.receivedAt}`),this.offlineQueue.flushWithStrategy(i,o.requestedAt,o.receivedAt)}}function ht(t,e){const s=`[Model:${e}]`;return{debug:(...r)=>t.debug(s,...r),info:(...r)=>t.info(s,...r),warn:(...r)=>t.warn(s,...r),error:(...r)=>t.error(s,...r)}}function Dg(t){return!!(t!=null&&t[et])&&Object.keys(t[et]).length>0}function xg(t){return!!(t!=null&&t[ee])&&Object.keys(t[ee]).length>0}function Ag(t){return!!(t!=null&&t[Re])&&t[Re].length>0}function Rg(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[tt])&&Object.keys(e[tt]).length>0}function Pg(t){return t.retention===ue.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function kg(t,e){return t.has(e)}function Lg(t){return!t.expiresAt||Date.now()<t.expiresAt}function Pi(t,e,s,r){const n=setTimeout(()=>r(t),e);s.set(t,n)}class Fg{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:ue.SINGLE},n=Date.now(),o=Date.now()){if(this.shouldExtendTTL(e,r))return this.extendExistingTTL(e,r.ttl),!1;const i=this.createCachedResponse(s,e,r,n,o);return this.storeResponse(e,i,r),!0}get(e){const s=this.responses.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.delete(e);return}return s.data}}getByPath(e,s="get"){return this.get(this.makeKey(e,s))}has(e){return this.get(e)!==void 0}delete(e){this.responses.delete(e),this.retentionPolicies.delete(e);const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}clearPath(e){Array.from(this.responses.keys()).filter(r=>this.extractPath(r)===e).forEach(r=>this.delete(r))}clear(){this.cleanupTimers.forEach(e=>clearTimeout(e)),this.responses.clear(),this.retentionPolicies.clear(),this.cleanupTimers.clear()}get size(){return this.responses.size}shouldCleanupAfterHandler(e){const s=this.retentionPolicies.get(e);return(s==null?void 0:s.retention)===ue.IMMEDIATE}shouldExtendTTL(e,s){if(!Pg(s)||!kg(this.responses,e))return!1;const r=this.responses.get(e);return Lg(r)}extendExistingTTL(e,s){const r=this.responses.get(e);r.expiresAt=Date.now()+s,this.resetCleanupTimer(e,s)}resetCleanupTimer(e,s){this.clearTimerIfExists(e),Pi(e,s,this.cleanupTimers,r=>this.delete(r))}clearTimerIfExists(e){const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}createCachedResponse(e,s,r,n,o){return{data:e,timestamp:o,requestedAt:n,receivedAt:o,path:this.extractPath(s),method:this.extractMethod(s),expiresAt:this.calculateExpiresAt(r)}}calculateExpiresAt(e){return e.retention===ue.TTL&&e.ttl?Date.now()+e.ttl:void 0}storeResponse(e,s,r){this.responses.set(e,s),this.retentionPolicies.set(e,r),this.applyRetentionPolicy(e,r)}applyRetentionPolicy(e,s){switch(s.retention){case ue.IMMEDIATE:break;case ue.TTL:s.ttl&&Pi(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case ue.SINGLE:break;case ue.PERMANENT:case ue.MANUAL:break}}makeKey(e,s){return`${s.toUpperCase()}:${e}`}extractPath(e){return e.split(":",2)[1]||e}extractMethod(e){return e.split(":",2)[0]||"get"}getTemporalMetadata(e){const s=this.responses.get(e);if(s)return{requestedAt:s.requestedAt,receivedAt:s.receivedAt}}getTemporalMetadataByPath(e,s="get"){return this.getTemporalMetadata(this.makeKey(e,s))}cleanup(){const e=Date.now();Array.from(this.responses.entries()).filter(([r,n])=>n.expiresAt&&e>n.expiresAt).map(([r])=>r).forEach(r=>this.delete(r))}}class Ng{static createAll(e){const{modelId:s,modelTypeName:r,modelData:n}=e,o=vc.create({modelId:s,modelTypeName:r}),i=new tg(e,ht(o,"fsm")),a=new rg(ht(o,"offline-queue")),c=new Gp(e),u=new Vp(e),d=new Fg;n.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(Dg(n)&&(h.effectManager=new Yp(r,s,n,ht(o,"effect"))),xg(n)){const f=ht(o,"subscription");h.subscriptionManager=new Cg(e,n,s,a,f),h.onlineLifecycleManager=new ng(e,ht(o,"online"))}return Ag(n)&&(h.httpRouteManager=new wo(n,ht(o,"http-routes"))),Rg(n)&&(h.serviceRequestManager=new gg(n,d)),h}}const U=D.getLogger("kos-model"),Ug="kos.extension.model.loader";class hl{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"serviceResponses");l(this,"serviceRequestManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const n=Ng.createAll(this);this.fsm=n.fsm,this.offlineQueue=n.offlineQueue,this.companionManager=n.companionManager,this.childResolver=n.childResolver,this.serviceResponses=n.serviceResponseStore,n.effectManager&&(this.effectManager=n.effectManager),n.subscriptionManager&&(this.subscriptionManager=n.subscriptionManager),n.httpRouteManager&&(this.httpRouteManager=n.httpRouteManager),n.onlineLifecycleManager&&(this.onlineLifecycleManager=n.onlineLifecycleManager),n.serviceRequestManager&&(this.serviceRequestManager=n.serviceRequestManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,serviceRequestManager:!1,serviceResponses:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),qp(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===v.ACTIVE}isOnline(){return this._onlineStatus===v.ONLINE}isReady(){return this._status===v.READY}async deactivate(){var e,s,r;U.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const n=Y.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,n)),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(n){throw U.debug(`Model ${this.modelId} failed to deactivated`),n}}async activate(){var e,s,r,n;U.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await Qt(this,x.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.ACTIVATE));const o=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,o)),this.initializeStateMachineForLifecycle(x.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(n=this.subscriptionManager)==null||n.registerAll(x.ACTIVATE),this.createLifecycleCompanions(x.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw U.debug(`Model ${this.modelId} failed to activate`),o}}async whenLoaded(){await mn([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{U.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await mn([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{U.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await mn([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{U.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,n;if(this.fsm.current===v.READY){U.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{U.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await Qt(this,x.READY),await Yc(this,bo.READY,x.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.READY));const o=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.ready)==null?void 0:r.call(s,o)),this.offlineQueue.flush(),this.initializeStateMachineForLifecycle(x.READY),(n=this.subscriptionManager)==null||n.registerAll(x.READY),this.createLifecycleCompanions(x.READY),U.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};V(Fc(this.modelTypeName,this.modelId),i),V(Nc(this.modelTypeName),i)}catch(o){throw U.error(o),Error(o)}}async load(){var n,o,i,a,c,u;const e=this[He];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED||this.fsm.current===v.LOADING){U.debug(`Model ${s} with id ${r} already loaded or loading`);return}U.debug(`Loading model ${s} with id ${r}`),await Qt(this,x.LOAD);try{const d=Y.getContext(r),h=`${Ug}.${s}`,f=await $.loader.executeLoader(h,{});f&&(U.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(x.LOAD)),await((i=(o=this.modelData)==null?void 0:o.load)==null?void 0:i.call(o,d)),X(()=>{this.loaded=!0}),U.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(x.LOAD),(a=this.subscriptionManager)==null||a.registerAll(x.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(x.LOAD)}catch(d){throw U.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,n,o,i,a;U.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const c=this.getChildren().map(d=>{var h;return(h=d.unload)==null?void 0:h.call(d)}).filter(d=>!!d);await Promise.allSettled(c);const u=Y.getContext(this.modelId);if(await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,u)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),this.modelData){const d=this.modelData;if(d._fsmInitialized=!1,d._fsmConfig){const h=((n=d._fsmOptions)==null?void 0:n.stateProperty)||"currentState";d[h]=void 0}d.stateHistory&&(d.stateHistory=[])}U.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(o=this.effectManager)==null||o.disposeAll(),(i=this.subscriptionManager)==null||i.disposeAll(),(a=this.httpRouteManager)==null||a.dispose()}catch(c){throw U.debug(`Model ${this.modelId} failed to unload`),c}}async init(){var o,i,a,c;const e=this[He];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,n=Y.getContext(s);U.debug(`Initializing model ${r} with id ${s}`),await Qt(this,x.INIT);try{await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(x.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,n)),this.initialized=!0,U.debug(`Model ${r} with id ${s} initialized`),(c=this.onlineLifecycleManager)==null||c.register(),this.initializeStateMachineForLifecycle(x.INIT),this.registerSubscribers(x.INIT),this.createLifecycleCompanions(x.INIT)}catch(u){throw U.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;U.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&pc(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;U.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(x.ONLINE)}async offline(){var s,r,n;U.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=Y.getContext(this.modelId);await((n=(r=this.modelData)==null?void 0:r.offline)==null?void 0:n.call(r,e))}accept(e){e.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(e){this.companionManager.add(e)}clearCompanionModels(){this.companionManager.clear()}}const ki=m.createLogger({name:"kos-model-instantiator"});class jg{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new jp(e,s,this.createModelInstance.bind(this))}createModelInstance(e,s,r={}){const n=this.registry.models[e];if(!n)throw new Error(`No model registered for type ${e}`);const o=n.singleton?e:s;if(this.cache.restoreFromDeleteCache(o),!this.cache.hasModel(o)){ki.debug(`Creating model instance: ${e} [${o}]`);const a=n.create?n.create({modelTypeId:e,id:o,options:r}):new n.class(o,r),c=new hl({modelTypeName:e,id:o,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(o);if(!i)throw ki.error(`Model ${e} [${o}] not found in cache`),new Error(`Model ${e} [${o}] not found in cache`);return{model:i,data:i.modelData}}createCompanionModels(e,s,r){this.companionInstantiator.createCompanionModels(e,s,r)}_createCompanionModels(e,s){this.createCompanionModels(e,s)}}let Bg=class{constructor(e){this._registry=e}get registry(){return this._registry}getModelTypeRegistry(e){const s=this.registry.models[e];if(!s)throw new Error(`No registration for model type ${e}`);return s}registerModel(e){const s=e.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...e.registration})}registerCompanionModel(e,s){var r,n;(r=this.registry).companionModels??(r.companionModels={}),(n=this.registry.companionModels)[e]??(n[e]=[]),this.registry.companionModels[e].some(o=>o.type===s)||this.registry.companionModels[e].push({type:s})}getModelSubscriptions(e){var s;return((s=this.getModelTypeRegistry(e))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(e){var r;const s=(r=this.getModelTypeRegistry(e))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${e}`);return s}getModelFactory(e){return Ft(e)}};const fl=10,Li=m.createLogger({name:"kos-model-manager"});class pl{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Np,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=e=>{const s=this.getModelById(e);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=e=>{var r,n;const s=this.getModelById(e);if(s)return((n=(r=s.modelData).toJSON)==null?void 0:n.call(r))||{}},globalThis.kos.kosModelDebug=e=>{var r;const s=this.getModelById(e);if(s)return((r=s.modelData)==null?void 0:r.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(e,s){const r=this.getInstance(s);return r._registry=new Bg(e),r.cache=new Up(e.preloadModels),r.instantiator=new jg(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Li.debug("Creating new instance of KosModelManager"),new this),(r=globalThis.kos)==null?void 0:r.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(e=>(Li.debug(`preloading ${e}`),typeof e=="string"?this.createModelInstance(e).model:this.createModelInstance(e.modelType,e.modelId,e.options).model))}get models(){return this.cache.models}getModelById(e){return this.cache.getModelById(e)}addModel(e){return this.cache.addModel(e)}removeModel(e){this.cache.removeModel(e.modelId)}hasModel(e){return this.cache.hasModel(e)}getModelsByType(e,s){return Array.from(this.models).filter(r=>r.modelTypeName===e).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(e){return this._registry.getModelSubscriptions(e)}getDataModelBuilder(e){return this._registry.getDataModelBuilder(e)}getModelFactory(e){return Ft(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(F.RESET,v.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),kc.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),fl)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}createLifecycleCompanions(e,s,r){this.instantiator.createCompanionModels(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var rr=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.RELOADING="reloading",t))(rr||{}),yt=(t=>(t.CREATE="create",t.INITIALIZE="init",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.UNLOAD="unload",t.RELOAD="reload",t))(yt||{});const Hg=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,o=>D.debug(o.machine.current)),r=b.createMachine({creating:b.state(b.transition("create","created")),created:b.state(b.immediate("initializing")),initializing:b.invoke(()=>t.init(),b.transition("done","initialized")),initialized:b.state(b.immediate("loading")),loading:b.invoke(()=>t.load(),b.transition("done","loaded")),loaded:b.state(b.immediate("readying"),b.transition("unload","unloading")),readying:b.invoke(()=>t.ready(),b.transition("done","ready",b.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:b.invoke(()=>t.reload(),b.transition("done","loading")),ready:b.state(b.transition("reload","reloading"),b.transition("unload","unloaded",b.action(t.unload.bind(t))),b.transition("go_online","ready",b.action(()=>{s.send("go_online")})),b.transition("go_offline","ready",b.action(()=>{s.send("go_offline")}))),unloaded:b.state()});return{service:b.interpret(r,o=>D.debug(o.machine.current)),online:s}},Q=m.createLogger({name:"kos-core"}),Kg=()=>{const t=me(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},qg=()=>{const t=window.location.protocol,e=me(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},zg=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=me(),r=s==null?void 0:s.host;let n;try{n=new URL(r).hostname}catch{}return n??e??t},Vg=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=me(),r=s==null?void 0:s.host;let n;try{n=new URL(r).port}catch{}return n??e??t},Gg=(t,e)=>{let s;return{promise:new Promise((o,i)=>{s=setTimeout(()=>{e?m.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):m.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},Fi=t=>typeof t.reload=="function",Yg=t=>typeof t.unload=="function";var gl=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(gl||{});class I{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=rr.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(ys.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(yt.GO_ONLINE)}),C(ys.DISCONNECTED,async()=>{this.fsmService.service.send(yt.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(ys.RELOAD,()=>{Q.warn("WebSocket requested reload"),this.fsmService.service.send(yt.RELOAD)}),C("/studio/project/reload",()=>{Q.warn("Project requested reload"),this.fsmService.service.send(yt.RELOAD)});const s=Tt.getInstance(),r=zg(),n=Vg(),o=qg();s.host=r,s.port=Number.parseInt(n),s.protocol=o,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Kg()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Hg(this),this.fsmService.service.send(yt.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var n,o,i,a;const e=Date.now();if(this._reloading){Q.info("reload already in progress");return}this._reloading=!0,Q.warn("reloading KOS Core"),Q.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Fi(c.modelData)&&(Q.info(`reloading model ${c.modelId}`),(n=c.unload)==null||n.call(c),await c.modelData.reload(),(o=c.registerSubscribers)==null||o.call(c),Q.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Fi(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{Q.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Q.debug("KOS Core going online"),await this._transport.whenReady(),Q.debug("KOS Transport Ready. Calling online() for models"),V("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Q.debug("KOS Core going offline"),V("/kosCore/offline","/kosCore/offline")}async unload(){var n;Q.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Q.debug("unloading KOS Core");const s=this.modelManager;for(const o of s.models)Yg(o.modelData)&&((n=o.unload)==null||n.call(o));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===rr.READY)}async ready(){Q.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(n=>({modelId:n.modelId,model:n,promise:n.whenReady()})),r=(await Promise.allSettled(e.map(n=>{const{promise:o,cancel:i}=Gg(5e3,n.model);Promise.race([n.promise.then(()=>{i()}),o])}))).filter(n=>n.status==="rejected");if(r.length)throw Q.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Q.debug("leaving kos-core ready() ")}get isReady(){return this.status===rr.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Q.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Q.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Q.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Q.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const n=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{$.dataMapper.registerDataMapper(u,p)}):$.dataMapper.registerDataMapper(u,d))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&$.propertyMapper.registerPropertyMapper(u,d)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&$.loader.registerLoader(u,d)}),A.model.getAll().forEach(([,u])=>{e.models={...e.models,...u.registration}}),e.models={...e.models,...A.model.getLegacyModels()},A.companion.getAll().forEach(([u,d])=>{e.companionModels={...e.companionModels},e.companionModels[u]=e.companionModels[u]||[];for(const h of d){let f;if(typeof h=="string"){const p=e.models[h];if(p!=null&&p.class){const y=p.class.prototype[He];f=y==null?void 0:y.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),A.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const o=pl.create(e,s);return n.modelManager=o,n}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function An(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function Wg(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function Qg(t){return await t.arrayBuffer()}function Zg(t,e){return new Blob([t],{type:e})}async function Xg(t){const e={},s=[],r=[];t.forEach((n,o)=>{r.push([o,n])});for(const[n,o]of r)if(o instanceof File){const i=await o.arrayBuffer();s.push({name:n,filename:o.name,type:o.type,data:An(i)})}else e[n]=o.toString();return{fields:e,files:s}}function Jg(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function em(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:An(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await Qg(t);return{data:An(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await Xg(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Ys=m.createLogger({name:"kos-fetch"}),tm=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,sm=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),rm=t=>t!=null&&t.studio?el:t!=null&&t.fos?tl:sl,nm=async(t,e)=>{const s=I.getInstance().transport;await s.whenReady();const r=ot(),n=new URL(t),o=`${n.pathname}${n.search}`;Ys.debug(`path: ${o}`);const i=(e==null?void 0:e.timeout)||tm,a=rm(e),c=await em(e==null?void 0:e.body),u={};c.contentType&&(u["content-type"]=c.contentType),c.encoding&&(u["content-encoding"]=c.encoding);const d=Ve(a({path:o,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...u}}),c.data);return new Promise(h=>{let f=null,p=null;if(e!=null&&e.signal){if(e.signal.aborted){h({headers:Zt({}),status:0,ok:!1,json:async()=>null,body:Xt(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}});return}e.signal.addEventListener("abort",()=>{p&&clearTimeout(p),f&&f(),h({headers:Zt({}),status:0,ok:!1,json:async()=>null,body:Xt(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})})}p=setTimeout(()=>{Ys.error(`Timeout occurred - url: ${t}`),f&&f(),h({headers:Zt({}),status:404,ok:!1,json:async()=>null,body:Xt(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i);const y=C(r,E=>{p&&clearTimeout(p);const S=(E==null?void 0:E.headers)||{},L=S["content-type"]||"text/plain",P=S["content-encoding"],O=(E==null?void 0:E.body)||"";let _=O;if(P==="base64"&&O)try{_=Wg(O)}catch(q){Ys.error("Failed to decode base64 response",q)}const K={headers:Zt(S),status:S.status&&parseInt(S.status)||200,ok:S.status==="200",json:async()=>{try{if(typeof _=="string")return _.length?JSON.parse(_):null;{const J=new TextDecoder().decode(_);return J.length?JSON.parse(J):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof _=="string"?_:new TextDecoder().decode(_),arrayBuffer:async()=>_ instanceof ArrayBuffer?_:new TextEncoder().encode(_).buffer,blob:async()=>_ instanceof ArrayBuffer?Zg(_,L):new Blob([_],{type:L}),formData:async()=>{const q=new FormData;if(L==="multipart/form-data"&&typeof _=="string")try{const J=JSON.parse(_);J.fields&&Object.entries(J.fields).forEach(([zt,Vt])=>{q.append(zt,Vt)}),J.files&&Ys.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return q},body:e!=null&&e.stream?Jg(async q=>{if(_ instanceof ArrayBuffer)q.enqueue(new Uint8Array(_));else{const J=new TextEncoder;q.enqueue(J.encode(_))}q.close()}):Xt(typeof _=="string"?_:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};y.unsubscribe(),sm().then(()=>h(K))});f=y.unsubscribe;const w=e!=null&&e.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${e}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=nm;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const om=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class im{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){om.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(n=>{var o;(o=n.accept)==null||o.call(n,this)}))}}class ml{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const am=async(t,e)=>{const s=new ml;e.forEach(n=>s.use(n));const r={data:t,result:{}};return await s.execute(r),r.result},Ft=t=>({type:t,build:(e,s)=>I.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=I.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),cm=t=>{I.getInstance().modelManager.registerModel(t)},lm=(t,e)=>{I.getInstance().modelManager.registerCompanionModel(t,e)},Ni="/kos/ui/internal/heartbeat/",um=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:n})=>{const o=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=o.subscribeTopic({topic:`${Ni}${t}`,callback:()=>{a=performance.now()}}),u=r??3e3,d=window.setInterval(()=>{let w=performance.now()-a;w=w/1e3,w>u/1e3&&i.abort()},u),h=n??2e3,f=window.setInterval(()=>{ll({msg:{},options:{topic:`${Ni}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},y=()=>{p(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:p}},yl=(...t)=>e=>t.reduce((s,r)=>r(s),e),dm={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function hm(t,e){let s=1;const r={...dm,...e},{maxAttempts:n,baseDelayMs:o,backoffFactor:i}=r;let a=o;for(;s<=n;)try{return await t()}catch(c){if(m.error(`Attempt ${s} failed: ${c}`),s<n)a=o*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw c}throw new Error("All attempts failed")}const fm=m.createLogger({name:"kos-service-request"}),ae=t=>({isMock:!1,URL:exports.BASE_URL}),pm=(t,e,s)=>async({id:r,tracker:n,urlOverride:o,ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d})=>{const h={method:"DELETE"};t&&(h.destinationAddress=t),n&&(h.tracker=n),Nt(h,{ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d});const f=await s(o||`${e}/${r}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},Nt=(t,{ordered:e,studio:s,fos:r,destinationAddress:n,bridge:o,timeout:i})=>(i&&(t.timeout=i),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),o&&(t.bridge=o),(n||n==="")&&(t.destinationAddress=n),t),gm=(t,e,s)=>async({urlOverride:r,ordered:n,studio:o,fos:i,bridge:a,timeout:c,destinationAddress:u})=>{const d={method:"GET"};t&&(d.destinationAddress=t),Nt(d,{timeout:c,ordered:n,studio:o,fos:i,bridge:a,destinationAddress:u});const f=await s(r||e,d);if(!f.ok){let y;try{y=await f.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${f.status}`,y)}return await f.json()},mm=(t,e,s)=>async({urlOverride:r,ordered:n,studio:o,fos:i,bridge:a,tracker:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),c&&(h.tracker=c),Nt(h,{timeout:u,ordered:n,studio:o,fos:i,bridge:a,destinationAddress:d});const f=r||e;fm.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},ym=(t,e,s)=>async({urlOverride:r,id:n,ordered:o,studio:i,fos:a,bridge:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),Nt(h,{timeout:u,ordered:o,studio:i,fos:a,bridge:c,destinationAddress:d});const f=r||`${e}/${n}`,p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class ge extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Ui=(t,e,s)=>async({model:r,urlOverride:n,ordered:o,tracker:i,studio:a,fos:c,bridge:u,timeout:d,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(f.destinationAddress=t),i&&(f.tracker=i),Nt(f,{timeout:d,ordered:o,studio:a,fos:c,bridge:u,destinationAddress:h});const p=await s(n||e,f);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},ji=(t="POST",e,s,r)=>async({model:n,id:o,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,destinationAddress:f})=>{const p={method:t};n&&(p.body=JSON.stringify(n)),e&&(p.destinationAddress=e),Nt(p,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,destinationAddress:f});const y=await r(i||`${s}/${o}`,p);if(!y.ok){let E;try{E=await y.json()}catch{}throw new ge(`There was a problem modifying the model; returned status ${y.status}`,E)}return await y.json()},ne={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:n,addModelPath:o,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:gm(t,s||e,c),getModelById:ym(t,r||e,c),getOne:mm(t,r||e,c),addModel:Ui(t,o||e,c),deleteModel:pm(t,n||e,c),modifyModel:ji("POST",t,i||e,c),putModel:ji("PUT",t,i||e,c),postModel:Ui(t,o||e,c)}}};function bm(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function vm(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function wm(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function Em(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function Mm(t){const e=t.serviceResponses;e&&e.clear()}const Tm=ot(),bl=()=>`kos-${Tm}`,Sm=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(bl()),To=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:n}=C(t,i=>{D.debug(`recieved response for refId ${t}: ${i}`),n(),clearTimeout(o);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),o=setTimeout(()=>{n(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),_m=async(t,e,s)=>{const r=To(s),n=await Promise.allSettled([t(e),r]);if(n[0].status==="fulfilled"){if(n[1].status==="rejected")throw Error(n[1].reason);if(n[0].value){if(n[1].value.error)throw Error(n[1].value.error);return n[0].value.data=n[1].value,n[0].value}}else throw Error(n[0].reason)},Im=async({topic:t,msg:e,requestId:s})=>{const r=s??ot(),n=To(r);V(t,e,{sync:r});const o=await n;if(o.error)throw Error(o.error);return o},he=new Map;class vl{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){X(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=Ie(this._parent))==null?void 0:e.model}get companionModels(){const e=Ie(this._id);return e!=null&&e.model?Cc(e.model):[]}get(e){var s,r;if(this._context.has(e))return this._context.get(e);if(this.companionModels.length>0){const n=this.companionModels.find(o=>{var i;return!o.id||!he.has(o.id)?!1:(i=he.get(o.id))==null?void 0:i.context.has(e)});if(n)return(s=he.get(n.id))==null?void 0:s.get(e)}if(this._parent)return(r=he.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const Y={createContext:(t,e)=>{const s=he.get(t)??new vl(t);if(e){if(!he.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return he.set(t,s),s},getContext:t=>he.get(t),deleteContext:t=>{he.delete(t)},setParentContext:(t,e)=>{var s;if(!he.has(e))throw new Error(`Parent context ${e} does not exist`);(s=he.get(t))==null||s.setParent(e)},rootContext:()=>he.get("root")};Y.createContext("root");const Om=t=>Y.getContext(t.id),yn=m.createLogger({name:"kos-data-container"});class So{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,n)=>(r[n]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=_e(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new mo({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}get revision(){return this._revision}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s))})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=M.isObservable(e)?e:M.observable.object(e),n=this._disposerMap.get(e.id);n&&(n(),this._disposerMap.delete(e.id)),this._data.set(r.id||"",r),s||this.increment();const o=M.observe(r,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(r.id||"",o)}removeModel(e){this._data.delete(e),this.increment();const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}updateModel(e){const s=M.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(yn.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(yn.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return yn.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class $m{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ie.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return Te(this.type)}}class Cm{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ie.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return Te(this.type)}}class wl{constructor(){l(this,"_token");M.makeAutoObservable(this),C("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class El{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const n=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:n})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(n=>!(n.method===e&&n.path===s)),this.openApiRoutes=this.openApiRoutes.filter(n=>!(n.method===e&&n.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:n,params:o}=this.extractPathParams(e.path),i={...e,params:o,query:n};for(const c of this.routes){const u=this.matchRoute(c.path,r);if(c.method===e.method&&u){i.params=u;let d=0;const h=async()=>{if(d<c.middlewares.length){const f=c.middlewares[d++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),n=this.parseQueryParams(r);for(const o of this.routes){const i=this.matchRoute(o.path,s);if(i)return{path:s,query:n,params:i}}return{path:s,query:n,params:{}}}matchRoute(e,s){const r=e.split("/").filter(Boolean),n=s.split("/").filter(Boolean);if(r.length!==n.length)return null;const o={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))o[r[i].slice(1)]=decodeURIComponent(n[i]);else if(r[i]!==n[i])return null;return o}parseQueryParams(e){return e?e.split("&").reduce((s,r)=>{const[n,o]=r.split("=").map(decodeURIComponent);return s[n]=o??"",s},{}):{}}}const Ml=m.createLogger({name:"intent-service"}),Dm=t=>{Jn(`/kos/intent/${t.type}`)?V(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):Ml.info(`No subscribers for intent ${t.type}. Intent not sent.`)},xm=async t=>new Promise(e=>{const{type:s,options:r}=t;if(Jn(`/kos/intent/${t.type}`)){const n=ot(),{unsubscribe:o}=C(n,a=>{clearTimeout(i),o(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=n),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{o(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);V(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:n})}else Ml.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Ae=m.createLogger({name:"app-startup-service"});async function Tl(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:n=!1}=e;if(t.length===0)return Ae.warn("No app IDs provided to waitForAppsToStart"),!0;Ae.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const o=t.map(c=>`/kos/app/started/${c}`),i=await so(o,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>Xc),[u,d]=await c.get("/api/kos/apps/started");return u?(Ae.error("Error fetching started apps:",u),[]):d}catch(c){Ae.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(u=>{const d=c.find(h=>h.appId===u);return!(!d||!d.started||n&&!d.postStarted)}),timeout:s}),a=t.filter(c=>{const u=i.find(d=>d.appId===c);return!!(!u||!u.started||n&&!u.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(Ae.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return Ae.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(o){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Ae.error(i,o),r)throw new Error(`${i} - ${o instanceof Error?o.message:String(o)}`);return!1}}async function Am(t,e={}){return Tl([t],e)}async function Rm(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const n=await r.json(),o=(n==null?void 0:n.data)??[];t.forEach(i=>{const a=o.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){Ae.error("Failed to check app startup status:",r),t.forEach(n=>s[n]=!1)}return s}async function Pm(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return Ae.error("Failed to fetch started apps:",t),[]}}const Rn=M.when,_o=M.computed,X=M.runInAction,W=M.autorun,Sl=M.reaction,Io=M.observable,Oo="Not Assigned",km="kos.trouble.added",Lm="kos.trouble.removed";var ve=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(ve||{}),bs=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(bs||{});const _l=m.createLogger({name:"config-bean-service",group:"Services"}),$o=exports.BASE_URL,Il=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:Fm,getOne:Nm}=ne.build({destinationAddress:"",basePath:`${$o}/kos/config/`}),Ol=async(t,e,s="/api/kos/config")=>(_l.debug(`sending modify request for ConfigBean: ${t}`),Fm({model:e,urlOverride:`${$o}${s}/${t}`})),$l=async(t,e="/api/kos/config")=>(_l.debug(`sending get request for ConfigBean: ${t}`),await Nm({urlOverride:`${$o}${e}/details/${t}/15`})),Co=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",zr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function Cl(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Dl(t,e="",s={}){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const n=e?`${e}.${r}`:r;typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])?Dl(t[r],n,s):s[n]=t[r]}return s}const xl=(t,e)=>{const s=t.details[0].bean||Cl(t.details[0].scopes),r=Dl(s);M.runInAction(()=>{const n={...r};e.props.setValues(n)})},Al=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let n=s.currentValue,o=s.previousValue;typeof n=="string"&&Co(n)&&(n=n.toLowerCase()=="true",o=(o==null?void 0:o.toLowerCase())=="true"),typeof n=="string"&&zr(n)&&(n=Number(n),o=Number(o)),e.props[r]=n,e.prevProps[r]=o})})},Rl=t=>Object.fromEntries(t.props.entries),Um=t=>e=>s=>t.build(e,s);var jm=Object.defineProperty,Bm=Object.getOwnPropertyDescriptor,Pl=(t,e,s,r)=>{for(var n=r>1?void 0:r?Bm(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&jm(e,s,n),n};function Hm(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Do="config-bean-model",Ws=m.getLogger(Do),Km=it("path");let dr=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=Ol,getConfigBean:r=$l}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=_e(),this.prevProps=_e()}get values(){return this.props.values}async ready(){Ws.debug(`readying config bean ${this.path}`),Ws.debug(`complete readying config bean ${this.path}`)}async load(){Ws.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;xl(e,this),Ws.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;X(()=>{s&&(this._schema=s)})}}get schemaKeys(){var t;return Object.keys(((t=this._schema)==null?void 0:t.schema)||{})}getSchemaForProperty(t){var s,r;if(this.schemaKeys.includes(t))return(s=this._schema)==null?void 0:s.schema[t];const e=Hm(this.schemaKeys,t);if(e)return(r=this._schema)==null?void 0:r.schema[e]}async updateProperty(t,e){this.props[t]=e,await this.updateConfigBean()}async updateConfigBean(){const t=Rl(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){Al(t,this)}};Pl([B({topic:`/kos/config/${Km}`,websocket:!0})],dr.prototype,"handleConfigBeanUpdated",1);dr=Pl([R(Do)],dr);const Es=new ye({class:dr,type:Do}),Vr=({path:t,lazy:e,serviceBasePath:s})=>(r,n)=>{r[N]=r[N]||{},r[N][n]={modelType:Es.type,id:`${Es.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:x.INIT,lazy:e}},{URL:kl}=ae(),{getOne:qm,getAll:zm}=ne.build({basePath:`${kl}/api/kos/regions/info`}),Ll=async()=>{try{return await qm({})}catch{return}},Fl=async()=>{try{return await zm({urlOverride:`${kl}/api/kos/regions`})}catch{return}},Vm=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Ll,getRegions:Fl},Symbol.toStringTag,{value:"Module"}));var le=(t=>(t[t.family=0]="family",t[t.scale=1]="scale",t[t.offset=2]="offset",t[t.decimals=3]="decimals",t[t.alias=4]="alias",t[t.system=5]="system",t))(le||{});const Nl={s:["time",1,0,0],second:["time",1,0,0],m:["time",1/60,0,0],minute:["time",1/60,0,0],h:["time",1/3600,0,0],hour:["time",1/3600,0,0],day:["time",1/86400,0,0],week:["time",1/604800,0,0],month:["time",1/2628e3,0,0],year:["time",1/31536e3,0,0],default:["time",1/.001,0,0],ms:["time",1/.001,0,0],millisecond:["time",1/.001,0,0],microsecond:["time",1/1e-6,0,0],nanosecond:["time",1/1e-9,0,0],picosecond:["time",1/1e-12,0,0]};function Gm(t,e){const s=e.id,r=e.units.reduce((n,o)=>{const i=[o.measure,o.scale,o.offset,o.decimals,o.alias,s];return n[o.name]=i,o.alias&&(n[o.alias]=i),n},{...Nl});return{...t,...r}}function Ym(t,e){const s=e.id,r=e.units.reduce((n,o)=>{const i=n[o.measure]||{},a=i[s]||{};i[s]=a;const c=[o.measure,o.scale,o.offset,o.decimals,o.alias,s];return a[o.name]=c,Object.hasOwn(o,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),n[o.measure]=i,o.alias&&(n[o.alias]=i),n},{time:{[s]:{...Nl}}});return Object.keys(r).forEach(n=>{t[n]={...t[n],...r[n]}}),t}function Wm(t,e){const s=e.id,r=e.units.reduce((n,o)=>{const i=n[o.measure]||{};return Object.hasOwn(o,"default")&&(i[s]=o.name),n[o.measure]=i,n},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(n=>{t[n]={...t[n],...r[n]}}),t}var Qm=Object.defineProperty,Zm=Object.getOwnPropertyDescriptor,xo=(t,e,s,r)=>{for(var n=r>1?void 0:r?Zm(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Qm(e,s,n),n};const nr="region-info-model",Wt=m.createLogger({name:"region-info-model"});let Ms=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[le.system]}getUnitMeasure(t){const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[le.family]}getDefaultUnitDecimalPlaces(t,e,s){if(!t||!e)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,n=this.measureMap[t];if(!n)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const o=n[e.toLowerCase()];if(!o)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(n).join(", ")}`);const i=o[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${t} and unit system: ${e}. Unit should come from list of units: ${Object.keys(o).join(", ")}`);return i[le.decimals]}getDefaultUnitForMeasure(t,e){if(!t||!e)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[t];if(!s)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[e.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(t,e,s){if(e[le.family]!==s[le.family])throw new Error(`Cannot convert between units of different families: ${e[le.family]} and ${s[le.family]}`);const r=e[le.offset],n=e[le.scale],o=s[le.scale],i=s[le.offset],a=s[le.decimals];return((t-r)/(n/o)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],n=this.unitSystemMap[s];if(!r||!n)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,n)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",n=s.unit||"";let o=this.unitSystemMap[r],i=this.unitSystemMap[n];if(!i&&s.measure&&s.system){const u=this.measureMap[s.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=u[s.system])==null?void 0:a.default,i||Wt.info("Could not find default unit for measure",s.measure)}if(!o&&e.measure&&e.system){const u=this.measureMap[e.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);o=(c=u[e.system])==null?void 0:c.default,o||Wt.info("Could not find default unit for measure",e.measure)}return!o||!i?(Wt.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,o,i)}async init(){Wt.debug("initializing region info")}async load(){Wt.debug("loading region info");const t=await Fl();t&&(this.regions=t.data.map(s=>s.id),this.timeZoneMap=t.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=t.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const e=await Ll();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const n={id:r.id,name:r.id};return s[r.id]=n,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(Gm,{}),this.measureMap=e.data.unitSystems.reduce(Ym,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(Wm,{}),this.timeFormats=e.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=e.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var t,e;await((e=(t=this.regionSource).ready)==null?void 0:e.call(t))}};xo([Vr({path:"kos:service:region:settings"})],Ms.prototype,"regionSource",2);xo([Vr({path:"kos:service:region"})],Ms.prototype,"region",2);Ms=xo([R(nr)],Ms);const re={registration:{[nr]:{class:Ms,singleton:!0}},type:nr,factory:ie.Singleton.create(nr)},hr=({source:t,defaultSystem:e="si",defaultMeasure:s})=>{let r={system:e,measure:s};return typeof t=="string"?r={...r,unit:t}:r={...r,...t},r},Ao=(t,e,s)=>{const{model:r}=Ie(re.type);if(!r)throw new Error("RegionInfo model not found");if(!ur(r))throw new Error("RegionInfo model not ready");const n={system:r.defaultUnitSystem},o=hr({source:e}),i=hr({source:s||n,defaultMeasure:r.getUnitMeasure(o.unit||"")});return r.convert(t,o,i)};function Bi(t,e,s){const r=e.toLowerCase().replace(/_/g,"-").replace(/s$/,""),n=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const o=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(n,{style:"unit",unit:r,unitDisplay:o,minimumFractionDigits:a,maximumFractionDigits:i}).format(t)}catch{return e}}const Xm=(t,e,s,r)=>{const n=Ao(t,e,s),o=hr({source:e}),{model:i}=Ie(re.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(o.unit||""),c={system:i.defaultUnitSystem},u=hr({source:s||c,defaultMeasure:i.getUnitMeasure(o.unit||"")}),d=i.getDefaultUnitForMeasure(a,u.system),h=i.getDefaultUnitDecimalPlaces(a,u.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:n,unit:d||o.unit||"",display:Bi(n,d||o.unit||"",{...f,mode:"long"}),shortDisplay:Bi(n,d||o.unit||"",{...f,mode:"short"})}};function Hi({start:t,end:e,count:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(t>=e)throw new Error("Start should be less than end.");const n=(e-t)/(s-1),o=[];for(let i=0;i<s;i++){const a=Math.round(t+i*n);o.push(a.toFixed(r))}return o}function Ki({start:t,end:e,interval:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(t>=e)throw new Error("Start should be less than end.");const n=[];let o=t;for(;o<=e;)n.push(o.toFixed(r)),o+=s;return n[n.length-1]!==e.toString()&&n.push(e.toString()),n}const ft=(t,e)=>s=>!t||!e?s:zr(s)?Ao(Number(s),t,e):s,Jm=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Hi(t.options).map(ft(s,r));if(t.options.type==="rangeInterval")return Ki(t.options).map(ft(s,r));if(t.options.type==="list"){const{list:n}=t.options;return n.map(ft(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Hi(t.options.unitSystems[e]).map(ft(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Ki(t.options.unitSystems[e]).map(ft(s,r));if(t.options.type==="unitSystemList"&&e){const{list:n}=t.options.unitSystems[e];return n.map(ft(s,r))}}return[]},ey=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var ty=Object.defineProperty,sy=Object.getOwnPropertyDescriptor,Ro=(t,e,s,r)=>{for(var n=r>1?void 0:r?sy(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&ty(e,s,n),n};function ry(t){return(t==null?void 0:t.type)==="enum"}function ny(t){switch(t){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return t}}function oy(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return je.format(r,e)}const or="config-bean-prop-model",pt=m.createLogger({name:"config-bean-prop-model"}),iy=it("path"),ay=it("serviceBasePath");let Ts=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return Il(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(t,e,s)}getDefaultUnitForMeasure(t,e){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(t,e)}get schemaType(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.type?t.type:"String"}get schemaFormat(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.format?ny(t.format):""}get options(){var i;const t=this.regionInfo.defaultUnitSystem,e=this.getConverter(),s=((i=e==null?void 0:e.to)==null?void 0:i.system)??t,r=this.bean.getSchemaForProperty(this.attribute),n=ry(r)?r.values:Jm(r,s,e==null?void 0:e.from,e==null?void 0:e.to),o=n.length>0?n.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,n):this.optionsExpander:o}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,n=(t==null?void 0:t.system)||e,o=t==null?void 0:t.unit;return{measure:r,system:n,unit:o}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),n=this.convertUnit(e.to,t,s);return{backend:r,display:n}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var n,o;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((n=s==null?void 0:s.to)==null?void 0:n.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(o=s==null?void 0:s.to)==null?void 0:o.unit);try{const c=this.getFormatterOptions(s);if(c){let u=String(t);return u=c.formatToParts(Number(t))[0].value,Number(u)}}catch(c){pt.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:n}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,n)}return e||""}async activate(){pt.debug(`activating config bean ${this.id}`)}get displayValue(){const t=this.value;if(typeof t=="boolean")return String(t);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return oy(t,s)}if(!isNaN(t))try{const e=this.getConverter(),s=this.getFormatterOptions(e);if(s){let r=String(t);return r=s.format(Number(t)),r}}catch(e){pt.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(n=>n.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var n;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((n=s==null?void 0:s.to)==null?void 0:n.system)??e;return ey(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,n;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((n=t==null?void 0:t.to)==null?void 0:n.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var o,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let n=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,u=this.formatter||c;if(u){let d=typeof u=="function"?u(((o=t==null?void 0:t.to)==null?void 0:o.system)||e):u;s&&(d={unit:this.getDefaultUnit(t),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{n=new Intl.NumberFormat(r,{...d})}catch(h){pt.error(`error creating formatter ${d}. Returning the raw value`,h)}}else pt.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return n}getConverter(){var r,n,o,i,a,c,u,d,h,f,p;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const y=(r=this.converter)==null?void 0:r.measure,w=(o=(n=this.converter)==null?void 0:n.to)==null?void 0:o.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,S=y||w||E||e,L=((u=(c=this.converter)==null?void 0:c.to)==null?void 0:u.unit)||this.regionInfo.getDefaultUnitForMeasure(S,((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),P=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(L),O=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:O,...this.converter.from},to:{...this.converter.to,unit:L,system:P},measure:S}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:w===E?s:y}}}}async updateProperty(t){pt.debug(`updating property ${this.attribute} with value ${t}`);let e=t;if(this.getConverter()&&!isNaN(e)){const{backend:n,display:o}=this.getConverterUnits();e=this.regionInfo.convert(Number(e),o,n)}const r=Array.isArray(e)?JSON.stringify(e):String(e);await this.bean.updateProperty(this.attribute,r)}};Ro([Lt({modelType:re.type})],Ts.prototype,"regionInfo",2);Ro([Vr({path:iy,serviceBasePath:ay})],Ts.prototype,"bean",2);Ts=Ro([R(or)],Ts);const at={registration:{[or]:{class:Ts,singleton:!1}},type:or,factory:ie.Factory.create(or)};function cy(t){const{path:e,attribute:s,converter:r,formatter:n,lazy:o,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(u,d)=>{u[N]=u[N]||{},u[N][d]={modelType:at.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:n,optionsExpander:i},lifecycle:x.INIT,lazy:o}}}const Ul="future-model",Ut=Ft(Ul),Gr=m.createLogger({name:"future-service",group:"Services"}),{isMock:ly,URL:Ns}=ae();var Ke=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(Ke||{});const{getAll:uy,modifyModel:dy,addModel:hy,deleteModel:fy,postModel:py}=ne.build({destinationAddress:"",basePath:`${Ns}/api/future`,mock:ly}),gy=async()=>await uy({}),jl=async(t,e="/api/kos/future")=>(Gr.info(`sending delete request for Future: ${t}`),await fy({id:t,urlOverride:`${Ns}${e}/${t}`})),Bl=async(t,e="/api/kos/future")=>(Gr.info("sending add request for Future"),await hy({model:t,urlOverride:`${Ns}${e}`})),my=async(t,e,s="/api/kos/future")=>(Gr.info(`sending modify request for Future: ${t}`),dy({model:e,id:t,urlOverride:`${Ns}${s}/${t}`})),Hl=async(t,e="/api/kos/future")=>(Gr.info(`sending cancel request for Future: ${t}`),py({urlOverride:`${Ns}${e}/${t}/cancel`,ordered:!0,model:{}})),Po=t=>({id:String(t.id),progress:t.progress,remainingTimeMs:t.remainingTimeMs,endState:t.endState,reason:t.reason,clientData:t.clientData,reasonData:t.reasonData,note:t.note,tracker:t.tracker}),ko=(t,e)=>{m.debug(`future dto ${t.id} end state ${t.endState}`),m.debug(`future model ${e.id} end state ${e.endState}`),e.endState?m.debug(`future model ${e.id} is already complete`):(m.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=Po(t);X(()=>{Object.keys(s).forEach(r=>{r==="id"?(e.futureId=s.id,s.tracker||(e.id=s.id)):r==="tracker"?e.id=s.tracker:e[r]=s[r]})})}))},Kl=t=>e=>s=>t.build(String(e),s),Lo=t=>e=>yl(Po,Kl(t)(e.tracker||e.id))(e);var yy=Object.defineProperty,by=Object.getOwnPropertyDescriptor,ql=(t,e,s,r)=>{for(var n=r>1?void 0:r?by(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&yy(e,s,n),n};const bn=m.getLogger(Ut.type);let fr=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=Hl,Rn(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{bn.info(`Future ${this.id} has completed with status ${this.status}`),st(this)})}async load(){bn.debug(`loading Future ${this.id}`)}unload(){bn.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Rn(()=>this.futureId!==Oo),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[u,d]of Object.entries(e))if(Math.abs(t)>=d){s=u,r=Math.round(t/d);break}const o=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return o.length===3?`${((a=o[1])==null?void 0:a.value)??0} ${((c=o[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),ko(t,this)}};ql([B({topic:`kos.future/${ar}`})],fr.prototype,"handleFutureUpdated",1);fr=ql([R(Ut.type)],fr);const zl=fr,Vl=Eo();var vy=Object.defineProperty,wy=Object.getOwnPropertyDescriptor,Gl=(t,e,s,r)=>{for(var n=r>1?void 0:r?wy(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&vy(e,s,n),n};const Yl="browser-router-model",Ey="kos.http.request",My="kos.http.response";let pr=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new El}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],n=e.headers.url,o=e.headers.method,i=e.headers["request-id"],a={id:i,method:o,path:n,body:t};let c=200;const u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),ul({msg:d,options:{responseId:i,destinationAddress:s,type:My,sourceAddress:r,status:c}})},status:function(d){return c=d,this}};if(a.path==="/openapi.json"){u.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,u)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};Gl([B({topic:Ey})],pr.prototype,"handleRequest",1);pr=Gl([R(Yl)],pr);const Fo=new Se({class:pr,type:Yl}),Wl="future-container-model",qe=Ft(Wl),Ql=t=>Lo(Ut)(t),Ty=t=>{const e=Ql(t);return qe.build(qe.type,{}).addFutureModel(e),e},Sy=t=>qe.build(qe.type,{}).getFuture(String(t)),rt={buildFutureModel:Ql,initiateFuture:Ty,getFuture:Sy};var _y=Object.defineProperty,Iy=Object.getOwnPropertyDescriptor,No=(t,e,s,r)=>{for(var n=r>1?void 0:r?Iy(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&_y(e,s,n),n};const Qs=m.getLogger(qe.type);let Ss=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=jl,addFuture:n=Bl}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=n,this.id=t,this._futures=new Ce,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){Qs.error("error deleting a Future"),Qs.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Lo(Ut)(s);return this.addFutureModel(r),r}}catch(e){throw Qs.error("error creating a Future"),Qs.error(e),e}}handleFutureUpdated(t,e){const s=rt.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),V(r,e.body,e.headers)}};No([$e],Ss.prototype,"_futures",2);No([B({topic:"kos.future"})],Ss.prototype,"handleFutureUpdated",1);Ss=No([R(qe.type)],Ss);const Zl=Ss,{URL:Us}=ae(),{getOne:Oy,postModel:$y,deleteModel:Xl}=ne.build({basePath:`${Us}/api/keyVal`}),Pn=m.createLogger({name:"key-value-service",group:"Services"}),Jl=async(t,e)=>{await Xl({urlOverride:`${Us}/api/keyVal/${t}/${e}`,id:e})},eu=async(t,e,s)=>{const r=await $y({urlOverride:`${Us}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Pn.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},tu=async(t="studio")=>{Pn.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await Oy({urlOverride:`${Us}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Pn.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},Cy=async t=>{await Xl({urlOverride:`${Us}/api/keyVal/${t}`,id:""})},Dy=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Jl,deleteKeyValueNamespace:Cy,getKeyValue:tu,updateKeyValue:eu},Symbol.toStringTag,{value:"Module"}));var xy=Object.defineProperty,Ay=Object.getOwnPropertyDescriptor,Uo=(t,e,s,r)=>{for(var n=r>1?void 0:r?Ay(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&xy(e,s,n),n};const su="key-value-model";let _s=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=_e(),this.namespace=e.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(t,e){this.logger.debug(`updating studio-state ${t} with value ${e}`),e!==void 0?(await eu(this.namespace,t,e),this.data[t]=e):(await Jl(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await tu(this.namespace);this.data.setValues(t)}handleStateUpdate(t){t.namespace===this.namespace&&(this.data[t.key]=t.value)}handleStateDelete(t){t.namespace===this.namespace&&(this.data[t.key]=void 0)}};Uo([B({topic:"/keyVal/set"})],_s.prototype,"handleStateUpdate",1);Uo([B({topic:"/keyVal/remove"})],_s.prototype,"handleStateDelete",1);_s=Uo([R(su)],_s);const jo=new ye({class:_s,type:su});var fe="INUMBER",jt="IOP1",Bt="IOP2",Ht="IOP3",Pe="IVAR",nt="IVARNAME",St="IFUNCALL",Yr="IFUNDEF",oe="IEXPR",Bo="IEXPREVAL",ct="IMEMBER",Wr="IENDSTATEMENT",_t="IARRAY";function k(t,e){this.type=t,this.value=e??0}k.prototype.toString=function(){switch(this.type){case fe:case jt:case Bt:case Ht:case Pe:case nt:case Wr:return this.value;case St:return"CALL "+this.value;case Yr:return"DEF "+this.value;case _t:return"ARRAY "+this.value;case ct:return"."+this.value;default:return"Invalid Instruction"}};function Qr(t){return new k(jt,t)}function Ue(t){return new k(Bt,t)}function ru(t){return new k(Ht,t)}function kn(t,e,s,r,n){for(var o=[],i=[],a,c,u,d,h=0;h<t.length;h++){var f=t[h],p=f.type;if(p===fe||p===nt)Array.isArray(f.value)?o.push.apply(o,kn(f.value.map(function(y){return new k(fe,y)}).concat(new k(_t,f.value.length)),e,s,r,n)):o.push(f);else if(p===Pe&&n.hasOwnProperty(f.value))f=new k(fe,n[f.value]),o.push(f);else if(p===Bt&&o.length>1)c=o.pop(),a=o.pop(),d=s[f.value],f=new k(fe,d(a.value,c.value)),o.push(f);else if(p===Ht&&o.length>2)u=o.pop(),c=o.pop(),a=o.pop(),f.value==="?"?o.push(a.value?c.value:u.value):(d=r[f.value],f=new k(fe,d(a.value,c.value,u.value)),o.push(f));else if(p===jt&&o.length>0)a=o.pop(),d=e[f.value],f=new k(fe,d(a.value)),o.push(f);else if(p===oe){for(;o.length>0;)i.push(o.shift());i.push(new k(oe,kn(f.value,e,s,r,n)))}else if(p===ct&&o.length>0)a=o.pop(),o.push(new k(fe,a.value[f.value]));else{for(;o.length>0;)i.push(o.shift());i.push(f)}}for(;o.length>0;)i.push(o.shift());return i}function nu(t,e,s){for(var r=[],n=0;n<t.length;n++){var o=t[n],i=o.type;if(i===Pe&&o.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===jt?u=Qr(c.value):c.type===Bt?u=Ue(c.value):c.type===Ht?u=ru(c.value):u=new k(c.type,c.value),r.push(u)}else i===oe?r.push(new k(oe,nu(o.value,e,s))):r.push(o)}return r}function Ze(t,e,s){var r=[],n,o,i,a,c,u;if(Ho(t))return xe(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===fe||p===nt)r.push(f.value);else if(p===Bt)o=r.pop(),n=r.pop(),f.value==="and"?r.push(n?!!Ze(o,e,s):!1):f.value==="or"?r.push(n?!0:!!Ze(o,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(n,Ze(o,e,s),s))):(a=e.binaryOps[f.value],r.push(a(xe(n,s),xe(o,s))));else if(p===Ht)i=r.pop(),o=r.pop(),n=r.pop(),f.value==="?"?r.push(Ze(n?o:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(xe(n,s),xe(o,s),xe(i,s))));else if(p===Pe)if(f.value in e.functions)r.push(e.functions[f.value]);else if(f.value in e.unaryOps&&e.parser.isOperatorEnabled(f.value))r.push(e.unaryOps[f.value]);else{var y=s[f.value];if(y!==void 0)r.push(y);else throw new Error("undefined variable: "+f.value)}else if(p===jt)n=r.pop(),a=e.unaryOps[f.value],r.push(a(xe(n,s)));else if(p===St){for(u=f.value,c=[];u-- >0;)c.unshift(xe(r.pop(),s));if(a=r.pop(),a.apply&&a.call)r.push(a.apply(void 0,c));else throw new Error(a+" is not a function")}else if(p===Yr)r.push(function(){for(var w=r.pop(),E=[],S=f.value;S-- >0;)E.unshift(r.pop());var L=r.pop(),P=function(){for(var O=Object.assign({},s),_=0,K=E.length;_<K;_++)O[E[_]]=arguments[_];return Ze(w,e,O)};return Object.defineProperty(P,"name",{value:L,writable:!1}),s[L]=P,P}());else if(p===oe)r.push(Ry(f,e));else if(p===Bo)r.push(f);else if(p===ct)n=r.pop(),r.push(n[f.value]);else if(p===Wr)r.pop();else if(p===_t){for(u=f.value,c=[];u-- >0;)c.unshift(r.pop());r.push(c)}else throw new Error("invalid Expression")}if(r.length>1)throw new Error("invalid Expression (parity)");return r[0]===0?0:xe(r[0],s)}function Ry(t,e,s){return Ho(t)?t:{type:Bo,value:function(r){return Ze(t.value,e,r)}}}function Ho(t){return t&&t.type===Bo}function xe(t,e){return Ho(t)?t.value(e):t}function Ko(t,e){for(var s=[],r,n,o,i,a,c,u=0;u<t.length;u++){var d=t[u],h=d.type;if(h===fe)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(qi).join(", ")+"]"):s.push(qi(d.value));else if(h===Bt)n=s.pop(),r=s.pop(),i=d.value,e?i==="^"?s.push("Math.pow("+r+", "+n+")"):i==="and"?s.push("(!!"+r+" && !!"+n+")"):i==="or"?s.push("(!!"+r+" || !!"+n+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+n+")))"):i==="=="?s.push("("+r+" === "+n+")"):i==="!="?s.push("("+r+" !== "+n+")"):i==="["?s.push(r+"[("+n+") | 0]"):s.push("("+r+" "+i+" "+n+")"):i==="["?s.push(r+"["+n+"]"):s.push("("+r+" "+i+" "+n+")");else if(h===Ht)if(o=s.pop(),n=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+n+" : "+o+")");else throw new Error("invalid Expression");else if(h===Pe||h===nt)s.push(d.value);else if(h===jt)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):e?i==="not"?s.push("(!"+r+")"):i==="!"?s.push("fac("+r+")"):s.push(i+"("+r+")"):i==="!"?s.push("("+r+"!)"):s.push("("+i+" "+r+")");else if(h===St){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===Yr){for(n=s.pop(),c=d.value,a=[];c-- >0;)a.unshift(s.pop());r=s.pop(),e?s.push("("+r+" = function("+a.join(", ")+") { return "+n+" })"):s.push("("+r+"("+a.join(", ")+") = "+n+")")}else if(h===ct)r=s.pop(),s.push(r+"."+d.value);else if(h===_t){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===oe)s.push("("+Ko(d.value,e)+")");else if(h!==Wr)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function qi(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function vt(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function qo(t,e,s){s=s||{};for(var r=!!s.withMembers,n=null,o=0;o<t.length;o++){var i=t[o];i.type===Pe||i.type===nt?!r&&!vt(e,i.value)?e.push(i.value):(n!==null&&(vt(e,n)||e.push(n)),n=i.value):i.type===ct&&r&&n!==null?n+="."+i.value:i.type===oe?qo(i.value,e,s):n!==null&&(vt(e,n)||e.push(n),n=null)}n!==null&&!vt(e,n)&&e.push(n)}function we(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}we.prototype.simplify=function(t){return t=t||{},new we(kn(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};we.prototype.substitute=function(t,e){return e instanceof we||(e=this.parser.parse(String(e))),new we(nu(this.tokens,t,e),this.parser)};we.prototype.evaluate=function(t){return t=t||{},Ze(this.tokens,this,t)};we.prototype.toString=function(){return Ko(this.tokens,!1)};we.prototype.symbols=function(t){t=t||{};var e=[];return qo(this.tokens,e,t),e};we.prototype.variables=function(t){t=t||{};var e=[];qo(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};we.prototype.toJSFunction=function(t,e){var s=this,r=new Function(t,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+Ko(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var Is="TEOF",j="TOP",Zr="TNUMBER",ou="TSTRING",ke="TPAREN",It="TBRACKET",Xr="TCOMMA",zo="TNAME",Vo="TSEMICOLON";function iu(t,e,s){this.type=t,this.value=e,this.index=s}iu.prototype.toString=function(){return this.type+": "+this.value};function G(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}G.prototype.newToken=function(t,e,s){return new iu(t,e,s??this.pos)};G.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};G.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};G.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(Is,"EOF");if(this.isWhitespace()||this.isComment())return this.next();if(this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName())return this.current;this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')};G.prototype.isString=function(){var t=!1,e=this.pos,s=this.expression.charAt(e);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,e+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var n=this.expression.substring(e+1,r);this.current=this.newToken(ou,this.unescape(n),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};G.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(ke,t),this.pos++,!0):!1};G.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(It,t),this.pos++,!0):!1};G.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(Xr,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(Vo,";"),this.pos++,!0):!1};G.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(r in this.consts)return this.current=this.newToken(Zr,this.consts[r]),this.pos+=r.length,!0}return!1};G.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(j,r),this.pos+=r.length,!0}return!1};G.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var n=this.expression.substring(t,e);return this.current=this.newToken(zo,n),this.pos+=n.length,!0}return!1};G.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
78
+ `||e==="\r")&&(t=!0,this.pos++,!(this.pos>=this.expression.length));)e=this.expression.charAt(this.pos);return t};var Py=/^[0-9a-f]{4}$/i;G.prototype.unescape=function(t){var e=t.indexOf("\\");if(e<0)return t;for(var s=t.substring(0,e);e>=0;){var r=t.charAt(++e);switch(r){case"'":s+="'";break;case'"':s+='"';break;case"\\":s+="\\";break;case"/":s+="/";break;case"b":s+="\b";break;case"f":s+="\f";break;case"n":s+=`
79
+ `;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var n=t.substring(e+1,e+5);Py.test(n)||this.parseError("Illegal escape sequence: \\u"+n),s+=String.fromCharCode(parseInt(n,16)),e+=4;break;default:throw this.parseError('Illegal escape sequence: "\\'+r+'"')}++e;var o=t.indexOf("\\",e);s+=t.substring(e,o<0?t.length:o),e=o}return s};G.prototype.isComment=function(){var t=this.expression.charAt(this.pos);return t==="/"&&this.expression.charAt(this.pos+1)==="*"?(this.pos=this.expression.indexOf("*/",this.pos)+2,this.pos===1&&(this.pos=this.expression.length),!0):!1};G.prototype.isRadixInteger=function(){var t=this.pos;if(t>=this.expression.length-2||this.expression.charAt(t)!=="0")return!1;++t;var e,s;if(this.expression.charAt(t)==="x")e=16,s=/^[0-9a-f]$/i,++t;else if(this.expression.charAt(t)==="b")e=2,s=/^[01]$/i,++t;else return!1;for(var r=!1,n=t;t<this.expression.length;){var o=this.expression.charAt(t);if(s.test(o))t++,r=!0;else break}return r&&(this.current=this.newToken(Zr,parseInt(this.expression.substring(n,t),e)),this.pos=t),r};G.prototype.isNumber=function(){for(var t=!1,e=this.pos,s=e,r=e,n=!1,o=!1,i;e<this.expression.length&&(i=this.expression.charAt(e),i>="0"&&i<="9"||!n&&i===".");)i==="."?n=!0:o=!0,e++,t=o;if(t&&(r=e),i==="e"||i==="E"){e++;for(var a=!0,c=!1;e<this.expression.length;){if(i=this.expression.charAt(e),a&&(i==="+"||i==="-"))a=!1;else if(i>="0"&&i<="9")c=!0,a=!1;else break;e++}c||(e=r)}return t?(this.current=this.newToken(Zr,parseFloat(this.expression.substring(s,e))),this.pos=e):this.pos=r,t};G.prototype.isOperator=function(){var t=this.pos,e=this.expression.charAt(this.pos);if(e==="+"||e==="-"||e==="*"||e==="/"||e==="%"||e==="^"||e==="?"||e===":"||e===".")this.current=this.newToken(j,e);else if(e==="∙"||e==="•")this.current=this.newToken(j,"*");else if(e===">")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,">="),this.pos++):this.current=this.newToken(j,">");else if(e==="<")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"<="),this.pos++):this.current=this.newToken(j,"<");else if(e==="|")if(this.expression.charAt(this.pos+1)==="|")this.current=this.newToken(j,"||"),this.pos++;else return!1;else if(e==="=")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"=="),this.pos++):this.current=this.newToken(j,e);else if(e==="!")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"!="),this.pos++):this.current=this.newToken(j,e);else return!1;return this.pos++,this.isOperatorEnabled(this.current.value)?!0:(this.pos=t,!1)};G.prototype.isOperatorEnabled=function(t){return this.parser.isOperatorEnabled(t)};G.prototype.getCoordinates=function(){var t=0,e,s=-1;do t++,e=this.pos-s,s=this.expression.indexOf(`
80
+ `,s+1);while(s>=0&&s<this.pos);return{line:t,column:e}};G.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)};function H(t,e,s){this.parser=t,this.tokens=e,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}H.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};H.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?vt(e,t.value):typeof e=="function"?e(t):t.value===e};H.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};H.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};H.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};H.prototype.expect=function(t,e){if(!this.accept(t,e)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(e||t))}};H.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.accept(zo)||this.accept(j,s))t.push(new k(Pe,this.current.value));else if(this.accept(Zr))t.push(new k(fe,this.current.value));else if(this.accept(ou))t.push(new k(fe,this.current.value));else if(this.accept(ke,"("))this.parseExpression(t),this.expect(ke,")");else if(this.accept(It,"["))if(this.accept(It,"]"))t.push(new k(_t,0));else{var r=this.parseArrayList(t);t.push(new k(_t,r))}else throw new Error("unexpected "+this.nextToken)};H.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};H.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};H.prototype.parseUntilEndStatement=function(t,e){return this.accept(Vo)?(this.nextToken&&this.nextToken.type!==Is&&!(this.nextToken.type===ke&&this.nextToken.value===")")&&e.push(new k(Wr)),this.nextToken.type!==Is&&this.parseExpression(e),t.push(new k(oe,e)),!0):!1};H.prototype.parseArrayList=function(t){for(var e=0;!this.accept(It,"]");)for(this.parseExpression(t),++e;this.accept(Xr);)this.parseExpression(t),++e;return e};H.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(j,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===St){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var n=0,o=e.value+1;n<o;n++){var i=r-n;t[i].type===Pe&&(t[i]=new k(nt,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new k(oe,s)),t.push(new k(Yr,e.value));continue}if(e.type!==Pe&&e.type!==ct)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new k(nt,e.value)),t.push(new k(oe,s)),t.push(Ue("="))}};H.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(j,"?");){var e=[],s=[];this.parseConditionalExpression(e),this.expect(j,":"),this.parseConditionalExpression(s),t.push(new k(oe,e)),t.push(new k(oe,s)),t.push(ru("?"))}};H.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(j,"or");){var e=[];this.parseAndExpression(e),t.push(new k(oe,e)),t.push(Ue("or"))}};H.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(j,"and");){var e=[];this.parseComparison(e),t.push(new k(oe,e)),t.push(Ue("and"))}};var ky=["==","!=","<","<=",">=",">","in"];H.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,ky);){var e=this.current;this.parseAddSub(t),t.push(Ue(e.value))}};var Ly=["+","-","||"];H.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(j,Ly);){var e=this.current;this.parseTerm(t),t.push(Ue(e.value))}};var Fy=["*","/","%"];H.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,Fy);){var e=this.current;this.parseFactor(t),t.push(Ue(e.value))}};H.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.save(),this.accept(j,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===ke&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===Vo||this.nextToken.type===Xr||this.nextToken.type===Is||this.nextToken.type===ke&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(Qr(r.value))}else this.parseExponential(t)};H.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(j,"^");)this.parseFactor(t),t.push(Ue("^"))};H.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(j,"!");)t.push(Qr("!"))};H.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.accept(j,s)){var r=this.current;this.parseAtom(t),t.push(Qr(r.value))}else for(this.parseMemberExpression(t);this.accept(ke,"(");)if(this.accept(ke,")"))t.push(new k(St,0));else{var n=this.parseArgumentList(t);t.push(new k(St,n))}};H.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(ke,")");)for(this.parseExpression(t),++e;this.accept(Xr);)this.parseExpression(t),++e;return e};H.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(j,".")||this.accept(It,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(zo),t.push(new k(ct,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(It,"]"),t.push(Ue("["))}else throw new Error("unexpected symbol: "+e.value)}};function Ny(t,e){return Number(t)+Number(e)}function Uy(t,e){return t-e}function jy(t,e){return t*e}function By(t,e){return t/e}function Hy(t,e){return t%e}function Ky(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function qy(t,e){return t===e}function zy(t,e){return t!==e}function Vy(t,e){return t>e}function Gy(t,e){return t<e}function Yy(t,e){return t>=e}function Wy(t,e){return t<=e}function Qy(t,e){return!!(t&&e)}function Zy(t,e){return!!(t||e)}function Xy(t,e){return vt(e,t)}function Jy(t){return(Math.exp(t)-Math.exp(-t))/2}function eb(t){return(Math.exp(t)+Math.exp(-t))/2}function tb(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function sb(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function rb(t){return Math.log(t+Math.sqrt(t*t-1))}function nb(t){return Math.log((1+t)/(1-t))/2}function zi(t){return Math.log(t)*Math.LOG10E}function ob(t){return-t}function ib(t){return!t}function ab(t){return t<0?Math.ceil(t):Math.floor(t)}function cb(t){return Math.random()*(t||1)}function Vi(t){return Go(t+1)}function lb(t){return isFinite(t)&&t===Math.round(t)}var ub=4.7421875,vn=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function Go(t){var e,s;if(lb(t)){if(t<=0)return isFinite(t)?1/0:NaN;if(t>171)return 1/0;for(var r=t-2,n=t-1;r>1;)n*=r,r--;return n===0&&(n=1),n}if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*Go(1-t));if(t>=171.35)return 1/0;if(t>85){var o=t*t,i=o*t,a=i*t,c=a*t;return Math.sqrt(2*Math.PI/t)*Math.pow(t/Math.E,t)*(1+1/(12*t)+1/(288*o)-139/(51840*i)-571/(2488320*a)+163879/(209018880*c)+5246819/(75246796800*c*t))}--t,s=vn[0];for(var u=1;u<vn.length;++u)s+=vn[u]/(t+u);return e=t+ub+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function db(t){return Array.isArray(t)?t.length:String(t).length}function Gi(){for(var t=0,e=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),n;e<r?(n=e/r,t=t*n*n+1,e=r):r>0?(n=r/e,t+=n*n):t+=r}return e===1/0?1/0:e*Math.sqrt(t)}function Yi(t,e,s){return t?e:s}function hb(t,e){return typeof e>"u"||+e==0?Math.round(t):(t=+t,e=-+e,isNaN(t)||!(typeof e=="number"&&e%1===0)?NaN:(t=t.toString().split("e"),t=Math.round(+(t[0]+"e"+(t[1]?+t[1]-e:-e))),t=t.toString().split("e"),+(t[0]+"e"+(t[1]?+t[1]+e:e))))}function fb(t,e,s){return s&&(s[t]=e),e}function pb(t,e){return t[e|0]}function gb(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function mb(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function yb(t,e){if(typeof t!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(e))throw new Error("Second argument to map is not an array");return e.map(function(s,r){return t(s,r)})}function bb(t,e,s){if(typeof t!="function")throw new Error("First argument to fold is not a function");if(!Array.isArray(s))throw new Error("Second argument to fold is not an array");return s.reduce(function(r,n,o){return t(r,n,o)},e)}function vb(t,e){if(typeof t!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(e))throw new Error("Second argument to filter is not an array");return e.filter(function(s,r){return t(s,r)})}function wb(t,e){if(!(Array.isArray(e)||typeof e=="string"))throw new Error("Second argument to indexOf is not a string or array");return e.indexOf(t)}function Eb(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function Mb(t){return(t>0)-(t<0)||+t}var Wi=1/3;function Tb(t){return t<0?-Math.pow(-t,Wi):Math.pow(t,Wi)}function Sb(t){return Math.exp(t)-1}function _b(t){return Math.log(1+t)}function Ib(t){return Math.log(t)/Math.LN2}function lt(t){this.options=t||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||Jy,cosh:Math.cosh||eb,tanh:Math.tanh||tb,asinh:Math.asinh||sb,acosh:Math.acosh||rb,atanh:Math.atanh||nb,sqrt:Math.sqrt,cbrt:Math.cbrt||Tb,log:Math.log,log2:Math.log2||Ib,ln:Math.log,lg:Math.log10||zi,log10:Math.log10||zi,expm1:Math.expm1||Sb,log1p:Math.log1p||_b,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||ab,"-":ob,"+":Number,exp:Math.exp,not:ib,length:db,"!":Vi,sign:Math.sign||Mb},this.binaryOps={"+":Ny,"-":Uy,"*":jy,"/":By,"%":Hy,"^":Math.pow,"||":Ky,"==":qy,"!=":zy,">":Vy,"<":Gy,">=":Yy,"<=":Wy,and:Qy,or:Zy,in:Xy,"=":fb,"[":pb},this.ternaryOps={"?":Yi},this.functions={random:cb,fac:Vi,min:mb,max:gb,hypot:Math.hypot||Gi,pyt:Math.hypot||Gi,pow:Math.pow,atan2:Math.atan2,if:Yi,gamma:Go,roundTo:hb,map:yb,fold:bb,filter:vb,indexOf:wb,join:Eb},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}lt.prototype.parse=function(t){var e=[],s=new H(this,new G(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect(Is,"EOF"),new we(e,this)};lt.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var au=new lt;lt.parse=function(t){return au.parse(t)};lt.evaluate=function(t,e){return au.parse(t).evaluate(e)};var Qi={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"remainder","^":"power","!":"factorial","<":"comparison",">":"comparison","<=":"comparison",">=":"comparison","==":"comparison","!=":"comparison","||":"concatenate",and:"logical",or:"logical",not:"logical","?":"conditional",":":"conditional","=":"assignment","[":"array","()=":"fndef"};function Ob(t){return Qi.hasOwnProperty(t)?Qi[t]:t}lt.prototype.isOperatorEnabled=function(t){var e=Ob(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var $b=Object.defineProperty,Cb=Object.getOwnPropertyDescriptor,Db=(t,e,s)=>e in t?$b(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xb=(t,e,s,r)=>{for(var n=r>1?void 0:r?Cb(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n},Ab=(t,e,s)=>(Db(t,e+"",s),s);const Rb="kos-expression-evaluator-model";class Pb{constructor(e,s,r,n){l(this,"name");l(this,"expression");l(this,"expr");l(this,"getContextData",null);l(this,"_lastResult",{value:void 0});this.name=e,this.expression=s,this.expr=r,this.getContextData=n,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(e){this._lastResult=e}evaluate(e){try{return{value:this.expr.evaluate(e),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let gr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"parser");l(this,"_data");l(this,"_expressions",new Map);l(this,"_results");l(this,"_contextRevision",0);this.id=t,this.logger=s.logger,this._data=_e(),this._results=_e(),this.parser=new lt}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(t){this._data.setValues(t),X(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(t,e){this._data[t]=e}updateNestedValue(t,e){const s=t.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${t}" - cannot be empty`);return}let n=this._data;for(const o of s)(n[o]===void 0||n[o]===null)&&(n[o]={}),n=n[o];n[r]=e,this.logger.debug(`Updated nested context value "${t}" to:`,e)}addModelToContext(t,e){this._data[t]=e}addExpression(t,e){try{const s=this.parser.parse(e),r=new Pb(t,e,s,()=>this.data);this._expressions.set(t,r),this.evaluateExpression(t),this.logger.debug(`Added expression "${t}": ${e}`)}catch(s){throw this.logger.error(`Failed to parse expression "${t}"`,s),s}}removeExpression(t){const e=this._expressions.delete(t);return e?(delete this._results[t],this.logger.debug(`Removed expression "${t}"`)):this.logger.warn(`Attempted to remove non-existent expression "${t}". Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpression(t){const e=this._expressions.get(t);return e||this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpressionValue(t){const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return e.result}getCachedExpressionValue(t){const e=this._expressions.get(t);if(e)return e.result}get expressions(){return Array.from(this._expressions.values())}get expressionNames(){return Array.from(this._expressions.keys())}get results(){return this.evaluateAllExpressions(),this._results}evaluateAllExpressions(){Array.from(this._expressions.keys()).forEach(e=>{this._expressions.get(e)&&this.evaluateExpression(e)})}evaluateExpression(t){this.logger.debug(`Evaluating expression: ${String(t)}`);const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${String(t)}" not found`);return}const s=e.evaluate(this.data);this.logger.debug(`Expression "${String(t)}" evaluated to:`,s);const r=e.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(t)}" result changed from`,r,"to",s),e.updateResult(s),this.updateResult(t,s))}updateResult(t,e){this.logger.debug(`ExpressionEvaluator.updateResult called for "${t}":`,e),X(()=>{this._results[t]=e})}createExpression(t){const e=ot();return this.addExpression(e,t),e}};Ab(gr,"Registration");gr=xb([R({modelTypeId:Rb,singleton:!1})],gr);const cu=gr.Registration,kb=m.createLogger({name:"kos-log-manager-service",group:"Services"}),Lb="/api/kos/logs/overrides",lu=async()=>(kb.debug("sending GET for kos-log-manager"),await De.get(Lb)),Fb=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:lu},Symbol.toStringTag,{value:"Module"}));var Nb=Object.defineProperty,Ub=Object.getOwnPropertyDescriptor,Jr=(t,e,s,r)=>{for(var n=r>1?void 0:r?Ub(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Nb(e,s,n),n};const uu="kos-log-manager-model",jb="/kos/logs/override/add/*",Bb="/kos/logs/override/remove/*",Hb=t=>{if(typeof t=="string")return t;if(typeof t=="number")switch(t){case 0:return"trace";case 1:return"debug";case 2:return"info";case 3:return"warn";case 4:return"error";default:return"info"}return"info"};let Ot=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new So}updateModel(t){}resolveLoggers(){const t=m.getLoggers(),s=Object.entries(t).map(([r,n])=>({name:r,level:Hb(n.getLevel())})).reduce((r,{name:n,level:o})=>(r[n]={name:n,level:o},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const n=m.getLoggers()[r.name];if(!n){this.logger.debug(`Logger ${r.name} not found`);return}n.setLevel(t.level)});const s=m.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const n=m.getLoggers()[r.name];n||this.logger.debug(`Logger ${r.name} not found`),n==null||n.resetLevel()});const s=m.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await lu();if(t){this.logger.error("Failed to load log overrides",t);return}const s=(e==null?void 0:e.filter(r=>{var n;return((n=r.type)==null?void 0:n.toUpperCase())==="UI"}).map(r=>({name:r.name??"",type:r.type??"",level:r.level??"info",id:r.name||""})))??[];this._overrides.addAll(s),s.forEach(r=>{this.setLogLevels(r)})}};Jr([mc("/api/kos/ui/loggers")],Ot.prototype,"getAllLoggers",1);Jr([B({topic:jb,websocket:!0,wildcardName:"nodeType"})],Ot.prototype,"handleOverrideAdded",1);Jr([B({topic:Bb,websocket:!0,wildcardName:"nodeType"})],Ot.prototype,"handleOverrideRemoved",1);Ot=Jr([R(uu)],Ot);const du=new Se({class:Ot,type:uu}),{URL:js}=ae(),{postModel:Yo,getOne:Kb}=ne.build({basePath:`${js}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const hu=async t=>{const e=await Yo({model:t,urlOverride:`${js}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},fu=async t=>{const e=await Yo({model:t,urlOverride:`${js}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},pu=async t=>{const e=await Yo({model:{},urlOverride:`${js}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},gu=async()=>{const t=await Kb({urlOverride:`${js}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},qb=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:gu,setDate:fu,setTime:hu,setTimezone:pu},Symbol.toStringTag,{value:"Module"}));var zb=Object.defineProperty,Vb=Object.getOwnPropertyDescriptor,en=(t,e,s,r)=>{for(var n=r>1?void 0:r?Vb(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&zb(e,s,n),n};const Jt="kos-time-model",Gb="/kos/time/time",Yb="/kos/time/day",Wb="/kos/time/timezone";let $t=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await hu(t)}async updateSystemDate(t){await fu(t)}async updateSystemTimezone(t){await pu(t)}handleTimeChange(){V(bs.TIME_CHANGE,{})}handleDayChange(){V(bs.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),V(bs.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await gu();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};en([B({topic:Gb,websocket:!0})],$t.prototype,"handleTimeChange",1);en([B({topic:Yb,websocket:!0})],$t.prototype,"handleDayChange",1);en([B({topic:Wb,websocket:!0})],$t.prototype,"handleTimeZoneChange",1);$t=en([R(Jt)],$t);const mr={registration:{[Jt]:{class:$t,singleton:!0}},type:Jt,predicate:Te(Jt),factory:ie.Singleton.create(Jt)};var Qb=Object.defineProperty,Zb=Object.getOwnPropertyDescriptor,mu=(t,e,s,r)=>{for(var n=r>1?void 0:r?Zb(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Qb(e,s,n),n};const yu="log-block-container-model";let yr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t,sortKey:"blockNum"})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};mu([$e],yr.prototype,"_models",2);yr=mu([R(yu)],yr);const Xb=m.createLogger({name:"log-stream-container-service",group:"Services"}),bu=()=>{var r;const t=me(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},Kt=bu(),Jb="/api/kos/logs/node/{nodeId}/streams",vu=async()=>(Xb.debug("sending GET for log-stream-container"),await De.get(Jb,{path:{nodeId:"primary"}},{destinationAddress:Kt})),wu=async(t,e="primary")=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:Kt})},Eu=async t=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:Kt})},ev=async()=>{await De.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:Kt})},Mu=async t=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:Kt}),Tu=async(t,e)=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:Kt}),tv=Object.freeze(Object.defineProperty({__proto__:null,createOverride:ev,getKosConnectionId:bu,getLogStreamBlock:Tu,getLogStreamBlocks:Mu,getLogStreams:vu,subscribeToLogStream:wu,unsubscribeFromLogStream:Eu},Symbol.toStringTag,{value:"Module"}));var sv=Object.getOwnPropertyDescriptor,rv=(t,e,s,r)=>{for(var n=r>1?void 0:r?sv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const Su="log-block-model";let Ln=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await Tu(this.stream,this.blockNum);if(t){this.logger.error(`Failed to get log block ${this.blockNum}`);return}e&&this.addLines(e.lines,!0)}updateModel(t){this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount}addLines(t,e){const s=e?[]:this.lines;this.lines=[...s,...t],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};Ln=rv([R(Su)],Ln);const Os=new ye({class:Ln,type:Su}),tn=new ye({class:yr,type:yu});tn.addRelatedModel(Os);var nv=Object.defineProperty,ov=Object.getOwnPropertyDescriptor,_u=(t,e,s,r)=>{for(var n=r>1?void 0:r?ov(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&nv(e,s,n),n};const Iu="log-stream-model";let br=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"_blocks");l(this,"name");l(this,"currentBlockId");l(this,"isResetting");l(this,"generatorInstance");l(this,"shouldStop",!1);this.id=t,this.logger=s.logger,this.currentBlockId="",this.name=e.name,this.nodeId=e.nodeId,this.isResetting=!0,this._blocks=tn.instance(`${t}-blocks`).options({}).build()}get firstLineNum(){const t=this.populated[0];return t?t.startLineNum:0}get currentBlock(){const t=this.currentBlockId;return this._blocks.getModel(t)}get populated(){return this._blocks.data.filter(t=>t.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((t,e)=>t+e.lineCount,0)}accept(t){t.visit(this)}updateBlock(t){var r;let e=this._blocks.models.getModel(`${t.stream}-block-${t.blockNum}`);const s={nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)};e||(e=Os.instance(`${t.stream}-block-${t.blockNum}`).options(s).build(),this._blocks.addModel(e)),e&&e.updateModel(s),(!this.currentBlock||t.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}addBlock(t){var s;const e=Os.instance(`${t.stream}-block-${t.blockNum}`).options({nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)}).build();this._blocks.addModel(e),(!this.currentBlock||t.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}removeBlock(t){this._blocks.models.removeModel(`${this.name}-block-${t}`)}async subscribe(){await wu(this.name)}async unsubscribe(){await Eu(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const e of this._blocks.models.data)e.lines=[];const t=this._blocks.data[this._blocks.data.length-1];t&&await t.syncLines(),this.isResetting=!1}async init(){this.logger.debug(`initializing log-stream ${this.id}`)}async load(){this.logger.debug(`loading log-stream ${this.id}`);const[t,e]=await Mu(this.name);if(t){this.logger.error(`Error loading log stream: ${t}`);return}if(e)for(const r of e)this.addBlock(r);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const r=this._blocks.data[this._blocks.data.length-2];r&&await r.syncLines()}}start(){return this.shouldStop=!1,this.generatorInstance=this.streamLogs(),this.generatorInstance}stop(){var t;this.shouldStop=!0,(t=this.generatorInstance)==null||t.next(),console.log("Requested generator stop.")}async*streamLogs(){const t=[];let e=null,s=0,r=this.currentBlockId;const n=Sl(()=>{const o=this.currentBlock;return o?{blockId:this.currentBlockId,lineCount:o.lines.length}:null},o=>{const i=this.currentBlock;if(i)if(r!==(o==null?void 0:o.blockId))r=o==null?void 0:o.blockId,s=0,t.push(...i.lines);else{const a=i.lines.slice(s);t.push(...a),s+=a.length}e&&(e(),e=null)},{fireImmediately:!0});try{for(const o of this.populated.filter(i=>i!==this.currentBlock))for(const i of o.lines)yield i;for(;;)for(t.length===0&&await new Promise(o=>e=o);t.length>0;)yield t.shift()}finally{n()}}};_u([$e],br.prototype,"_blocks",2);br=_u([R(Iu)],br);const vs=new ye({class:br,type:Iu});var iv=Object.defineProperty,av=Object.getOwnPropertyDescriptor,ut=(t,e,s,r)=>{for(var n=r>1?void 0:r?av(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&iv(e,s,n),n};const Ou="log-stream-container-model",cv="/kos/logs/subscription/addBlock/*",lv="/kos/logs/subscription/updateBlock/*",uv="/kos/logs/subscription/removeBlock/*",dv="/kos/logs/subscription/lines/*",$u="/kos/logs/streams/add/*";let Le=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t}),this.selectedStream=void 0}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}updateModel(t){}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}updateSelectedStream(t){this.selectedStream=t}handleStreamAdded(t){this.logger.debug(`Received topic: ${$u}`);const e=t.stream,s=vs.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.addBlock(t)}handleRemoveBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.removeBlock(t.blockNum)}handleUpdateBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.updateBlock(t)}handleLogLine(t,e){var n;this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&((n=r.currentBlock)==null||n.addLines(t.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(t){const e=vs.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(e),await e.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[t,e]=await vu();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=vs.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};ut([$e],Le.prototype,"_models",2);ut([B({topic:[$u],websocket:!0})],Le.prototype,"handleStreamAdded",1);ut([B({topic:[cv],websocket:!0})],Le.prototype,"handleAddBlock",1);ut([B({topic:[uv],websocket:!0})],Le.prototype,"handleRemoveBlock",1);ut([B({topic:[lv],websocket:!0})],Le.prototype,"handleUpdateBlock",1);ut([B({topic:[dv],websocket:!0})],Le.prototype,"handleLogLine",1);Le=ut([R(Ou)],Le);const Bs=new Se({class:Le,type:Ou});Bs.addRelatedModel(vs);Bs.addRelatedModel(tn);Bs.addRelatedModel(Os);const hv=t=>t.rank!==void 0,fv=t=>t.visibleRole!==void 0,pv=t=>t.color!==void 0,gv=t=>{const e=t.info;return hv(e)?e.rank:0},mv=t=>{const e=t.info;return pv(e)?e.color:"orange"},yv=t=>{const e=t.info;return fv(e)?e.visibleRole:"TECHNICIAN"},{URL:sn}=ae(),{getAll:bv,postModel:Cu}=ne.build({basePath:`${sn}/api/kos/troubles`}),Du=async t=>await bv({urlOverride:`${sn}${t}`}),xu=async(t,e="/api/kos/troubles",s)=>{try{const r=await Cu({model:{},urlOverride:`${sn}${e}/resolve/${t}`,tracker:s});return r!=null&&r.data&&rt.initiateFuture(r.data),r.data}catch{const n={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve trouble"};return rt.initiateFuture(n),n}},vv=async(t,e="/api/kos/troubles",s)=>{try{const r=await Cu({model:t,urlOverride:`${sn}${e}/resolve/`,tracker:s});return r!=null&&r.data&&rt.initiateFuture(r.data),r.data}catch{const n={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve troubles"};return rt.initiateFuture(n),n}},wv=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:vv,getTroubles:Du,resolveTrouble:xu},Symbol.toStringTag,{value:"Module"})),vr="troubleDataMapper",Zs=new Map;ks(vr,{register:(t,e)=>{var s;Zs.has(t)||Zs.set(t,[]),(s=Zs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Zs.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:m.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const Hs="troubleMapper",Xs=new Map;ks(Hs,{register:(t,e)=>{var s;Xs.has(t)||Xs.set(t,[]),(s=Xs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Xs.get(t);if(!s)return[];const r=s.map(i=>i(e)),o=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(o))}});$[Hs].register("nozzle",async t=>[t.data.nozzlePath]);$[Hs].register("path",async t=>[t.data.path]);const Ev=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(o=>$[Hs].execute(o,t));return(await Promise.allSettled(r)).forEach(o=>{o.status==="fulfilled"&&o.value.forEach(i=>e.add(i))}),Array.from(e)},Au=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>$[vr].execute(i,t)),r=$[vr].execute(t.type,t);s.push(r);const o=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...t.data,...o}};class Mv{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class Tv{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class gt{static getHandler(e){switch(e){case"ResolvableTrouble":return new Mv;case"BlockPumpTrouble":return new Tv;default:return}}}var Sv=Object.defineProperty,_v=Object.getOwnPropertyDescriptor,Ru=(t,e,s,r)=>{for(var n=r>1?void 0:r?_v(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Sv(e,s,n),n};const es="trouble-model";function Js(t){return typeof t.shouldDefer=="boolean"}let wr=class{constructor(t,{resolvable:e,tags:s,info:r,id:n,clientData:o,rank:i,ifaces:a,type:c,group:u,createTime:d,role:h,color:f,servicePath:p,...y},w){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"servicePath");l(this,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=w.logger,this.type=c,this._troubleId=n,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=f,this.tags=s,this.info=r,this.group=u,this.servicePath=p??"/api/kos/troubles",this.createTime=d,this.clientData=o,this.data={},Object.assign(this.data,y),this.futureHandler=new qr(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=gt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:gt.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=gt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:gt.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=gt.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=gt.getHandler(this.type))==null?void 0:t.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await Au(this)}get deferredCompanion(){const t=$n(this.id,e=>Js(e));if(t&&Js(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=$n(this.id,e=>Js(e));return t&&Js(t.modelData)?t.modelData.shouldDefer:!1}clearDefer(){var t;(t=this.deferredCompanion)==null||t.clearDefer()}defer(){var t;(t=this.deferredCompanion)==null||t.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(t){var e;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(e=this.deferredCompanion)==null||e.defer();return}return await xu(this._troubleId,this.servicePath,t)}};Ru([hi()],wr.prototype,"resolve",1);wr=Ru([R(es)],wr);const $s={registration:{[es]:{class:wr,singleton:!1}},type:es,predicate:Te(es),factory:ie.Factory.create(es)};var Pu=Object.defineProperty,Iv=Object.getOwnPropertyDescriptor,Ov=(t,e,s)=>e in t?Pu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Wo=(t,e,s,r)=>{for(var n=r>1?void 0:r?Iv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Pu(e,s,n),n},$v=(t,e,s)=>(Ov(t,e+"",s),s);function Zi(t){return $.propertyMapper.hasMapper(ve.TroubleRank)?$.propertyMapper.executeMapper(ve.TroubleRank,t):gv(t)}function Xi(t){return($.propertyMapper.hasMapper(ve.TroubleColor)?$.propertyMapper.executeMapper(ve.TroubleColor,t):mv(t)).toLowerCase()}function Ji(t){return($.propertyMapper.hasMapper(ve.TroubleRole)?$.propertyMapper.executeMapper(ve.TroubleRole,t):yv(t)).toLowerCase()}const Cv="trouble-container-model";class pe{}l(pe,"INDEX_TROUBLES_BY_IFACE","byIface"),l(pe,"INDEX_TROUBLES_BY_TYPE","byType"),l(pe,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(pe,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(pe,"SORT_KEY_RANK","rank"),l(pe,"TROUBLES_DEFERRED","true");let Ct=class{constructor(t,e){l(this,"id");l(this,"servicePath","/api/kos/troubles");this.id=t,this.servicePath=e.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");const t=await Du(this.servicePath);try{t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:Zi(e),color:Xi(e),role:Ji(e),id:String(e.id)},r=$s.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw this.logger.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&st(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:Zi(t),color:Xi(t),role:Ji(t),id:String(t.id)};if(e.role==="NONE")return;const s=$s.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};$v(Ct,"Registration");Wo([B({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],Ct.prototype,"handleTroubleRemoved",1);Wo([B({topic:"/kos/trouble/add",websocket:!0})],Ct.prototype,"handleTroubleAdded",1);Ct=Wo([R({modelTypeId:Cv,singleton:!0}),wc(),gc({containerProperty:"troubles",containerOptions:{indexMap:{[pe.INDEX_TROUBLES_BY_IFACE]:Ev,[pe.INDEX_TROUBLES_BY_TYPE]:"type",[pe.INDEX_TROUBLES_BY_GROUP]:"group",[pe.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:pe.SORT_KEY_RANK}})],Ct);const Dt=Ct.Registration,{URL:ku}=ae(),{getAll:Dv}=ne.build({basePath:`${ku}/api/kos/ota`}),ea=m.createLogger({name:"ota-service",group:"Services"}),xv=async()=>{ea.debug("sending GET request to /api/kos/ota/artifacts");const t=await Dv({urlOverride:`${ku}/api/kos/ota/artifacts`});return ea.debug("getArtifacts - response:",t),t==null?void 0:t.data};var Av=Object.defineProperty,Rv=Object.getOwnPropertyDescriptor,rn=(t,e,s,r)=>{for(var n=r>1?void 0:r?Rv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Av(e,s,n),n};const Lu="ota-model",Pv=t=>{let e=null;for(const s in t){const r=t[s],n=r.lastUpdateTime;(!e||e.lastUpdateTime<n)&&(e=r)}return e},wn=t=>{const e=t.artifactInfo,s=Pv(t.requests),r=(e==null?void 0:e.identifier)||(s==null?void 0:s.kabId);if(!r)return;let n;switch(t.status){case"INSTALLED":n="ready";break;case"INVALID":n="error";break;case"MISSING":n=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":n="pending"}const o=e===void 0;return{id:r,manifest:o,label:e==null?void 0:e.version,name:e==null?void 0:e.name,status:n,error:n==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:n==="error"?s==null?void 0:s.errorCount:0,progress:n==="downloading"&&s&&!o?s.currentSize/(e==null?void 0:e.size)*100:void 0,size:e==null?void 0:e.size}};let xt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new So);l(this,"troubleContainer");this.id=t,this.logger=s.logger}get downloadInProgressTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:e[0]}get updatePendingTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:e[0]}get pausedDueToErrorsTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:e[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var t;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(t=this.updatePendingTrouble)==null||t.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const t=await xv();t&&t.forEach(e=>{const s=wn(e);s&&this.data.addModel(s)})}catch(t){this.logger.error(`loading ota ${this.id} - error:`,t)}}async handleAllArtifacts(t){this.logger.debug("handleAllArtifacts:",t),await this.data.clear();try{t.forEach(e=>{const s=wn(e);s&&this.data.addModel(s)})}catch(e){this.logger.error(`handleAllArtifacts ${this.id} - error:`,e)}}handleChangedArtifacts(t){this.logger.debug("handleChangedArtifacts:",t);try{t.forEach(e=>{const s=wn(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};rn([Lt({modelType:Dt.type})],xt.prototype,"troubleContainer",2);rn([B({topic:"/kos/ota/artifacts/all",websocket:!0})],xt.prototype,"handleAllArtifacts",1);rn([B({topic:"/kos/ota/artifacts/changed",websocket:!0})],xt.prototype,"handleChangedArtifacts",1);xt=rn([R(Lu)],xt);const Er=new Se({class:xt,type:Lu});function kv(t){let e;const s=async(...r)=>{e&&e.abort(),e=new AbortController;const n=e;try{return await t(...r,n.signal)}finally{e===n&&(e=void 0)}};return s.cancel=()=>{e&&(e.abort(),e=void 0)},s.getController=()=>e,s.isActive=()=>!!e,s}const En=m.createLogger({name:"software-info-service",group:"Services"}),Qo=async t=>{En.debug("sending GET for software-info");const[e,s]=await Vl.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(En.debug("Request was aborted"),new ge("Request was aborted")):(En.error("Failed to fetch software-info",e),new ge("Failed to fetch software-info"));return s},Lv=kv(Qo),Fv=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Qo,getSoftwareInfosWithCancel:Lv},Symbol.toStringTag,{value:"Module"}));var Nv=Object.getOwnPropertyDescriptor,Uv=(t,e,s,r)=>{for(var n=r>1?void 0:r?Nv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const ts="software-info-model";let Fn=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=t,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(t,e){return t.reduce((s,r)=>(s[r[e]]=[...s[r[e]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const t=await Qo(),e=(t==null?void 0:t.nodes)||{};X(()=>{const r=Object.keys(e).map(n=>e[n][0]).map(n=>({nodeName:n.nodeType,kosVersion:n.kosVersion,group:this.groupBy(n.artifacts,"group")}));this.nodes=r})}catch(t){t instanceof ge&&this.logger.error("Failed to fetch software-info",t)}}};Fn=Uv([R(ts)],Fn);const Mr={registration:{[ts]:{class:Fn,singleton:!1}},type:ts,predicate:Te(ts),factory:ie.Factory.create(ts)},{URL:Fu}=ae(),{getOne:jv}=ne.build({basePath:`${Fu}/api/kos/state`}),Bv=m.createLogger({name:"state-bean-service",group:"Services"}),Nu=async({path:t})=>(Bv.debug("sending GET for state-bean"),await jv({urlOverride:`${Fu}/api/kos/state/${t}`})),Hv=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Nu},Symbol.toStringTag,{value:"Module"}));var Kv=Object.defineProperty,qv=Object.getOwnPropertyDescriptor,Uu=(t,e,s,r)=>{for(var n=r>1?void 0:r?qv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Kv(e,s,n),n};const ss="state-bean-model",zv=it("path");let Tr=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=t,this.logger=s.logger,this.props=Io.map(new Map),On(e,this)}updateModel(t){On(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&Co(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&zr(r)&&(r=Number(r)),this.props.set(e,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(t){Object.entries(t).forEach(([e,s])=>{this.props.set(e,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const t=await Nu({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};Uu([B({topic:`/kos/state/${zv}`,websocket:!0})],Tr.prototype,"handleConfigBeanUpdated",1);Tr=Uu([R(ss)],Tr);const Cs={registration:{[ss]:{class:Tr,singleton:!1}},type:ss,predicate:Te(ss),factory:ie.Factory.create(ss)};var Vv=Object.defineProperty,Gv=Object.getOwnPropertyDescriptor,ju=(t,e,s,r)=>{for(var n=r>1?void 0:r?Gv(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Vv(e,s,n),n};const rs="state-prop-model",ta=it("path");let Sr=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=t,this.logger=s.logger,this.path=e.path,this.attribute=e.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var t;return((t=this.value)==null?void 0:t.toString())??""}};ju([Lt({modelType:Cs.type,id:`state-bean-${ta}`,options:{path:ta}})],Sr.prototype,"stateBean",2);Sr=ju([R(rs)],Sr);const Zo={registration:{[rs]:{class:Sr,singleton:!1}},type:rs,predicate:Te(rs),factory:ie.Factory.create(rs)},{URL:Yv}=ae(),{getAll:Wv}=ne.build({basePath:`${Yv}/api/state-prop`}),Qv=m.createLogger({name:"state-prop-service",group:"Services"}),Zv=async()=>(Qv.debug("sending GET for state-prop"),await Wv({})),Xv=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Zv},Symbol.toStringTag,{value:"Module"})),{URL:Xo}=ae(),{getOne:Bu}=ne.build({basePath:`${Xo}/api/translation`}),ws=m.createLogger({name:"translation-service",group:"Services"}),Jv=()=>{const t=window.location.origin,e=me();return(e==null?void 0:e.host)||t},Hu=async(t,e)=>{ws.debug(`Loading translations from: ${t}`);const s=e??Jv();try{const r=await fetch(`${s}${t}`);return r.status!==200?(ws.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw ws.error("Error fetching translations",r),r}},ew=async()=>{ws.debug("Getting system localization descriptor");const t=await Bu({urlOverride:`${Xo}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get localization descriptor ${t==null?void 0:t.status}`);return t.data},Ku=t=>async()=>{ws.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await Bu({urlOverride:`${Xo}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},qu="langResolver";var tw=Object.getOwnPropertyDescriptor,sw=(t,e,s,r)=>{for(var n=r>1?void 0:r?tw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const ns="translation-model";function rw(t){const e=typeof t=="string",s=e?!1:!!(t!=null&&t.data)&&typeof(t==null?void 0:t.data)!="string",r=e?t:t==null?void 0:t.defaultValue,n=e||t==null?void 0:t.context,o=e?void 0:s?t==null?void 0:t.data:t;return{isBasicOptions:e,defaultValue:r,context:n,data:o}}function zu(t,e=""){return Object.keys(t).reduce((s,r)=>{const n=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])){const o=zu(t[r],n);return{...s,...o}}else return{...s,[n]:t[r]}},{})}function Vu(t,e){const s={...t};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(typeof e[r]=="object"&&e[r]!==null&&typeof t[r]=="object"&&t[r]!==null?s[r]=Vu(t[r],e[r]):s[r]=e[r]);return s}const Nn=(t,e)=>{const s=/__(.*?)__/g,r=t.replace(s,(n,o)=>Object.prototype.hasOwnProperty.call(e||{},o.trim())?e==null?void 0:e[o.trim()]:n);return r===t?r:s.test(r)?Nn(r,e):r},er=(t,e,s)=>{const r=/{{(.*?)}}/g,o=Nn(t,e).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return Nn(o,e)},sa=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let Un=class{constructor(t,e,s){l(this,"id");l(this,"namespace");l(this,"descriptor");l(this,"defaultLocale");l(this,"currentLocale");l(this,"bundleResolver");l(this,"data");l(this,"logger");l(this,"resolver");l(this,"disposer");l(this,"context");l(this,"rootUrl");this.id=t,this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.currentLocale||"en",this.namespace=e.namespace,this.descriptor=e.descriptor,this.rootUrl=e.rootUrl,this.data={},this.resolver=e.resolver||s.kosContext.get(qu),this.bundleResolver=e.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(t){const e=this.descriptor[t];if(!t||!e)return[this.defaultLocale];if(!this.defaultLocale&&!e.fallbacks)return[t];let s=e.fallbacks||[this.defaultLocale];return s.includes(t)||(s=[t,...s]),s}async loadTranslations(){const t=this.getTranslationLocales(this.currentLocale).reverse(),e=t.map(r=>{if(this.bundleResolver){const n=Y.getContext(this.id);return this.bundleResolver(this.namespace,r,n)}try{const n=this.resolver(this.namespace,r);return Hu(n,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);X(()=>{const r=s.reduce((n,o,i)=>(o.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,o.value),o.value&&(n=Vu(n,o.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),n),{});this.data=zu(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=sa(this.namespace,t);if(e!==this.namespace){const r=this.context.getModel(e);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(t,e){if(!t)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:n}=rw(e),{namespace:o,key:i}=sa(this.namespace,t),a=`${i}_${r}`;if(o!==this.namespace){const c=this.context.getModel(o);return c?c.resolveKey(i,e):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>er(u,this.data,n)):er(this.data[a],this.data,n)}if(this.data[i]){const c=this.data[i];return Array.isArray(c)?c.map(u=>er(u,this.data,n)):er(this.data[i],this.data,n)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=M.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};Un=sw([Br(),R(ns)],Un);const _r={registration:{[ns]:{class:Un,singleton:!1}},type:ns,predicate:Te(ns),factory:ie.Factory.create(ns)};var nw=Object.defineProperty,ow=Object.getOwnPropertyDescriptor,Gu=(t,e,s,r)=>{for(var n=r>1?void 0:r?ow(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&nw(e,s,n),n};const os="translation-container-model",iw=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function aw(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error("namespace "+t+" not found in descriptor");const r=s.basePath,n=s.locales[e].file;return iw([r,n])}let Ir=class{constructor(t,e,s){l(this,"id");l(this,"lang");l(this,"rootUrl");l(this,"descriptor");l(this,"_defaultNamespace");l(this,"resolver");l(this,"logger");l(this,"descriptorUrl");l(this,"namespaces",[]);l(this,"_models");this.id=t,this.lang=e.lang||"en",this.descriptor=e.descriptor,this._defaultNamespace=e.defaultNamespace,this.descriptorUrl=e.descriptorUrl,this.rootUrl=e.rootUrl,this.resolver=e.resolver||aw.bind(this),s.kosContext.set(qu,this.resolver),this.logger=s.logger,this._models=new Ce({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(t){return this.logger.debug("getting model "+t),this._models.getModel("translation-"+t)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const t of this.namespaces){const e=this.resolveNamespace(t);await de(e)}}resolveNamespace(t){var s;if((s=this.descriptor.namespaces)==null?void 0:s[t]){const r=Object.keys(this.descriptor.namespaces[t].locales)[0],n=this.descriptor.namespaces[t].locales[r].defaultLocale,o=_r.factory("translation-"+t)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:n,descriptor:this.descriptor.namespaces[t].locales,resolver:this.resolver});return this.addModel(o),this.namespaces.includes(t)||X(()=>{this.namespaces.push(t)}),o}else{this.logger.warn("namespace "+t+" not found in descriptor");const r=_r.factory("translation-"+t)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug("initializing translation-container container "+this.id)}async load(){this.logger.debug("loading translation-container container "+this.id)}};Gu([$e],Ir.prototype,"_models",2);Ir=Gu([R(os)],Ir);const Fe={registration:{[os]:{class:Ir,singleton:!0}},type:os,predicate:Te(os),factory:ie.Singleton.create(os)},cw={set(t,e){const s=Y.getContext(Fe.type);s&&s.set(t,e)},get(t){const e=Y.getContext(Fe.type);return e==null?void 0:e.get(t)}},Yu={async init(t){const e=Fe.factory(t);return await de(e),{translations:e}}};function lw(t){return(t==null?void 0:t.troubles)!==void 0&&(t==null?void 0:t.troubles)instanceof Array&&(t==null?void 0:t.troublesByType)!==void 0&&typeof(t==null?void 0:t.troublesByType)=="object"}const Wu="kos-ws-event",Jo=Ft(Wu);var uw=Object.defineProperty,dw=Object.getOwnPropertyDescriptor,ei=(t,e,s,r)=>{for(var n=r>1?void 0:r?dw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&uw(e,s,n),n};const hw=({headers:t,body:e})=>Object.entries(t).map(([r,n])=>`${r}:${n}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){m.debug("kos event received");const{body:r,headers:n}=e.body,o=n["request-id"]||n["response-id"],i=n["request-id"]||n["response-id"]||n.topic||n.type;if(i){let a=i;if(o)a=`${a}-${s?"send":"receive"}`;else{const u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const c={msgId:a,content:r,headers:n,timestamp:Date.now(),raw:hw({headers:n,body:r}),direction:s?"send":"receive",mocked:!!n.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};ei([B({topic:[Ps.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);ei([B({topic:[Ps.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=ei([R(Jo.type)],exports.WsEventModel);const ra=me(),fw=ra.debug==="true"||ra.debug===!0,pw="/api/system/canvas",Qu=async(t,e)=>{const s=e||pw,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:fw?"false":"true"},body:t})},gw=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Qu},Symbol.toStringTag,{value:"Module"}));function na(t,e,s){{const r=t.filter((n,o)=>o%4!==3);return btoa(String.fromCharCode(...r))}}var mw=Object.defineProperty,yw=Object.getOwnPropertyDescriptor,Zu=(t,e,s,r)=>{for(var n=r>1?void 0:r?yw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&mw(e,s,n),n};const Xu="canvas-renderer-model";function Mn(t){return typeof t.onDone=="function"}let Or=class{constructor(t,e,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);l(this,"_clearOnComplete");l(this,"isStreaming",!1);l(this,"renderLoopId",null);l(this,"sendIntervalId",null);l(this,"timeoutId",null);l(this,"apiPath");l(this,"endpointName");l(this,"width",50);l(this,"height",30);l(this,"fps",10);l(this,"durationMs",null);l(this,"_onFrame",null);this.id=t,this.logger=s.logger,this.width=e.width??50,this.height=e.height??30,this.fps=e.fps??10,this.durationMs=e.durationMs??null,this.apiPath=e.apiPath??"/api/system/canvas",this.endpointName=e.endpoint}set onFrame(t){this._onFrame=t}set renderer(t){var e,s;this._renderer&&(this.stopStreaming(),(s=(e=this._renderer).dispose)==null||s.call(e)),this._renderer=t,this.isStreaming&&this.startStreaming()}setClearOnComplete(t){this._clearOnComplete=t}sendDataFrame(t,e){Qu(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=na(t);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,n=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)n[i]=255;const o=na(n);this.logger.debug(`Sending clear frame: ${t}x${e}, apiPath: ${this.apiPath}`),this.sendDataFrame(o,this.apiPath),(s=this._onFrame)==null||s.call(this,o)}}isOneShotDone(){var t,e;return Mn(this._renderer)&&((e=(t=this._renderer).isOneShot)==null?void 0:e.call(t))===!0&&this._renderer.isOneShotDone}startStreaming(){var t,e,s,r;{if(!this._renderer)return;if(!this.apiPath){this.logger.error(`No endpoint configured for canvas renderer ${this.id}`);return}this.isStreaming=!0,this._renderer.reset(),(e=(t=this._renderer).play)==null||e.call(t);const n=Mn(this._renderer);Mn(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),V("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((d=(u=this._renderer)==null?void 0:u.isOneShot)==null?void 0:d.call(u))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const o=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(o&&this._onFrame&&this.handleFrame(o),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,u;const a=(u=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:u.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!n&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(t,e)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),e.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(t,e)=>{this.startStreaming(),e.send({status:"OK"})})}};Zu([Lt({modelType:Fo.type})],Or.prototype,"router",2);Or=Zu([R(Xu)],Or);const ti=new ye({class:Or,type:Xu});class Ju{constructor({src:e}){l(this,"video");l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);l(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=e,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(e,s){this.canvas.width=e,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,e,s)}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}onDone(e){this.doneCallback=e}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}}class bw{constructor(){l(this,"canvas");l(this,"gl");l(this,"lastWidth",0);l(this,"lastHeight",0);l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl");if(!e)throw new Error("WebGL not supported");this.gl=e}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(e*s*4);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const n=new Uint8ClampedArray(r.length);for(let o=0;o<s;o++){const i=o*e*4,a=(s-1-o)*e*4;n.set(r.subarray(i,i+e*4),a)}return n}}class vw extends bw{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,n=`
81
81
  attribute vec2 a_position;
82
82
  void main() {
83
83
  gl_Position = vec4(a_position, 0, 1);
@@ -111,8 +111,8 @@ ${u}topics:${e}
111
111
  vec3 rgb = hslToRgb(hue, 1.0, 0.5);
112
112
  gl_FragColor = vec4(rgb, 1.0);
113
113
  }
114
- `,i=this.compileShader(r.VERTEX_SHADER,n),a=this.compileShader(r.FRAGMENT_SHADER,o);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 n=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const o=this.speedPx/r;this.hueOffset=(this.hueOffset+o)%1}n.viewport(0,0,s,r),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.program),n.enableVertexAttribArray(this.aPosition),n.bindBuffer(n.ARRAY_BUFFER,this.posBuffer),n.vertexAttribPointer(this.aPosition,2,n.FLOAT,!1,0,0),n.uniform1f(this.uMinHue,this.minHue/360),n.uniform1f(this.uMaxHue,this.maxHue/360),n.uniform1f(this.uHueOffset,this.hueOffset),n.uniform1f(this.uGridHeight,r),n.drawArrays(n.TRIANGLES,0,6)}compileShader(s,r){const n=this.gl.createShader(s);if(this.gl.shaderSource(n,r),this.gl.compileShader(n),!this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(n)||"Shader compile failed");return n}createProgram(s,r){const n=this.gl.createProgram();if(this.gl.attachShader(n,s),this.gl.attachShader(n,r),this.gl.linkProgram(n),!this.gl.getProgramParameter(n,this.gl.LINK_STATUS))throw new Error("Program linking failed");return n}}class dt{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("2d");if(!e)throw new Error("2D canvas not supported");this.ctx=e}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}}function ti(t){class e extends t{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(n){this.doneCallback=n}signalDoneIfNeeded(){var n;this.oneShotDone||((n=this.doneCallback)==null||n.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return e}const vw=ti(dt);class ww extends vw{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:n=2,loop:o=!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=n,this.loop=o}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 n=this.loop?-this.offset:0,o=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(n,0,o,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 Ew=ti(dt);class Ju extends Ew{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 Mw extends Xu{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 Tw(t){const e=t.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(e))throw new Error(`Invalid hex color: ${t}`);let s,r,n;return e.length===3?(s=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),n=parseInt(e[2]+e[2],16)):(s=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),n=parseInt(e.substring(4,6),16)),{r:s,g:r,b:n}}function ed(t){return typeof t=="string"?Tw(t):t}function Or(t){const e=ed(t);return`rgb(${e.r},${e.g},${e.b})`}class Sw extends dt{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=ed(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let n=0;n<=5;n++){const o=1-n/5*.6;r.push({r:Math.floor(this.baseColor.r*o),g:Math.floor(this.baseColor.g*o),b:Math.floor(this.baseColor.b*o)})}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 n=this.ctx.createImageData(s,r),o=n.data;o.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 y=this.trailColors[p];u=y.r,d=y.g,h=y.b}}const f=(i*s+a)*4;o[f]=u,o[f+1]=d,o[f+2]=h,o[f+3]=255}this.ctx.putImageData(n,0,0)}}class _w{constructor(e,s){l(this,"baseRenderer");l(this,"overlayIcons",new Map);l(this,"overlayConfigs");l(this,"loadedIcons",new Set);l(this,"canvas");l(this,"ctx");l(this,"persistOverlaysOnComplete");l(this,"baseRendererCompleted",!1);l(this,"completionCallback",null);l(this,"hasSignaledCompletion",!1);this.baseRenderer=s(e.baseRenderer.type,e.baseRenderer.data),this.overlayConfigs=e.overlays,this.persistOverlaysOnComplete=e.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const e of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(e.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${e.src}`,r)},s.src=e.src,this.overlayIcons.set(e.src,s)}}calculateOverlayPosition(e,s,r){let n,o;if(typeof e.position=="string")switch(e.position){case"top-left":n=0,o=0;break;case"top-center":n=(s-e.size)/2,o=0;break;case"top-right":n=s-e.size,o=0;break;case"center-left":n=0,o=(r-e.size)/2;break;case"center":n=(s-e.size)/2,o=(r-e.size)/2;break;case"center-right":n=s-e.size,o=(r-e.size)/2;break;case"bottom-left":n=0,o=r-e.size;break;case"bottom-center":n=(s-e.size)/2,o=r-e.size;break;case"bottom-right":n=s-e.size,o=r-e.size;break;default:n=0,o=0}else n=e.position.x,o=e.position.y;return e.offset&&(n+=e.offset.x||0,o+=e.offset.y||0),{x:n,y:o}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(e,s){if(this.canvas.width=e,this.canvas.height=s,this.ctx.clearRect(0,0,e,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(e,s);else{this.baseRenderer.renderFrame(e,s);const r=this.baseRenderer.readPixels(e,s);if(r&&r.length>0){const n=new ImageData(r,e,s);this.ctx.putImageData(n,0,0)}this.renderOverlays(e,s)}}renderOverlays(e,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const n=this.overlayIcons.get(r.src);if(!n||!this.loadedIcons.has(r.src))continue;const o=this.calculateOverlayPosition(r,e,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(n,o.x,o.y,r.size,r.size),this.ctx.restore()}}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(e){this.completionCallback=e,this.hasSignaledCompletion&&e()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class td extends dt{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 n=this.scrollConfig.direction||"left",o=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=o*u;switch(n){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,n,i),this.checkScrollCompletion(s,r,n,i)}drawScrollingImage(s,r,n,o){var h,f,p,y,w,E,S,L,P;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):n==="left"||n==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r);let u,d;switch(n==="left"||n==="right"?(u=0,((E=this.scrollConfig)==null?void 0:E.offsetY)==="center"||((S=this.scrollConfig)==null?void 0:S.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((L=this.scrollConfig)==null?void 0:L.offsetX)==="center"||((P=this.scrollConfig)==null?void 0:P.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),n){case"left":{const O=s-this.position;if(O<s&&O>-a&&this.ctx.drawImage(this.img,O,d,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>o){const _=O+a+o;_<s&&this.ctx.drawImage(this.img,_,d,a,c)}break}case"right":{const O=-a+this.position;if(O>-a&&O<s&&this.ctx.drawImage(this.img,O,d,a,c),this.loopConfig&&this.pauseDuration===0&&O-o-a>-a){const _=O-a-o;_<s&&this.ctx.drawImage(this.img,_,d,a,c)}break}case"up":{const O=r-this.position;if(O>-c&&O<r&&this.ctx.drawImage(this.img,u,O,a,c),this.loopConfig&&this.pauseDuration===0&&O+c+o<r){const _=O+c+o;_>-c&&this.ctx.drawImage(this.img,u,_,a,c)}break}case"down":{const O=-c+this.position;if(O>-c&&O<r&&this.ctx.drawImage(this.img,u,O,a,c),this.loopConfig&&this.pauseDuration===0&&O-o-c>-c){const _=O-c-o;_<r&&this.ctx.drawImage(this.img,u,_,a,c)}break}}}checkScrollCompletion(s,r,n,o){var h,f,p,y,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):n==="left"||n==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r),n){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let u=!1;const d=1;switch(n){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 n=await(await fetch(s)).text();this.originalSvgData=n;const o=this.applySvgColorOverride(n),i=`data:image/svg+xml;base64,${btoa(o)}`;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=Or(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 Iw extends dt{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=Or(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 o=this.ctx.measureText(r).width;this.lineWidths.push(o),s=Math.max(s,o)}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 n=this.scrollConfig.direction||"left",o=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=o*u;switch(n){case"left":case"right":case"up":case"down":this.position+=d;break}}this.drawScrollingText(s,r,n,i),this.checkScrollCompletion(s,r,n)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const n=this.textHeight;let o=(r-n)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],c=this.lineWidths[i],u=(s-c)/2,d=o+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,n,o){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;n==="left"||n==="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(n,s,r,o,i,a)}drawMultiLineScrollText(s,r,n,o,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>o){const u=c+this.textWidth+o;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-o-this.textWidth>-this.textWidth){const u=c-this.textWidth-o;u<r&&this.drawTextBlock(u,a,"left")}break}case"up":{const c=n-this.position;if(c>-this.textHeight&&c<n&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c+this.textHeight+o<n){const u=c+this.textHeight+o;u>-this.textHeight&&this.drawTextBlock(i,u,"center")}break}case"down":{const c=-this.textHeight+this.position;if(c>-this.textHeight&&c<n&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c-o-this.textHeight>-this.textHeight){const u=c-this.textHeight-o;u<n&&this.drawTextBlock(i,u,"center")}break}}}drawTextBlock(s,r,n){for(let o=0;o<this.lines.length;o++){const i=this.lines[o],a=this.lineWidths[o];let c;n==="center"?c=s-a/2:c=s;const u=r+o*this.lineHeight;this.ctx.fillText(i,c,u)}}checkScrollCompletion(s,r,n){if(!this.isPlaying)return;let o=!1;const i=1;switch(n){case"left":o=s-this.position<-this.textWidth-i;break;case"right":o=-this.textWidth+this.position>s+i;break;case"up":o=r-this.position<-this.textHeight-i;break;case"down":o=-this.textHeight+this.position>r+i;break}o&&(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 Ow{constructor(e){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=e.patterns,this.loopConfig=e.loop??!1,this.transitionDuration=e.transitionDuration??0,this.patternOverrides=e.patternOverrides??{},this.patternStore=e.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var o,i,a,c;const e=this.patterns[this.currentPatternIndex],s=this.patternStore.get(e);if(!s){console.warn(`Pattern "${e}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(o=this.currentRenderer).dispose)==null||i.call(o));const r=this.patternOverrides[e]??{},n={...s.data,...r};try{this.currentRenderer=$r({mode:s.type,data:n}),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 "${e}":`,u),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const $w=ti(dt);class Cw extends $w{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=Or(r)}setColor(s){this.color=Or(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 Dw extends dt{constructor({minHue:s=0,maxHue:r=360,speed:n=1}={}){super();l(this,"offset",0);l(this,"minHue");l(this,"maxHue");l(this,"speed");this.minHue=s,this.maxHue=r,this.speed=n}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,r,n){let o,i,a;if(r===0)o=i=a=n;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=n<.5?n*(1+r):n+r-n*r,d=2*n-u;o=c(d,u,s+1/3),i=c(d,u,s),a=c(d,u,s-1/3)}return[Math.round(o*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const n=this.ctx.createImageData(s,r),o=n.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);o[i++]=h,o[i++]=f,o[i++]=p,o[i++]=255}this.ctx.putImageData(n,0,0)}}const na=new Map;Ps(te,{register(t,e){na.set(t,e)},execute(t,e){const s=na.get(t);return s?new s(e):null}});$.canvas.registerRenderer("video",Mw);$.canvas.registerRenderer("video-basic",Xu);$[te].register("image-static",Ju);$[te].register("image-scrolling",td);const xw=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new td(t):new Ju(t)}};$[te].register("image",xw);$[te].register("color",Cw);$[te].register("matrix",Sw);$[te].register("sweep",Dw);$[te].register("gradient",ww);$[te].register("drop",bw);$[te].register("sequence",Ow);$[te].register("text",Iw);const Aw=class{constructor(t){const e=(s,r)=>{const n=$r({mode:s,data:r});if(!n)throw new Error(`Failed to create renderer of type: ${s}`);return n};return new _w(t,e)}};$[te].register("overlay",Aw);const $r=({mode:t,data:e})=>{const s=$[te].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var Rw=Object.defineProperty,Pw=Object.getOwnPropertyDescriptor,qt=(t,e,s,r)=>{for(var n=r>1?void 0:r?Pw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Rw(e,s,n),n};const sd="canvas-dispatcher-model";function kw(t){if(t=t.replace(/^#/,""),t.length===3&&(t=t.split("").map(s=>s+s).join("")),t.length!==6)return null;const e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:e&255}}let ze=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new Ce}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=ei.instance(t).options({apiPath:e.apiPath,width:e.width,height:e.height,fps:e.fps,durationMs:e.durationMs??null,endpoint:t}).build();return this._endpointRenderers.addModel(s),s}addContent(t,e){this._content.has(t)&&this.logger.warn(`Content "${t}" already exists. Overwriting.`),this._content.set(t,e)}addPattern(t,e){this._patterns.has(t)&&this.logger.warn(`Pattern "${t}" already exists. Overwriting.`),this._patterns.set(t,e)}async handlePatternsPost(t,e){var n,o;const s=t.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(n=e.status)==null||n.call(e,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(o=e.status)==null||o.call(e,200).send({status:"OK"})}async handlePatternApplication(t,e){var u,d,h;const s=t.params.pattern,r=t.params.endpoint,n=this._endpointRenderers.getModel(r);if(!n){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=e.status)==null||d.call(e,404).send({error:`Pattern "${s}" not found`});return}const o=this._patterns.get(s),i=o.type,a=t.body||{};this.data={...o.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;n.renderer=$r({mode:i,data:c}),n.setClearOnComplete(o.clearOnComplete),n.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var u,d,h;const s=t.params.color,r=kw(s);if(!r){(u=e.status)==null||u.call(e,400).send({error:"Invalid color format"});return}const n=t.params.endpoint,o=this._endpointRenderers.getModel(n);if(!o){(d=e.status)==null||d.call(e,404).send({error:`Endpoint "${n}" not found`});return}const{r:i,b:a,g:c}=r;o.renderer=$r({mode:"color",data:{r:i,g:c,b:a}}),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleEndpointCreation(t,e){var r,n;const s=t.body;if(!s.apiPath||!s.id){(r=e.status)==null||r.call(e,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(n=e.status)==null||n.call(e,200).send({status:"OK"})}async load(t){var s;const e=t==null?void 0:t.get(At.loader);e&&((s=e.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};qt([$e],ze.prototype,"_endpointRenderers",2);qt([Ls("/api/ui/canvas/patterns")],ze.prototype,"handlePatternsPost",1);qt([Ls("/api/ui/canvas/pattern/:endpoint/:pattern")],ze.prototype,"handlePatternApplication",1);qt([Ls("/api/ui/canvas/color/:endpoint/:color")],ze.prototype,"handleColorApplication",1);qt([Ls("/api/ui/canvas/endpoint")],ze.prototype,"handleEndpointCreation",1);ze=qt([R(sd)],ze);const At=new Se({class:ze,type:sd}),{URL:si}=ae(),{getOne:rd}=ne.build({basePath:`${si}/api/device`}),Cr=m.createLogger({name:"device-service",group:"Services"}),nd=async()=>{Cr.debug("sending GET for device serial number");try{const t=await rd({urlOverride:`${si}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof ge)return Cr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},od=async()=>{Cr.debug("sending GET for device details");try{const t=await rd({urlOverride:`${si}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof ge)return Cr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Lw=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:od,getSerialNumber:nd},Symbol.toStringTag,{value:"Module"}));var Fw=Object.defineProperty,Nw=Object.getOwnPropertyDescriptor,id=(t,e,s,r)=>{for(var n=r>1?void 0:r?Nw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Fw(e,s,n),n};const ad="device-model",Uw="/kos/criticalData/changed",jw="/kos/criticalData/available";let Dr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=t,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[t]=this.nodeId.split("-");return t}get nodeName(){const[,t]=this.nodeId.split("-");return t}updateModel(t){this._serialNumber=t.serialNumber??"unassigned",this._name=t.name??"unassigned",this._nodeId=t.nodeId??"unassigned"}async loadDeviceData(){const[t,e]=await od();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}if(e){const{name:s,nodeId:r}=e;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[t,e]=await nd();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}this.updateModel({serialNumber:e,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};id([B({topic:[Uw,jw],websocket:!0})],Dr.prototype,"handleCriticalDataChanged",1);Dr=id([R(ad)],Dr);const xr=new Se({class:Dr,type:ad});var Bw=Object.getOwnPropertyDescriptor,Hw=(t,e,s,r)=>{for(var n=r>1?void 0:r?Bw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const cd="network-interface-model";let Un=class{constructor(t,e,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=t,this.logger=s.logger,this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}updateModel(t){this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};Un=Hw([R(cd)],Un);const ri=new ye({class:Un,type:cd}),{URL:Kw}=ae(),{getAll:qw}=ne.build({basePath:`${Kw}/api/kos/network/interfaces`}),oa=m.createLogger({name:"network-interface-service",group:"Services"}),ld=async()=>{oa.debug("sending GET for copy-logs");try{const t=await qw({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof ge)return oa.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},zw=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:ld},Symbol.toStringTag,{value:"Module"}));var Vw=Object.defineProperty,Gw=Object.getOwnPropertyDescriptor,ud=(t,e,s,r)=>{for(var n=r>1?void 0:r?Gw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Vw(e,s,n),n};const dd="network-interface-container-model";let Ar=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await ld();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=ri.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};ud([$e],Ar.prototype,"_models",2);Ar=ud([R(dd)],Ar);const Cs=new Se({class:Ar,type:dd});Cs.addRelatedModel(ri);const{URL:Yw}=ae(),{getAll:Ww}=ne.build({basePath:`${Yw}/api/kos/storage/devices`}),ia=m.createLogger({name:"storage-device-service",group:"Services"}),hd=async()=>{ia.debug("sending GET for storage-device");const t=await Ww({});return!(t!=null&&t.data)||t.status!==200?(ia.error("Failed to retrieve storage-device data",t),[]):t.data},Qw=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:hd},Symbol.toStringTag,{value:"Module"}));var Zw=Object.getOwnPropertyDescriptor,Xw=(t,e,s,r)=>{for(var n=r>1?void 0:r?Zw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const fd="storage-device-model";let jn=class{constructor(t,e,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=t,this.logger=s.logger,this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}updateModel(t){this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};jn=Xw([jr(),R(fd)],jn);const Rr=new ye({class:jn,type:fd});var Jw=Object.defineProperty,eE=Object.getOwnPropertyDescriptor,ni=(t,e,s,r)=>{for(var n=r>1?void 0:r?eE(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Jw(e,s,n),n};const pd="storage-device-container-model",tE="/kos/storage";let Ds=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const n={...s,kosParentId:this.id};r.updateModel(n)}else{const n={...s,kosParentId:this.id},o=Rr.instance(s.id).options(n).build();this.addModel(o)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await hd()).forEach(e=>{if(e.deviceType!=="disk"){const s={...e,kosParentId:this.id},r=Rr.instance(e.id).options(s).build();this.addModel(r)}})}};ni([$e],Ds.prototype,"_models",2);ni([B({topic:tE,websocket:!0})],Ds.prototype,"handleStorageAvailability",1);Ds=ni([R(pd)],Ds);const Rt=new Se({class:Ds,type:pd});Rt.addRelatedModel(Rr);const{URL:oi}=ae(),{getAll:sE,postModel:rE}=ne.build({basePath:`${oi}/api/kos/update/available`}),aa=m.createLogger({name:"usb-update-service",group:"Services"}),gd=async()=>{aa.debug("sending GET for usb-update");const t=await sE({urlOverride:`${oi}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(aa.error("Failed to retrieve usb-update data",t),[]):t.data},md=async(t,e,s)=>{const r=await rE({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${oi}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},nE=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:gd,installUpdate:md},Symbol.toStringTag,{value:"Module"}));var oE=Object.defineProperty,iE=Object.getOwnPropertyDescriptor,yd=(t,e,s,r)=>{for(var n=r>1?void 0:r?iE(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&oE(e,s,n),n};const bd="usb-update-model";let Pr=class{constructor(t,e,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=t,this.logger=s.logger,this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes,this.futureHandler=new Kr(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),md(this.manifestId,this.deviceId,t)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};yd([di()],Pr.prototype,"install",1);Pr=yd([R(bd)],Pr);const ii=new ye({class:Pr,type:bd});var aE=Object.defineProperty,cE=Object.getOwnPropertyDescriptor,rn=(t,e,s,r)=>{for(var n=r>1?void 0:r?cE(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&aE(e,s,n),n};const vd="usb-update-container-model";let Pt=class{constructor(t,e,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await gd();X(()=>{const e=t.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!e.includes(s.id)).forEach(s=>this.removeModel(s.id)),t.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,n=ii.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(n)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var t;(t=this.disposer)==null||t.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};rn([Lt({modelType:Rt.type})],Pt.prototype,"storageService",2);rn([$e],Pt.prototype,"_models",2);rn([wc({dependencies:t=>[t.isUsbInserted]})],Pt.prototype,"usbInsertedEffect",1);Pt=rn([R(vd)],Pt);const xs=new Se({class:Pt,type:vd});xs.addRelatedModel(ii);const lE=()=>({...{[Ut.type]:{class:ql},[qe.type]:{class:Ql,singleton:!0},...re.registration,...at.registration,...Dt.registration,...Sr.registration,...Fe.registration,[Xo.type]:{class:exports.WsEventModel,singleton:!0},...$s.registration,...Qo.registration,...gr.registration}}),ai=lE(),uE={models:ai,preloadModels:[]},ca=!0,wd=t=>()=>{const e=ai;return Dc(Bn)(Os).model(Dt).model(Rt).model(xs).model(xr).model(wr).model(ws).model(Er).model(Uo).model(Cs).model(At).model(ei).model(au).model(Lo,ca).model(js).model(uu,ca),Object.keys(e).forEach(s=>{const r=e[s];Cc(Bn)(s,r)}),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t)}},Me={};Me.core={models:wd(Me)};Me.preload=A.model.preloadModel(Me);Me.model=A.model.register(Me);Me.companion=A.companion.register(Me);Me.legacy=A.model.registerLegacyModel(Me);const Bn=Me;class dE{registerTroubleRankMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleRank,e),this}registerTroubleRoleMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleRole,e),this}registerTroubleColorMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleColor,e),this}registerModelLoader(e,s){$.loader.registerLoader(e,s)}registerCanvasPatternLoader(e){$.loader.registerLoader(At.loader,e)}}const hE=async(t,e)=>{const s=Uo.instance(t).options({}).build(),r=e?`${e}-`:"";return await de(s),{getState:n=>s.data[`${r}${n}`],updateState:async(n,o)=>{await s.updateState(`${r}${n}`,o)},clean:async()=>{for(const n of s.data.keys)await s.updateState(`${r}${n}`,void 0)},unsubscribe:()=>{st(s)}}},Ed="kos:service:region",Md="regionId",fE=`${Ed}-${Md}`,Td=async t=>{const e=at.factory(fE)({path:Ed,attribute:Md});await de(e),e.updateProperty(t)},ci="/kos-timer-event",li="/kos-timer-event/tick",ui="defaultTimerEnd",os=m.createLogger({name:"timer-manager"}),pE=t=>t.updateProperty!==void 0;class Sd{constructor(e,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=e;const n=typeof s=="number"?s:s.value||60;this.timeout=n,this.state="inactive",this.remainingTime=n,pE(s)&&W(()=>{m.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const o=s.value||60;this.updateTimeout(o)}),this.addTimeoutAction({name:ui}),r&&r.forEach(o=>{this.addTimeoutAction(o)})}get id(){return this.name}start(){if(this.state==="active"){os.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&&(os.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(e){this.timeout=e,this.restart()}addTimeoutAction(e){const s=e.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=e.name,n=this.timeoutActions.get(s).find(o=>o.name===r);n?n.action=e.action:this.timeoutActions.get(s).push(e)}removeTimeoutAction(e){for(const[s,r]of this.timeoutActions.entries()){const n=r.filter(o=>o.name!==e);n.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,n)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(e){this.timeoutActions.has(e)&&this.timeoutActions.get(e).forEach(s=>{var r;os.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(os.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){V(`${li}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){V(ci,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const is=new Map,mt=(t,e)=>{const s=is.get(t);if(!s){os.error(`Timer ${t} not found`);return}e(s)},_d={createRelativeTimer(t,e,s){const r=new Date,n=Math.round((e.getTime()-r.getTime())/1e3);return this.createTimer(t,n,s)},createTimer(t,e=60,s){if(is.has(t))return is.get(t);const r=new Sd(t,e,s);return is.set(t,r),r},getTimer(t){return is.get(t)},clearTimer(t){mt(t,e=>e.pause())},restartTimer(t){mt(t,e=>e.restart())},resetTimer(t){mt(t,e=>e.reset())},addTimeoutAction(t,e){mt(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){mt(t,s=>s.removeTimeoutAction(e))},startTimer(t){mt(t,e=>e.start())}},Id="kos:service:region:settings",Od="timeZone",gE=`${Id}-${Od}`,Hn=async t=>{const e=at.factory(gE)({path:Id,attribute:Od});await de(e),e.updateProperty(t)},mE=t=>!t||!t.data;function di(t={}){const{alias:e,namespace:s,abortController:r=!1,trackerPolicy:n="id"}=t;return(o,i,a)=>{o[ls]=o[ls]||{},e&&(o[hs]=o[hs]||new Map,o[hs].set(i,e));const c=a.value,u=async function(...d){const h=ot();m.debug(`Calling future service ${i} with tracker ${h}`);let f,p;r&&(f=new AbortController);const y=rt.initiateFuture({tracker:h,id:Io});s&&(y.namespace=s),m.debug(`waiting for future ${y.id} to be ready`),await de(y),m.debug(`future ${y.id} is ready`),X(()=>{m.debug(`Adding future ${y.id} to futureHandler`),this.futureHandler.addFuture(y,e)}),r&&f&&(p=W(()=>{(y.status==="CANCELLED"||y.endState===Ke.Canceled)&&(m.debug(`Future ${y.id} cancelled, aborting request`),f==null||f.abort())}),f.signal.addEventListener("abort",async()=>{if(y.status!=="CANCELLED"&&y.endState!==Ke.Canceled&&!y.endState){m.debug(`AbortController aborted, cancelling future ${y.id}`);try{await y.cancelFuture()}catch(E){m.error(`Failed to cancel future ${y.id}:`,E)}}},{once:!0}));const w=()=>{p&&(p(),p=void 0)};try{const E=[...d];if(r&&f){const P=E[E.length-1];P&&typeof P=="object"&&"aborted"in P?E[E.length-1]=f.signal:E.push(f.signal)}if(n==="context"){const P=E[E.length-1];if(po(P))P.$tracker=h;else{const O={[Br]:!0,$tracker:h};E.push(O)}}else E.push(h);const S=await c.apply(this,E);m.debug(`received future response for ${h}`,S);const L=mE(S)?S:S==null?void 0:S.data;return L?(L.progress=1,m.debug("mapping future response to future model"),y.endState?m.debug(`future ${y.id} has already completed. Not updating the model`):Po(L,y)):this.futureHandler.removeFuture(e),w(),L}catch(E){if(w(),r&&(f!=null&&f.signal.aborted)){const S=new Error("Operation cancelled");throw m.debug(`Operation ${i} was cancelled`),S}throw m.error(E),E}};o[ls][i]={handler:u}}}const yE=({path:t})=>(e,s)=>{e[N]=e[N]||{},e[N][s]={modelType:$s.type,id:`${$s.type}-${t}`,options:{path:t},lifecycle:x.INIT}};function bE(t){const{path:e,attribute:s}=t;return(r,n)=>{r[N]=r[N]||{},r[N][n]={modelType:Qo.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:x.INIT}}}const Et=m.createLogger({name:"services",group:"Services"}),vE=async(t,e)=>$d(t,e,`${exports.BASE_URL}/api/server/login`),$d=async(t,e,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:t,password:e})});if(!r.ok){const o=await r.json();throw Error(`${o==null?void 0:o.error}`)}return await r.json()},wE=async t=>Cd(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Cd=async(t,e=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${e}?email=${t}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},EE=async(t,e)=>Dd(t,e,`${exports.BASE_URL}/api/server/resetPassword`),Dd=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{Et.debug(`resetting password with token ${t} and password ${e.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e})});if(Et.debug(`password reset returned status ${r.status}`),!r.ok){Et.error(`password reset failed with message ${r.statusText}`);const o=await r.json();throw Error(`${o==null?void 0:o.error}:There was a problem resetting the password.`)}return await r.json()},ME=async(t,e,s)=>xd(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),xd=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Et.debug(`accepting invite with token ${t} and password ${e.replace(/./g,"*")}`);const n=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e,name:s})});if(Et.debug(`invitation accept returned status ${n.status}`),!n.ok){Et.error(`invite failed with message ${n.statusText}`);const i=await n.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await n.json()};function TE(t,e,s,r){const n=t instanceof Promise?{promise:t,abortController:e,cancelFuture:s,future:r}:t,{promise:o,abortController:i,cancelFuture:a,future:c}=n,u=o;let d=0,h="PENDING",f=!0;const p=new Set;let y;return c&&typeof c=="object"&&(y=M.autorun(()=>{const w=c.progress||0,E=c.status||"PENDING",S=!c.endState;(w!==d||E!==h||S!==f)&&(d=w,h=E,f=S,p.forEach(L=>{try{L(d,h)}catch(P){console.warn("Progress callback error:",P)}}))})),o.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(w=>{try{w(d,h)}catch(E){console.warn("Progress callback error:",E)}})),y&&y(),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(E){console.warn("Progress callback error:",E)}}),y&&y()},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 SE=Qe.keyframes`
114
+ `,i=this.compileShader(r.VERTEX_SHADER,n),a=this.compileShader(r.FRAGMENT_SHADER,o);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 n=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const o=this.speedPx/r;this.hueOffset=(this.hueOffset+o)%1}n.viewport(0,0,s,r),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(this.program),n.enableVertexAttribArray(this.aPosition),n.bindBuffer(n.ARRAY_BUFFER,this.posBuffer),n.vertexAttribPointer(this.aPosition,2,n.FLOAT,!1,0,0),n.uniform1f(this.uMinHue,this.minHue/360),n.uniform1f(this.uMaxHue,this.maxHue/360),n.uniform1f(this.uHueOffset,this.hueOffset),n.uniform1f(this.uGridHeight,r),n.drawArrays(n.TRIANGLES,0,6)}compileShader(s,r){const n=this.gl.createShader(s);if(this.gl.shaderSource(n,r),this.gl.compileShader(n),!this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(n)||"Shader compile failed");return n}createProgram(s,r){const n=this.gl.createProgram();if(this.gl.attachShader(n,s),this.gl.attachShader(n,r),this.gl.linkProgram(n),!this.gl.getProgramParameter(n,this.gl.LINK_STATUS))throw new Error("Program linking failed");return n}}class dt{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("2d");if(!e)throw new Error("2D canvas not supported");this.ctx=e}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}}function si(t){class e extends t{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(n){this.doneCallback=n}signalDoneIfNeeded(){var n;this.oneShotDone||((n=this.doneCallback)==null||n.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return e}const ww=si(dt);class Ew extends ww{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:n=2,loop:o=!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=n,this.loop=o}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 n=this.loop?-this.offset:0,o=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(n,0,o,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 Mw=si(dt);class ed extends Mw{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 Tw extends Ju{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 Sw(t){const e=t.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(e))throw new Error(`Invalid hex color: ${t}`);let s,r,n;return e.length===3?(s=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),n=parseInt(e[2]+e[2],16)):(s=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),n=parseInt(e.substring(4,6),16)),{r:s,g:r,b:n}}function td(t){return typeof t=="string"?Sw(t):t}function $r(t){const e=td(t);return`rgb(${e.r},${e.g},${e.b})`}class _w extends dt{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=td(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let n=0;n<=5;n++){const o=1-n/5*.6;r.push({r:Math.floor(this.baseColor.r*o),g:Math.floor(this.baseColor.g*o),b:Math.floor(this.baseColor.b*o)})}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 n=this.ctx.createImageData(s,r),o=n.data;o.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 y=this.trailColors[p];u=y.r,d=y.g,h=y.b}}const f=(i*s+a)*4;o[f]=u,o[f+1]=d,o[f+2]=h,o[f+3]=255}this.ctx.putImageData(n,0,0)}}class Iw{constructor(e,s){l(this,"baseRenderer");l(this,"overlayIcons",new Map);l(this,"overlayConfigs");l(this,"loadedIcons",new Set);l(this,"canvas");l(this,"ctx");l(this,"persistOverlaysOnComplete");l(this,"baseRendererCompleted",!1);l(this,"completionCallback",null);l(this,"hasSignaledCompletion",!1);this.baseRenderer=s(e.baseRenderer.type,e.baseRenderer.data),this.overlayConfigs=e.overlays,this.persistOverlaysOnComplete=e.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const e of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(e.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${e.src}`,r)},s.src=e.src,this.overlayIcons.set(e.src,s)}}calculateOverlayPosition(e,s,r){let n,o;if(typeof e.position=="string")switch(e.position){case"top-left":n=0,o=0;break;case"top-center":n=(s-e.size)/2,o=0;break;case"top-right":n=s-e.size,o=0;break;case"center-left":n=0,o=(r-e.size)/2;break;case"center":n=(s-e.size)/2,o=(r-e.size)/2;break;case"center-right":n=s-e.size,o=(r-e.size)/2;break;case"bottom-left":n=0,o=r-e.size;break;case"bottom-center":n=(s-e.size)/2,o=r-e.size;break;case"bottom-right":n=s-e.size,o=r-e.size;break;default:n=0,o=0}else n=e.position.x,o=e.position.y;return e.offset&&(n+=e.offset.x||0,o+=e.offset.y||0),{x:n,y:o}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(e,s){if(this.canvas.width=e,this.canvas.height=s,this.ctx.clearRect(0,0,e,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(e,s);else{this.baseRenderer.renderFrame(e,s);const r=this.baseRenderer.readPixels(e,s);if(r&&r.length>0){const n=new ImageData(r,e,s);this.ctx.putImageData(n,0,0)}this.renderOverlays(e,s)}}renderOverlays(e,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const n=this.overlayIcons.get(r.src);if(!n||!this.loadedIcons.has(r.src))continue;const o=this.calculateOverlayPosition(r,e,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(n,o.x,o.y,r.size,r.size),this.ctx.restore()}}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(e){this.completionCallback=e,this.hasSignaledCompletion&&e()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class sd extends dt{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 n=this.scrollConfig.direction||"left",o=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=o*u;switch(n){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,n,i),this.checkScrollCompletion(s,r,n,i)}drawScrollingImage(s,r,n,o){var h,f,p,y,w,E,S,L,P;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):n==="left"||n==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r);let u,d;switch(n==="left"||n==="right"?(u=0,((E=this.scrollConfig)==null?void 0:E.offsetY)==="center"||((S=this.scrollConfig)==null?void 0:S.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((L=this.scrollConfig)==null?void 0:L.offsetX)==="center"||((P=this.scrollConfig)==null?void 0:P.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),n){case"left":{const O=s-this.position;if(O<s&&O>-a&&this.ctx.drawImage(this.img,O,d,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>o){const _=O+a+o;_<s&&this.ctx.drawImage(this.img,_,d,a,c)}break}case"right":{const O=-a+this.position;if(O>-a&&O<s&&this.ctx.drawImage(this.img,O,d,a,c),this.loopConfig&&this.pauseDuration===0&&O-o-a>-a){const _=O-a-o;_<s&&this.ctx.drawImage(this.img,_,d,a,c)}break}case"up":{const O=r-this.position;if(O>-c&&O<r&&this.ctx.drawImage(this.img,u,O,a,c),this.loopConfig&&this.pauseDuration===0&&O+c+o<r){const _=O+c+o;_>-c&&this.ctx.drawImage(this.img,u,_,a,c)}break}case"down":{const O=-c+this.position;if(O>-c&&O<r&&this.ctx.drawImage(this.img,u,O,a,c),this.loopConfig&&this.pauseDuration===0&&O-o-c>-c){const _=O-c-o;_<r&&this.ctx.drawImage(this.img,u,_,a,c)}break}}}checkScrollCompletion(s,r,n,o){var h,f,p,y,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):n==="left"||n==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r),n){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let u=!1;const d=1;switch(n){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 n=await(await fetch(s)).text();this.originalSvgData=n;const o=this.applySvgColorOverride(n),i=`data:image/svg+xml;base64,${btoa(o)}`;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=$r(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 Ow extends dt{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=$r(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 o=this.ctx.measureText(r).width;this.lineWidths.push(o),s=Math.max(s,o)}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 n=this.scrollConfig.direction||"left",o=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=o*u;switch(n){case"left":case"right":case"up":case"down":this.position+=d;break}}this.drawScrollingText(s,r,n,i),this.checkScrollCompletion(s,r,n)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const n=this.textHeight;let o=(r-n)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],c=this.lineWidths[i],u=(s-c)/2,d=o+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,n,o){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;n==="left"||n==="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(n,s,r,o,i,a)}drawMultiLineScrollText(s,r,n,o,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>o){const u=c+this.textWidth+o;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-o-this.textWidth>-this.textWidth){const u=c-this.textWidth-o;u<r&&this.drawTextBlock(u,a,"left")}break}case"up":{const c=n-this.position;if(c>-this.textHeight&&c<n&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c+this.textHeight+o<n){const u=c+this.textHeight+o;u>-this.textHeight&&this.drawTextBlock(i,u,"center")}break}case"down":{const c=-this.textHeight+this.position;if(c>-this.textHeight&&c<n&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c-o-this.textHeight>-this.textHeight){const u=c-this.textHeight-o;u<n&&this.drawTextBlock(i,u,"center")}break}}}drawTextBlock(s,r,n){for(let o=0;o<this.lines.length;o++){const i=this.lines[o],a=this.lineWidths[o];let c;n==="center"?c=s-a/2:c=s;const u=r+o*this.lineHeight;this.ctx.fillText(i,c,u)}}checkScrollCompletion(s,r,n){if(!this.isPlaying)return;let o=!1;const i=1;switch(n){case"left":o=s-this.position<-this.textWidth-i;break;case"right":o=-this.textWidth+this.position>s+i;break;case"up":o=r-this.position<-this.textHeight-i;break;case"down":o=-this.textHeight+this.position>r+i;break}o&&(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 $w{constructor(e){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=e.patterns,this.loopConfig=e.loop??!1,this.transitionDuration=e.transitionDuration??0,this.patternOverrides=e.patternOverrides??{},this.patternStore=e.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var o,i,a,c;const e=this.patterns[this.currentPatternIndex],s=this.patternStore.get(e);if(!s){console.warn(`Pattern "${e}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(o=this.currentRenderer).dispose)==null||i.call(o));const r=this.patternOverrides[e]??{},n={...s.data,...r};try{this.currentRenderer=Cr({mode:s.type,data:n}),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 "${e}":`,u),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const Cw=si(dt);class Dw extends Cw{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=$r(r)}setColor(s){this.color=$r(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 xw extends dt{constructor({minHue:s=0,maxHue:r=360,speed:n=1}={}){super();l(this,"offset",0);l(this,"minHue");l(this,"maxHue");l(this,"speed");this.minHue=s,this.maxHue=r,this.speed=n}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,r,n){let o,i,a;if(r===0)o=i=a=n;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=n<.5?n*(1+r):n+r-n*r,d=2*n-u;o=c(d,u,s+1/3),i=c(d,u,s),a=c(d,u,s-1/3)}return[Math.round(o*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const n=this.ctx.createImageData(s,r),o=n.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);o[i++]=h,o[i++]=f,o[i++]=p,o[i++]=255}this.ctx.putImageData(n,0,0)}}const oa=new Map;ks(te,{register(t,e){oa.set(t,e)},execute(t,e){const s=oa.get(t);return s?new s(e):null}});$.canvas.registerRenderer("video",Tw);$.canvas.registerRenderer("video-basic",Ju);$[te].register("image-static",ed);$[te].register("image-scrolling",sd);const Aw=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new sd(t):new ed(t)}};$[te].register("image",Aw);$[te].register("color",Dw);$[te].register("matrix",_w);$[te].register("sweep",xw);$[te].register("gradient",Ew);$[te].register("drop",vw);$[te].register("sequence",$w);$[te].register("text",Ow);const Rw=class{constructor(t){const e=(s,r)=>{const n=Cr({mode:s,data:r});if(!n)throw new Error(`Failed to create renderer of type: ${s}`);return n};return new Iw(t,e)}};$[te].register("overlay",Rw);const Cr=({mode:t,data:e})=>{const s=$[te].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var Pw=Object.defineProperty,kw=Object.getOwnPropertyDescriptor,qt=(t,e,s,r)=>{for(var n=r>1?void 0:r?kw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Pw(e,s,n),n};const rd="canvas-dispatcher-model";function Lw(t){if(t=t.replace(/^#/,""),t.length===3&&(t=t.split("").map(s=>s+s).join("")),t.length!==6)return null;const e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:e&255}}let ze=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new Ce}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=ti.instance(t).options({apiPath:e.apiPath,width:e.width,height:e.height,fps:e.fps,durationMs:e.durationMs??null,endpoint:t}).build();return this._endpointRenderers.addModel(s),s}addContent(t,e){this._content.has(t)&&this.logger.warn(`Content "${t}" already exists. Overwriting.`),this._content.set(t,e)}addPattern(t,e){this._patterns.has(t)&&this.logger.warn(`Pattern "${t}" already exists. Overwriting.`),this._patterns.set(t,e)}async handlePatternsPost(t,e){var n,o;const s=t.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(n=e.status)==null||n.call(e,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(o=e.status)==null||o.call(e,200).send({status:"OK"})}async handlePatternApplication(t,e){var u,d,h;const s=t.params.pattern,r=t.params.endpoint,n=this._endpointRenderers.getModel(r);if(!n){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=e.status)==null||d.call(e,404).send({error:`Pattern "${s}" not found`});return}const o=this._patterns.get(s),i=o.type,a=t.body||{};this.data={...o.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;n.renderer=Cr({mode:i,data:c}),n.setClearOnComplete(o.clearOnComplete),n.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var u,d,h;const s=t.params.color,r=Lw(s);if(!r){(u=e.status)==null||u.call(e,400).send({error:"Invalid color format"});return}const n=t.params.endpoint,o=this._endpointRenderers.getModel(n);if(!o){(d=e.status)==null||d.call(e,404).send({error:`Endpoint "${n}" not found`});return}const{r:i,b:a,g:c}=r;o.renderer=Cr({mode:"color",data:{r:i,g:c,b:a}}),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleEndpointCreation(t,e){var r,n;const s=t.body;if(!s.apiPath||!s.id){(r=e.status)==null||r.call(e,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(n=e.status)==null||n.call(e,200).send({status:"OK"})}async load(t){var s;const e=t==null?void 0:t.get(At.loader);e&&((s=e.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};qt([$e],ze.prototype,"_endpointRenderers",2);qt([Fs("/api/ui/canvas/patterns")],ze.prototype,"handlePatternsPost",1);qt([Fs("/api/ui/canvas/pattern/:endpoint/:pattern")],ze.prototype,"handlePatternApplication",1);qt([Fs("/api/ui/canvas/color/:endpoint/:color")],ze.prototype,"handleColorApplication",1);qt([Fs("/api/ui/canvas/endpoint")],ze.prototype,"handleEndpointCreation",1);ze=qt([R(rd)],ze);const At=new Se({class:ze,type:rd}),{URL:ri}=ae(),{getOne:nd}=ne.build({basePath:`${ri}/api/device`}),Dr=m.createLogger({name:"device-service",group:"Services"}),od=async()=>{Dr.debug("sending GET for device serial number");try{const t=await nd({urlOverride:`${ri}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof ge)return Dr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},id=async()=>{Dr.debug("sending GET for device details");try{const t=await nd({urlOverride:`${ri}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof ge)return Dr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Fw=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:id,getSerialNumber:od},Symbol.toStringTag,{value:"Module"}));var Nw=Object.defineProperty,Uw=Object.getOwnPropertyDescriptor,ad=(t,e,s,r)=>{for(var n=r>1?void 0:r?Uw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Nw(e,s,n),n};const cd="device-model",jw="/kos/criticalData/changed",Bw="/kos/criticalData/available";let xr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=t,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[t]=this.nodeId.split("-");return t}get nodeName(){const[,t]=this.nodeId.split("-");return t}updateModel(t){this._serialNumber=t.serialNumber??"unassigned",this._name=t.name??"unassigned",this._nodeId=t.nodeId??"unassigned"}async loadDeviceData(){const[t,e]=await id();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}if(e){const{name:s,nodeId:r}=e;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[t,e]=await od();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}this.updateModel({serialNumber:e,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};ad([B({topic:[jw,Bw],websocket:!0})],xr.prototype,"handleCriticalDataChanged",1);xr=ad([R(cd)],xr);const Ar=new Se({class:xr,type:cd});var Hw=Object.getOwnPropertyDescriptor,Kw=(t,e,s,r)=>{for(var n=r>1?void 0:r?Hw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const ld="network-interface-model";let jn=class{constructor(t,e,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=t,this.logger=s.logger,this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}updateModel(t){this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};jn=Kw([R(ld)],jn);const ni=new ye({class:jn,type:ld}),{URL:qw}=ae(),{getAll:zw}=ne.build({basePath:`${qw}/api/kos/network/interfaces`}),ia=m.createLogger({name:"network-interface-service",group:"Services"}),ud=async()=>{ia.debug("sending GET for copy-logs");try{const t=await zw({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof ge)return ia.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Vw=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:ud},Symbol.toStringTag,{value:"Module"}));var Gw=Object.defineProperty,Yw=Object.getOwnPropertyDescriptor,dd=(t,e,s,r)=>{for(var n=r>1?void 0:r?Yw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&Gw(e,s,n),n};const hd="network-interface-container-model";let Rr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await ud();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=ni.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};dd([$e],Rr.prototype,"_models",2);Rr=dd([R(hd)],Rr);const Ds=new Se({class:Rr,type:hd});Ds.addRelatedModel(ni);const{URL:Ww}=ae(),{getAll:Qw}=ne.build({basePath:`${Ww}/api/kos/storage/devices`}),aa=m.createLogger({name:"storage-device-service",group:"Services"}),fd=async()=>{aa.debug("sending GET for storage-device");const t=await Qw({});return!(t!=null&&t.data)||t.status!==200?(aa.error("Failed to retrieve storage-device data",t),[]):t.data},Zw=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:fd},Symbol.toStringTag,{value:"Module"}));var Xw=Object.getOwnPropertyDescriptor,Jw=(t,e,s,r)=>{for(var n=r>1?void 0:r?Xw(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const pd="storage-device-model";let Bn=class{constructor(t,e,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=t,this.logger=s.logger,this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}updateModel(t){this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};Bn=Jw([Br(),R(pd)],Bn);const Pr=new ye({class:Bn,type:pd});var eE=Object.defineProperty,tE=Object.getOwnPropertyDescriptor,oi=(t,e,s,r)=>{for(var n=r>1?void 0:r?tE(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&eE(e,s,n),n};const gd="storage-device-container-model",sE="/kos/storage";let xs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const n={...s,kosParentId:this.id};r.updateModel(n)}else{const n={...s,kosParentId:this.id},o=Pr.instance(s.id).options(n).build();this.addModel(o)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await fd()).forEach(e=>{if(e.deviceType!=="disk"){const s={...e,kosParentId:this.id},r=Pr.instance(e.id).options(s).build();this.addModel(r)}})}};oi([$e],xs.prototype,"_models",2);oi([B({topic:sE,websocket:!0})],xs.prototype,"handleStorageAvailability",1);xs=oi([R(gd)],xs);const Rt=new Se({class:xs,type:gd});Rt.addRelatedModel(Pr);const{URL:ii}=ae(),{getAll:rE,postModel:nE}=ne.build({basePath:`${ii}/api/kos/update/available`}),ca=m.createLogger({name:"usb-update-service",group:"Services"}),md=async()=>{ca.debug("sending GET for usb-update");const t=await rE({urlOverride:`${ii}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(ca.error("Failed to retrieve usb-update data",t),[]):t.data},yd=async(t,e,s)=>{const r=await nE({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${ii}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},oE=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:md,installUpdate:yd},Symbol.toStringTag,{value:"Module"}));var iE=Object.defineProperty,aE=Object.getOwnPropertyDescriptor,bd=(t,e,s,r)=>{for(var n=r>1?void 0:r?aE(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&iE(e,s,n),n};const vd="usb-update-model";let kr=class{constructor(t,e,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=t,this.logger=s.logger,this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes,this.futureHandler=new qr(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),yd(this.manifestId,this.deviceId,t)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};bd([hi()],kr.prototype,"install",1);kr=bd([R(vd)],kr);const ai=new ye({class:kr,type:vd});var cE=Object.defineProperty,lE=Object.getOwnPropertyDescriptor,nn=(t,e,s,r)=>{for(var n=r>1?void 0:r?lE(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=(r?i(e,s,n):i(n))||n);return r&&n&&cE(e,s,n),n};const wd="usb-update-container-model";let Pt=class{constructor(t,e,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await md();X(()=>{const e=t.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!e.includes(s.id)).forEach(s=>this.removeModel(s.id)),t.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,n=ai.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(n)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var t;(t=this.disposer)==null||t.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};nn([Lt({modelType:Rt.type})],Pt.prototype,"storageService",2);nn([$e],Pt.prototype,"_models",2);nn([Ec({dependencies:t=>[t.isUsbInserted]})],Pt.prototype,"usbInsertedEffect",1);Pt=nn([R(wd)],Pt);const As=new Se({class:Pt,type:wd});As.addRelatedModel(ai);const uE=()=>({...{[Ut.type]:{class:zl},[qe.type]:{class:Zl,singleton:!0},...re.registration,...at.registration,...Dt.registration,..._r.registration,...Fe.registration,[Jo.type]:{class:exports.WsEventModel,singleton:!0},...Cs.registration,...Zo.registration,...mr.registration}}),ci=uE(),dE={models:ci,preloadModels:[]},la=!0,Ed=t=>()=>{const e=ci;return xc(Hn)($s).model(Dt).model(Rt).model(As).model(Ar).model(Er).model(Es).model(Mr).model(jo).model(Ds).model(At).model(ti).model(cu).model(Fo,la).model(Bs).model(du,la),Object.keys(e).forEach(s=>{const r=e[s];Dc(Hn)(s,r)}),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t)}},Me={};Me.core={models:Ed(Me)};Me.preload=A.model.preloadModel(Me);Me.model=A.model.register(Me);Me.companion=A.companion.register(Me);Me.legacy=A.model.registerLegacyModel(Me);const Hn=Me;class hE{registerTroubleRankMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleRank,e),this}registerTroubleRoleMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleRole,e),this}registerTroubleColorMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleColor,e),this}registerModelLoader(e,s){$.loader.registerLoader(e,s)}registerCanvasPatternLoader(e){$.loader.registerLoader(At.loader,e)}}const fE=async(t,e)=>{const s=jo.instance(t).options({}).build(),r=e?`${e}-`:"";return await de(s),{getState:n=>s.data[`${r}${n}`],updateState:async(n,o)=>{await s.updateState(`${r}${n}`,o)},clean:async()=>{for(const n of s.data.keys)await s.updateState(`${r}${n}`,void 0)},unsubscribe:()=>{st(s)}}},Md="kos:service:region",Td="regionId",pE=`${Md}-${Td}`,Sd=async t=>{const e=at.factory(pE)({path:Md,attribute:Td});await de(e),e.updateProperty(t)},li="/kos-timer-event",ui="/kos-timer-event/tick",di="defaultTimerEnd",is=m.createLogger({name:"timer-manager"}),gE=t=>t.updateProperty!==void 0;class _d{constructor(e,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=e;const n=typeof s=="number"?s:s.value||60;this.timeout=n,this.state="inactive",this.remainingTime=n,gE(s)&&W(()=>{m.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const o=s.value||60;this.updateTimeout(o)}),this.addTimeoutAction({name:di}),r&&r.forEach(o=>{this.addTimeoutAction(o)})}get id(){return this.name}start(){if(this.state==="active"){is.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&&(is.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(e){this.timeout=e,this.restart()}addTimeoutAction(e){const s=e.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=e.name,n=this.timeoutActions.get(s).find(o=>o.name===r);n?n.action=e.action:this.timeoutActions.get(s).push(e)}removeTimeoutAction(e){for(const[s,r]of this.timeoutActions.entries()){const n=r.filter(o=>o.name!==e);n.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,n)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(e){this.timeoutActions.has(e)&&this.timeoutActions.get(e).forEach(s=>{var r;is.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(is.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){V(`${ui}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){V(li,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const as=new Map,mt=(t,e)=>{const s=as.get(t);if(!s){is.error(`Timer ${t} not found`);return}e(s)},Id={createRelativeTimer(t,e,s){const r=new Date,n=Math.round((e.getTime()-r.getTime())/1e3);return this.createTimer(t,n,s)},createTimer(t,e=60,s){if(as.has(t))return as.get(t);const r=new _d(t,e,s);return as.set(t,r),r},getTimer(t){return as.get(t)},clearTimer(t){mt(t,e=>e.pause())},restartTimer(t){mt(t,e=>e.restart())},resetTimer(t){mt(t,e=>e.reset())},addTimeoutAction(t,e){mt(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){mt(t,s=>s.removeTimeoutAction(e))},startTimer(t){mt(t,e=>e.start())}},Od="kos:service:region:settings",$d="timeZone",mE=`${Od}-${$d}`,Kn=async t=>{const e=at.factory(mE)({path:Od,attribute:$d});await de(e),e.updateProperty(t)},yE=t=>!t||!t.data;function hi(t={}){const{alias:e,namespace:s,abortController:r=!1,trackerPolicy:n="id"}=t;return(o,i,a)=>{o[us]=o[us]||{},e&&(o[fs]=o[fs]||new Map,o[fs].set(i,e));const c=a.value,u=async function(...d){const h=ot();m.debug(`Calling future service ${i} with tracker ${h}`);let f,p;r&&(f=new AbortController);const y=rt.initiateFuture({tracker:h,id:Oo});s&&(y.namespace=s),m.debug(`waiting for future ${y.id} to be ready`),await de(y),m.debug(`future ${y.id} is ready`),X(()=>{m.debug(`Adding future ${y.id} to futureHandler`),this.futureHandler.addFuture(y,e)}),r&&f&&(p=W(()=>{(y.status==="CANCELLED"||y.endState===Ke.Canceled)&&(m.debug(`Future ${y.id} cancelled, aborting request`),f==null||f.abort())}),f.signal.addEventListener("abort",async()=>{if(y.status!=="CANCELLED"&&y.endState!==Ke.Canceled&&!y.endState){m.debug(`AbortController aborted, cancelling future ${y.id}`);try{await y.cancelFuture()}catch(E){m.error(`Failed to cancel future ${y.id}:`,E)}}},{once:!0}));const w=()=>{p&&(p(),p=void 0)};try{const E=[...d];if(r&&f){const P=E[E.length-1];P&&typeof P=="object"&&"aborted"in P?E[E.length-1]=f.signal:E.push(f.signal)}if(n==="context"){const P=E[E.length-1];if(go(P))P.$tracker=h;else{const O={[Hr]:!0,$tracker:h};E.push(O)}}else E.push(h);const S=await c.apply(this,E);m.debug(`received future response for ${h}`,S);const L=yE(S)?S:S==null?void 0:S.data;return L?(L.progress=1,m.debug("mapping future response to future model"),y.endState?m.debug(`future ${y.id} has already completed. Not updating the model`):ko(L,y)):this.futureHandler.removeFuture(e),w(),L}catch(E){if(w(),r&&(f!=null&&f.signal.aborted)){const S=new Error("Operation cancelled");throw m.debug(`Operation ${i} was cancelled`),S}throw m.error(E),E}};o[us][i]={handler:u}}}const bE=({path:t})=>(e,s)=>{e[N]=e[N]||{},e[N][s]={modelType:Cs.type,id:`${Cs.type}-${t}`,options:{path:t},lifecycle:x.INIT}};function vE(t){const{path:e,attribute:s}=t;return(r,n)=>{r[N]=r[N]||{},r[N][n]={modelType:Zo.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:x.INIT}}}const Et=m.createLogger({name:"services",group:"Services"}),wE=async(t,e)=>Cd(t,e,`${exports.BASE_URL}/api/server/login`),Cd=async(t,e,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:t,password:e})});if(!r.ok){const o=await r.json();throw Error(`${o==null?void 0:o.error}`)}return await r.json()},EE=async t=>Dd(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Dd=async(t,e=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${e}?email=${t}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},ME=async(t,e)=>xd(t,e,`${exports.BASE_URL}/api/server/resetPassword`),xd=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{Et.debug(`resetting password with token ${t} and password ${e.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e})});if(Et.debug(`password reset returned status ${r.status}`),!r.ok){Et.error(`password reset failed with message ${r.statusText}`);const o=await r.json();throw Error(`${o==null?void 0:o.error}:There was a problem resetting the password.`)}return await r.json()},TE=async(t,e,s)=>Ad(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),Ad=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Et.debug(`accepting invite with token ${t} and password ${e.replace(/./g,"*")}`);const n=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e,name:s})});if(Et.debug(`invitation accept returned status ${n.status}`),!n.ok){Et.error(`invite failed with message ${n.statusText}`);const i=await n.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await n.json()};function SE(t,e,s,r){const n=t instanceof Promise?{promise:t,abortController:e,cancelFuture:s,future:r}:t,{promise:o,abortController:i,cancelFuture:a,future:c}=n,u=o;let d=0,h="PENDING",f=!0;const p=new Set;let y;return c&&typeof c=="object"&&(y=M.autorun(()=>{const w=c.progress||0,E=c.status||"PENDING",S=!c.endState;(w!==d||E!==h||S!==f)&&(d=w,h=E,f=S,p.forEach(L=>{try{L(d,h)}catch(P){console.warn("Progress callback error:",P)}}))})),o.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(w=>{try{w(d,h)}catch(E){console.warn("Progress callback error:",E)}})),y&&y(),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(E){console.warn("Progress callback error:",E)}}),y&&y()},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 _E=Qe.keyframes`
116
116
  0% {
117
117
  left: -90px;
118
118
  color: #eee;
@@ -124,13 +124,13 @@ ${u}topics:${e}
124
124
  left: 90px;
125
125
  color: #eee;
126
126
  }
127
- `,_E=Qe.css`
127
+ `,IE=Qe.css`
128
128
  font-size: 100px;
129
129
  margin-top: -80px;
130
130
  position: relative;
131
- animation: ${SE} ease-in-out infinite alternate;
131
+ animation: ${_E} ease-in-out infinite alternate;
132
132
  animation-duration: 1.2s;
133
- `,IE=({children:t})=>ha.createPortal(t,document.body);function Ad({message:t="Wait a moment while we load your app.",theme:e="light"}){return T.jsx(IE,{children:T.jsxs(OE,{theme:e,children:[t,T.jsx("div",{css:_E,children:"."})]})})}const OE=Vn.div`
133
+ `,OE=({children:t})=>fa.createPortal(t,document.body);function Rd({message:t="Wait a moment while we load your app.",theme:e="light"}){return T.jsx(OE,{children:T.jsxs($E,{theme:e,children:[t,T.jsx("div",{css:IE,children:"."})]})})}const $E=Gn.div`
134
134
  padding-inline: 20px;
135
135
  width: 100%;
136
136
  height: 100vh;
@@ -144,7 +144,7 @@ ${u}topics:${e}
144
144
  left: 0;
145
145
  color: ${({theme:t})=>t==="light"?"black":"white"};
146
146
  z-index: 10000;
147
- `;class Rd extends g.Component{constructor(e){super(e),this.state={error:null,errorInfo:null}}componentDidCatch(e,s){this.setState({error:e,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||T.jsxs("div",{children:[T.jsx("h2",{children:"Something went wrong."}),T.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),T.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const $E={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},CE=({value:t=0,title:e,status:s="normal",subtitle:r})=>{const n=Qe.css`
147
+ `;class Pd extends g.Component{constructor(e){super(e),this.state={error:null,errorInfo:null}}componentDidCatch(e,s){this.setState({error:e,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||T.jsxs("div",{children:[T.jsx("h2",{children:"Something went wrong."}),T.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),T.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const CE={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},DE=({value:t=0,title:e,status:s="normal",subtitle:r})=>{const n=Qe.css`
148
148
  display: flex;
149
149
  flex-direction: column;
150
150
  `,o=Qe.css`
@@ -164,7 +164,7 @@ ${u}topics:${e}
164
164
  `,a=Qe.css`
165
165
  width: ${t}%;
166
166
  height: 35px;
167
- background-color: ${$E[s]};
167
+ background-color: ${CE[s]};
168
168
  text-align: center;
169
169
  line-height: 32px;
170
170
  color: black;
@@ -182,7 +182,7 @@ ${u}topics:${e}
182
182
  transform: translateX(100%) scaleX(0.5);
183
183
  }
184
184
  }
185
- `;return T.jsxs("div",{css:n,children:[T.jsxs("div",{css:o,children:[T.jsx("div",{css:i,children:e}),T.jsx("div",{css:[a,t<0?c:""]})]}),T.jsx("div",{children:r})]})},DE={setModel:()=>!1},nn=g.createContext(DE),xE=()=>{const t=g.useContext(nn);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},Pd=({children:t})=>{const[e,s]=g.useState(),r=g.useCallback(n=>(s(n),!0),[s]);return T.jsx(nn.Provider,{value:{model:e,setModel:r},children:t})},kd=m.createLogger({name:"kos-model-hierarchy-context"}),AE={models:[],addModel:()=>{kd.debug("Default implementation being used. Do Nothing.")}},on=g.createContext(AE),RE=({children:t})=>{const[e,s]=g.useState([]),r=g.useCallback(n=>{e.includes(n)||(kd.debug("adding to hierarchy context",n.id),s(o=>[...o,n]))},[e]);return T.jsx(on.Provider,{value:{models:e,addModel:r},children:t})},PE=()=>!0,Ld=t=>{const e=g.useContext(on);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||PE;return g.useMemo(()=>e.models.filter(s),[e.models,s])},kE=t=>Ld({filter:s=>{const r=Ie(s.id);return(r==null?void 0:r.type)===t}})[0],LE=m.createLogger({name:"kos-model-loader"}),FE=()=>T.jsx("div",{}),Fd=({fallback:t,children:e,...s})=>T.jsx(Pd,{children:T.jsx(Rd,{fallback:t,children:T.jsx(g.Suspense,{children:T.jsx(Nd,{...s,children:e})})})}),Nd=t=>{const[e,s]=g.useState(),[r,n]=g.useState(!1),{setModel:o}=g.useContext(nn),i=g.useContext(on);if(g.useEffect(()=>{t.model&&(s(t.model),o(t.model),n(!0),i&&i.addModel(t.model))},[i,t.model,o]),t.error)throw LE.error(t.error),new Error(t.error);const a=t.loading||T.jsx(FE,{});return T.jsx(T.Fragment,{children:e&&r?t.children:a})},or={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Ud=g.createContext(or),NE=({translations:t=or,children:e})=>{const s={header:{...or.header,...t.header},createModal:{...or.createModal,...t.createModal}};return T.jsx(Ud.Provider,{value:s,children:e})};function UE(t,e){const s=I.create(t,!1,e),r=s.whenReady().then(()=>s);return so(r)}const jd=g.createContext(void 0),jE=(t={models:{},preloadModels:[]},e)=>{const s=UE(t,e),r=({children:n})=>{const o=s.read(),[i,a]=g.useState(o.isOnline);return g.useEffect(()=>{const c=W(()=>{a(o.isOnline)});return()=>{c()}},[o]),T.jsx(jd.Provider,{value:{kosCore:o,online:i},children:n})};return{KosCoreContextProvider:Gn.observer(r)}},Bd=()=>{const t=g.useContext(jd);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},BE=8,HE=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),Xe=new Map;function KE(t,e){if(Xe.has(t)){const s=Xe.get(t);if(s.status==="finished"){const r=I.getInstance().modelManager.getModelById(t);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=e().then(()=>{Xe.set(t,{status:"finished",key:t})},n=>{throw Xe.set(t,{status:"error",error:n}),n}),r={status:"pending",promise:s};throw Xe.set(t,r),s}}function qE(t,e){return KE(t,e)}async function zE(t,e){const{modelId:s,factory:r,modelType:n,options:o,activate:i}=e;let a=0;await t.whenReady();let c;if(o){const d=typeof n=="string"?t.modelManager.getModelFactory(n):r;if(!d)throw Error("No Factory Specified. Cannot create a new instance");c=d.build(s,o)}const u=t.modelManager.getModelById(s);if(!u){if(a>BE)throw Error(`KOS Model ${s} has not been found`);await HE(a),a=a+1}return await(u==null?void 0:u.whenReady()),u?(c=u.modelData,{kosModel:u,model:c}):{kosModel:void 0,model:void 0}}const Z=t=>{const{modelId:e,modelType:s,activate:r,destroyOnUnmount:n}=t,o=Bd(),[i,a]=g.useState(!1),[c,u]=g.useState(),{kosModel:d,model:h}=qE(e||s||"",()=>zE(o.kosCore,t));return g.useEffect(()=>{t.forceUpdate&&h&&mo(h)&&h.updateModel(t.options||{})},[h]),g.useEffect(()=>{async function f(){try{return await o.kosCore.whenReady(),r&&await(d==null?void 0:d.fsm.transitionTo(F.GO_ACTIVE,v.ACTIVE)),a(!0),d}catch(y){throw u(y.message),y}}let p;return o.kosCore&&e&&f().then(y=>{p=W(()=>{const w=(y==null?void 0:y.status)===v.READY;a(w)})}).catch(y=>{console.error(y)}),()=>{if(r){if(h!=null&&h.id){const y=o.kosCore.modelManager.getModelById(h.id);y==null||y.fsm.transitionTo(F.GO_INACTIVE,v.INACTIVE).then(()=>{if(n){const w=h.id;st(h).then(()=>{Xe.delete(w),p==null||p()})}})}}else n&&h&&st(h).then(()=>{Xe.delete(e),p==null||p()})}},[r,n,o.kosCore,d,h,e]),{model:h,ready:i,error:c,status:{model:h,ready:i,error:c},KosModelLoader:Fd}},hi=()=>{const t=gr.type;return Z({modelId:t,modelType:gr.type,options:{}})},fi=g.createContext(void 0),VE=({children:t})=>{const{model:e,ready:s}=hi(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(fi.Provider,{value:r,children:t})},GE=()=>{const t=g.useContext(fi);if(!t)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return t},pi=()=>{const t=Er.type;return Z({modelId:t,modelType:Er.type,options:{}})};function YE(t){return()=>e=>{const{model:s,status:r,KosModelLoader:n}=pi();return T.jsx(n,{...r,children:T.jsx(t,{...e,softwareInfo:s})})}}const gi=g.createContext(void 0),WE=({children:t})=>{const{model:e,ready:s}=pi(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(gi.Provider,{value:r,children:t})},QE=()=>{const t=g.useContext(gi);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Hd=new vl,Kd=g.createContext(Hd);function ZE({children:t}){return T.jsx(Kd.Provider,{value:Hd,children:t})}const mi=g.createContext(void 0),XE=()=>{const t=window.location.origin,e=me();return(e==null?void 0:e.host)||t},JE=({children:t,appContext:e,locale:s="en",resolver:r,rootUrl:n,descriptorResolver:o})=>{const[i,a]=g.useState(!1),[c,u]=g.useState(),[d,h]=g.useState(),f=n||XE(),p=g.useMemo(()=>e??"app/system",[e]);g.useEffect(()=>{async function E(){const L=(Array.isArray(p)?p:[p]).map(K=>(o||Hu(K))()),_=(await Promise.allSettled(L)).map(K=>{if(K.status==="rejected"){m.warn("Failed to load localization descriptor",K.reason);return}return K.value}).filter(K=>!!K).reverse().reduce((K,q)=>{const J=q.path;return Object.keys(q.namespaces).forEach(zt=>{const Vt=q.namespaces[zt];Vt.basePath=J}),{...K,namespaces:{...K.namespaces,...q.namespaces}}},{});u(_)}E()},[p,o]),g.useEffect(()=>{async function E(){if(c){const S=f,{translations:L}=await Gu.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:S});h(L),a(!0)}}E()},[s,c,r,f]);const y=g.useMemo(()=>i?{setLocale:E=>{d&&(d.currentLocale=E)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,d]),w=i?t:null;return T.jsx(mi.Provider,{value:y,children:w})},eM=()=>{const t=g.useContext(mi);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},tM=()=>{const t=At.type;return Z({modelId:t,modelType:At.type,options:{}})};function sM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=tM();return T.jsx(n,{...r,children:T.jsx(t,{...e,canvasDispatcher:s})})}}const rM=(t,e,s)=>{const r=atob(t),n=new Uint8ClampedArray(e*s*4);for(let o=0,i=0;o<r.length&&i<n.length;o+=3,i+=4)n[i]=r.charCodeAt(o),n[i+1]=r.charCodeAt(o+1),n[i+2]=r.charCodeAt(o+2),n[i+3]=255;return n};function nM({ctx:t,format:e,dataString:s,width:r,height:n,pixelSize:o}){const i=rM(s,r,n),a=new ImageData(i,r,n),c=document.createElement("canvas");c.width=r,c.height=n;const u=c.getContext("2d");u==null||u.putImageData(a,0,0),t.imageSmoothingEnabled=!1,t.clearRect(0,0,r*o,n*o),t.drawImage(c,0,0,r*o,n*o)}const oM=m.createLogger({name:"canvas-streamer"});oM.debug("main-view component loaded");const Mn=10,qd=Gn.observer(({canvasDispatcher:t,height:e=30,width:s=50,defaultFps:r=10,showPreview:n=!1,name:o,apiPath:i="/api/system/canvas"})=>{const a=g.useRef(null),[c,u]=g.useState();g.useEffect(()=>{const h=t.addNamedEndpoint(o,{apiPath:i,fps:r,width:s,height:e,id:o});u(h)},[t]);const d=g.useCallback(h=>{if(a.current&&n){const f=a.current.getContext("2d");f&&nM({ctx:f,format:"base64",dataString:h,height:e,width:s,pixelSize:Mn})}},[s,e,n]);return g.useEffect(()=>{c&&(c.onFrame=d,c.width=s,c.height=e,c.fps=r)},[c,d,s,e,r]),n&&ha.createPortal(T.jsx(aM,{children:T.jsx(cM,{children:T.jsx("canvas",{ref:a,width:s*Mn,height:e*Mn,style:{border:"1px solid black"}})})}),document.body)}),iM=sM(qd),aM=Vn.div`
185
+ `;return T.jsxs("div",{css:n,children:[T.jsxs("div",{css:o,children:[T.jsx("div",{css:i,children:e}),T.jsx("div",{css:[a,t<0?c:""]})]}),T.jsx("div",{children:r})]})},xE={setModel:()=>!1},on=g.createContext(xE),AE=()=>{const t=g.useContext(on);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},kd=({children:t})=>{const[e,s]=g.useState(),r=g.useCallback(n=>(s(n),!0),[s]);return T.jsx(on.Provider,{value:{model:e,setModel:r},children:t})},Ld=m.createLogger({name:"kos-model-hierarchy-context"}),RE={models:[],addModel:()=>{Ld.debug("Default implementation being used. Do Nothing.")}},an=g.createContext(RE),PE=({children:t})=>{const[e,s]=g.useState([]),r=g.useCallback(n=>{e.includes(n)||(Ld.debug("adding to hierarchy context",n.id),s(o=>[...o,n]))},[e]);return T.jsx(an.Provider,{value:{models:e,addModel:r},children:t})},kE=()=>!0,Fd=t=>{const e=g.useContext(an);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||kE;return g.useMemo(()=>e.models.filter(s),[e.models,s])},LE=t=>Fd({filter:s=>{const r=Ie(s.id);return(r==null?void 0:r.type)===t}})[0],FE=m.createLogger({name:"kos-model-loader"}),NE=()=>T.jsx("div",{}),Nd=({fallback:t,children:e,...s})=>T.jsx(kd,{children:T.jsx(Pd,{fallback:t,children:T.jsx(g.Suspense,{children:T.jsx(Ud,{...s,children:e})})})}),Ud=t=>{const[e,s]=g.useState(),[r,n]=g.useState(!1),{setModel:o}=g.useContext(on),i=g.useContext(an);if(g.useEffect(()=>{t.model&&(s(t.model),o(t.model),n(!0),i&&i.addModel(t.model))},[i,t.model,o]),t.error)throw FE.error(t.error),new Error(t.error);const a=t.loading||T.jsx(NE,{});return T.jsx(T.Fragment,{children:e&&r?t.children:a})},ir={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},jd=g.createContext(ir),UE=({translations:t=ir,children:e})=>{const s={header:{...ir.header,...t.header},createModal:{...ir.createModal,...t.createModal}};return T.jsx(jd.Provider,{value:s,children:e})};function jE(t,e){const s=I.create(t,!1,e),r=s.whenReady().then(()=>s);return ro(r)}const Bd=g.createContext(void 0),BE=(t={models:{},preloadModels:[]},e)=>{const s=jE(t,e),r=({children:n})=>{const o=s.read(),[i,a]=g.useState(o.isOnline);return g.useEffect(()=>{const c=W(()=>{a(o.isOnline)});return()=>{c()}},[o]),T.jsx(Bd.Provider,{value:{kosCore:o,online:i},children:n})};return{KosCoreContextProvider:Yn.observer(r)}},Hd=()=>{const t=g.useContext(Bd);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},HE=8,KE=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),Xe=new Map;function qE(t,e){if(Xe.has(t)){const s=Xe.get(t);if(s.status==="finished"){const r=I.getInstance().modelManager.getModelById(t);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=e().then(()=>{Xe.set(t,{status:"finished",key:t})},n=>{throw Xe.set(t,{status:"error",error:n}),n}),r={status:"pending",promise:s};throw Xe.set(t,r),s}}function zE(t,e){return qE(t,e)}async function VE(t,e){const{modelId:s,factory:r,modelType:n,options:o,activate:i}=e;let a=0;await t.whenReady();let c;if(o){const d=typeof n=="string"?t.modelManager.getModelFactory(n):r;if(!d)throw Error("No Factory Specified. Cannot create a new instance");c=d.build(s,o)}const u=t.modelManager.getModelById(s);if(!u){if(a>HE)throw Error(`KOS Model ${s} has not been found`);await KE(a),a=a+1}return await(u==null?void 0:u.whenReady()),u?(c=u.modelData,{kosModel:u,model:c}):{kosModel:void 0,model:void 0}}const Z=t=>{const{modelId:e,modelType:s,activate:r,destroyOnUnmount:n}=t,o=Hd(),[i,a]=g.useState(!1),[c,u]=g.useState(),{kosModel:d,model:h}=zE(e||s||"",()=>VE(o.kosCore,t));return g.useEffect(()=>{t.forceUpdate&&h&&yo(h)&&h.updateModel(t.options||{})},[h]),g.useEffect(()=>{async function f(){try{return await o.kosCore.whenReady(),r&&await(d==null?void 0:d.fsm.transitionTo(F.GO_ACTIVE,v.ACTIVE)),a(!0),d}catch(y){throw u(y.message),y}}let p;return o.kosCore&&e&&f().then(y=>{p=W(()=>{const w=(y==null?void 0:y.status)===v.READY;a(w)})}).catch(y=>{console.error(y)}),()=>{if(r){if(h!=null&&h.id){const y=o.kosCore.modelManager.getModelById(h.id);y==null||y.fsm.transitionTo(F.GO_INACTIVE,v.INACTIVE).then(()=>{if(n){const w=h.id;st(h).then(()=>{Xe.delete(w),p==null||p()})}})}}else n&&h&&st(h).then(()=>{Xe.delete(e),p==null||p()})}},[r,n,o.kosCore,d,h,e]),{model:h,ready:i,error:c,status:{model:h,ready:i,error:c},KosModelLoader:Nd}},fi=()=>{const t=mr.type;return Z({modelId:t,modelType:mr.type,options:{}})},pi=g.createContext(void 0),GE=({children:t})=>{const{model:e,ready:s}=fi(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(pi.Provider,{value:r,children:t})},YE=()=>{const t=g.useContext(pi);if(!t)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return t},gi=()=>{const t=Mr.type;return Z({modelId:t,modelType:Mr.type,options:{}})};function WE(t){return()=>e=>{const{model:s,status:r,KosModelLoader:n}=gi();return T.jsx(n,{...r,children:T.jsx(t,{...e,softwareInfo:s})})}}const mi=g.createContext(void 0),QE=({children:t})=>{const{model:e,ready:s}=gi(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(mi.Provider,{value:r,children:t})},ZE=()=>{const t=g.useContext(mi);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Kd=new wl,qd=g.createContext(Kd);function XE({children:t}){return T.jsx(qd.Provider,{value:Kd,children:t})}const yi=g.createContext(void 0),JE=()=>{const t=window.location.origin,e=me();return(e==null?void 0:e.host)||t},eM=({children:t,appContext:e,locale:s="en",resolver:r,rootUrl:n,descriptorResolver:o})=>{const[i,a]=g.useState(!1),[c,u]=g.useState(),[d,h]=g.useState(),f=n||JE(),p=g.useMemo(()=>e??"app/system",[e]);g.useEffect(()=>{async function E(){const L=(Array.isArray(p)?p:[p]).map(K=>(o||Ku(K))()),_=(await Promise.allSettled(L)).map(K=>{if(K.status==="rejected"){m.warn("Failed to load localization descriptor",K.reason);return}return K.value}).filter(K=>!!K).reverse().reduce((K,q)=>{const J=q.path;return Object.keys(q.namespaces).forEach(zt=>{const Vt=q.namespaces[zt];Vt.basePath=J}),{...K,namespaces:{...K.namespaces,...q.namespaces}}},{});u(_)}E()},[p,o]),g.useEffect(()=>{async function E(){if(c){const S=f,{translations:L}=await Yu.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:S});h(L),a(!0)}}E()},[s,c,r,f]);const y=g.useMemo(()=>i?{setLocale:E=>{d&&(d.currentLocale=E)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,d]),w=i?t:null;return T.jsx(yi.Provider,{value:y,children:w})},tM=()=>{const t=g.useContext(yi);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},sM=()=>{const t=At.type;return Z({modelId:t,modelType:At.type,options:{}})};function rM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=sM();return T.jsx(n,{...r,children:T.jsx(t,{...e,canvasDispatcher:s})})}}const nM=(t,e,s)=>{const r=atob(t),n=new Uint8ClampedArray(e*s*4);for(let o=0,i=0;o<r.length&&i<n.length;o+=3,i+=4)n[i]=r.charCodeAt(o),n[i+1]=r.charCodeAt(o+1),n[i+2]=r.charCodeAt(o+2),n[i+3]=255;return n};function oM({ctx:t,format:e,dataString:s,width:r,height:n,pixelSize:o}){const i=nM(s,r,n),a=new ImageData(i,r,n),c=document.createElement("canvas");c.width=r,c.height=n;const u=c.getContext("2d");u==null||u.putImageData(a,0,0),t.imageSmoothingEnabled=!1,t.clearRect(0,0,r*o,n*o),t.drawImage(c,0,0,r*o,n*o)}const iM=m.createLogger({name:"canvas-streamer"});iM.debug("main-view component loaded");const Tn=10,zd=Yn.observer(({canvasDispatcher:t,height:e=30,width:s=50,defaultFps:r=10,showPreview:n=!1,name:o,apiPath:i="/api/system/canvas"})=>{const a=g.useRef(null),[c,u]=g.useState();g.useEffect(()=>{const h=t.addNamedEndpoint(o,{apiPath:i,fps:r,width:s,height:e,id:o});u(h)},[t]);const d=g.useCallback(h=>{if(a.current&&n){const f=a.current.getContext("2d");f&&oM({ctx:f,format:"base64",dataString:h,height:e,width:s,pixelSize:Tn})}},[s,e,n]);return g.useEffect(()=>{c&&(c.onFrame=d,c.width=s,c.height=e,c.fps=r)},[c,d,s,e,r]),n&&fa.createPortal(T.jsx(cM,{children:T.jsx(lM,{children:T.jsx("canvas",{ref:a,width:s*Tn,height:e*Tn,style:{border:"1px solid black"}})})}),document.body)}),aM=rM(zd),cM=Gn.div`
186
186
  display: flex;
187
187
  flex-direction: column;
188
188
  gap: 8px;
@@ -190,9 +190,9 @@ ${u}topics:${e}
190
190
  width: 100%;
191
191
  justify-content: space-between;
192
192
  align-items: center;
193
- `,cM=Vn.div`
193
+ `,lM=Gn.div`
194
194
  display: flex;
195
195
  flex-direction: column;
196
196
  align-items: center;
197
- `,zd=()=>{const t=xr.type;return Z({modelId:t,modelType:xr.type,options:{}})};function lM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=zd();return T.jsx(n,{...r,children:T.jsx(t,{...e,device:s})})}}function uM(t,e,s){const r=new Promise(n=>{I.getInstance().whenReady().then(()=>{const{model:o}=I.getInstance().modelManager.createModelInstance(t,e??t,s);return o.whenReady().then(()=>{n(o.modelData)})})});return so(r)}function dM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=hi();return T.jsx(n,{...r,children:T.jsx(t,{...e,kosTime:s})})}}const Vd=()=>{const t=Cs.type;return Z({modelId:t,modelType:Cs.type,options:{}})};function hM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=Vd();return T.jsx(n,{...r,children:T.jsx(t,{...e,networkInterfaceContainer:s})})}}const Gd=()=>{const t=wr.type;return Z({modelId:t,modelType:wr.type,options:{}})};function fM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=Gd();return T.jsx(n,{...r,children:T.jsx(t,{...e,oTA:s})})}}function pM(t,e){g.useEffect(()=>{function s(n){t.current&&!t.current.contains(n.target)&&e()}function r(n){n.key==="Escape"&&e()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[t,e])}function gM(t){const e=g.useRef(null),s=t.onAlert;return pM(e,s),T.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const mM=t=>{var u;const{stateProp:e}=t,[s,r]=g.useState((u=t.stateProp)==null?void 0:u.value),[n,o]=g.useState(!1),[i,a]=g.useState(void 0);return g.useEffect(()=>{async function d(h){try{h&&(await de(h),o(!0))}catch(f){a(f.message)}}d(e)},[e]),g.useEffect(()=>{const d=W(()=>{e&&n&&r(e.value)});return()=>{d()}},[n,e]),[s,{ready:n,error:i}]},Yd=()=>{const[t,e]=g.useState(!1),[s,r]=g.useState([]),n=Rt.type,o=Z({modelId:n,modelType:Rt.type,options:{}});return g.useEffect(()=>{const i=W(()=>{var a,c;e(((a=o.model)==null?void 0:a.isStorageInserted)??!1),r(((c=o.model)==null?void 0:c.data)??[])});return()=>{i()}},[o.model]),{...o,inserted:t,devices:s}};function yM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=Yd();return T.jsx(n,{...r,children:T.jsx(t,{...e,storageDeviceContainer:s})})}}const Tn=m.createLogger({name:"use-timer"}),bM=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:n})=>{const o=_d.getTimer(t);g.useEffect(()=>{if(!o){console.warn(`Timer with name ${t} does not exist.`);return}const u=C(ci,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===t&&(f===ui?e({name:h,action:f,remainingTime:p,timer:o}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:p,timer:o}))});return n&&o.start(),()=>{u.unsubscribe()}},[n,e,r,t,o]),g.useEffect(()=>{if(!o||!s)return;const u=`${li}/${t}`,d=C(u,h=>{const{name:f,remainingTime:p}=h==null?void 0:h.body;f===t&&s({name:f,remainingTime:p,timer:o})});return()=>{d.unsubscribe()}},[s,t,o]);const i=g.useCallback(()=>{o?o.start():Tn.warn(`Timer with name ${t} does not exist.`)},[o,t]),a=g.useCallback(()=>{o?o.reset():Tn.warn(`Timer with name ${t} does not exist.`)},[o,t]),c=g.useCallback(()=>{o?o.pause():Tn.warn(`Timer with name ${t} does not exist.`)},[o,t]);return{timer:o,start:i,reset:a,pause:c}},vM=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},wM=t=>t instanceof RegExp,EM=t=>typeof t=="string",MM=(t,e,s)=>{if(t===""||e==="")return t;let r=e;wM(r)||(r=new RegExp("("+vM(r)+")","gi"));const n=t.split(r);for(let o=1,i=n.length;o<i;o+=2)n[o]=s(n[o],o);return n},Wd=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(n=>EM(n)?MM(n,e,s):n)};function TM(t,e){let s=t;return Object.entries(e).forEach(([r,n])=>{const o=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=Wd(s,o,(i,a)=>n.type==="br"?T.jsx("br",{}):g.cloneElement(n,{key:`${r}-${a}`},i))}),s}const SM=t=>{const{i18nKey:e,t:s,defaults:r,components:n,values:o={},context:i}=t,a=s(e,{defaultValue:r,data:o,context:i,returnObjects:!0}),c=TM(a,n||{});return T.jsx("span",{className:t.className,children:c})},bt=new Map;function _M(t,e){if(bt.has(t)){const s=bt.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(n=>{bt.set(t,{status:"finished",result:n})},n=>{throw bt.set(t,{status:"error",error:n}),n}),r={status:"pending",promise:s};throw bt.set(t,r),s}}function Kn(t,e){return _M(t,e)}const IM=async()=>{const t=await Ic(Fe.type);return await de(t.model),t.model},OM=async(t,e,s)=>{const r=t.resolveNamespace(e);await de(r);for(const n of s){const o=t.resolveNamespace(n);await de(o),bt.set(n,{status:"finished",result:o})}return r},$M=(t,e)=>{const s=[t].flat(),[r,...n]=s,o=Kn(Fe.type,IM),i=s.join("__"),a=Kn(i,()=>OM(o,r,n)),c=g.useMemo(()=>({exists:d=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:g.useCallback((d,h)=>{const f=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(m.debug(`Translation model ${t} not ready for key: ${f}`),f)},[e==null?void 0:e.keyPrefix,t,a]),i18n:c}},Qd=()=>{const t=Fe.type;return Z({modelId:t,modelType:Fe.type,options:{}})};function CM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=Qd();return T.jsx(n,{...r,children:T.jsx(t,{...e,translationContainer:s})})}}const DM=t=>Z({modelId:t,modelType:Os.type}),yi=()=>Z({modelId:Dt.type,modelType:Dt.type,options:{}}),xM=({troubleType:t,condition:e})=>{const{model:s}=yi(),[r,n]=g.useState(!1),[o,i]=g.useState([]),a=g.useCallback(()=>{var c,u;return o.length>0&&((c=o[0])!=null&&c.resolvable)?(u=o[0])==null?void 0:u.resolve():Promise.resolve(void 0)},[o]);return g.useEffect(()=>W(()=>{const u=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],d=e?u.filter(e):u;n(d.length>0),i(d)}),[e,s,t]),[r,a,o.length>0?o[0]:void 0,o]};function AM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=yi();return T.jsx(n,{...r,children:T.jsx(t,{...e,troubleContainer:s})})}}const Zd=()=>{const t=xs.type,e=Z({modelId:t,modelType:xs.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=g.useState(!1),[n,o]=g.useState(!1),[i,a]=g.useState([]);return g.useEffect(()=>{const c=W(()=>{var u,d,h;r(((u=e.model)==null?void 0:u.isUsbInserted)??!1),o(((d=e.model)==null?void 0:d.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{c()}},[e.model]),{...e,inserted:s,updateAvailable:n,updates:i}};function RM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=Zd();return T.jsx(n,{...r,children:T.jsx(t,{...e,usbUpdateContainer:s})})}}const PM=({path:t,propKey:e})=>{const{status:s}=Z({modelType:ws.type,modelId:t,options:{path:t}}),[r,n]=g.useState(!1),[o,i]=g.useState(),[a,c]=g.useState(""),[u,d]=g.useState(),h=f=>{o&&e&&o.updateProperty(e,f)};return g.useEffect(()=>{var f;s.model&&i(s.model),s.model&&e&&((f=s.model)!=null&&f.props.has(e)?c(s.model.props[e]):d(`property ${e} not found`)),s.ready&&n(s.ready)},[s.ready,s.model,e]),g.useEffect(()=>{e&&M.autorun(()=>{const f=o==null?void 0:o.props[e];c(f||"")})},[o,e]),{config:o,ready:r,value:a,error:u,updateValue:h}},kM=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},Xd=({configProperty:t,optionsTransformer:e})=>{const[s,r]=g.useState(!1),[n,o]=g.useState(""),[i,a]=g.useReducer(kM,{value:String(t==null?void 0:t.value),displayValue:t==null?void 0:t.displayValue,significantValue:t==null?void 0:t.significantValue,unit:t==null?void 0:t.unit,options:t==null?void 0:t.options,mappedOptions:[],updateProperty:t==null?void 0:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}),c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&(t==null||t.updateProperty(d))},[t]);return g.useEffect(()=>{async function u(d){try{d&&(await de(d),r(!0))}catch(h){o(h.message)}}u(t)},[t]),g.useEffect(()=>{const u=W(()=>{if(t&&s){let d=[];e&&(d=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:d,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{u()}},[t,e,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:n}};function LM(t,e){const s=e??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return t===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[t]??0}function FM(t,e){return new Date(t,e,0).getDate()}function Jd(t,e){const s=LM(e,t),r=[];for(let n=1;n<=s;n++)r.push(n);return r}function eh(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function th(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function sh(t,e=[2018,2028]){const s=th(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function bi(t="numeric",e="en-US"){const s=new Intl.DateTimeFormat(e,{month:t,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function NM({locale:t="en-US",year:e,month:s,day:r,formatOptions:n={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:o}){const i=s-1,a=new Date(e,i,r),c=new Intl.DateTimeFormat(t,{month:n.month}).format(a),u=new Intl.DateTimeFormat(t,{year:n.year}).format(a),d=new Intl.DateTimeFormat(t,{day:n.day}).format(a);return o?o=="MMDDYY"?`${c} ${d} ${u}`:o==="DDMMYY"?`${d} ${c} ${u}`:o==="YYMMDD"?`${u} ${c} ${d}`:`${u} ${d} ${c}`:new Intl.DateTimeFormat(t,n).format(a)}function be(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function UM(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function rh(t,e,s){const r=be(e),n=new Date(r,t,1).getDay(),o=new Date(r,t+1,0).getDate();return[...Array(42).keys()].map(a=>a<n||a>o+n-1?{label:"",value:0,disabled:!0}:s[a-n])}function as(t,e,s){const r=e-1,n=new Date(t,r,s);return new Date(n).getMonth()===r&&new Date(n).getDate()===s}function cs(t,e){return new Date(t,e,0).getDate()}function nh(t="en-US",e="short"){const s=new Intl.DateTimeFormat(t,{weekday:e}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function oh({locale:t="en-US",year:e=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:n=[],formatOptions:{yearFormat:o="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=vi(o,r),u=ih(o,r,t),d=ah(i,t),h=ch(i,t),f=wi(e,s),p=lh(e,s,t,n),y=hh(s,e,p),w=uh(t,a);return{daysArray:f,monthsArray:d,yearsArray:c,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:y,dayNamesArray:w}}function vi(t="long",e=[2018,2028]){return g.useMemo(()=>sh(t,e),[t,e])}function ih(t="long",e=[2018,2028],s="en-US"){const r=vi(t,e);return g.useMemo(()=>r.map(o=>({label:o.toLocaleString(s).replace(",",""),value:o})),[s,r])}function ah(t,e="en-US"){return g.useMemo(()=>bi(t,e),[t,e])}function ch(t,e="en-US"){const s=g.useMemo(()=>eh(),[]),r=g.useMemo(()=>bi(t,e),[t,e]);return g.useMemo(()=>[...Array(12).keys()].map(o=>({label:r[o],value:Number(s[o])})),[r,s])}function wi(t,e){const s=be(t);return g.useMemo(()=>Jd(s,e),[e,s])}const jM=(t,e,s,r=[])=>{const n=new Date(t,e,s).getDay();return r.length>0&&r.includes(n)};function lh(t,e,s="en-US",r=[]){const n=wi(t,e);return g.useMemo(()=>n.map(i=>({label:i.toLocaleString(s),value:i,disabled:jM(t,e,i,r)})),[r,s,e,n,t])}function uh(t="en-US",e="short"){return g.useMemo(()=>nh(t,e),[t,e])}function dh({year:t=new Date().getFullYear(),month:e=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const n=e,o=new Date(t,n,s);return{formattedDate:je.format(o,r)}}function hh(t,e,s){return g.useMemo(()=>rh(t,e,s),[t,e,s])}var fh=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(fh||{});function BM({locale:t="en-US",date:{year:e=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:n="long",monthFormat:o="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:u=[]}={}}){const[d,h]=g.useState(e),[f,p]=g.useState(c),[y,w]=g.useState(s),[E,S]=g.useState(r);g.useEffect(()=>{h(e)},[e]),g.useEffect(()=>{w(s)},[s]),g.useEffect(()=>{S(r)},[r]);const{yearsArray:L,yearsOptionsArray:P,monthsArray:O,monthsOptionsArray:_,daysArray:K,daysOptionsArray:q,calendarDayArray:J,dayNamesArray:zt}=oh({locale:t,year:d,yearRange:f,month:y,formatOptions:{yearFormat:n,monthFormat:o,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:Vt}=dh({year:d,month:y,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:w,setDay:S,nextMonth:()=>{const se=y<11?be(d):be(d+1),ce=y<11?y+1:0;if(!as(se,ce,E)){const Ge=cs(se,ce);S(Ge)}ce===0&&h(se),w(ce)},previousMonth:()=>{const se=be(y===0?d-1:d),ce=y===0?11:y-1;if(!as(se,ce,E)){const Ge=cs(se,ce);S(Ge)}ce===11&&h(se),w(ce)},nextYear:()=>{const se=d<f[1]?d+1:f[0],ce=be(se);if(as(ce,y,E))h(se);else{const Ge=cs(be(d+1),y);S(Ge),h(se)}},previousYear:()=>{const se=d>f[0]?d-1:f[0],ce=be(se);if(as(ce,y,E))h(se);else{const Ge=cs(be(d-1),y);S(Ge),h(se)}}},dateState:{year:d,yearRange:f,month:y,day:E,yearsArray:L,yearsOptionsArray:P,monthsArray:O,monthsOptionsArray:_,daysArray:K,daysOptionsArray:q,calendarDayNames:zt,calendarDayArray:J,formattedDate:Vt}}}function ph({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[n,o]=g.useState("Formatting Time..."),[i,a]=g.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:u,ready:d}=Z({modelId:re.type,modelType:re.type,options:{}}),h=typeof t=="string"?je.parseISO(t):t;return g.useEffect(()=>{c?a(""):e?a(je.format(h,e)):d&&a(je.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[c,t,e,h,u,d]),g.useEffect(()=>{s?o(je.format(h,s)):d&&o(je.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[t,s,h,u,d]),{formattedDate:i,formattedTime:n}}const gh=({secondsFromMidnight:t=0})=>{const[e,s]=g.useState(0),[r,n]=g.useState(0),[o,i]=g.useState(0),[a,c]=g.useState(new Date),{formattedTime:u}=ph({date:a,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const d=Number(t),h=Math.floor(d/3600),f=Math.floor(d%3600/60),p=d%60;s(h),n(f),i(p);const y=new Date;y.setHours(0,0,0,0);const w=new Date(y.getTime()+d*1e3);c(new Date(w))},[t]),{hours:e,minutes:r,seconds:o,formattedTime:u,timeActions:{setHours:s,setMinutes:n,setSeconds:i}}},HM=({configProperty:t})=>{const{value:e}=Xd({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:n,seconds:o,formattedTime:i,timeActions:a}=gh({secondsFromMidnight:s}),c=g.useRef();return g.useEffect(()=>{const u=r*3600+n*60+o;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{t&&t.updateProperty(u.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[t,r,n,o]),{hours:r,minutes:n,seconds:o,formattedTime:i,timeActions:a}};function KM(t,e={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=e;g.useEffect(()=>{const n=()=>{try{t({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(n):setTimeout(n,1));const o=s?setInterval(n,s):null;return()=>{o&&clearInterval(o)}},[t,s,r])}const qM=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),zM=(t=qM)=>{const[e,s]=g.useState([]),[r,n]=g.useState(),{model:o,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=W(()=>{s((o==null?void 0:o.dateFormatOptions.map(t))||[])});return()=>{c()}},[o,i,t]),g.useEffect(()=>{const c=W(()=>{o!=null&&o.dateFormatId&&(o!=null&&o.selectedDateFormat)&&n({id:o==null?void 0:o.dateFormatId,value:o==null?void 0:o.selectedDateFormat})});return()=>{c()}},[o==null?void 0:o.selectedDateFormat,o==null?void 0:o.dateFormatId]);const a=g.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(o==null||o.setSelectedDateFormat(u))},[o]);return{raw:(o==null?void 0:o.dateFormatOptions.map(c=>c.id))??[],regionModel:o,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:e}}},VM=t=>T.jsx("option",{title:t,value:t,children:t},t),mh="kos:service:region:settings",yh="timeZone",GM=`${mh}-${yh}`,YM=(t=VM)=>{const[e,s]=g.useState([]),[r,n]=g.useState(""),{model:o,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=at.factory(GM)({path:mh,attribute:yh});g.useEffect(()=>{const u=W(()=>{s((o==null?void 0:o.timeZones.map(t))||[]),o!=null&&o.timeZones.length&&Hn(o==null?void 0:o.timeZones[0])});return()=>{u()}},[o,i,t]),g.useEffect(()=>{const u=W(()=>{n(a.value||"")});return()=>{u()}},[a.value]);const c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&Hn(d)},[]);return{options:e,raw:(o==null?void 0:o.timeZones)??[],regionModel:o,selectedTimeZone:r,timeZones:(o==null?void 0:o.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:e}}},bh="kos:service:region",vh="regionId",WM=`${bh}-${vh}`,QM=t=>T.jsx("option",{title:t,value:t,children:t},t),wh=(t=QM)=>{const[e,s]=g.useState([]),[r,n]=g.useState("factory"),{model:o,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=at.factory(WM)({path:bh,attribute:vh});g.useEffect(()=>{const u=W(()=>{s((o==null?void 0:o.availableRegions.map(t))||[])});return()=>{u()}},[o,i,t]),g.useEffect(()=>{const u=W(()=>{n(a.value||"factory")});return()=>{u()}},[a.value]);const c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&Td(d)},[]);return{raw:(o==null?void 0:o.availableRegions)??[],regionModel:o,regionData:o==null?void 0:o.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:e}}},ZM=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),XM=(t=ZM)=>{const[e,s]=g.useState([]),[r,n]=g.useState(),{model:o,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=W(()=>{s((o==null?void 0:o.timeFormatOptions.map(t))||[])});return()=>{c()}},[o,i,t]),g.useEffect(()=>{const c=W(()=>{o!=null&&o.timeFormatId&&(o!=null&&o.selectedTimeFormat)&&n({id:o==null?void 0:o.timeFormatId,value:o==null?void 0:o.selectedTimeFormat})});return()=>{c()}},[o==null?void 0:o.selectedTimeFormat,o==null?void 0:o.timeFormatId]);const a=g.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(o==null||o.setSelectedTimeFormat(u))},[o]);return{raw:(o==null?void 0:o.timeFormatOptions.map(c=>c.id))??[],regionModel:o,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:e}}},JM=(t,e)=>g.useMemo(()=>So(t),e),eT={config:{attributes:!0,childList:!0,subtree:!0}};function tT(t,e,s=eT){const[r,n]=g.useState(null);g.useEffect(()=>{if(!e||typeof e!="function")throw new Error("A valid callback function is required");const o=new MutationObserver(e);n(o)},[e,s,n]),g.useEffect(()=>{if(!r)return()=>{};if(!t)throw new Error("A valid DOM element is required");const{config:o}=s;try{r.observe(t,o)}catch(i){m.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const Eh={validateStart:function(t){return!0},validateStop:function(t){const e=t.event.currentTarget.getBoundingClientRect(),[s,r]=t.xy;return s<e.left||s>e.right||r<e.top||r>e.bottom}},Sn=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function sT({onPressed:t,onRelease:e,intersectionStrategy:s=Eh}){const r=g.useRef(!1),n=Ah.useGesture({onDragStart:c=>{Sn.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{Sn.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{Sn.info("onDragEnd",c.type),r.current&&e&&(e(),r.current=!1)}}),o=()=>{t&&t(),r.current=!0},i=()=>{r.current&&e&&(e(),r.current=!1)},a=()=>{r.current&&e&&(e(),r.current=!1)};return{dom:n,mesh:()=>({onPointerDown:o,onPointerUp:i,onPointerOut:a})}}const Mh=()=>{const[t,e]=g.useState(!1),s=I.getInstance();return g.useEffect(()=>{const r=W(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function Th(t=!1,e="2-digit"){return g.useMemo(()=>{const s=t?12:24;return Array.from({length:s},(r,n)=>{const o=t&&n===0?12:n%s;return{id:n,label:e==="2-digit"?o.toString().padStart(2,"0"):o.toString()}})},[e,t])}function qn(t,e="2-digit",s=0,r=0){return g.useMemo(()=>Array.from({length:t},(n,o)=>{const i=String(o+s);return{id:o+r,label:e==="2-digit"?i.padStart(2,"0"):i}}),[t,s,r,e])}function Sh(t="en-US"){return g.useMemo(()=>["AM","PM"].map(e=>{const s=new Intl.DateTimeFormat(t,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(e==="AM"?0:12))[2].value;return{id:s,label:s}}),[t])}function _h({formatOptions:{hour12:t=!0,hour:e="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:n="en-US"}){const o=Th(t,e),i=qn(60,s),a=qn(60,r),c=Sh(n);return{hourOptions:o,minuteOptions:i,secondOptions:a,amPmOptions:c}}function Ih(t,e){return je.format(t,e)}function Oh({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[n,o]=g.useState(e),i=g.useCallback(w=>{o(E=>{const S=new Date(E);return S.setHours(Number(w)),S})},[]),a=g.useCallback(w=>{o(E=>{const S=new Date(E);return S.setMinutes(Number(w)),S})},[]),c=g.useCallback(w=>{o(E=>{const S=new Date(E);return S.setSeconds(Number(w)),S})},[]),u=g.useCallback(w=>{const E=new Date(w);o(E)},[]),d=Ih(n,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:y}=_h({formatOptions:t,locale:s});return{amPmOptions:y,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:c,setTime:u,time:new Date(n)}}const rT=t=>{const{regionModel:e}=wh(),s=g.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return Oh({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function nT(t){return e=>{const[s]=Mh();return s?T.jsx(Ad,{message:"Wait a moment while your project reloads..."}):T.jsx(t,{...e})}}const la=m.createLogger({name:"studio-properties-service",group:"Services"}),oT="/api/kos/studio/properties",$h=async t=>{if(la.debug("sending GET for studio-properties"),!t)throw la.error("connectionId is undefined"),new Error("connectionId is undefined");return await De.get(oT,{},{destinationAddress:t,timeout:500})},iT=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:$h},Symbol.toStringTag,{value:"Module"}));var aT=Object.getOwnPropertyDescriptor,cT=(t,e,s,r)=>{for(var n=r>1?void 0:r?aT(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const Ch="studio-properties-model",lT="/kos/studio/properties",ua={"kos.studio.tool.legacy":1};let zn=class{constructor(t,e,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=t,this.logger=s.logger,this.data=_e(),this.connectionId=e.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var t;(t=this.unsubscribe)==null||t.call(this)}async initializePropertiesSession(){this.unsubscribe=Tt.getInstance().subscribeTopic({topic:lT,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await $h(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(ua);return}if(e){const s=Object.keys(e).reduce((r,n)=>(r[n]=e[n]??n,r),{});this.data.setValues(s??ua),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return So(()=>this.get(t))}};zn=cT([R(Ch)],zn);const uT=new ye({class:zn,type:Ch});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>M.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>M.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>Gn.observer});exports.AuthState=pl;exports.BrowserKosRouter=wl;exports.BrowserRouter=Lo;exports.CanvasDispatcher=At;exports.CanvasDispatcherServices=pw;exports.CanvasRenderer=ei;exports.CanvasStreamer=iM;exports.CanvasStreamerBase=qd;exports.ChildModels=Be;exports.CompanionParentModel=He;exports.ConfigBean=ws;exports.ContainerAwareSetup=fo;exports.CoreExtensionManager=dE;exports.CoreModels=ai;exports.CreateModelTranslationsContext=Ud;exports.CreateModelTranslationsProvider=NE;exports.DateDisplayFormat=fh;exports.DateHelpers=Yh;exports.DependencyLifecycle=x;exports.DependencyModels=N;exports.Device=xr;exports.DeviceServices=Lw;exports.DomIntersectionStrategy=Eh;exports.EVENT_KOS_MODEL_READY=Zn;exports.EVENT_TROUBLE_ADDED=Pm;exports.EVENT_TROUBLE_REMOVED=km;exports.EXTENSION_CANVAS_RENDERER=te;exports.EXTENSION_FEATURE_FLAG_RESOLVER=ic;exports.EXTENSION_TROUBLE_DATA_MAPPER=br;exports.EXTENSION_TROUBLE_MAPPER=Bs;exports.ErrorBoundaryWithFallback=Rd;exports.EventBus=Lh;exports.EventBusFunctional=Nh;exports.EventBusState=jh;exports.ExtensionManager=$;exports.FUTURE_CONTAINER_MODEL_TYPE=Yl;exports.FUTURE_MODEL_TYPE=Nl;exports.FUTURE_NOT_ASSIGNED=Io;exports.FeatureFlagService=ac;exports.FetchError=ge;exports.FutureAliases=hs;exports.FutureContainerFactory=qe;exports.FutureContainerModel=Ql;exports.FutureContainerSetup=co;exports.FutureEndState=Ke;exports.FutureFactory=Ut;exports.FutureHandler=Kr;exports.FutureManager=rt;exports.FutureModel=ql;exports.FutureService=ls;exports.HEADER_CACHE_CONTROL=ma;exports.HEADER_CONTENT_TYPE=ga;exports.HEADER_DESTINATION_ADDR=Ne;exports.HEADER_FOS_REQUEST_ID=ya;exports.HEADER_METHOD=kr;exports.HEADER_ORDERED=Wn;exports.HEADER_REQUEST_ID=As;exports.HEADER_REQUEST_TYPE=Oe;exports.HEADER_RESPONSE_ID=Lr;exports.HEADER_SOURCE_ADDR=pa;exports.HEADER_TOPIC=fa;exports.HEADER_URL=kt;exports.HEADER_WORK_TRACKER=Qn;exports.HttpRouteHandlers=Re;exports.KOS_EXECUTION_CONTEXT=Br;exports.KOS_MODEL_ID=ir;exports.KeyValue=Uo;exports.KeyValueServices=Cy;exports.Kos=ie;exports.KosConfigPropertySpec=at;exports.KosContainerIndex=go;exports.KosContextBean=bl;exports.KosContextManager=Y;exports.KosCore=I;exports.KosCoreModelPropertyMapper=ve;exports.KosDataContainer=To;exports.KosDependencyTypes=Hf;exports.KosExpressionEvaluator=au;exports.KosExtensionUtils=Xh;exports.KosFeatureFlags=cc;exports.KosFetchMethods=Ec;exports.KosGlobalConfig=io;exports.KosHttpRouteManager=vo;exports.KosLog=m;exports.KosLogManager=uu;exports.KosLogManagerServices=Lb;exports.KosMockEvents=wa;exports.KosModel=dl;exports.KosModelCollectionProvider=RE;exports.KosModelContainer=Ce;exports.KosModelContext=nn;exports.KosModelEvents=F;exports.KosModelFactory=ps;exports.KosModelLoader=Fd;exports.KosModelLoaderDisplay=Nd;exports.KosModelManager=fl;exports.KosModelProvider=Pd;exports.KosModelRegistrationFactory=ye;exports.KosModelRegistry=Bn;exports.KosModelState=v;exports.KosModelSymbol=ao;exports.KosModelVisitor=om;exports.KosObservableData=Sc;exports.KosRegistration=Om;exports.KosSingletonRegistration=$m;exports.KosTime=gr;exports.KosTimeContext=fi;exports.KosTimeProvider=VE;exports.KosTimeServices=Kb;exports.KosTimer=Sd;exports.KosToken=vl;exports.KosTranslationProvider=JE;exports.KosTranslations=Gu;exports.KosWSTransportStatus=ul;exports.KosWsEvents=Rs;exports.LOADER_FEATURE_FLAG=df;exports.LOGIN_HOST=ba;exports.LOGIN_URL=Rh;exports.LoadingMessage=Ad;exports.LogBlock=Is;exports.LogBlockContainer=en;exports.LogConfig=ds;exports.LogStream=bs;exports.LogStreamContainer=js;exports.LogStreamServices=ev;exports.LoggerSetup=ho;exports.MODEL_DELETION_DELAY=hl;exports.MiddlewareChain=gl;exports.ModelEffects=et;exports.MultipleFutureContainerSetup=lo;exports.MultipleFutureHandler=Mc;exports.NestedModelContext=on;exports.NetworkInterface=ri;exports.NetworkInterfaceContainer=Cs;exports.NetworkInterfaceServices=zw;exports.ObservableData=_e;exports.Ota=wr;exports.OutsideAlerter=gM;exports.PLUGIN_EXTENSION_NAME=Jh;exports.PORT=va;exports.PROFILE_LOG_DEBUG=Qa;exports.PROFILE_LOG_INFO=Za;exports.PROFILE_RELAX_STORE_VALIDATION=tf;exports.PROFILE_TOOLS_PREVIEW=Wa;exports.ParentModel=us;exports.PluginExtensionManager=ef;exports.ProgressBar=CE;exports.ReferenceConfig=er;exports.RegionInfo=re;exports.RegionServices=zm;exports.RegistrationManager=A;exports.Registry=uE;exports.ReplayStrategy=Je;exports.ResponseRetention=ue;exports.STATUS=Yn;exports.ServiceFactory=ne;exports.ServiceRequestHandlers=tt;exports.SingletonKosModelRegistrationFactory=Se;exports.SoftwareInfo=Er;exports.SoftwareInfoContext=gi;exports.SoftwareInfoProvider=WE;exports.SoftwareInfoServices=Lv;exports.StateActionHandlers=pf;exports.StateBean=$s;exports.StateBeanServices=Bv;exports.StateEntryHandlers=wt;exports.StateExitHandlers=fs;exports.StateMachineSetup=ks;exports.StateProp=Qo;exports.StatePropServices=Zv;exports.StorageDevice=Rr;exports.StorageDeviceContainer=Rt;exports.StorageDeviceServices=Qw;exports.StudioProperties=uT;exports.StudioPropertiesServices=iT;exports.SubscriptionHandlers=ee;exports.TIMER_END=ui;exports.TIMER_EVENT=ci;exports.TOPIC_TIMER_TICK_EVENT=li;exports.TimerManager=_d;exports.TokenContext=Kd;exports.TokenProvider=ZE;exports.Topics=ys;exports.Trans=SM;exports.TransitionMap=tr;exports.Transitions=yo;exports.Translation=Sr;exports.TranslationContainer=Fe;exports.TranslationContainerContext=mi;exports.TranslationContext=aw;exports.TransportFactory=Dn;exports.Trouble=Os;exports.TroubleAwareSetup=uo;exports.TroubleContainer=Dt;exports.TroubleServices=vv;exports.Troubles=pe;exports.UsbUpdate=ii;exports.UsbUpdateContainer=xs;exports.UsbUpdateServices=nE;exports.WS_EVENT_TYPE=Yu;exports.WebSocketEvents=ms;exports.WebSocketTransport=Tt;exports.WsEventFactory=Xo;exports.acceptOrgInvitation=xd;exports.addDaysToDate=Ba;exports.addFuture=jl;exports.addMonthsToDate=ja;exports.api=zl;exports.applyMixins=Hh;exports.arraysEqual=Kh;exports.buildConfigBeanModel=Nm;exports.buildFuture=ko;exports.buildFutureModel=Hl;exports.cancelFuture=Bl;exports.checkAppsStarted=Am;exports.checkWildcardPattern=Rc;exports.clearAllServiceResponses=Em;exports.clearPath=wm;exports.clearServiceResponse=vm;exports.convert=xo;exports.convertFileSizeRaw=Bh;exports.convertWithUnits=Zm;exports.createBaseMessage=tl;exports.createBroadcastMessageResponse=ol;exports.createCancellablePromise=TE;exports.createClient=wo;exports.createFosBaseMessage=el;exports.createHeaders=Qt;exports.createKosHtpMessageResponse=il;exports.createKosMessage=rl;exports.createKosMessageResponse=al;exports.createMessageBody=Ve;exports.createModelDependency=qc;exports.createOptionKey=Lf;exports.createPropKey=it;exports.createReadableStream=Zt;exports.createStudioMessage=Jc;exports.createStudioMessageRequest=sl;exports.createStudioMessageResponse=nl;exports.debounce=Ga;exports.del=mc;exports.deleteFuture=Ul;exports.destroyKosModel=st;exports.evaluateScopes=$l;exports.executeChildrenModelLifecycle=Gc;exports.executeDependentModelLifecycle=Wt;exports.executeListLifecycle=Vc;exports.fetchModel=uM;exports.findModel=ip;exports.findModels=Oc;exports.formatDate=qa;exports.formatDateSince=Ua;exports.formatDateTime=Va;exports.formatTime=za;exports.get=gc;exports.getAllKosCompanionModels=$c;exports.getCalendarMonthArray=rh;exports.getConfigBean=Ol;exports.getDayStrings=nh;exports.getDays=FM;exports.getDaysArray=Jd;exports.getDaysInMonth=oo;exports.getDependenciesByLifecycle=zc;exports.getFormattedDate=NM;exports.getFormattedMonth=UM;exports.getFormattedMonthsArray=bi;exports.getFormattedYear=be;exports.getFormattedYearsArray=sh;exports.getFutures=py;exports.getHttpRouteHandlers=yc;exports.getKosCompanionModel=ap;exports.getKosLocalizationDescriptor=Hu;exports.getKosMessageLogging=tc;exports.getKosModel=Ic;exports.getKosModelSync=Ie;exports.getKosModelType=op;exports.getKosSessionKey=yl;exports.getLastDayOfMonth=cs;exports.getLocalizationDescriptor=Jv;exports.getLogLevel=ec;exports.getLogMessageToStudio=sc;exports.getMessageBody=Cn;exports.getMonthsArray=eh;exports.getObservableCompanions=cp;exports.getQueryParams=me;exports.getServiceResponse=ym;exports.getStartedApps=Rm;exports.getTranslations=Bu;exports.getYearsArray=th;exports.hasCachedResponse=bm;exports.hasDecimals=_l;exports.hasHttpRouteHandlers=cr;exports.hasKosProfile=_n;exports.hslStringToHex=uc;exports.hslToHex=lc;exports.httpDelete=qf;exports.initKosProvider=jE;exports.initializeStateMachine=fc;exports.injectStateMachineSupport=hc;exports.isBoolean=$o;exports.isKosCompanionTypeFactory=kc;exports.isKosDataModel=gs;exports.isKosExecutionContext=po;exports.isKosLoggingEnabled=nf;exports.isKosModel=Te;exports.isKosModelContainer=bo;exports.isKosModelReady=lr;exports.isLeapYear=no;exports.isLocalRefId=Tm;exports.isNumber=qr;exports.isPrintable=Hp;exports.isTroubleAware=cw;exports.isValidDate=as;exports.kosAction=X;exports.kosAutoEffect=W;exports.kosChild=$e;exports.kosCompanion=Nf;exports.kosComputed=So;exports.kosConfigBean=zr;exports.kosConfigProperty=ay;exports.kosContainerAware=pc;exports.kosContext=Uf;exports.kosDependency=Lt;exports.kosEffect=Tl;exports.kosFuture=di;exports.kosFutureAware=jf;exports.kosLogger=zf;exports.kosLoggerAware=vc;exports.kosModel=R;exports.kosModelEffect=wc;exports.kosMultipleFutureAware=Bf;exports.kosObservable=_o;exports.kosParentAware=jr;exports.kosReference=Vf;exports.kosServiceRequest=Gf;exports.kosStateBean=yE;exports.kosStateEntry=Qf;exports.kosStateExit=Zf;exports.kosStateGuard=Xf;exports.kosStateMachine=Wf;exports.kosStateProp=bE;exports.kosSubscribe=Mp;exports.kosTopicHandler=B;exports.kosTroubleAware=Jf;exports.kosWhen=An;exports.login=$d;exports.mapConfigBeanModelToDto=Al;exports.mapDataToModel=In;exports.mapDtoToConfigBeanModel=Dl;exports.mapDtoToFutureModel=Po;exports.mapDtoToFutureOptions=Ro;exports.mapUpdateDtoToConfigBeanModel=xl;exports.modelEventTopicFactory=Lc;exports.modelFactory=Ft;exports.modelTypeEventTopicFactory=Fc;exports.modifyConfigBean=Il;exports.modifyFuture=gy;exports.pairedClientHeartbeat=lm;exports.parseWildcardSegment=Ac;exports.pipe=ml;exports.post=Ls;exports.preloadKosModel=dp;exports.processId=Gh;exports.processMiddleware=im;exports.put=Kf;exports.registerCompanionModel=up;exports.registerCoreModels=wd;exports.registerExtensionPoint=Ps;exports.registerHttpRoutes=tg;exports.registerKosModel=Dc;exports.registerLegacyModel=Cc;exports.resetKosModel=np;exports.resetPassword=Dd;exports.resolveBaseUrl=Qc;exports.resolveChild=Yc;exports.resolveContainerDeltas=qh;exports.resolveItemListDeltas=Vh;exports.resolveKosCompanion=On;exports.resolveKosContext=Im;exports.resolveKosProfiles=Ja;exports.resolveListDeltas=zh;exports.resolveServiceUrl=ae;exports.resolveVariable=dc;exports.retryWithExponentialBackoff=dm;exports.sendAsyncIntent=Dm;exports.sendBroadcastMessage=vg;exports.sendIntent=Cm;exports.sendKosHttpMessageResponse=ll;exports.sendKosMessage=mg;exports.sendKosMessageResponse=cl;exports.sendRequest=Sm;exports.sendStudioMessage=bg;exports.sendStudioMessageRequest=yg;exports.startPasswordReset=Cd;exports.stringComponentInsert=Wd;exports.studioAcceptOrgInvitation=ME;exports.studioLogin=vE;exports.studioResetPassword=EE;exports.studioStartPasswordReset=wE;exports.subscribeStore=hE;exports.syncPublish=_m;exports.transitionToActive=jc;exports.transitionToInit=Kc;exports.transitionToLoad=Hc;exports.transitionToReady=Bc;exports.transitionToUnload=Bp;exports.troubleByTypeReducer=Tc;exports.troubleDataFactory=xu;exports.unloadKosModel=rp;exports.updateCompanionModelRegistration=cm;exports.updateModelRegistration=am;exports.updateRegion=Td;exports.updateTimeZone=Hn;exports.useAmPmValues=Sh;exports.useCalendarDayArray=hh;exports.useConfigBean=PM;exports.useConfigProperty=Xd;exports.useContextModel=xE;exports.useContextModelHierarchy=Ld;exports.useDateArrays=oh;exports.useDateProps=BM;exports.useDateRelativeConfig=HM;exports.useDateRelativeData=gh;exports.useDayNames=uh;exports.useDayOptions=lh;exports.useDays=wi;exports.useDevice=zd;exports.useFormattedDate=dh;exports.useFormattedTime=Ih;exports.useFunctionWarmup=KM;exports.useHourValues=Th;exports.useKosCore=Bd;exports.useKosDateFormats=zM;exports.useKosModel=Z;exports.useKosRegions=wh;exports.useKosTime=hi;exports.useKosTimeContext=GE;exports.useKosTimeFormats=XM;exports.useKosTimeZones=YM;exports.useKosTranslation=$M;exports.useKosTranslationContext=eM;exports.useLocalComputed=JM;exports.useModelFromHierarchy=kE;exports.useMonths=ah;exports.useMonthsOptions=ch;exports.useMutationObserver=tT;exports.useNetworkInterfaceContainer=Vd;exports.useOta=Gd;exports.usePressGesture=sT;exports.useProjectReload=Mh;exports.useRegionTimeProps=rT;exports.useRegionalTimeDate=ph;exports.useSoftwareInfo=pi;exports.useSoftwareInfoContext=QE;exports.useStateProperty=mM;exports.useStorageDeviceContainer=Yd;exports.useSuspenseData=Kn;exports.useTimeOptions=_h;exports.useTimeProps=Oh;exports.useTimeValues=qn;exports.useTimer=bM;exports.useTranslationContainer=Qd;exports.useTroubleContainerModel=yi;exports.useTroubleModel=DM;exports.useTroublePresence=xM;exports.useUsbUpdateContainer=Zd;exports.useYears=vi;exports.useYearsOptions=ih;exports.uuid=ot;exports.variableToHex=hf;exports.waitForAppToStart=xm;exports.waitForAppsToStart=Ml;exports.waitForRequest=Mo;exports.whenReady=de;exports.withDevice=lM;exports.withKosTime=dM;exports.withNetworkInterfaceContainer=hM;exports.withOta=fM;exports.withProjectReloading=nT;exports.withSoftwareInfo=YE;exports.withStorageDeviceContainer=yM;exports.withTranslationContainer=CM;exports.withTroubleContainer=AM;exports.withUsbUpdateContainer=RM;exports.wrapPromise=so;
197
+ `,Vd=()=>{const t=Ar.type;return Z({modelId:t,modelType:Ar.type,options:{}})};function uM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=Vd();return T.jsx(n,{...r,children:T.jsx(t,{...e,device:s})})}}function dM(t,e,s){const r=new Promise(n=>{I.getInstance().whenReady().then(()=>{const{model:o}=I.getInstance().modelManager.createModelInstance(t,e??t,s);return o.whenReady().then(()=>{n(o.modelData)})})});return ro(r)}function hM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=fi();return T.jsx(n,{...r,children:T.jsx(t,{...e,kosTime:s})})}}const Gd=()=>{const t=Ds.type;return Z({modelId:t,modelType:Ds.type,options:{}})};function fM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=Gd();return T.jsx(n,{...r,children:T.jsx(t,{...e,networkInterfaceContainer:s})})}}const Yd=()=>{const t=Er.type;return Z({modelId:t,modelType:Er.type,options:{}})};function pM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=Yd();return T.jsx(n,{...r,children:T.jsx(t,{...e,oTA:s})})}}function gM(t,e){g.useEffect(()=>{function s(n){t.current&&!t.current.contains(n.target)&&e()}function r(n){n.key==="Escape"&&e()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[t,e])}function mM(t){const e=g.useRef(null),s=t.onAlert;return gM(e,s),T.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const yM=t=>{var u;const{stateProp:e}=t,[s,r]=g.useState((u=t.stateProp)==null?void 0:u.value),[n,o]=g.useState(!1),[i,a]=g.useState(void 0);return g.useEffect(()=>{async function d(h){try{h&&(await de(h),o(!0))}catch(f){a(f.message)}}d(e)},[e]),g.useEffect(()=>{const d=W(()=>{e&&n&&r(e.value)});return()=>{d()}},[n,e]),[s,{ready:n,error:i}]},Wd=()=>{const[t,e]=g.useState(!1),[s,r]=g.useState([]),n=Rt.type,o=Z({modelId:n,modelType:Rt.type,options:{}});return g.useEffect(()=>{const i=W(()=>{var a,c;e(((a=o.model)==null?void 0:a.isStorageInserted)??!1),r(((c=o.model)==null?void 0:c.data)??[])});return()=>{i()}},[o.model]),{...o,inserted:t,devices:s}};function bM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=Wd();return T.jsx(n,{...r,children:T.jsx(t,{...e,storageDeviceContainer:s})})}}const Sn=m.createLogger({name:"use-timer"}),vM=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:n})=>{const o=Id.getTimer(t);g.useEffect(()=>{if(!o){console.warn(`Timer with name ${t} does not exist.`);return}const u=C(li,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===t&&(f===di?e({name:h,action:f,remainingTime:p,timer:o}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:p,timer:o}))});return n&&o.start(),()=>{u.unsubscribe()}},[n,e,r,t,o]),g.useEffect(()=>{if(!o||!s)return;const u=`${ui}/${t}`,d=C(u,h=>{const{name:f,remainingTime:p}=h==null?void 0:h.body;f===t&&s({name:f,remainingTime:p,timer:o})});return()=>{d.unsubscribe()}},[s,t,o]);const i=g.useCallback(()=>{o?o.start():Sn.warn(`Timer with name ${t} does not exist.`)},[o,t]),a=g.useCallback(()=>{o?o.reset():Sn.warn(`Timer with name ${t} does not exist.`)},[o,t]),c=g.useCallback(()=>{o?o.pause():Sn.warn(`Timer with name ${t} does not exist.`)},[o,t]);return{timer:o,start:i,reset:a,pause:c}},wM=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},EM=t=>t instanceof RegExp,MM=t=>typeof t=="string",TM=(t,e,s)=>{if(t===""||e==="")return t;let r=e;EM(r)||(r=new RegExp("("+wM(r)+")","gi"));const n=t.split(r);for(let o=1,i=n.length;o<i;o+=2)n[o]=s(n[o],o);return n},Qd=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(n=>MM(n)?TM(n,e,s):n)};function SM(t,e){let s=t;return Object.entries(e).forEach(([r,n])=>{const o=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=Qd(s,o,(i,a)=>n.type==="br"?T.jsx("br",{}):g.cloneElement(n,{key:`${r}-${a}`},i))}),s}const _M=t=>{const{i18nKey:e,t:s,defaults:r,components:n,values:o={},context:i}=t,a=s(e,{defaultValue:r,data:o,context:i,returnObjects:!0}),c=SM(a,n||{});return T.jsx("span",{className:t.className,children:c})},bt=new Map;function IM(t,e){if(bt.has(t)){const s=bt.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(n=>{bt.set(t,{status:"finished",result:n})},n=>{throw bt.set(t,{status:"error",error:n}),n}),r={status:"pending",promise:s};throw bt.set(t,r),s}}function qn(t,e){return IM(t,e)}const OM=async()=>{const t=await Oc(Fe.type);return await de(t.model),t.model},$M=async(t,e,s)=>{const r=t.resolveNamespace(e);await de(r);for(const n of s){const o=t.resolveNamespace(n);await de(o),bt.set(n,{status:"finished",result:o})}return r},CM=(t,e)=>{const s=[t].flat(),[r,...n]=s,o=qn(Fe.type,OM),i=s.join("__"),a=qn(i,()=>$M(o,r,n)),c=g.useMemo(()=>({exists:d=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:g.useCallback((d,h)=>{const f=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(m.debug(`Translation model ${t} not ready for key: ${f}`),f)},[e==null?void 0:e.keyPrefix,t,a]),i18n:c}},Zd=()=>{const t=Fe.type;return Z({modelId:t,modelType:Fe.type,options:{}})};function DM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=Zd();return T.jsx(n,{...r,children:T.jsx(t,{...e,translationContainer:s})})}}const xM=t=>Z({modelId:t,modelType:$s.type}),bi=()=>Z({modelId:Dt.type,modelType:Dt.type,options:{}}),AM=({troubleType:t,condition:e})=>{const{model:s}=bi(),[r,n]=g.useState(!1),[o,i]=g.useState([]),a=g.useCallback(()=>{var c,u;return o.length>0&&((c=o[0])!=null&&c.resolvable)?(u=o[0])==null?void 0:u.resolve():Promise.resolve(void 0)},[o]);return g.useEffect(()=>W(()=>{const u=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],d=e?u.filter(e):u;n(d.length>0),i(d)}),[e,s,t]),[r,a,o.length>0?o[0]:void 0,o]};function RM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=bi();return T.jsx(n,{...r,children:T.jsx(t,{...e,troubleContainer:s})})}}const Xd=()=>{const t=As.type,e=Z({modelId:t,modelType:As.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=g.useState(!1),[n,o]=g.useState(!1),[i,a]=g.useState([]);return g.useEffect(()=>{const c=W(()=>{var u,d,h;r(((u=e.model)==null?void 0:u.isUsbInserted)??!1),o(((d=e.model)==null?void 0:d.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{c()}},[e.model]),{...e,inserted:s,updateAvailable:n,updates:i}};function PM(t){return e=>{const{model:s,status:r,KosModelLoader:n}=Xd();return T.jsx(n,{...r,children:T.jsx(t,{...e,usbUpdateContainer:s})})}}const kM=({path:t,propKey:e})=>{const{status:s}=Z({modelType:Es.type,modelId:t,options:{path:t}}),[r,n]=g.useState(!1),[o,i]=g.useState(),[a,c]=g.useState(""),[u,d]=g.useState(),h=f=>{o&&e&&o.updateProperty(e,f)};return g.useEffect(()=>{var f;s.model&&i(s.model),s.model&&e&&((f=s.model)!=null&&f.props.has(e)?c(s.model.props[e]):d(`property ${e} not found`)),s.ready&&n(s.ready)},[s.ready,s.model,e]),g.useEffect(()=>{e&&M.autorun(()=>{const f=o==null?void 0:o.props[e];c(f||"")})},[o,e]),{config:o,ready:r,value:a,error:u,updateValue:h}},LM=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},Jd=({configProperty:t,optionsTransformer:e})=>{const[s,r]=g.useState(!1),[n,o]=g.useState(""),[i,a]=g.useReducer(LM,{value:String(t==null?void 0:t.value),displayValue:t==null?void 0:t.displayValue,significantValue:t==null?void 0:t.significantValue,unit:t==null?void 0:t.unit,options:t==null?void 0:t.options,mappedOptions:[],updateProperty:t==null?void 0:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}),c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&(t==null||t.updateProperty(d))},[t]);return g.useEffect(()=>{async function u(d){try{d&&(await de(d),r(!0))}catch(h){o(h.message)}}u(t)},[t]),g.useEffect(()=>{const u=W(()=>{if(t&&s){let d=[];e&&(d=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:d,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{u()}},[t,e,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:n}};function FM(t,e){const s=e??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return t===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[t]??0}function NM(t,e){return new Date(t,e,0).getDate()}function eh(t,e){const s=FM(e,t),r=[];for(let n=1;n<=s;n++)r.push(n);return r}function th(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function sh(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function rh(t,e=[2018,2028]){const s=sh(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function vi(t="numeric",e="en-US"){const s=new Intl.DateTimeFormat(e,{month:t,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function UM({locale:t="en-US",year:e,month:s,day:r,formatOptions:n={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:o}){const i=s-1,a=new Date(e,i,r),c=new Intl.DateTimeFormat(t,{month:n.month}).format(a),u=new Intl.DateTimeFormat(t,{year:n.year}).format(a),d=new Intl.DateTimeFormat(t,{day:n.day}).format(a);return o?o=="MMDDYY"?`${c} ${d} ${u}`:o==="DDMMYY"?`${d} ${c} ${u}`:o==="YYMMDD"?`${u} ${c} ${d}`:`${u} ${d} ${c}`:new Intl.DateTimeFormat(t,n).format(a)}function be(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function jM(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function nh(t,e,s){const r=be(e),n=new Date(r,t,1).getDay(),o=new Date(r,t+1,0).getDate();return[...Array(42).keys()].map(a=>a<n||a>o+n-1?{label:"",value:0,disabled:!0}:s[a-n])}function cs(t,e,s){const r=e-1,n=new Date(t,r,s);return new Date(n).getMonth()===r&&new Date(n).getDate()===s}function ls(t,e){return new Date(t,e,0).getDate()}function oh(t="en-US",e="short"){const s=new Intl.DateTimeFormat(t,{weekday:e}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function ih({locale:t="en-US",year:e=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:n=[],formatOptions:{yearFormat:o="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=wi(o,r),u=ah(o,r,t),d=ch(i,t),h=lh(i,t),f=Ei(e,s),p=uh(e,s,t,n),y=fh(s,e,p),w=dh(t,a);return{daysArray:f,monthsArray:d,yearsArray:c,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:y,dayNamesArray:w}}function wi(t="long",e=[2018,2028]){return g.useMemo(()=>rh(t,e),[t,e])}function ah(t="long",e=[2018,2028],s="en-US"){const r=wi(t,e);return g.useMemo(()=>r.map(o=>({label:o.toLocaleString(s).replace(",",""),value:o})),[s,r])}function ch(t,e="en-US"){return g.useMemo(()=>vi(t,e),[t,e])}function lh(t,e="en-US"){const s=g.useMemo(()=>th(),[]),r=g.useMemo(()=>vi(t,e),[t,e]);return g.useMemo(()=>[...Array(12).keys()].map(o=>({label:r[o],value:Number(s[o])})),[r,s])}function Ei(t,e){const s=be(t);return g.useMemo(()=>eh(s,e),[e,s])}const BM=(t,e,s,r=[])=>{const n=new Date(t,e,s).getDay();return r.length>0&&r.includes(n)};function uh(t,e,s="en-US",r=[]){const n=Ei(t,e);return g.useMemo(()=>n.map(i=>({label:i.toLocaleString(s),value:i,disabled:BM(t,e,i,r)})),[r,s,e,n,t])}function dh(t="en-US",e="short"){return g.useMemo(()=>oh(t,e),[t,e])}function hh({year:t=new Date().getFullYear(),month:e=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const n=e,o=new Date(t,n,s);return{formattedDate:je.format(o,r)}}function fh(t,e,s){return g.useMemo(()=>nh(t,e,s),[t,e,s])}var ph=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(ph||{});function HM({locale:t="en-US",date:{year:e=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:n="long",monthFormat:o="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:u=[]}={}}){const[d,h]=g.useState(e),[f,p]=g.useState(c),[y,w]=g.useState(s),[E,S]=g.useState(r);g.useEffect(()=>{h(e)},[e]),g.useEffect(()=>{w(s)},[s]),g.useEffect(()=>{S(r)},[r]);const{yearsArray:L,yearsOptionsArray:P,monthsArray:O,monthsOptionsArray:_,daysArray:K,daysOptionsArray:q,calendarDayArray:J,dayNamesArray:zt}=ih({locale:t,year:d,yearRange:f,month:y,formatOptions:{yearFormat:n,monthFormat:o,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:Vt}=hh({year:d,month:y,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:w,setDay:S,nextMonth:()=>{const se=y<11?be(d):be(d+1),ce=y<11?y+1:0;if(!cs(se,ce,E)){const Ge=ls(se,ce);S(Ge)}ce===0&&h(se),w(ce)},previousMonth:()=>{const se=be(y===0?d-1:d),ce=y===0?11:y-1;if(!cs(se,ce,E)){const Ge=ls(se,ce);S(Ge)}ce===11&&h(se),w(ce)},nextYear:()=>{const se=d<f[1]?d+1:f[0],ce=be(se);if(cs(ce,y,E))h(se);else{const Ge=ls(be(d+1),y);S(Ge),h(se)}},previousYear:()=>{const se=d>f[0]?d-1:f[0],ce=be(se);if(cs(ce,y,E))h(se);else{const Ge=ls(be(d-1),y);S(Ge),h(se)}}},dateState:{year:d,yearRange:f,month:y,day:E,yearsArray:L,yearsOptionsArray:P,monthsArray:O,monthsOptionsArray:_,daysArray:K,daysOptionsArray:q,calendarDayNames:zt,calendarDayArray:J,formattedDate:Vt}}}function gh({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[n,o]=g.useState("Formatting Time..."),[i,a]=g.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:u,ready:d}=Z({modelId:re.type,modelType:re.type,options:{}}),h=typeof t=="string"?je.parseISO(t):t;return g.useEffect(()=>{c?a(""):e?a(je.format(h,e)):d&&a(je.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[c,t,e,h,u,d]),g.useEffect(()=>{s?o(je.format(h,s)):d&&o(je.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[t,s,h,u,d]),{formattedDate:i,formattedTime:n}}const mh=({secondsFromMidnight:t=0})=>{const[e,s]=g.useState(0),[r,n]=g.useState(0),[o,i]=g.useState(0),[a,c]=g.useState(new Date),{formattedTime:u}=gh({date:a,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const d=Number(t),h=Math.floor(d/3600),f=Math.floor(d%3600/60),p=d%60;s(h),n(f),i(p);const y=new Date;y.setHours(0,0,0,0);const w=new Date(y.getTime()+d*1e3);c(new Date(w))},[t]),{hours:e,minutes:r,seconds:o,formattedTime:u,timeActions:{setHours:s,setMinutes:n,setSeconds:i}}},KM=({configProperty:t})=>{const{value:e}=Jd({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:n,seconds:o,formattedTime:i,timeActions:a}=mh({secondsFromMidnight:s}),c=g.useRef();return g.useEffect(()=>{const u=r*3600+n*60+o;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{t&&t.updateProperty(u.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[t,r,n,o]),{hours:r,minutes:n,seconds:o,formattedTime:i,timeActions:a}};function qM(t,e={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=e;g.useEffect(()=>{const n=()=>{try{t({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(n):setTimeout(n,1));const o=s?setInterval(n,s):null;return()=>{o&&clearInterval(o)}},[t,s,r])}const zM=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),VM=(t=zM)=>{const[e,s]=g.useState([]),[r,n]=g.useState(),{model:o,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=W(()=>{s((o==null?void 0:o.dateFormatOptions.map(t))||[])});return()=>{c()}},[o,i,t]),g.useEffect(()=>{const c=W(()=>{o!=null&&o.dateFormatId&&(o!=null&&o.selectedDateFormat)&&n({id:o==null?void 0:o.dateFormatId,value:o==null?void 0:o.selectedDateFormat})});return()=>{c()}},[o==null?void 0:o.selectedDateFormat,o==null?void 0:o.dateFormatId]);const a=g.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(o==null||o.setSelectedDateFormat(u))},[o]);return{raw:(o==null?void 0:o.dateFormatOptions.map(c=>c.id))??[],regionModel:o,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:e}}},GM=t=>T.jsx("option",{title:t,value:t,children:t},t),yh="kos:service:region:settings",bh="timeZone",YM=`${yh}-${bh}`,WM=(t=GM)=>{const[e,s]=g.useState([]),[r,n]=g.useState(""),{model:o,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=at.factory(YM)({path:yh,attribute:bh});g.useEffect(()=>{const u=W(()=>{s((o==null?void 0:o.timeZones.map(t))||[]),o!=null&&o.timeZones.length&&Kn(o==null?void 0:o.timeZones[0])});return()=>{u()}},[o,i,t]),g.useEffect(()=>{const u=W(()=>{n(a.value||"")});return()=>{u()}},[a.value]);const c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&Kn(d)},[]);return{options:e,raw:(o==null?void 0:o.timeZones)??[],regionModel:o,selectedTimeZone:r,timeZones:(o==null?void 0:o.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:e}}},vh="kos:service:region",wh="regionId",QM=`${vh}-${wh}`,ZM=t=>T.jsx("option",{title:t,value:t,children:t},t),Eh=(t=ZM)=>{const[e,s]=g.useState([]),[r,n]=g.useState("factory"),{model:o,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=at.factory(QM)({path:vh,attribute:wh});g.useEffect(()=>{const u=W(()=>{s((o==null?void 0:o.availableRegions.map(t))||[])});return()=>{u()}},[o,i,t]),g.useEffect(()=>{const u=W(()=>{n(a.value||"factory")});return()=>{u()}},[a.value]);const c=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&Sd(d)},[]);return{raw:(o==null?void 0:o.availableRegions)??[],regionModel:o,regionData:o==null?void 0:o.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:e}}},XM=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),JM=(t=XM)=>{const[e,s]=g.useState([]),[r,n]=g.useState(),{model:o,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=W(()=>{s((o==null?void 0:o.timeFormatOptions.map(t))||[])});return()=>{c()}},[o,i,t]),g.useEffect(()=>{const c=W(()=>{o!=null&&o.timeFormatId&&(o!=null&&o.selectedTimeFormat)&&n({id:o==null?void 0:o.timeFormatId,value:o==null?void 0:o.selectedTimeFormat})});return()=>{c()}},[o==null?void 0:o.selectedTimeFormat,o==null?void 0:o.timeFormatId]);const a=g.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(o==null||o.setSelectedTimeFormat(u))},[o]);return{raw:(o==null?void 0:o.timeFormatOptions.map(c=>c.id))??[],regionModel:o,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:e}}},eT=(t,e)=>g.useMemo(()=>_o(t),e),tT={config:{attributes:!0,childList:!0,subtree:!0}};function sT(t,e,s=tT){const[r,n]=g.useState(null);g.useEffect(()=>{if(!e||typeof e!="function")throw new Error("A valid callback function is required");const o=new MutationObserver(e);n(o)},[e,s,n]),g.useEffect(()=>{if(!r)return()=>{};if(!t)throw new Error("A valid DOM element is required");const{config:o}=s;try{r.observe(t,o)}catch(i){m.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const Mh={validateStart:function(t){return!0},validateStop:function(t){const e=t.event.currentTarget.getBoundingClientRect(),[s,r]=t.xy;return s<e.left||s>e.right||r<e.top||r>e.bottom}},_n=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function rT({onPressed:t,onRelease:e,intersectionStrategy:s=Mh}){const r=g.useRef(!1),n=Rh.useGesture({onDragStart:c=>{_n.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{_n.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{_n.info("onDragEnd",c.type),r.current&&e&&(e(),r.current=!1)}}),o=()=>{t&&t(),r.current=!0},i=()=>{r.current&&e&&(e(),r.current=!1)},a=()=>{r.current&&e&&(e(),r.current=!1)};return{dom:n,mesh:()=>({onPointerDown:o,onPointerUp:i,onPointerOut:a})}}const Th=()=>{const[t,e]=g.useState(!1),s=I.getInstance();return g.useEffect(()=>{const r=W(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function Sh(t=!1,e="2-digit"){return g.useMemo(()=>{const s=t?12:24;return Array.from({length:s},(r,n)=>{const o=t&&n===0?12:n%s;return{id:n,label:e==="2-digit"?o.toString().padStart(2,"0"):o.toString()}})},[e,t])}function zn(t,e="2-digit",s=0,r=0){return g.useMemo(()=>Array.from({length:t},(n,o)=>{const i=String(o+s);return{id:o+r,label:e==="2-digit"?i.padStart(2,"0"):i}}),[t,s,r,e])}function _h(t="en-US"){return g.useMemo(()=>["AM","PM"].map(e=>{const s=new Intl.DateTimeFormat(t,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(e==="AM"?0:12))[2].value;return{id:s,label:s}}),[t])}function Ih({formatOptions:{hour12:t=!0,hour:e="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:n="en-US"}){const o=Sh(t,e),i=zn(60,s),a=zn(60,r),c=_h(n);return{hourOptions:o,minuteOptions:i,secondOptions:a,amPmOptions:c}}function Oh(t,e){return je.format(t,e)}function $h({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[n,o]=g.useState(e),i=g.useCallback(w=>{o(E=>{const S=new Date(E);return S.setHours(Number(w)),S})},[]),a=g.useCallback(w=>{o(E=>{const S=new Date(E);return S.setMinutes(Number(w)),S})},[]),c=g.useCallback(w=>{o(E=>{const S=new Date(E);return S.setSeconds(Number(w)),S})},[]),u=g.useCallback(w=>{const E=new Date(w);o(E)},[]),d=Oh(n,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:y}=Ih({formatOptions:t,locale:s});return{amPmOptions:y,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:c,setTime:u,time:new Date(n)}}const nT=t=>{const{regionModel:e}=Eh(),s=g.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return $h({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function oT(t){return e=>{const[s]=Th();return s?T.jsx(Rd,{message:"Wait a moment while your project reloads..."}):T.jsx(t,{...e})}}const ua=m.createLogger({name:"studio-properties-service",group:"Services"}),iT="/api/kos/studio/properties",Ch=async t=>{if(ua.debug("sending GET for studio-properties"),!t)throw ua.error("connectionId is undefined"),new Error("connectionId is undefined");return await De.get(iT,{},{destinationAddress:t,timeout:500})},aT=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Ch},Symbol.toStringTag,{value:"Module"}));var cT=Object.getOwnPropertyDescriptor,lT=(t,e,s,r)=>{for(var n=r>1?void 0:r?cT(e,s):e,o=t.length-1,i;o>=0;o--)(i=t[o])&&(n=i(n)||n);return n};const Dh="studio-properties-model",uT="/kos/studio/properties",da={"kos.studio.tool.legacy":1};let Vn=class{constructor(t,e,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=t,this.logger=s.logger,this.data=_e(),this.connectionId=e.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var t;(t=this.unsubscribe)==null||t.call(this)}async initializePropertiesSession(){this.unsubscribe=Tt.getInstance().subscribeTopic({topic:uT,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await Ch(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(da);return}if(e){const s=Object.keys(e).reduce((r,n)=>(r[n]=e[n]??n,r),{});this.data.setValues(s??da),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return _o(()=>this.get(t))}};Vn=lT([R(Dh)],Vn);const dT=new ye({class:Vn,type:Dh});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>M.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>M.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>Yn.observer});exports.AuthState=gl;exports.BrowserKosRouter=El;exports.BrowserRouter=Fo;exports.CanvasDispatcher=At;exports.CanvasDispatcherServices=gw;exports.CanvasRenderer=ti;exports.CanvasStreamer=aM;exports.CanvasStreamerBase=zd;exports.ChildModels=Be;exports.CompanionParentModel=He;exports.ConfigBean=Es;exports.ContainerAwareSetup=po;exports.CoreExtensionManager=hE;exports.CoreModels=ci;exports.CreateModelTranslationsContext=jd;exports.CreateModelTranslationsProvider=UE;exports.DateDisplayFormat=ph;exports.DateHelpers=Wh;exports.DependencyLifecycle=x;exports.DependencyModels=N;exports.Device=Ar;exports.DeviceServices=Fw;exports.DomIntersectionStrategy=Mh;exports.EVENT_KOS_MODEL_READY=Xn;exports.EVENT_TROUBLE_ADDED=km;exports.EVENT_TROUBLE_REMOVED=Lm;exports.EXTENSION_CANVAS_RENDERER=te;exports.EXTENSION_FEATURE_FLAG_RESOLVER=ac;exports.EXTENSION_TROUBLE_DATA_MAPPER=vr;exports.EXTENSION_TROUBLE_MAPPER=Hs;exports.ErrorBoundaryWithFallback=Pd;exports.EventBus=Fh;exports.EventBusFunctional=Uh;exports.EventBusState=Bh;exports.ExtensionManager=$;exports.FUTURE_CONTAINER_MODEL_TYPE=Wl;exports.FUTURE_MODEL_TYPE=Ul;exports.FUTURE_NOT_ASSIGNED=Oo;exports.FeatureFlagService=cc;exports.FetchError=ge;exports.FutureAliases=fs;exports.FutureContainerFactory=qe;exports.FutureContainerModel=Zl;exports.FutureContainerSetup=lo;exports.FutureEndState=Ke;exports.FutureFactory=Ut;exports.FutureHandler=qr;exports.FutureManager=rt;exports.FutureModel=zl;exports.FutureService=us;exports.HEADER_CACHE_CONTROL=ya;exports.HEADER_CONTENT_TYPE=ma;exports.HEADER_DESTINATION_ADDR=Ne;exports.HEADER_FOS_REQUEST_ID=ba;exports.HEADER_METHOD=Lr;exports.HEADER_ORDERED=Qn;exports.HEADER_REQUEST_ID=Rs;exports.HEADER_REQUEST_TYPE=Oe;exports.HEADER_RESPONSE_ID=Fr;exports.HEADER_SOURCE_ADDR=ga;exports.HEADER_TOPIC=pa;exports.HEADER_URL=kt;exports.HEADER_WORK_TRACKER=Zn;exports.HttpRouteHandlers=Re;exports.KOS_EXECUTION_CONTEXT=Hr;exports.KOS_MODEL_ID=ar;exports.KeyValue=jo;exports.KeyValueServices=Dy;exports.Kos=ie;exports.KosConfigPropertySpec=at;exports.KosContainerIndex=mo;exports.KosContextBean=vl;exports.KosContextManager=Y;exports.KosCore=I;exports.KosCoreModelPropertyMapper=ve;exports.KosDataContainer=So;exports.KosDependencyTypes=Kf;exports.KosExpressionEvaluator=cu;exports.KosExtensionUtils=Jh;exports.KosFeatureFlags=lc;exports.KosFetchMethods=Mc;exports.KosGlobalConfig=ao;exports.KosHttpRouteManager=wo;exports.KosLog=m;exports.KosLogManager=du;exports.KosLogManagerServices=Fb;exports.KosMockEvents=Ea;exports.KosModel=hl;exports.KosModelCollectionProvider=PE;exports.KosModelContainer=Ce;exports.KosModelContext=on;exports.KosModelEvents=F;exports.KosModelFactory=gs;exports.KosModelLoader=Nd;exports.KosModelLoaderDisplay=Ud;exports.KosModelManager=pl;exports.KosModelProvider=kd;exports.KosModelRegistrationFactory=ye;exports.KosModelRegistry=Hn;exports.KosModelState=v;exports.KosModelSymbol=co;exports.KosModelVisitor=im;exports.KosObservableData=_c;exports.KosRegistration=$m;exports.KosSingletonRegistration=Cm;exports.KosTime=mr;exports.KosTimeContext=pi;exports.KosTimeProvider=GE;exports.KosTimeServices=qb;exports.KosTimer=_d;exports.KosToken=wl;exports.KosTranslationProvider=eM;exports.KosTranslations=Yu;exports.KosWSTransportStatus=dl;exports.KosWsEvents=Ps;exports.LOADER_FEATURE_FLAG=hf;exports.LOGIN_HOST=va;exports.LOGIN_URL=Ph;exports.LoadingMessage=Rd;exports.LogBlock=Os;exports.LogBlockContainer=tn;exports.LogConfig=hs;exports.LogStream=vs;exports.LogStreamContainer=Bs;exports.LogStreamServices=tv;exports.LoggerSetup=fo;exports.MODEL_DELETION_DELAY=fl;exports.MiddlewareChain=ml;exports.ModelEffects=et;exports.MultipleFutureContainerSetup=uo;exports.MultipleFutureHandler=Tc;exports.NestedModelContext=an;exports.NetworkInterface=ni;exports.NetworkInterfaceContainer=Ds;exports.NetworkInterfaceServices=Vw;exports.ObservableData=_e;exports.Ota=Er;exports.OutsideAlerter=mM;exports.PLUGIN_EXTENSION_NAME=ef;exports.PORT=wa;exports.PROFILE_LOG_DEBUG=Za;exports.PROFILE_LOG_INFO=Xa;exports.PROFILE_RELAX_STORE_VALIDATION=sf;exports.PROFILE_TOOLS_PREVIEW=Qa;exports.ParentModel=ds;exports.PluginExtensionManager=tf;exports.ProgressBar=DE;exports.ReferenceConfig=tr;exports.RegionInfo=re;exports.RegionServices=Vm;exports.RegistrationManager=A;exports.Registry=dE;exports.ReplayStrategy=Je;exports.ResponseRetention=ue;exports.STATUS=Wn;exports.ServiceFactory=ne;exports.ServiceRequestHandlers=tt;exports.SingletonKosModelRegistrationFactory=Se;exports.SoftwareInfo=Mr;exports.SoftwareInfoContext=mi;exports.SoftwareInfoProvider=QE;exports.SoftwareInfoServices=Fv;exports.StateActionHandlers=gf;exports.StateBean=Cs;exports.StateBeanServices=Hv;exports.StateEntryHandlers=wt;exports.StateExitHandlers=ps;exports.StateMachineSetup=Ls;exports.StateProp=Zo;exports.StatePropServices=Xv;exports.StorageDevice=Pr;exports.StorageDeviceContainer=Rt;exports.StorageDeviceServices=Zw;exports.StudioProperties=dT;exports.StudioPropertiesServices=aT;exports.SubscriptionHandlers=ee;exports.TIMER_END=di;exports.TIMER_EVENT=li;exports.TOPIC_TIMER_TICK_EVENT=ui;exports.TimerManager=Id;exports.TokenContext=qd;exports.TokenProvider=XE;exports.Topics=bs;exports.Trans=_M;exports.TransitionMap=sr;exports.Transitions=bo;exports.Translation=_r;exports.TranslationContainer=Fe;exports.TranslationContainerContext=yi;exports.TranslationContext=cw;exports.TransportFactory=xn;exports.Trouble=$s;exports.TroubleAwareSetup=ho;exports.TroubleContainer=Dt;exports.TroubleServices=wv;exports.Troubles=pe;exports.UsbUpdate=ai;exports.UsbUpdateContainer=As;exports.UsbUpdateServices=oE;exports.WS_EVENT_TYPE=Wu;exports.WebSocketEvents=ys;exports.WebSocketTransport=Tt;exports.WsEventFactory=Jo;exports.acceptOrgInvitation=Ad;exports.addDaysToDate=Ha;exports.addFuture=Bl;exports.addMonthsToDate=Ba;exports.api=Vl;exports.applyMixins=Kh;exports.arraysEqual=qh;exports.buildConfigBeanModel=Um;exports.buildFuture=Lo;exports.buildFutureModel=Kl;exports.cancelFuture=Hl;exports.checkAppsStarted=Rm;exports.checkWildcardPattern=Pc;exports.clearAllServiceResponses=Mm;exports.clearPath=Em;exports.clearServiceResponse=wm;exports.convert=Ao;exports.convertFileSizeRaw=Hh;exports.convertWithUnits=Xm;exports.createBaseMessage=sl;exports.createBroadcastMessageResponse=il;exports.createCancellablePromise=SE;exports.createClient=Eo;exports.createFosBaseMessage=tl;exports.createHeaders=Zt;exports.createKosHtpMessageResponse=al;exports.createKosMessage=nl;exports.createKosMessageResponse=cl;exports.createMessageBody=Ve;exports.createModelDependency=zc;exports.createOptionKey=Ff;exports.createPropKey=it;exports.createReadableStream=Xt;exports.createStudioMessage=el;exports.createStudioMessageRequest=rl;exports.createStudioMessageResponse=ol;exports.debounce=Ya;exports.del=yc;exports.deleteFuture=jl;exports.destroyKosModel=st;exports.evaluateScopes=Cl;exports.executeChildrenModelLifecycle=Yc;exports.executeDependentModelLifecycle=Qt;exports.executeListLifecycle=Gc;exports.fetchModel=dM;exports.findModel=ap;exports.findModels=$c;exports.formatDate=za;exports.formatDateSince=ja;exports.formatDateTime=Ga;exports.formatTime=Va;exports.get=mc;exports.getAllKosCompanionModels=Cc;exports.getCalendarMonthArray=nh;exports.getConfigBean=$l;exports.getDayStrings=oh;exports.getDays=NM;exports.getDaysArray=eh;exports.getDaysInMonth=io;exports.getDependenciesByLifecycle=Vc;exports.getFormattedDate=UM;exports.getFormattedMonth=jM;exports.getFormattedMonthsArray=vi;exports.getFormattedYear=be;exports.getFormattedYearsArray=rh;exports.getFutures=gy;exports.getHttpRouteHandlers=bc;exports.getKosCompanionModel=cp;exports.getKosLocalizationDescriptor=Ku;exports.getKosMessageLogging=sc;exports.getKosModel=Oc;exports.getKosModelSync=Ie;exports.getKosModelType=ip;exports.getKosSessionKey=bl;exports.getLastDayOfMonth=ls;exports.getLocalizationDescriptor=ew;exports.getLogLevel=tc;exports.getLogMessageToStudio=rc;exports.getMessageBody=Dn;exports.getMonthsArray=th;exports.getObservableCompanions=lp;exports.getQueryParams=me;exports.getServiceResponse=bm;exports.getStartedApps=Pm;exports.getTranslations=Hu;exports.getYearsArray=sh;exports.hasCachedResponse=vm;exports.hasDecimals=Il;exports.hasHttpRouteHandlers=lr;exports.hasKosProfile=In;exports.hslStringToHex=dc;exports.hslToHex=uc;exports.httpDelete=zf;exports.initKosProvider=BE;exports.initializeStateMachine=pc;exports.injectStateMachineSupport=fc;exports.isBoolean=Co;exports.isKosCompanionTypeFactory=Lc;exports.isKosDataModel=ms;exports.isKosExecutionContext=go;exports.isKosLoggingEnabled=of;exports.isKosModel=Te;exports.isKosModelContainer=vo;exports.isKosModelReady=ur;exports.isLeapYear=oo;exports.isLocalRefId=Sm;exports.isNumber=zr;exports.isPrintable=Kp;exports.isTroubleAware=lw;exports.isValidDate=cs;exports.kosAction=X;exports.kosAutoEffect=W;exports.kosChild=$e;exports.kosCompanion=Uf;exports.kosComputed=_o;exports.kosConfigBean=Vr;exports.kosConfigProperty=cy;exports.kosContainerAware=gc;exports.kosContext=jf;exports.kosDependency=Lt;exports.kosEffect=Sl;exports.kosFuture=hi;exports.kosFutureAware=Bf;exports.kosLogger=Vf;exports.kosLoggerAware=wc;exports.kosModel=R;exports.kosModelEffect=Ec;exports.kosMultipleFutureAware=Hf;exports.kosObservable=Io;exports.kosParentAware=Br;exports.kosReference=Gf;exports.kosServiceRequest=Yf;exports.kosStateBean=bE;exports.kosStateEntry=Zf;exports.kosStateExit=Xf;exports.kosStateGuard=Jf;exports.kosStateMachine=Qf;exports.kosStateProp=vE;exports.kosSubscribe=Tp;exports.kosTopicHandler=B;exports.kosTroubleAware=ep;exports.kosWhen=Rn;exports.login=Cd;exports.mapConfigBeanModelToDto=Rl;exports.mapDataToModel=On;exports.mapDtoToConfigBeanModel=xl;exports.mapDtoToFutureModel=ko;exports.mapDtoToFutureOptions=Po;exports.mapUpdateDtoToConfigBeanModel=Al;exports.modelEventTopicFactory=Fc;exports.modelFactory=Ft;exports.modelTypeEventTopicFactory=Nc;exports.modifyConfigBean=Ol;exports.modifyFuture=my;exports.pairedClientHeartbeat=um;exports.parseWildcardSegment=Rc;exports.pipe=yl;exports.post=Fs;exports.preloadKosModel=hp;exports.processId=Yh;exports.processMiddleware=am;exports.put=qf;exports.registerCompanionModel=dp;exports.registerCoreModels=Ed;exports.registerExtensionPoint=ks;exports.registerHttpRoutes=sg;exports.registerKosModel=xc;exports.registerLegacyModel=Dc;exports.resetKosModel=op;exports.resetPassword=xd;exports.resolveBaseUrl=Zc;exports.resolveChild=Wc;exports.resolveContainerDeltas=zh;exports.resolveItemListDeltas=Gh;exports.resolveKosCompanion=$n;exports.resolveKosContext=Om;exports.resolveKosProfiles=ec;exports.resolveListDeltas=Vh;exports.resolveServiceUrl=ae;exports.resolveVariable=hc;exports.retryWithExponentialBackoff=hm;exports.sendAsyncIntent=xm;exports.sendBroadcastMessage=wg;exports.sendIntent=Dm;exports.sendKosHttpMessageResponse=ul;exports.sendKosMessage=yg;exports.sendKosMessageResponse=ll;exports.sendRequest=_m;exports.sendStudioMessage=vg;exports.sendStudioMessageRequest=bg;exports.startPasswordReset=Dd;exports.stringComponentInsert=Qd;exports.studioAcceptOrgInvitation=TE;exports.studioLogin=wE;exports.studioResetPassword=ME;exports.studioStartPasswordReset=EE;exports.subscribeStore=fE;exports.syncPublish=Im;exports.transitionToActive=Bc;exports.transitionToInit=qc;exports.transitionToLoad=Kc;exports.transitionToReady=Hc;exports.transitionToUnload=Hp;exports.troubleByTypeReducer=Sc;exports.troubleDataFactory=Au;exports.unloadKosModel=np;exports.updateCompanionModelRegistration=lm;exports.updateModelRegistration=cm;exports.updateRegion=Sd;exports.updateTimeZone=Kn;exports.useAmPmValues=_h;exports.useCalendarDayArray=fh;exports.useConfigBean=kM;exports.useConfigProperty=Jd;exports.useContextModel=AE;exports.useContextModelHierarchy=Fd;exports.useDateArrays=ih;exports.useDateProps=HM;exports.useDateRelativeConfig=KM;exports.useDateRelativeData=mh;exports.useDayNames=dh;exports.useDayOptions=uh;exports.useDays=Ei;exports.useDevice=Vd;exports.useFormattedDate=hh;exports.useFormattedTime=Oh;exports.useFunctionWarmup=qM;exports.useHourValues=Sh;exports.useKosCore=Hd;exports.useKosDateFormats=VM;exports.useKosModel=Z;exports.useKosRegions=Eh;exports.useKosTime=fi;exports.useKosTimeContext=YE;exports.useKosTimeFormats=JM;exports.useKosTimeZones=WM;exports.useKosTranslation=CM;exports.useKosTranslationContext=tM;exports.useLocalComputed=eT;exports.useModelFromHierarchy=LE;exports.useMonths=ch;exports.useMonthsOptions=lh;exports.useMutationObserver=sT;exports.useNetworkInterfaceContainer=Gd;exports.useOta=Yd;exports.usePressGesture=rT;exports.useProjectReload=Th;exports.useRegionTimeProps=nT;exports.useRegionalTimeDate=gh;exports.useSoftwareInfo=gi;exports.useSoftwareInfoContext=ZE;exports.useStateProperty=yM;exports.useStorageDeviceContainer=Wd;exports.useSuspenseData=qn;exports.useTimeOptions=Ih;exports.useTimeProps=$h;exports.useTimeValues=zn;exports.useTimer=vM;exports.useTranslationContainer=Zd;exports.useTroubleContainerModel=bi;exports.useTroubleModel=xM;exports.useTroublePresence=AM;exports.useUsbUpdateContainer=Xd;exports.useYears=wi;exports.useYearsOptions=ah;exports.uuid=ot;exports.variableToHex=ff;exports.waitForAppToStart=Am;exports.waitForAppsToStart=Tl;exports.waitForRequest=To;exports.whenReady=de;exports.withDevice=uM;exports.withKosTime=hM;exports.withNetworkInterfaceContainer=fM;exports.withOta=pM;exports.withProjectReloading=oT;exports.withSoftwareInfo=WE;exports.withStorageDeviceContainer=bM;exports.withTranslationContainer=DM;exports.withTroubleContainer=RM;exports.withUsbUpdateContainer=PM;exports.wrapPromise=ro;
198
198
  //# sourceMappingURL=index.cjs.map