@kosdev-code/kos-ui-sdk 2.1.3 → 2.1.5
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/core/core/decorators/index.d.ts +1 -0
- package/core/core/decorators/index.d.ts.map +1 -1
- package/core/core/decorators/kos-multiple-future-aware.d.ts +193 -0
- package/core/core/decorators/kos-multiple-future-aware.d.ts.map +1 -0
- package/core/core/decorators/kosModel.d.ts.map +1 -1
- package/core/core/decorators/propKeys.d.ts +2 -0
- package/core/core/decorators/propKeys.d.ts.map +1 -1
- package/index.cjs +50 -50
- package/index.cjs.map +1 -1
- package/index.js +4041 -3942
- package/index.js.map +1 -1
- package/models/decorators/future-service.d.ts.map +1 -1
- package/package.json +2 -2
package/index.cjs
CHANGED
|
@@ -1,83 +1,83 @@
|
|
|
1
|
-
"use strict";var hh=Object.defineProperty;var fh=(e,t,s)=>t in e?hh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var l=(e,t,s)=>(fh(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("loglevel"),E=require("mobx"),y=require("robot3"),je=require("date-fns"),T=require("@emotion/react/jsx-runtime"),Lo=require("@emotion/styled"),Xi=require("react-dom"),qe=require("@emotion/react"),g=require("react"),Fo=require("mobx-react-lite"),ph=require("@use-gesture/react"),Or="method",Ji="topic",At="url",Is="request-id",Sr="response-id",No="status",Le="dst-addr",ea="src-addr",Ie="type",Uo="ordered",jo="tracker",ta="Content-Type",sa="Cache-Control",ra="requestId",oa=process.env.KOS_LOGIN_URL||"http://localhost",na=process.env.KOS_APP_PORT||"8080",gh=`${oa}:${na}`,Zs="{MODEL_ID}";var Os=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Os||{}),ia=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(ia||{});const Bo="/kos/model/ready/";C.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const K=globalThis.kos.subscriptions,mh=()=>Symbol("eventKey");function Ko(e){return K[e]&&Object.getOwnPropertySymbols(K[e]).length>0}function $(e,t){const s=mh();return K[e]||(C.debug(`Initializing subscription for ${e}`),K[e]={}),C.debug(`Subscribing to ${e} with id ${s.toString()}`),K[e][s]=t,{count:K[e]?Object.getOwnPropertySymbols(K[e]).length:0,unsubscribe:()=>(C.debug(`Unsubscribing from ${e} with id ${s.toString()}`),K[e]&&K[e][s]&&delete K[e][s],K[e]&&Object.getOwnPropertySymbols(K[e]).length===0&&delete K[e],{count:K[e]?Object.getOwnPropertySymbols(K[e]).length:0})}}function z(e,t,s={}){if(!K[e]||Object.getOwnPropertySymbols(K[e]).length===0)return C.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const r=Object.getOwnPropertySymbols(K[e]).length;return Object.getOwnPropertySymbols(K[e]).forEach(o=>{if(s.sync){const n=s.sync;C.debug(`Performing sync publish for ${e} with sync id ${n}`),K[e][o]({body:t,headers:s}).then(i=>{C.debug(`Response recieved for ${n}, publishing back to source.`),z(n,i)})}else C.debug(`Performing async publish for ${e}`),K[e][o]({body:t,headers:s})}),{eventType:e,subscribers:r}}function yh(){C.warn("Resetting event bus"),Object.keys(K).forEach(e=>delete K[e])}function aa(e,t){const s=$(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function Ho(e,t){return new Promise((s,r)=>{let o=null;const n=aa(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}const bh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:Ko,once:aa,publish:z,reset:yh,subscribe:$,waitFor:Ho},Symbol.toStringTag,{value:"Module"}));function $r(e,t){const s=$(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function Cr(e,t){return new Promise((s,r)=>{let o=null;const n=$r(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}function ca(e,t){const s=e.map(r=>Cr(r,t));return Promise.all(s)}function la(e,t){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};e.forEach(c=>{const u=$r(c,d=>{i||(i=!0,a(),s({eventType:c,data:d}))});o.push(u)}),t&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${e.join(", ")}`)))},t))})}function ua(e,t,s){return $(e,o=>{o&&t(o)&&s(o)}).unsubscribe}function da(e,t,s){return $(e,o=>{if(o){const n=t(o);s(n)}}).unsubscribe}function ha(e,t,s){let r=null;const o=$(e,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},t)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function fa(e,t,s){let r=0,o=null;const n=$(e,i=>{const a=Date.now(),c=a-r;c>=t?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},t-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function pa(e,t,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=$(e,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},t)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function zo(e,t=1){const s=[];return $(e,r=>{r&&(s.push(r),s.length>t&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),$(e,r))}}function ga(e,t){const s=e.map(r=>$(r,o=>{o&&t(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function ma(e,t){let s=e;const r=[],o=new Set;return Object.values(t).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=$(n,a=>{const c=t[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function ya(e,t,s,r){const o=Cr(t,r);return z(e,s),o}async function*ba(e){const t=[],s=[],r=$(e,o=>{o&&(s.length>0?s.shift()(o):t.push(o))});try{for(;;)t.length>0?yield t.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const vh={once:$r,waitFor:Cr,waitForAll:ca,race:la,filter:ua,map:da,debounce:ha,throttle:fa,buffer:pa,replay:zo,merge:ga,stateMachine:ma,request:ya,eventIterator:ba},wh=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:vh,buffer:pa,debounce:ha,eventIterator:ba,filter:ua,map:da,merge:ga,once:$r,race:la,replay:zo,request:ya,stateMachine:ma,throttle:fa,waitFor:Cr,waitForAll:ca},Symbol.toStringTag,{value:"Module"}));async function Dr(e,t){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=t,i=Ho(e,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(c),100)})])}function va(e,t,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=$(e,a=>{a&&(n=!0,t(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||t(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function wa(e,t){let s;const r=new Set,o=async()=>{try{typeof t=="string"?s=await(await fetch(t)).json():s=await t(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};$(e,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let n=!1;const i=()=>{n||(n=!0,o())};return{get state(){return s},async getState(){return i(),s===void 0&&await new Promise(a=>{const c=()=>{s!==void 0?a():setTimeout(c,10)};c()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function Vo(e,t){if(typeof e=="string")return Dr(e,t);const s=e,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=t,i=await r(),a=t.transformState?t.transformState(i):i;if(o&&o(a))return a;const c=s.map(d=>Ho(d,n)),u=await Promise.all(c);return u[u.length-1]}function Ea(e,t,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=$(e,async u=>{if(u){if(n){const d=n(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await t(u)}}),c=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(n){const f=n(h);i.has(f)||(i.add(f),await t(h))}else await t(h)}catch(u){console.error("Failed to fetch missed events:",u)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function Ma(e){const{connectEvent:t,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=e,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await Dr(t,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:d});return a.state="connected",a.data=h,u(),h},subscribe(d){return c.add(d),d(a),()=>{c.delete(d)}},async reconnect(){a.state="connecting",u();try{const d=await n();a.state="connected",a.data=d,u()}catch{a.state="error",u(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,u=()=>{c.forEach(d=>d(a))};return $(t,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),$(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&$(r,()=>{a.state="error",u()}),o&&$(o,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const Eh={waitForOrGetState:Dr,subscribeWithInitialState:va,createStatefulEventStream:wa,waitForAllWithState:Vo,createResilientEventHandler:Ea,createConnectionStateManager:Ma},Mh=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Eh,createConnectionStateManager:Ma,createResilientEventHandler:Ea,createStatefulEventStream:wa,subscribeWithInitialState:va,waitForAllWithState:Vo,waitForOrGetState:Dr},Symbol.toStringTag,{value:"Module"})),Th=(e,t=0)=>{if(!+e)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=t<0?0:t,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(s)),i=parseFloat((e/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function Go(e){let t="pending",s;const r=e.then(n=>{t="success",s=n},n=>{t="error",s=n});return{read:()=>{switch(t){case"pending":throw r;case"error":throw s;default:return s}}}}function tt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}function _h(e,t){t.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(e.prototype,r,o)})})}function Ih(e,t){const s=e??[],r=t??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const Yo=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},Ta=e=>e,_a=e=>e,Oh=({container:e,onAddItem:t,onUpdateItem:s,onRemoveItem:r=Ta,idMapper:o=_a})=>n=>{const i=n.map(o),c=Yo(i,e.data).map(r).filter(Boolean);e.removeAll(c);const u=i.map(d=>{const h=e.getModel(d.id);return h&&s?s(d,h):t(d)}).filter(Boolean);e.addAll(u)},Sh=({container:e,onAddItem:t,onRemoveItem:s=Ta,idMapper:r=_a})=>o=>{const n=o.map(r);Yo(n,e.models).forEach(s),n.forEach(t)},$h=({items:e,onAddItem:t,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);Yo(n,e).forEach(s),n.forEach(t)},Ch=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},ui=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),di=[{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 Ia(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=di.length;s++){const r=di[s];if(Math.abs(t)<r.amount)return ui.format(Math.round(t),r.name);t/=r.amount}return ui.format(Math.round(t),"years")}const qo=e=>e%4===0&&e%100!==0||e%400===0,Wo=(e,t)=>[31,qo(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],Oa=(e,t)=>{const s=new Date(e),r=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(r,Wo(s.getFullYear(),s.getMonth()))),s},Sa=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},yt="en-US",$a={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"}},Ca={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"}},Da=(e,{dateStyle:t="short",locales:s=yt}={dateStyle:"short",locales:yt})=>{const r=t==="short"?$a.short:{dateStyle:t};return new Intl.DateTimeFormat(s,r).format(e)},xa=(e,{locales:t=yt,timeStyle:s="short"}={locales:yt,timeStyle:"short"})=>{const r=Ca[s];return new Intl.DateTimeFormat(t,r).format(e)},Aa=(e,{dateStyle:t="short",locales:s=yt,timeStyle:r="short"}={dateStyle:"short",locales:yt,timeStyle:"short"})=>{const o={...t&&$a[t],...r&&Ca[r]};return new Intl.DateTimeFormat(s,o).format(e)},Dh=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Sa,addMonthsToDate:Oa,formatDate:Da,formatDateSince:Ia,formatDateTime:Aa,formatTime:xa,getDaysInMonth:Wo,isLeapYear:qo},Symbol.toStringTag,{value:"Module"}));function Ra(e,t,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{t.apply(e,o)},s)}}const te="canvas-renderer",Zr=new Map,hi=new Map,Xr=new Map,Jr=new Map,Ss=(e,t)=>{Pa[e]=t},Pa={indexExtension:{registerIndexExtension:(e,t)=>{const s=Jr.get(e)||{};Object.assign(s,t),Jr.set(e,t)},loadIndexExtensions:e=>Jr.get(e)||{}},loader:{registerLoader:(e,t)=>{hi.set(e,t)},executeLoader:async(e,t)=>{const s=hi.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{Xr.set(e,t)},hasMapper:e=>Xr.has(e),executeMapper:(e,t,s)=>{const r=Xr.get(e);return r?r(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=Zr.get(e)||[];s.push(t),Zr.set(e,s)},executeMapper:async(e,t,s)=>{const r=Zr.get(e);if(!r)return{};const o={};for(const n of r){const i=await n(t,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(e,t)=>{if(!S[te]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${e}".`);return}S[te].register(e,t)}}},S=Pa,xh=async({context:e,extension:t})=>{const s=await S.loader.executeLoader(t,{});return e==null||e.set(t,s),s},Ah=async({extension:e,contextData:t,data:s})=>await S.dataMapper.executeMapper(e,s,t),Rh=async({extension:e,contextData:t,data:s})=>await S.propertyMapper.executeMapper(e,s,t),Ph=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Ah,executeLoaderExtension:xh,executePropertyMapperExtension:Rh},Symbol.toStringTag,{value:"Module"})),kh="Extensions";class Lh{constructor(){l(this,"extensions");this.extensions={}}register(t,s,r){this.extensions[t]={},this.extensions[t][s]={component:r}}get(t,s){if(!this.extensions[t])throw new Error(`Extension point ${t} not found`);return this.extensions[t][s]}get allExtensions(){return this.extensions}}const ge=(e=null)=>(e||window.location.search.replace("?","")).split("&").map(t=>{const[s,r]=t.split("=");return[s,decodeURIComponent(r||"")]}).reduce((t,[s,r])=>(t[s]=r,t),{}),ka="studio.tools.preview",Fh="studio.relax.store.validation",La="studio.log.debug",Fa="studio.log.info",Nh={profiles:[ka]};var Zi;const Uh=((Zi=globalThis.getKosConfig)==null?void 0:Zi.call(globalThis))||JSON.stringify(Nh),Na=JSON.parse(Uh);globalThis.kosConfig=Na;const Qo=Na,Ua=()=>Qo.profiles||[],go=e=>Ua().includes(e),jh=()=>Qo.logging||!1,Bh=()=>{const e=go(La),t=go(Fa);return e?"DEBUG":t?"INFO":void 0},ja=()=>{const e=ge(),t=Bh(),r=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Ba=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Ka=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Ha="ws-log",Kh=C.methodFactory,za=Ba(),Hh=Ka();C.methodFactory=function(e,t,s){const r=Kh(e,t,s);return function(o,n){var c;const i=s?String(s):"",a=i?`[${String(i).substring(i.lastIndexOf(":")+1)}] | `:"[root] | ";r(`${a}${o}`,n||""),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==Ha||za&&Hh)&&globalThis.kosLog(`UI: ${a}${o}`)}};let Va=ja();C.setLevel(Va);window.setKosLogLevel=e=>{Va=e,C.setLevel(e)};const Xs=C.getLogger(Ha);window.enableKosMessageLog=()=>{Xs.setLevel(C.levels.INFO)};window.disableKosMessageLog=()=>{Xs.setLevel(C.levels.ERROR)};za?window.enableKosMessageLog():window.disableKosMessageLog();const zh=["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(";"),Vh=["color: black","display: block","padding: 4px","background-color: yellow","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),Ps=e=>t=>{C.getLevel()<=e&&t()},m={...C,ifDebug:Ps(C.levels.DEBUG),ifInfo:Ps(C.levels.INFO),ifWarn:Ps(C.levels.WARN),ifError:Ps(C.levels.ERROR),getLogger:e=>C.getLogger(`kos::${e}`),getLoggers:()=>C.getLoggers(),createLogger:({name:e,group:t})=>{var n,i,a,c;const s=`${t?`${t}:`:"kos"}::${e}`,r=C.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(u=>u.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Xs.info(`%c⬆ ${t}`,zh)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Xs.info(`%c⬇ ${t}`,Vh)}},Ga="featureFlagResolver",ks=new Map;Ss(Ga,{register:(e,t)=>{var s;ks.has(e)||ks.set(e,[]),(s=ks.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=ks.get(e);if(!s)return[];const r=s.map(a=>a(t)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${e} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return qa.updateFlags(i),Object.keys(i)}});const Gh="kos.loader.featureFlag";class Ya{constructor(t={}){l(this,"flags",{});this.flags=t}isFeatureEnabled(t){return!!this.flags[t]}enableFeature(t){this.flags[t]=!0}disableFeature(t){this.flags[t]=!1}toggleFeature(t){this.flags[t]=!this.flags[t]}updateFlags(t){this.flags={...this.flags,...t}}}window.KosFeatureFlags=window.KosFeatureFlags??new Ya;const qa=window.KosFeatureFlags,Wa=(e,t,s)=>{s/=100;const r=t*Math.min(s,1-s)/100,o=n=>{const i=(n+e/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},Qa=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return Wa(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Za=(e,t)=>getComputedStyle(e).getPropertyValue(t),Yh=(e,t)=>Qa(Za(e,t)),qh=(e,t)=>{const s={...e};return s.id&&delete s.id,s},mo=(e,t,s=qh)=>{const r=s(e,t);E.runInAction(()=>{Object.assign(t,r)})},eo=new Map,Xa={addToDeletionQueue:(e,t)=>{const s=eo.get(e)||[];s.push(t),eo.set(e,s)},cancelDeletion:e=>{const t=eo.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},Wh=m.createLogger({name:"kos-dependency-manager"});class Qh{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(t,s){Xa.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(t)||r.push(t),this._usedByCache.set(s,r);const o=this._usesCache.get(t)||[];o.includes(s)||o.push(s),this._usesCache.set(t,o)}remove(t,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==t));const o=this._usesCache.get(t)||[];this._usesCache.set(t,o.filter(n=>n!==s))}canDestroy(t){const s=this._usedByCache.get(t);return s!=null&&s.length?(Wh.info(`Model ${t} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var v=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.READY_FAILED="ready_failed",e.RESETTING="resetting",e.RESET="reset",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.FAILED="failed",e.INACTIVE="inactive",e.ACTIVE="active",e.ACTIVATING="activating",e.DEACTIVATING="deactivating",e))(v||{}),P=(e=>(e.CREATE="create",e.INITIALIZE="init",e.LOAD="load",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.RESET="go_offline",e.UNLOAD="unload",e.FAILED="failed",e.GO_ACTIVE="go_active",e.GO_INACTIVE="go_inactive",e.TIMEOUT="timeout",e))(P||{});const fi=m.createLogger({name:"kos-model-cache"});class Zh{constructor(t=[]){l(this,"_modelsById",E.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=t}get models(){return Array.from(this._modelsById.values()).map(t=>t).filter(t=>!this._toDelete.has(t.modelId))}getModelById(t){if(t&&!this._toDelete.has(t))return this._modelsById.get(t)}addModel(t){const s=this.getModelById(t.modelId)||t;return this._modelsById.set(s.modelId,s),s}removeModel(t){this._modelsById.delete(t),this._toDelete.delete(t)}hasModel(t){return!!t&&this._modelsById.has(t)&&!this._toDelete.has(t)}restoreFromDeleteCache(t){if(t&&this._toDelete.has(t)){const s=this._toDelete.get(t);this._toDelete.delete(t),this._modelsById.set(t,s)}}markForDeletion(t){this._modelsById.delete(t.modelId),this._toDelete.set(t.modelId,t)}preload(t){return this._isPreloaded?(fi.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(fi.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const ee=Symbol("SubscriptionHandlers"),k=Symbol("DependencyModels"),os=Symbol("FutureService"),Be=Symbol("ChildModels"),ns=Symbol("ParentModel"),is=Symbol("LogConfig"),Vs=Symbol("ReferenceConfig"),Zo=Symbol("KosModelSymbol"),Ze=Symbol("ModelEffects"),bt=Symbol("CompanionParentModel"),Xo=Symbol("FutureContainerSetup"),Jo=Symbol("TroubleAwareSetup"),en=Symbol("LoggerSetup"),tn=Symbol("ContainerAwareSetup"),Oe=(e,t)=>{e[Be]=e[Be]||{},e[Be][t]=!0},st=e=>`{PROP_${String(e)}}`,Xh=e=>`{PROP_${String(e)}}`,Jh=st("kosParentId"),xr=e=>t=>{t[ns]=t[ns]||{};const s=(e==null?void 0:e.parentId)||Jh;t[ns]={parentId:s}};function ef(e){return t=>{const s=(e==null?void 0:e.mode)||"decorator",r=(e==null?void 0:e.parentProperty)||"companionParent",o=(e==null?void 0:e.excludeProperties)||[];return xr()(t),t.prototype[bt]={mode:s,parentProperty:r,excludeProperties:o},t}}function Ja(e){return t=>{const s=e!=null&&e.legacy?"_models":(e==null?void 0:e.containerProperty)||"container",r=(e==null?void 0:e.includeMethods)!==!1,o=(e==null?void 0:e.includeGetters)!==!1,n=(e==null?void 0:e.modelsProperty)||"models",i=(e==null?void 0:e.containerOptions)||{};return t.prototype[tn]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(e==null?void 0:e.legacy)||!1},t}}function tf(e,t,s){const r=s.value;s.value=function(...o){const n=G.getContext(this.id);return o.push(n),r.apply(this,o)}}function sf(e){return t=>{const s=(e==null?void 0:e.mode)||"full",r=(e==null?void 0:e.handlerProperty)||"futureHandler";return t.prototype[Xo]={mode:s,handlerProperty:r},t}}var H=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(H||{});const rf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:H},Symbol.toStringTag,{value:"Module"})),xe=Symbol("HttpRouteHandlers"),pi="__httpBrowserRouter";function Ar(e){return function(s){return function(r,o,n){r[xe]=r[xe]||[];const i={method:e,path:s,handler:o};return r[xe].push(i),r[k]=r[k]||{},r[k][pi]||(r[k][pi]={modelType:"browser-router-model",lifecycle:H.INIT}),n}}}const ec=Ar("GET"),$s=Ar("POST"),of=Ar("PUT"),tc=Ar("DELETE"),nf=tc;function Js(e){return!!(e!=null&&e[xe])&&e[xe].length>0}function sc(e){return(e==null?void 0:e[xe])||[]}const af=({group:e}={group:""})=>t=>{t[is]=t[is]||{},t[is]={group:e}};class rc{static create({modelId:t,modelTypeName:s,component:r}){const o=[r??"kos",s,t].filter(Boolean).join(".");return m.createLogger({name:o})}}function oc(e){return t=>{const s=(e==null?void 0:e.loggerProperty)||"logger",r=e==null?void 0:e.loggerContext;t.prototype[en]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=t.prototype[Zo])==null?void 0:i.type};let n;return Object.defineProperty(t.prototype,s,{get(){if(!n){const i=o();n=rc.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),t}}function nc(e){return(t,s,r)=>{t[Ze]=t[Ze]||{},t[Ze][s]={dependencies:e==null?void 0:e.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const cf=e=>(t,s)=>{t[Vs]=t[Vs]||{},t[Vs][s]=e};function lf(e){return t=>{const s=(e==null?void 0:e.pathProperty)||"path";return t.prototype[Jo]={pathProperty:s},t.prototype[k]=t.prototype[k]||{},t.prototype[k].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},t}}const Rt=({modelType:e,id:t,options:s,lifecycle:r})=>(o,n)=>{o[k]=o[k]||{},o[k][n]={modelType:e,id:t,options:s,lifecycle:r||H.INIT}};class uf{constructor(t,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=hn.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,E.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(t,s){this.futures.set(s||t.id,t),this.context=s||t.id;const r=Y(()=>{var o,n;(t.endState||t.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,t))});this.disposers.set(s||t.id,r)}removeFuture(t){var s;this.futures.delete(t||this.context),(s=this.disposers.get(t||this.context))==null||s(),this.disposers.delete(t||this.context)}getFuture(t){return this.futures.get(t||this.context)}get futureMap(){return this.futures}}class Rr{constructor(t){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=t,E.makeAutoObservable(this)}removeFuture(){var t;this._future=void 0,(t=this.disposer)==null||t.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(t){this._future=t;const s=Y(()=>{var r,o;(t.endState||t.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw m.error(t),t}}}const ic=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},ac=Symbol("KosObservableData");class cc{constructor(){l(this,"map");l(this,"_revision",1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(t,s)=>{var r;return s==="_revision"||t[s]!==void 0?t[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(t,s,r)=>{var o;return this.map.has(s),this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,E.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>[...Array.from(this.map.keys()),"_revision"]});this.map=E.observable.map(new Map),E.makeObservable(this,{_revision:E.observable})}setValue(t,s){const r=this.map.has(t);this.map.set(t,s),r||E.action(()=>{this._revision++})()}getValue(t){return this.map.get(t)}has(t){return this.map.has(t)}get entries(){return Array.from(this.map.entries())}get keys(){return this._revision,Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(t){t&&Object.keys(t).forEach(s=>{this.setValue(s,t[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}cc.prototype[ac]=!0;function df(e,t){return new Proxy(e,{construct:(s,r)=>{const o=new e(...r);return o.setValues(t),o.proxy}})}const Te=e=>{const t=df(cc,e);return new t(e)};function hf(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class sn{constructor({container:t,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=t,this._map=E.observable.map(new Map),this._key=s,this.data=Te(),this.generateIndex(),E.autorun(()=>{this._container.revision&&this.generateIndex()}),E.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(t,s,r=this._map,o=this.data){const n=r.get(t)||new Set;n.add(s),r.set(t,n),o[t]=Array.from(n)}resolveIndex(t,s){this.data.keys.filter(o=>!Object.keys(s).includes(o)).forEach(o=>{delete this.data[o],this._map.delete(o)}),Object.keys(s).forEach(o=>{const n=s[o],i=this.data[o]||[];if(hf(n,i))m.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=t.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){E.runInAction(async()=>{const t=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,t,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,t,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,t,s)}this.resolveIndex(t,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(t){const s=this._map.get(t);return s?Array.from(s):[]}}function ff(e,t,s=[]){const r=Object.getOwnPropertyDescriptors(e);return Object.keys(r).filter(i=>E.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>E.reaction(()=>e[i],(a,c)=>{t({name:i,newValue:a,oldValue:c})}))}const Kt=m.createLogger({name:"kos-container-model"});class Se{constructor(t){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");this._data=E.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?S.indexExtension.loadIndexExtensions(t.extensionId):{},r=(t==null?void 0:t.indexMap)||{};this._optionsMap={...r,...s};const o=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=E.observable.map(o),this.idx=Te(),this._parentId=t==null?void 0:t.parentId,E.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],r=new sn({container:this,key:s});this._index.set(t,r),this.idx[t]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((t,s)=>{var r;return t[s]=(r=this.index.get(s))==null?void 0:r.keys,t},{})}sortFn(t,s){const r=this._sortKey;return r?String(t[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){E.runInAction(()=>{this._revision=this._revision+1})}addAll(t){E.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){E.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&G.setParentContext(t.id,this._parentId),s||this.increment();const r=this._disposerMap.get(t.id);r&&(r(),this._disposerMap.delete(t.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([d,h])=>[h,d])),a=d=>{var f,p;n.includes(d.name)&&((f=this.index.get(i.get(d.name)))==null||f.refresh());const h=o.filter(([,b])=>typeof b=="function");for(const[b]of h)(p=this.index.get(b))==null||p.refresh()},c=ff(t,a,n.filter(d=>typeof d=="string")),u=E.observe(t,a);this._disposerMap.set(t.id||"",()=>[u,...c].forEach(d=>d()))}removeModel(t,s){this._data.delete(t),s||this.increment();const r=this._disposerMap.get(t);r&&(r(),this._disposerMap.delete(t))}updateModel(t){this._data.set(t.id||"",t),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(Kt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const r=this.index.get(t);return r.index.has(s)?r.getByKey(s):(Kt.info(`key ${s} not found in ${t} index: ${Array.from(r.index.keys())}`),[])}else return Kt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Xe(t).then(()=>{Kt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Kt.error(r))}),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const ue=async e=>{if(e.id){const t=O.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error(`Model with ID ${e.id} not found`);await(t==null?void 0:t.whenReady())}else throw new Error("Data model must have a valid ID");return e},Xe=async e=>{await O.getInstance().whenReady(),await O.getInstance().modelManager.initiateDestroyModel(e)},pf=async e=>{if(await O.getInstance().whenReady(),!e.id)throw new Error("Model ID is required");const t=O.getInstance().modelManager.getModelById(e.id);t&&await t.fsm.transitionTo(P.UNLOAD,v.UNLOADED)},gf=async e=>{await O.getInstance().whenReady(),await O.getInstance().modelManager.reloadModel(e),m.debug(`reload model initiated for model ${e.id}, model ready: ${er(e)} - ${Date.now()} `),await ue(e),m.debug(`reload model complete for model ${e.id}, model ready: ${er(e)} - ${Date.now()} `)},mf=async e=>{if(await O.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=O.getInstance().modelManager.getModelById(e);return t==null?void 0:t.modelTypeName},lc=async e=>{if(await O.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=O.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},_e=e=>{if(!e)throw new Error("Model ID is required");const t=O.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},uc=(e,t)=>{if(!e)throw new Error("Model type is required");return O.getInstance().modelManager.getModelsByType(e).filter(o=>Object.keys(t).every(n=>o[n]===t[n]))},yf=(e,t)=>uc(e,t)[0],bf=(e,t)=>{if(!e.id)throw new Error("Model ID is required");const s=O.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(t);return r==null?void 0:r.modelData},dc=e=>{if(!e.id)throw new Error("Model ID is required");const t=O.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return Array.from(t.companionModels.all()).map(r=>r.modelData)},vf=e=>{if(!e)throw new Error("Model ID is required");const t=O.getInstance().modelManager.getModelById(e);if(!t)throw new Error("Model not found");return t.companionModels.data},yo=(e,t)=>{const s=O.getInstance().modelManager.getModelById(e);if(!s){m.info(`Model not found for id ${e}`);return}return Array.from(s.companionModels.all()).find(o=>t(o.modelData))},Ee=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,er=e=>{const t=O.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},wf=m.createLogger({name:"kos-model-factory"}),as={byModelType:e=>O.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const r=as.byModelType(t);if(!r)throw wf.error(`No registered factory found for model type ${t}. Please register a factory for this model type. `),Error(`No factory found for model type ${t}`);return r.build(e,s)}},ie={Factory:{create:e=>t=>(s,r)=>(r&&G.setParentContext(t,r),as.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&G.setParentContext(e,s),as.getModelInstance(e,e,t))},Model:{instance:e=>t=>as.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const gi=window.KosRegistry.coreModels,to=window.KosRegistry.preloadModels,so=window.KosRegistry.companionModels,Ls=window.KosRegistry.models,x={model:{registerLegacyModel:e=>(t,s)=>(gi.set(t,s),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(to.includes(t)||to.push(t),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const r=ro(t)?t.registration():t;return Ls.set(r.type,r),ro(t)&&t.relatedModels.forEach(o=>Ls.set(o.type,o.registration())),O.getInstance().isReady&&(O.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),O.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],ro(t)&&t.relatedModels.forEach(o=>O.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&x.model.preloadModel(e)(r.type),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}},get:e=>Ls.get(e),getAll:()=>Array.from(Ls.entries()),getPreloadModels:()=>to,getLegacyModels:()=>Array.from(gi.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const r=so.get(t)||[];return r.push(s),so.set(t,r),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(so.entries())}},hc=x.model.registerLegacyModel,fc=x.model.register,Ef=x.companion.register,Mf=x.model.preloadModel,pc=e=>typeof e.updateModel=="function",ro=e=>e.registration!==void 0&&typeof e.registration=="function";class gc{constructor(t){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=Ee(t.type),this.type=t.type,this.loader=`kos.extension.model.loader.${t.type}`,this.factory=t.factory,this.class=t.class}addRelatedModel(t){this.relatedModels.push(t)}registerRelatedModels(){this.relatedModels.forEach(t=>t.register())}register(){x.model.register({})(this.registration()),this.registerRelatedModels()}}class me extends gc{constructor(t){super({...t,singleton:!1,factory:ie.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const r=_e(t);if(!r)throw new Error("Model not found with id "+t);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(pc(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error("Model is not of type "+this.type)}})},options:r=>({build:()=>{const o=s(r);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class Me extends gc{constructor(t){super({...t,singleton:!0,factory:ie.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const r=_e(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=t(r);if(this.guard(o)){if(pc(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})},options:r=>({build:()=>{const o=t(r);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const vt=({value:e,modelId:t,modelData:s})=>{let r=e;if(Array.isArray(r))return[...e];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=vt({value:r[n],modelId:t,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp(".*({PROP_(.+)})");let n=r!=null&&r.includes(Zs)?r.replace(Zs,t):r;const i=n.match(o);if(i&&s&&(Object.getOwnPropertyNames(s).includes(i[2])||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(i[2]))){const a=s[i[2]];n=a?n.replace(i[1],a):void 0}return n}else return r;return r},bo=m.createLogger({group:"decorators",name:"kos-model"});function Tf(e,t,s){var n;const r=(n=e[ns])==null?void 0:n.parentId;if(!r)return;const o=vt({value:r,modelData:s,modelId:t});o&&typeof o=="string"&&G.setParentContext(t,o)}function _f(e){const t=e[os];t&&Object.entries(t).forEach(([s,{handler:r}])=>{e[s]=r})}function If(e,t){const s=e[k]||{};Object.entries(s).forEach(([r,o])=>{const n=vt({value:o.id||o.modelType,modelData:e,modelId:t}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,u])=>(a[c]=vt({value:u,modelData:e,modelId:t}),a),{});if(typeof n=="string"){if(!o.lazy){const a=O.getInstance().modelManager.createModelInstance(o.modelType,n,i);e[r]=a.data}O.getInstance().modelManager.addDependency(t,n)}})}function Of(e){const t=e[Xo];if(!t)return;const{mode:s,handlerProperty:r}=t,o=new Rr(e);e[r]=o,s==="full"&&(Object.defineProperty(e,"future",{get(){return o.future},enumerable:!0,configurable:!0}),Object.defineProperty(e,"progress",{get(){var n;return((n=o.future)==null?void 0:n.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"status",{get(){var n;return((n=o.future)==null?void 0:n.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isCancelled",{get(){var n;return((n=o.future)==null?void 0:n.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function Sf(e){const t=e[Jo];if(!t)return;const{pathProperty:s}=t;Object.defineProperty(e,"troubles",{get(){const r=this[s];if(r==null){const o=`@kosTroubleAware: Path property '${s}' is undefined on model ${this.id||"unknown"}. Returning empty troubles array.`;return this.logger&&typeof this.logger.warn=="function"?this.logger.warn(o):console.warn(o),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((o,n)=>n.rank-o.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(e,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(e,"troublesByType",{get(){return this.troubles.reduce(ic,{})},enumerable:!0,configurable:!0})}function $f(e,t){const s=e[tn];if(!s)return;const{containerProperty:r,includeMethods:o,includeGetters:n,modelsProperty:i,containerOptions:a,legacy:c}=s,u={...a,parentId:a.parentId||t},d=new Se(u);e[r]=d,e[Be]||(e[Be]={}),e[Be][r]=d,o&&(e.getModel=h=>d.getModel(h),e.addModel=h=>{d.addModel(h)},e.removeModel=h=>{d.removeModel(h)}),n&&(Object.defineProperty(e,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(e,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function Cf(e,t){const s=e.constructor.prototype[bt];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=t[o];if(!i){bo.warn(`Companion decorator configured but no parent model found at '${o}'`);return}if(e.getCompanionParent=()=>i,r==="composition")return;const a=["init","load","unload","ready","dispose","destroy","activate"],c=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace","getCompanionParent"],u=p=>{const b=i.constructor.prototype[ee]||{};return Object.values(b).some(w=>{const M=w==null?void 0:w.handler;return M===i[p]||M===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||c.includes(p)||n.includes(p)||u(p)||p in e,h=new Set;Object.getOwnPropertyNames(i).filter(p=>!d(p)).forEach(p=>h.add(p));let f=Object.getPrototypeOf(i);for(;f&&f!==Object.prototype;)Object.getOwnPropertyNames(f).filter(p=>!d(p)).forEach(p=>h.add(p)),f=Object.getPrototypeOf(f);for(const p of h)try{const b=i[p];typeof b=="function"?e[p]=(...w)=>b.apply(i,w):Object.defineProperty(e,p,{get:()=>i[p],set:w=>{i[p]=w},enumerable:!0,configurable:!0})}catch(b){bo.debug(`Skipping companion proxy for property ${p}:`,b)}}function Df(e){try{return E.makeAutoObservable(e)}catch(t){return bo.error("Failed to make observable:",t),e}}const xf={construct(e,t){var c;const[s,r={}]=t,o=G.createContext(s);Tf(e,s,r);const i=!!e.prototype[en]?null:m.createLogger({name:e.prototype.modelTypeId,group:((c=e[is])==null?void 0:c.group)??"kos-model"}),a=new e(s,r,{logger:i,kosContext:o});return _f(a),Of(a),Sf(a),$f(a,s),Cf(a,r),If(a,s),Df(a)}};function A(e){return t=>{var n,i;const s=t,r=typeof e=="string"?{modelTypeId:e,autoRegister:!1}:{autoRegister:!1,...e};s.prototype.modelTypeId=r.modelTypeId,s.prototype[Zo]=!0,(n=s.prototype)[ee]??(n[ee]={}),(i=s.prototype)[k]??(i[k]={}),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,xf);if(r.singleton!==void 0){let a;r.singleton?a=new Me({class:o,type:r.modelTypeId}):a=new me({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}const Af=({topic:e,handler:t,websocket:s=!1,condition:r=()=>!0})=>o=>{o[ee]=o[ee]||{},Array.isArray(e)?e.forEach(n=>{o[ee][n]={websocket:s,handler:t,condition:r}}):o[ee][e]={websocket:s,handler:Ra(o,E.action(t),200),condition:r}};function mc(e,t,s){const r={};if(!e.endsWith("/*"))return r;const o=e.slice(0,-2);if(t.startsWith(o)){const n=t.slice(o.length+1),i=s||"path";r[i]=n}return r}function yc(e){return e.endsWith("/*")}function U({topic:e,condition:t=(_,F)=>!0,transform:s=_=>_,websocket:r=!1,fos:o=!1,bridge:n=!1,skipParse:i=!1,lifecycle:a,destinationAddress:c,debounce:u,throttle:d,buffer:h,filter:f,once:p,replay:b,wildcardName:w,flow:M}){return(_,F,Q)=>{_[ee]=_[ee]||{};let I=Q.value;const W=typeof u=="number"?u:u==null?void 0:u.delay,B=typeof d=="number"?d:d==null?void 0:d.interval;W&&W>0?I=Rf(I,u):B&&B>0?I=Pf(I,d):h?I=kf(I,h):p&&(I=Lf(I));let J=t;if(f){const $e=t;J=(ci,li,Qr)=>f(Qr)?$e(ci,li,Qr):!1}const Ue={websocket:r,fos:o,bridge:n,handler:I,condition:J,transform:s,lifecycle:a,skipParse:i,destinationAddress:c,wildcardName:w,flow:M};Array.isArray(e)?e.forEach($e=>{_[ee][$e]=Ue}):_[ee][e]=Ue,b&&Ff(e,b.bufferSize)}}function Rf(e,t){const s=typeof t=="number"?t:t.delay,r=typeof t=="object"?t.discardIntermediate:!1;let o=null,n=[];return function(i){r?(o&&clearTimeout(o),o=setTimeout(()=>{e.call(this,i),o=null},s)):(n.push(i),o&&clearTimeout(o),o=setTimeout(()=>{const a=[...n];n=[],e.call(this,a),o=null},s))}}function Pf(e,t){const s=typeof t=="number"?t:t.interval,r=typeof t=="object"?t.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const u=[...i];i=[],e.call(this,u)}};return function(u){const d=Date.now(),h=d-o;r?h>=s?(o=d,e.call(this,u)):n||(n=setTimeout(()=>{o=Date.now(),e.call(this,u),n=null},s-h)):(i.push(u),h>=s?(o=d,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function kf(e,t){const s=[];let r=null;const o=t.maxSize||1e3,n=i=>{s.length>0&&(e.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=o){r&&(clearTimeout(r),r=null),n(this);return}r||(r=setTimeout(()=>{n(this),r=null},t.time))}}function Lf(e){let t=!1;return function(s){t||(t=!0,e.call(this,s))}}function Ff(e,t){(Array.isArray(e)?e:[e]).forEach(r=>{zo(r,t)})}function bc(e,t){return`${Bo}${e}${t?`/${t}`:`/${e}`}`}function vc(e){return`${Bo}${e}`}function oo(e){const t=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of e){const i=E.when(o,()=>{t.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});t.push(i)}})}const wc=5e3;class Nf extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const Ec=(e,t,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} - ${s} timed out after ${e}ms`),a(new Nf(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{r&&clearTimeout(r)}}},Mc=e=>e.fsm.transitionTo(P.GO_ACTIVE,v.ACTIVE),Tc=e=>e.whenReady(),_c=e=>e.fsm.transitionTo(P.LOAD,v.LOADED),Uf=e=>e.fsm.transitionTo(P.UNLOAD,v.UNLOADED),Ic=e=>e.fsm.transitionTo(P.INITIALIZE,v.INITIALIZED);var rn=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(rn||{});const Gs={active:Mc,ready:Tc,load:_c,init:Ic},Oc=(e,t)=>{const s=t.id||t.modelType,r=vt({value:s,modelData:e.modelData,modelId:e.modelId});m.debug(`activating dependent model ${t.modelType} with id ${r}`);const o=Object.keys((t==null?void 0:t.options)||{}).reduce((i,a)=>{const c=t.options[a];return i[a]=vt({value:c,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:O.getInstance().modelManager.createModelInstance(t.modelType,r,o),dataModelId:r}},Sc=(e,t=H.READY)=>{var o;const s=((o=e.modelData)==null?void 0:o[k])||{};return Object.keys(s).length===0?(m.debug(`${e.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===t).map(n=>{const i=s[n],{dependentModel:a,dataModelId:c}=Oc(e,i);e.modelData[n]=a.data,m.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const u=async(f,p,b)=>{var w;await((w=f.whenReady)==null?void 0:w.call(f)),m.debug(`dependent model ${p} with id ${b} - READY`)},{promise:d,cancel:h}=Ec(wc,e,e.status);return Promise.race([u(a.model,i.modelType,c).then(()=>{h()}).catch(f=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${c}:`,f),h()}),d])}).filter(n=>!!n)},$c=async(e,t,s,r)=>{if(m.debug(`Execute lifecycle with ${t.length} models`),t.length===0){m.debug(`${e.modelId} has no children. Returning`);return}if(!s){m.error(`${e.modelId} is not transitioning with a valid target ${s}`);return}const o=t.map(a=>{let c;return Gs[s]&&a?c=Gs[s](a):(a||m.error("model is undefined. This shouldn't happen"),Gs[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),i=(await Promise.allSettled(o.map(a=>{var d;const{promise:c,cancel:u}=Ec(wc,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{m.error(`Model ${a.modelId} - ${a.type} failed to transition to ${s}: ${h.message}`),u()}),c])}))).filter(a=>a.status==="rejected");i.length>0&&m.error(`Model ${e.modelId} had ${i.length} failed child models on ${r}`)},Cc=async(e,t,s)=>{await $c(e,e.getChildren().filter(r=>!!r),t,s)},zt=async(e,t)=>{const r=(await Promise.allSettled(Sc(e,t))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${t}`),m.error(r))},jf=e=>typeof e.toJSON=="function",cs=e=>e[k]!==void 0,on=e=>e.revision!==void 0&&e.index!==void 0,Dc=e=>{if(e){if(cs(e))return e;if(on(e))return e.data;if(e instanceof Map||e instanceof E.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(cs);if(Array.isArray(e))return e.filter(cs)}};function Bf(e){const t=`KosModel(${e.modelTypeName}:${e.modelId})`;try{Object.defineProperty(e,Symbol.toStringTag,{value:t,configurable:!0})}catch{e.toString=()=>t}try{Object.defineProperty(e.constructor,"name",{value:`KosModel_${e.modelTypeName}`,configurable:!0})}catch{e.constructor.name=`KosModel_${e.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in e&&Object.defineProperty(e,r,{enumerable:!1});Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:e.modelId,type:e.modelTypeName,initialized:e.initialized,loaded:e.loaded,status:e.status,onlineStatus:e.onlineStatus,activeStatus:e.activeStatus,companions:(o=(r=e.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=e.getChildren)==null?void 0:n.call(e).map(i=>i.modelId),effects:!!e.effectManager,subs:!!e.subscriptionManager}}}),Kf(e.modelData,e.modelTypeName,e.modelId,e)}function Kf(e,t,s,r){Object.defineProperty(e,Symbol.toStringTag,{value:`KosModelData(${t}:${s})`,configurable:!0});try{Object.defineProperty(e.constructor,"name",{value:`${t}ModelData`,configurable:!0})}catch{e.constructor.name=`${t}ModelData`}Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[k]||{};return{id:s,type:t,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=e.toJSON)==null?void 0:u.call(e))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(e,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(e))if(!(n.startsWith("_")||typeof e[n]=="function"))try{const i=e[n];cs(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:on(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class Hf{constructor(t){this.model=t}resolve(){const t=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(t).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{G.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const t=((s=this.model.modelData)==null?void 0:s[Be])||{};return Object.keys(t).map(r=>Dc(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.model.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}}class zf{constructor(t){l(this,"companions",new E.ObservableMap);this.hostModel=t}add(t){this.companions.set(t.modelTypeName,t)}clear(){this.companions.clear()}get(t){return this.companions.get(t)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Vf{constructor(t,s,r,o){l(this,"disposers",[]);this.modelTypeName=t,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const t=((s=this.modelData)==null?void 0:s[Ze])||{};for(const r of Object.keys(t)){const{value:o,dependencies:n,options:i}=t[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),E.runInAction(()=>a())},u=n?E.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):E.autorun(c);this.disposers.push(u)}}disposeAll(){for(const t of this.disposers)try{t()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Gf=m.createLogger({name:"model-active-machine"}),Yf=e=>{const t=y.createMachine(v.INACTIVE,{[v.FAILED]:y.state(y.transition(P.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:y.state(y.transition(P.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:y.invoke(()=>(e.activeStatus=v.ACTIVATING,e.activate()),y.transition("done",v.ACTIVE,y.action(()=>{e.activeStatus=v.ACTIVE})),y.transition("error",v.FAILED,y.action(()=>{e.activeStatus=v.FAILED}))),[v.ACTIVE]:y.state(y.transition(P.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:y.invoke(()=>(e.activeStatus=v.DEACTIVATING,e.deactivate()),y.transition("done",v.INACTIVE,y.action(()=>{e.activeStatus=v.INACTIVE})),y.transition("error",v.FAILED,y.action(()=>{e.activeStatus=v.FAILED})))});return{service:y.interpret(t,r=>Gf.debug(r.machine.current)),machine:t}},mi=m.createLogger({name:"model-online-machine"}),qf=e=>{const t=y.createMachine(v.OFFLINE,{[v.ONLINE]:y.state(y.transition(P.GO_OFFLINE,v.OFFLINE,y.action(async()=>{await e.offline(),e.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:y.state(y.transition(P.GO_ONLINE,v.ONLINE,y.action(async()=>{mi.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=v.ONLINE,await e.fsm.transitionTo(P.INITIALIZE,v.INITIALIZED)})))}),s=y.interpret(t,r=>mi.debug(r.machine.current));return{machine:t,service:s}},Wf=e=>{var r;const t=Yf(e).service,s=qf(e).service;return y.createMachine(v.CREATING,{[v.CREATING]:y.state(y.transition(P.CREATE,v.CREATED)),[v.CREATED]:y.state(y.immediate(v.INITIALIZING)),[v.INITIALIZING]:y.invoke(()=>(X(()=>{e.status=v.INITIALIZING}),e.init()),y.transition("done",v.INITIALIZED,y.action(()=>{e.status=v.INITIALIZED})),y.transition("error",v.FAILED,y.action(()=>{m.error(`Model ${e.modelId} - ${e.modelTypeName} failed to initialize. Transitioning to FAILED state.`),e.status=v.FAILED}))),[v.INITIALIZED]:y.state(y.immediate(v.LOADING)),[v.LOADING]:y.invoke(()=>(X(()=>{e.status=v.LOADING}),e.load()),y.transition("done",v.LOADED,y.action(()=>{e.status=v.LOADED})),y.transition("error",v.FAILED,y.action(()=>{e.status=v.FAILED}))),[v.LOADED]:y.state(y.immediate(v.READYING),y.transition(P.UNLOAD,v.UNLOADING)),[v.RESETTING]:y.invoke(()=>{var o;return X(()=>{e.status=v.RESETTING}),(o=e.unload)==null||o.call(e),e.load()},y.transition("done",v.LOADED,y.action(()=>{e.status=v.LOADED}))),[v.READYING]:y.invoke(()=>(X(()=>{e.status=v.READYING}),e.ready()),y.transition("done",v.READY,y.action(()=>{X(()=>{e.status=v.READY}),s.send(P.GO_ONLINE)})),y.transition("error",v.FAILED,y.action(()=>{e.status=v.FAILED}))),[v.READY]:y.state(y.transition(P.UNLOAD,v.UNLOADED,y.action((r=e.unload)==null?void 0:r.bind(e))),y.transition(P.RESET,v.RESETTING),y.transition(P.GO_ONLINE,v.READY,y.action(()=>{s.send(P.GO_ONLINE)})),y.transition(P.GO_OFFLINE,v.READY,y.action(()=>{s.send(P.GO_OFFLINE)})),y.transition(P.GO_ACTIVE,v.READY,y.action(()=>{t.send(P.GO_ACTIVE)})),y.transition(P.GO_INACTIVE,v.READY,y.action(()=>{t.send(P.GO_INACTIVE)}))),[v.UNLOADED]:y.state(),[v.FAILED]:y.state()})},Qf=m.createLogger({name:"kos-model-lifecycle"}),Zf=e=>({service:y.interpret(Wf(e),s=>Qf.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class Xf{constructor(t,s){l(this,"disposer");l(this,"service");this.model=t,this.log=s;const r=Zf(t);this.service=r.service,this.service.send(P.CREATE)}get current(){return this.service.machine.current}async transitionTo(t,s,r=v.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${t} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=E.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${t}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(t)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(t){return[v.ACTIVE,v.INACTIVE].includes(t)?this.model.activeStatus:this.model.status}}const xc="browser-router-model";class nn{constructor(t,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=t,this.logger=s}registerAll(){var s;if(!Js(this.model))return;let t=this.model.__httpBrowserRouter;if(!t)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){t=o;break}}if(t||(t=(s=_e(xc))==null?void 0:s.model),!t)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(t)}setRouter(t){this.router=t,this.registered||this.registerRoutes()}hasRoutes(){return Js(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const t=sc(this.model);t.length!==0&&(this.logger.debug(`Registering ${t.length} HTTP routes`),t.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(t){const s=/\{PROP_([^}]+)\}/g;let r=t;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(t))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${t}`)}return r}registerRoute(t){if(!this.router)return;const s=this.model[t.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${t.handler}' not found on model`);return}const r=this.resolvePropKey(t.path);this.logger.debug(`Registering ${t.method} ${r} -> ${t.handler}`+(r!==t.path?` (resolved from ${t.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${t.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(t.method,r),this.router.use(t.method,r,o),this.registeredRoutes.push({method:t.method,path:r})}checkForDuplicateRoute(t,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===t&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${t} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let t=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);t+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${t} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function Jf(e,t){if(!Js(e))return;const s=_e(xc);if(!(s!=null&&s.model))throw t.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new nn(e,t).setRouter(s.model)}class ep{constructor(t){l(this,"queue",[]);this.log=t}enqueue(t){this.queue.push(t)}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const t of this.queue)try{t()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class tp{constructor(t,s){l(this,"unsubscribers",[]);this.model=t,this.log=s}register(){const t=this.model.modelId,s=$("/kosCore/online",async()=>{this.log.debug(`Online event received for ${t}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${t} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(P.GO_ONLINE,v.ONLINE)}),r=$("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${t} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(P.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(t=>t()),this.unsubscribers=[]}}class sp{constructor(t){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=t,this.subscription={queue:[],resolvers:[],closed:!1};const s=$(t,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(t=>{this.subscription.closed?t({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{t({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(t=>{t(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(t){throw this.subscription.closed=!0,this.unsubscribe(),t}[Symbol.asyncIterator](){return this}}function yi(e){return new sp(e)}var Ac=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(Ac||{});const Rc=({path:e,requestId:t,method:s,destinationAddress:r})=>{let o=`${Or}:${s}
|
|
1
|
+
"use strict";var gh=Object.defineProperty;var mh=(e,t,s)=>t in e?gh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var l=(e,t,s)=>(mh(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("loglevel"),E=require("mobx"),y=require("robot3"),je=require("date-fns"),T=require("@emotion/react/jsx-runtime"),Fo=require("@emotion/styled"),ea=require("react-dom"),qe=require("@emotion/react"),g=require("react"),No=require("mobx-react-lite"),yh=require("@use-gesture/react"),Sr="method",ta="topic",At="url",Is="request-id",$r="response-id",Uo="status",Le="dst-addr",sa="src-addr",Oe="type",jo="ordered",Bo="tracker",ra="Content-Type",oa="Cache-Control",na="requestId",ia=process.env.KOS_LOGIN_URL||"http://localhost",aa=process.env.KOS_APP_PORT||"8080",bh=`${ia}:${aa}`,Xs="{MODEL_ID}";var Ss=(e=>(e.SEND="/ws/log/msg/send",e.RECEIVED="/ws/log/msg/receive",e))(Ss||{}),ca=(e=>(e.MSG_RECEIVE="/mock/msg/receive",e))(ca||{});const Ko="/kos/model/ready/";C.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const K=globalThis.kos.subscriptions,vh=()=>Symbol("eventKey");function Ho(e){return K[e]&&Object.getOwnPropertySymbols(K[e]).length>0}function $(e,t){const s=vh();return K[e]||(C.debug(`Initializing subscription for ${e}`),K[e]={}),C.debug(`Subscribing to ${e} with id ${s.toString()}`),K[e][s]=t,{count:K[e]?Object.getOwnPropertySymbols(K[e]).length:0,unsubscribe:()=>(C.debug(`Unsubscribing from ${e} with id ${s.toString()}`),K[e]&&K[e][s]&&delete K[e][s],K[e]&&Object.getOwnPropertySymbols(K[e]).length===0&&delete K[e],{count:K[e]?Object.getOwnPropertySymbols(K[e]).length:0})}}function z(e,t,s={}){if(!K[e]||Object.getOwnPropertySymbols(K[e]).length===0)return C.debug(`No subscriptions for ${e}. Not publishing.`),{eventType:e,subscribers:0};const r=Object.getOwnPropertySymbols(K[e]).length;return Object.getOwnPropertySymbols(K[e]).forEach(o=>{if(s.sync){const n=s.sync;C.debug(`Performing sync publish for ${e} with sync id ${n}`),K[e][o]({body:t,headers:s}).then(i=>{C.debug(`Response recieved for ${n}, publishing back to source.`),z(n,i)})}else C.debug(`Performing async publish for ${e}`),K[e][o]({body:t,headers:s})}),{eventType:e,subscribers:r}}function wh(){C.warn("Resetting event bus"),Object.keys(K).forEach(e=>delete K[e])}function la(e,t){const s=$(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function zo(e,t){return new Promise((s,r)=>{let o=null;const n=la(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}const Eh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:Ho,once:la,publish:z,reset:wh,subscribe:$,waitFor:zo},Symbol.toStringTag,{value:"Module"}));function Cr(e,t){const s=$(e,r=>{s.unsubscribe(),t(r)});return s.unsubscribe}function Dr(e,t){return new Promise((s,r)=>{let o=null;const n=Cr(e,i=>{o&&clearTimeout(o),s(i)});t&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${e}`))},t))})}function ua(e,t){const s=e.map(r=>Dr(r,t));return Promise.all(s)}function da(e,t){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};e.forEach(c=>{const u=Cr(c,d=>{i||(i=!0,a(),s({eventType:c,data:d}))});o.push(u)}),t&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${e.join(", ")}`)))},t))})}function ha(e,t,s){return $(e,o=>{o&&t(o)&&s(o)}).unsubscribe}function fa(e,t,s){return $(e,o=>{if(o){const n=t(o);s(n)}}).unsubscribe}function pa(e,t,s){let r=null;const o=$(e,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},t)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function ga(e,t,s){let r=0,o=null;const n=$(e,i=>{const a=Date.now(),c=a-r;c>=t?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},t-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function ma(e,t,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=$(e,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},t)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function Go(e,t=1){const s=[];return $(e,r=>{r&&(s.push(r),s.length>t&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),$(e,r))}}function ya(e,t){const s=e.map(r=>$(r,o=>{o&&t(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function ba(e,t){let s=e;const r=[],o=new Set;return Object.values(t).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=$(n,a=>{const c=t[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function va(e,t,s,r){const o=Dr(t,r);return z(e,s),o}async function*wa(e){const t=[],s=[],r=$(e,o=>{o&&(s.length>0?s.shift()(o):t.push(o))});try{for(;;)t.length>0?yield t.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const Mh={once:Cr,waitFor:Dr,waitForAll:ua,race:da,filter:ha,map:fa,debounce:pa,throttle:ga,buffer:ma,replay:Go,merge:ya,stateMachine:ba,request:va,eventIterator:wa},Th=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:Mh,buffer:ma,debounce:pa,eventIterator:wa,filter:ha,map:fa,merge:ya,once:Cr,race:da,replay:Go,request:va,stateMachine:ba,throttle:ga,waitFor:Dr,waitForAll:ua},Symbol.toStringTag,{value:"Module"}));async function xr(e,t){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=t,i=zo(e,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(c),100)})])}function Ea(e,t,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=$(e,a=>{a&&(n=!0,t(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||t(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function Ma(e,t){let s;const r=new Set,o=async()=>{try{typeof t=="string"?s=await(await fetch(t)).json():s=await t(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};$(e,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let n=!1;const i=()=>{n||(n=!0,o())};return{get state(){return s},async getState(){return i(),s===void 0&&await new Promise(a=>{const c=()=>{s!==void 0?a():setTimeout(c,10)};c()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function Vo(e,t){if(typeof e=="string")return xr(e,t);const s=e,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=t,i=await r(),a=t.transformState?t.transformState(i):i;if(o&&o(a))return a;const c=s.map(d=>zo(d,n)),u=await Promise.all(c);return u[u.length-1]}function Ta(e,t,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=$(e,async u=>{if(u){if(n){const d=n(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await t(u)}}),c=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(n){const f=n(h);i.has(f)||(i.add(f),await t(h))}else await t(h)}catch(u){console.error("Failed to fetch missed events:",u)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function _a(e){const{connectEvent:t,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=e,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await xr(t,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:d});return a.state="connected",a.data=h,u(),h},subscribe(d){return c.add(d),d(a),()=>{c.delete(d)}},async reconnect(){a.state="connecting",u();try{const d=await n();a.state="connected",a.data=d,u()}catch{a.state="error",u(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,u=()=>{c.forEach(d=>d(a))};return $(t,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),$(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&$(r,()=>{a.state="error",u()}),o&&$(o,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const _h={waitForOrGetState:xr,subscribeWithInitialState:Ea,createStatefulEventStream:Ma,waitForAllWithState:Vo,createResilientEventHandler:Ta,createConnectionStateManager:_a},Oh=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:_h,createConnectionStateManager:_a,createResilientEventHandler:Ta,createStatefulEventStream:Ma,subscribeWithInitialState:Ea,waitForAllWithState:Vo,waitForOrGetState:xr},Symbol.toStringTag,{value:"Module"})),Ih=(e,t=0)=>{if(!+e)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=t<0?0:t,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(s)),i=parseFloat((e/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function Yo(e){let t="pending",s;const r=e.then(n=>{t="success",s=n},n=>{t="error",s=n});return{read:()=>{switch(t){case"pending":throw r;case"error":throw s;default:return s}}}}function tt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}function Sh(e,t){t.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(e.prototype,r,o)})})}function $h(e,t){const s=e??[],r=t??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const qo=(e,t)=>{const s=e.map(n=>n.id);return t.map(n=>n.id).filter(n=>!s.includes(n))},Oa=e=>e,Ia=e=>e,Ch=({container:e,onAddItem:t,onUpdateItem:s,onRemoveItem:r=Oa,idMapper:o=Ia})=>n=>{const i=n.map(o),c=qo(i,e.data).map(r).filter(Boolean);e.removeAll(c);const u=i.map(d=>{const h=e.getModel(d.id);return h&&s?s(d,h):t(d)}).filter(Boolean);e.addAll(u)},Dh=({container:e,onAddItem:t,onRemoveItem:s=Oa,idMapper:r=Ia})=>o=>{const n=o.map(r);qo(n,e.models).forEach(s),n.forEach(t)},xh=({items:e,onAddItem:t,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);qo(n,e).forEach(s),n.forEach(t)},Ah=(e,t="parent-")=>{let s=e;return s.startsWith(t)&&(s=s.replace(t,"")),s},hi=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),fi=[{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 Sa(e){let t=(e.getTime()-Date.now())/1e3;for(let s=0;s<=fi.length;s++){const r=fi[s];if(Math.abs(t)<r.amount)return hi.format(Math.round(t),r.name);t/=r.amount}return hi.format(Math.round(t),"years")}const Wo=e=>e%4===0&&e%100!==0||e%400===0,Qo=(e,t)=>[31,Wo(e)?29:28,31,30,31,30,31,31,30,31,30,31][t],$a=(e,t)=>{const s=new Date(e),r=e.getDate();return s.setDate(1),s.setMonth(s.getMonth()+t),s.setDate(Math.min(r,Qo(s.getFullYear(),s.getMonth()))),s},Ca=(e,t)=>{const s=new Date(e);return s.setDate(s.getDate()+t),s},yt="en-US",Da={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"}},xa={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"}},Aa=(e,{dateStyle:t="short",locales:s=yt}={dateStyle:"short",locales:yt})=>{const r=t==="short"?Da.short:{dateStyle:t};return new Intl.DateTimeFormat(s,r).format(e)},Ra=(e,{locales:t=yt,timeStyle:s="short"}={locales:yt,timeStyle:"short"})=>{const r=xa[s];return new Intl.DateTimeFormat(t,r).format(e)},Pa=(e,{dateStyle:t="short",locales:s=yt,timeStyle:r="short"}={dateStyle:"short",locales:yt,timeStyle:"short"})=>{const o={...t&&Da[t],...r&&xa[r]};return new Intl.DateTimeFormat(s,o).format(e)},Rh=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Ca,addMonthsToDate:$a,formatDate:Aa,formatDateSince:Sa,formatDateTime:Pa,formatTime:Ra,getDaysInMonth:Qo,isLeapYear:Wo},Symbol.toStringTag,{value:"Module"}));function ka(e,t,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{t.apply(e,o)},s)}}const te="canvas-renderer",Xr=new Map,pi=new Map,Jr=new Map,eo=new Map,$s=(e,t)=>{La[e]=t},La={indexExtension:{registerIndexExtension:(e,t)=>{const s=eo.get(e)||{};Object.assign(s,t),eo.set(e,t)},loadIndexExtensions:e=>eo.get(e)||{}},loader:{registerLoader:(e,t)=>{pi.set(e,t)},executeLoader:async(e,t)=>{const s=pi.get(e);if(s)return await s(t)}},propertyMapper:{registerPropertyMapper:(e,t)=>{Jr.set(e,t)},hasMapper:e=>Jr.has(e),executeMapper:(e,t,s)=>{const r=Jr.get(e);return r?r(t,s):""}},dataMapper:{registerDataMapper:(e,t)=>{const s=Xr.get(e)||[];s.push(t),Xr.set(e,s)},executeMapper:async(e,t,s)=>{const r=Xr.get(e);if(!r)return{};const o={};for(const n of r){const i=await n(t,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(e,t)=>{if(!S[te]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${e}".`);return}S[te].register(e,t)}}},S=La,Ph=async({context:e,extension:t})=>{const s=await S.loader.executeLoader(t,{});return e==null||e.set(t,s),s},kh=async({extension:e,contextData:t,data:s})=>await S.dataMapper.executeMapper(e,s,t),Lh=async({extension:e,contextData:t,data:s})=>await S.propertyMapper.executeMapper(e,s,t),Fh=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:kh,executeLoaderExtension:Ph,executePropertyMapperExtension:Lh},Symbol.toStringTag,{value:"Module"})),Nh="Extensions";class Uh{constructor(){l(this,"extensions");this.extensions={}}register(t,s,r){this.extensions[t]={},this.extensions[t][s]={component:r}}get(t,s){if(!this.extensions[t])throw new Error(`Extension point ${t} not found`);return this.extensions[t][s]}get allExtensions(){return this.extensions}}const ge=(e=null)=>(e||window.location.search.replace("?","")).split("&").map(t=>{const[s,r]=t.split("=");return[s,decodeURIComponent(r||"")]}).reduce((t,[s,r])=>(t[s]=r,t),{}),Fa="studio.tools.preview",jh="studio.relax.store.validation",Na="studio.log.debug",Ua="studio.log.info",Bh={profiles:[Fa]};var Ji;const Kh=((Ji=globalThis.getKosConfig)==null?void 0:Ji.call(globalThis))||JSON.stringify(Bh),ja=JSON.parse(Kh);globalThis.kosConfig=ja;const Zo=ja,Ba=()=>Zo.profiles||[],mo=e=>Ba().includes(e),Hh=()=>Zo.logging||!1,zh=()=>{const e=mo(Na),t=mo(Ua);return e?"DEBUG":t?"INFO":void 0},Ka=()=>{const e=ge(),t=zh(),r=e.kosLogLevel??t??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Ha=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",za=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Ga="ws-log",Gh=C.methodFactory,Va=Ha(),Vh=za();C.methodFactory=function(e,t,s){const r=Gh(e,t,s);return function(o,n){var c;const i=s?String(s):"",a=i?`[${String(i).substring(i.lastIndexOf(":")+1)}] | `:"[root] | ";r(`${a}${o}`,n||""),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==Ga||Va&&Vh)&&globalThis.kosLog(`UI: ${a}${o}`)}};let Ya=Ka();C.setLevel(Ya);window.setKosLogLevel=e=>{Ya=e,C.setLevel(e)};const Js=C.getLogger(Ga);window.enableKosMessageLog=()=>{Js.setLevel(C.levels.INFO)};window.disableKosMessageLog=()=>{Js.setLevel(C.levels.ERROR)};Va?window.enableKosMessageLog():window.disableKosMessageLog();const Yh=["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(";"),qh=["color: black","display: block","padding: 4px","background-color: yellow","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),ks=e=>t=>{C.getLevel()<=e&&t()},m={...C,ifDebug:ks(C.levels.DEBUG),ifInfo:ks(C.levels.INFO),ifWarn:ks(C.levels.WARN),ifError:ks(C.levels.ERROR),getLogger:e=>C.getLogger(`kos::${e}`),getLoggers:()=>C.getLoggers(),createLogger:({name:e,group:t})=>{var n,i,a,c;const s=`${t?`${t}:`:"kos"}::${e}`,r=C.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(u=>u.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Js.info(`%c⬆ ${t}`,Yh)},wsReceive:(...e)=>{const t=String(e).replace(/\n/g,"\\n");Js.info(`%c⬇ ${t}`,qh)}},qa="featureFlagResolver",Ls=new Map;$s(qa,{register:(e,t)=>{var s;Ls.has(e)||Ls.set(e,[]),(s=Ls.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Ls.get(e);if(!s)return[];const r=s.map(a=>a(t)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${e} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return Qa.updateFlags(i),Object.keys(i)}});const Wh="kos.loader.featureFlag";class Wa{constructor(t={}){l(this,"flags",{});this.flags=t}isFeatureEnabled(t){return!!this.flags[t]}enableFeature(t){this.flags[t]=!0}disableFeature(t){this.flags[t]=!1}toggleFeature(t){this.flags[t]=!this.flags[t]}updateFlags(t){this.flags={...this.flags,...t}}}window.KosFeatureFlags=window.KosFeatureFlags??new Wa;const Qa=window.KosFeatureFlags,Za=(e,t,s)=>{s/=100;const r=t*Math.min(s,1-s)/100,o=n=>{const i=(n+e/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},Xa=e=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(e);if(!s)throw Error("Invalid HSL string");return Za(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Ja=(e,t)=>getComputedStyle(e).getPropertyValue(t),Qh=(e,t)=>Xa(Ja(e,t)),Zh=(e,t)=>{const s={...e};return s.id&&delete s.id,s},yo=(e,t,s=Zh)=>{const r=s(e,t);E.runInAction(()=>{Object.assign(t,r)})},to=new Map,ec={addToDeletionQueue:(e,t)=>{const s=to.get(e)||[];s.push(t),to.set(e,s)},cancelDeletion:e=>{const t=to.get(e);t&&t.forEach(s=>{clearTimeout(s)})}},Xh=m.createLogger({name:"kos-dependency-manager"});class Jh{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(t,s){ec.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(t)||r.push(t),this._usedByCache.set(s,r);const o=this._usesCache.get(t)||[];o.includes(s)||o.push(s),this._usesCache.set(t,o)}remove(t,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==t));const o=this._usesCache.get(t)||[];this._usesCache.set(t,o.filter(n=>n!==s))}canDestroy(t){const s=this._usedByCache.get(t);return s!=null&&s.length?(Xh.info(`Model ${t} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var v=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.READY_FAILED="ready_failed",e.RESETTING="resetting",e.RESET="reset",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.FAILED="failed",e.INACTIVE="inactive",e.ACTIVE="active",e.ACTIVATING="activating",e.DEACTIVATING="deactivating",e))(v||{}),P=(e=>(e.CREATE="create",e.INITIALIZE="init",e.LOAD="load",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.RESET="go_offline",e.UNLOAD="unload",e.FAILED="failed",e.GO_ACTIVE="go_active",e.GO_INACTIVE="go_inactive",e.TIMEOUT="timeout",e))(P||{});const gi=m.createLogger({name:"kos-model-cache"});class ef{constructor(t=[]){l(this,"_modelsById",E.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=t}get models(){return Array.from(this._modelsById.values()).map(t=>t).filter(t=>!this._toDelete.has(t.modelId))}getModelById(t){if(t&&!this._toDelete.has(t))return this._modelsById.get(t)}addModel(t){const s=this.getModelById(t.modelId)||t;return this._modelsById.set(s.modelId,s),s}removeModel(t){this._modelsById.delete(t),this._toDelete.delete(t)}hasModel(t){return!!t&&this._modelsById.has(t)&&!this._toDelete.has(t)}restoreFromDeleteCache(t){if(t&&this._toDelete.has(t)){const s=this._toDelete.get(t);this._toDelete.delete(t),this._modelsById.set(t,s)}}markForDeletion(t){this._modelsById.delete(t.modelId),this._toDelete.set(t.modelId,t)}preload(t){return this._isPreloaded?(gi.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(gi.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),t(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const ee=Symbol("SubscriptionHandlers"),k=Symbol("DependencyModels"),os=Symbol("FutureService"),Be=Symbol("ChildModels"),ns=Symbol("ParentModel"),is=Symbol("LogConfig"),Vs=Symbol("ReferenceConfig"),Xo=Symbol("KosModelSymbol"),Ze=Symbol("ModelEffects"),bt=Symbol("CompanionParentModel"),Jo=Symbol("FutureContainerSetup"),en=Symbol("MultipleFutureContainerSetup"),as=Symbol("FutureAliases"),tn=Symbol("TroubleAwareSetup"),sn=Symbol("LoggerSetup"),rn=Symbol("ContainerAwareSetup"),Ie=(e,t)=>{e[Be]=e[Be]||{},e[Be][t]=!0},st=e=>`{PROP_${String(e)}}`,tf=e=>`{PROP_${String(e)}}`,sf=st("kosParentId"),Ar=e=>t=>{t[ns]=t[ns]||{};const s=(e==null?void 0:e.parentId)||sf;t[ns]={parentId:s}};function rf(e){return t=>{const s=(e==null?void 0:e.mode)||"decorator",r=(e==null?void 0:e.parentProperty)||"companionParent",o=(e==null?void 0:e.excludeProperties)||[];return Ar()(t),t.prototype[bt]={mode:s,parentProperty:r,excludeProperties:o},t}}function tc(e){return t=>{const s=e!=null&&e.legacy?"_models":(e==null?void 0:e.containerProperty)||"container",r=(e==null?void 0:e.includeMethods)!==!1,o=(e==null?void 0:e.includeGetters)!==!1,n=(e==null?void 0:e.modelsProperty)||"models",i=(e==null?void 0:e.containerOptions)||{};return t.prototype[rn]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(e==null?void 0:e.legacy)||!1},t}}function of(e,t,s){const r=s.value;s.value=function(...o){const n=V.getContext(this.id);return o.push(n),r.apply(this,o)}}function nf(e){return t=>{const s=(e==null?void 0:e.mode)||"full",r=(e==null?void 0:e.handlerProperty)||"futureHandler";return t.prototype[Jo]={mode:s,handlerProperty:r},t}}function af(e){return t=>{const s=(e==null?void 0:e.mode)||"full",r=(e==null?void 0:e.handlerProperty)||"futureHandler";return t.prototype[en]={mode:s,handlerProperty:r},t}}var H=(e=>(e.INIT="init",e.LOAD="load",e.READY="ready",e.ACTIVATE="activate",e.ONLINE="online",e))(H||{});const cf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:H},Symbol.toStringTag,{value:"Module"})),xe=Symbol("HttpRouteHandlers"),mi="__httpBrowserRouter";function Rr(e){return function(s){return function(r,o,n){r[xe]=r[xe]||[];const i={method:e,path:s,handler:o};return r[xe].push(i),r[k]=r[k]||{},r[k][mi]||(r[k][mi]={modelType:"browser-router-model",lifecycle:H.INIT}),n}}}const sc=Rr("GET"),Cs=Rr("POST"),lf=Rr("PUT"),rc=Rr("DELETE"),uf=rc;function er(e){return!!(e!=null&&e[xe])&&e[xe].length>0}function oc(e){return(e==null?void 0:e[xe])||[]}const df=({group:e}={group:""})=>t=>{t[is]=t[is]||{},t[is]={group:e}};class nc{static create({modelId:t,modelTypeName:s,component:r}){const o=[r??"kos",s,t].filter(Boolean).join(".");return m.createLogger({name:o})}}function ic(e){return t=>{const s=(e==null?void 0:e.loggerProperty)||"logger",r=e==null?void 0:e.loggerContext;t.prototype[sn]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=t.prototype[Xo])==null?void 0:i.type};let n;return Object.defineProperty(t.prototype,s,{get(){if(!n){const i=o();n=nc.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),t}}function ac(e){return(t,s,r)=>{t[Ze]=t[Ze]||{},t[Ze][s]={dependencies:e==null?void 0:e.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const hf=e=>(t,s)=>{t[Vs]=t[Vs]||{},t[Vs][s]=e};function ff(e){return t=>{const s=(e==null?void 0:e.pathProperty)||"path";return t.prototype[tn]={pathProperty:s},t.prototype[k]=t.prototype[k]||{},t.prototype[k].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},t}}const Rt=({modelType:e,id:t,options:s,lifecycle:r})=>(o,n)=>{o[k]=o[k]||{},o[k][n]={modelType:e,id:t,options:s,lifecycle:r||H.INIT}};class cc{constructor(t,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=pn.map(new Map),this.context="",this.defaultContext=s||"",this.container=t,E.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(t,s){this.futures.set(s||t.id,t),this.context=s||t.id;const r=Y(()=>{var o,n;(t.endState||t.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,t))});this.disposers.set(s||t.id,r)}removeFuture(t){var s;this.futures.delete(t||this.context),(s=this.disposers.get(t||this.context))==null||s(),this.disposers.delete(t||this.context)}getFuture(t){return this.futures.get(t||this.context)}get futureMap(){return this.futures}}class Pr{constructor(t){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=t,E.makeAutoObservable(this)}removeFuture(){var t;this._future=void 0,(t=this.disposer)==null||t.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(t){this._future=t;const s=Y(()=>{var r,o;(t.endState||t.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,t))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var t;return((t=this._future)==null?void 0:t.timeRemaining)||""}get status(){var t;return((t=this._future)==null?void 0:t.status)||"NOT_RESOLVED"}get progress(){var t;return((t=this._future)==null?void 0:t.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(t){throw m.error(t),t}}}const lc=(e,t)=>{const s=t.type;return e[s]||(e[s]=[]),e[s].push(t),e},uc=Symbol("KosObservableData");class dc{constructor(){l(this,"map");l(this,"_revision",1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(t,s)=>{var r;return s==="_revision"||t[s]!==void 0?t[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(t,s,r)=>{var o;return this.map.has(s),this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,E.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>[...Array.from(this.map.keys()),"_revision"]});this.map=E.observable.map(new Map),E.makeObservable(this,{_revision:E.observable})}setValue(t,s){const r=this.map.has(t);this.map.set(t,s),r||E.action(()=>{this._revision++})()}getValue(t){return this.map.get(t)}has(t){return this.map.has(t)}get entries(){return Array.from(this.map.entries())}get keys(){return this._revision,Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(t){t&&Object.keys(t).forEach(s=>{this.setValue(s,t[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}dc.prototype[uc]=!0;function pf(e,t){return new Proxy(e,{construct:(s,r)=>{const o=new e(...r);return o.setValues(t),o.proxy}})}const Te=e=>{const t=pf(dc,e);return new t(e)};function gf(e,t){return e.length!==t.length?!1:e.every(s=>t.includes(s))}class on{constructor({container:t,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=t,this._map=E.observable.map(new Map),this._key=s,this.data=Te(),this.generateIndex(),E.autorun(()=>{this._container.revision&&this.generateIndex()}),E.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(t,s,r=this._map,o=this.data){const n=r.get(t)||new Set;n.add(s),r.set(t,n),o[t]=Array.from(n)}resolveIndex(t,s){this.data.keys.filter(o=>!Object.keys(s).includes(o)).forEach(o=>{delete this.data[o],this._map.delete(o)}),Object.keys(s).forEach(o=>{const n=s[o],i=this.data[o]||[];if(gf(n,i))m.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=t.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){E.runInAction(async()=>{const t=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,t,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,t,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,t,s)}this.resolveIndex(t,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(t){const s=this._map.get(t);return s?Array.from(s):[]}}function mf(e,t,s=[]){const r=Object.getOwnPropertyDescriptors(e);return Object.keys(r).filter(i=>E.isComputedProp(e,i)).filter(i=>s.includes(i)).map(i=>E.reaction(()=>e[i],(a,c)=>{t({name:i,newValue:a,oldValue:c})}))}const Kt=m.createLogger({name:"kos-container-model"});class Se{constructor(t){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");this._data=E.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1;const s=t!=null&&t.extensionId?S.indexExtension.loadIndexExtensions(t.extensionId):{},r=(t==null?void 0:t.indexMap)||{};this._optionsMap={...r,...s};const o=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=E.observable.map(o),this.idx=Te(),this._parentId=t==null?void 0:t.parentId,E.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],r=new on({container:this,key:s});this._index.set(t,r),this.idx[t]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((t,s)=>{var r;return t[s]=(r=this.index.get(s))==null?void 0:r.keys,t},{})}sortFn(t,s){const r=this._sortKey;return r?String(t[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){E.runInAction(()=>{this._revision=this._revision+1})}addAll(t){E.runInAction(()=>{t.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(t){E.runInAction(()=>{t.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(t,s){this._data.set(t.id||"",t),t.id&&this._parentId&&V.setParentContext(t.id,this._parentId),s||this.increment();const r=this._disposerMap.get(t.id);r&&(r(),this._disposerMap.delete(t.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([d,h])=>[h,d])),a=d=>{var f,p;n.includes(d.name)&&((f=this.index.get(i.get(d.name)))==null||f.refresh());const h=o.filter(([,b])=>typeof b=="function");for(const[b]of h)(p=this.index.get(b))==null||p.refresh()},c=mf(t,a,n.filter(d=>typeof d=="string")),u=E.observe(t,a);this._disposerMap.set(t.id||"",()=>[u,...c].forEach(d=>d()))}removeModel(t,s){this._data.delete(t),s||this.increment();const r=this._disposerMap.get(t);r&&(r(),this._disposerMap.delete(t))}updateModel(t){this._data.set(t.id||"",t),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(Kt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const r=this.index.get(t);return r.index.has(s)?r.getByKey(s):(Kt.info(`key ${s} not found in ${t} index: ${Array.from(r.index.keys())}`),[])}else return Kt.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(t=>{const s=t.id;Xe(t).then(()=>{Kt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Kt.error(r))}),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const ue=async e=>{if(e.id){const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error(`Model with ID ${e.id} not found`);await(t==null?void 0:t.whenReady())}else throw new Error("Data model must have a valid ID");return e},Xe=async e=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(e)},yf=async e=>{if(await I.getInstance().whenReady(),!e.id)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e.id);t&&await t.fsm.transitionTo(P.UNLOAD,v.UNLOADED)},bf=async e=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(e),m.debug(`reload model initiated for model ${e.id}, model ready: ${tr(e)} - ${Date.now()} `),await ue(e),m.debug(`reload model complete for model ${e.id}, model ready: ${tr(e)} - ${Date.now()} `)},vf=async e=>{if(await I.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return t==null?void 0:t.modelTypeName},hc=async e=>{if(await I.getInstance().whenReady(),!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},_e=e=>{if(!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);return{model:t==null?void 0:t.modelData,type:t==null?void 0:t.modelTypeName}},fc=(e,t)=>{if(!e)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(e).filter(o=>Object.keys(t).every(n=>o[n]===t[n]))},wf=(e,t)=>fc(e,t)[0],Ef=(e,t)=>{if(!e.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(t);return r==null?void 0:r.modelData},pc=e=>{if(!e.id)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return Array.from(t.companionModels.all()).map(r=>r.modelData)},Mf=e=>{if(!e)throw new Error("Model ID is required");const t=I.getInstance().modelManager.getModelById(e);if(!t)throw new Error("Model not found");return t.companionModels.data},bo=(e,t)=>{const s=I.getInstance().modelManager.getModelById(e);if(!s){m.info(`Model not found for id ${e}`);return}return Array.from(s.companionModels.all()).find(o=>t(o.modelData))},Ee=e=>t=>Object.getPrototypeOf(t).modelTypeId===e,tr=e=>{const t=I.getInstance().modelManager.getModelById(e.id);if(!t)throw new Error("Model not found");return t.isReady()},Tf=m.createLogger({name:"kos-model-factory"}),cs={byModelType:e=>I.getInstance().modelManager.getModelFactory(e),getModelInstance:(e,t,s)=>{const r=cs.byModelType(t);if(!r)throw Tf.error(`No registered factory found for model type ${t}. Please register a factory for this model type. `),Error(`No factory found for model type ${t}`);return r.build(e,s)}},ie={Factory:{create:e=>t=>(s,r)=>(r&&V.setParentContext(t,r),cs.getModelInstance(t,e,s))},Singleton:{create:e=>(t,s)=>(s&&V.setParentContext(e,s),cs.getModelInstance(e,e,t))},Model:{instance:e=>t=>cs.getModelInstance(t,e)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const yi=window.KosRegistry.coreModels,so=window.KosRegistry.preloadModels,ro=window.KosRegistry.companionModels,Fs=window.KosRegistry.models,x={model:{registerLegacyModel:e=>(t,s)=>(yi.set(t,s),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}),preloadModel:e=>t=>(so.includes(t)||so.push(t),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}),register:e=>(t,s)=>{const r=oo(t)?t.registration():t;return Fs.set(r.type,r),oo(t)&&t.relatedModels.forEach(o=>Fs.set(o.type,o.registration())),I.getInstance().isReady&&(I.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),I.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],oo(t)&&t.relatedModels.forEach(o=>I.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&x.model.preloadModel(e)(r.type),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}},get:e=>Fs.get(e),getAll:()=>Array.from(Fs.entries()),getPreloadModels:()=>so,getLegacyModels:()=>Array.from(yi.entries()).reduce((e,[t,s])=>(e[t]=s,e),{})},companion:{register:e=>(t,s)=>{const r=ro.get(t)||[];return r.push(s),ro.set(t,r),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e),root:e}},getAll:()=>Array.from(ro.entries())}},gc=x.model.registerLegacyModel,mc=x.model.register,_f=x.companion.register,Of=x.model.preloadModel,yc=e=>typeof e.updateModel=="function",oo=e=>e.registration!==void 0&&typeof e.registration=="function";class bc{constructor(t){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=t.singleton,this.guard=Ee(t.type),this.type=t.type,this.loader=`kos.extension.model.loader.${t.type}`,this.factory=t.factory,this.class=t.class}addRelatedModel(t){this.relatedModels.push(t)}registerRelatedModels(){this.relatedModels.forEach(t=>t.register())}register(){x.model.register({})(this.registration()),this.registerRelatedModels()}}class me extends bc{constructor(t){super({...t,singleton:!1,factory:ie.Factory.create(t.type)})}instance(t){const s=this.factory(t);return{get:()=>{const r=_e(t);if(!r)throw new Error("Model not found with id "+t);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(yc(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error("Model is not of type "+this.type)}})},options:r=>({build:()=>{const o=s(r);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class Me extends bc{constructor(t){super({...t,singleton:!0,factory:ie.Singleton.create(t.type)})}instance(){const t=this.factory;return{get:()=>{const r=_e(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=t(r);if(this.guard(o)){if(yc(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})},options:r=>({build:()=>{const o=t(r);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const vt=({value:e,modelId:t,modelData:s})=>{let r=e;if(Array.isArray(r))return[...e];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=vt({value:r[n],modelId:t,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp(".*({PROP_(.+)})");let n=r!=null&&r.includes(Xs)?r.replace(Xs,t):r;const i=n.match(o);if(i&&s&&(Object.getOwnPropertyNames(s).includes(i[2])||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(i[2]))){const a=s[i[2]];n=a?n.replace(i[1],a):void 0}return n}else return r;return r},vo=m.createLogger({group:"decorators",name:"kos-model"});function If(e,t,s){var n;const r=(n=e[ns])==null?void 0:n.parentId;if(!r)return;const o=vt({value:r,modelData:s,modelId:t});o&&typeof o=="string"&&V.setParentContext(t,o)}function Sf(e){const t=e[os];t&&Object.entries(t).forEach(([s,{handler:r}])=>{e[s]=r})}function $f(e,t){const s=e[k]||{};Object.entries(s).forEach(([r,o])=>{const n=vt({value:o.id||o.modelType,modelData:e,modelId:t}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,u])=>(a[c]=vt({value:u,modelData:e,modelId:t}),a),{});if(typeof n=="string"){if(!o.lazy){const a=I.getInstance().modelManager.createModelInstance(o.modelType,n,i);e[r]=a.data}I.getInstance().modelManager.addDependency(t,n)}})}function Cf(e){const t=e[Jo];if(!t)return;const{mode:s,handlerProperty:r}=t,o=new Pr(e);e[r]=o,s==="full"&&(Object.defineProperty(e,"future",{get(){return o.future},enumerable:!0,configurable:!0}),Object.defineProperty(e,"progress",{get(){var n;return((n=o.future)==null?void 0:n.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"status",{get(){var n;return((n=o.future)==null?void 0:n.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isCancelled",{get(){var n;return((n=o.future)==null?void 0:n.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function Df(e){const t=e[en];if(!t)return;const{mode:s,handlerProperty:r}=t,o=new cc(e);e[r]=o,Object.defineProperty(e,"future",{get(){return o.future},enumerable:!0,configurable:!0});const n=e[as];n instanceof Map&&n.forEach(i=>{const a=`${i}Future`;Object.defineProperty(e,a,{get(){return o.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(e,`${i}Progress`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}Status`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}IsRunning`,{get(){const c=o.futureMap.get(i);return c?!c.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,`${i}IsCancelled`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const c=o.futureMap.get(i);c&&await c.cancelFuture()})}),s==="full"&&(Object.defineProperty(e,"progress",{get(){var i;return((i=o.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"status",{get(){var i;return((i=o.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"isCancelled",{get(){var i;return((i=o.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),e.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function xf(e){const t=e[tn];if(!t)return;const{pathProperty:s}=t;Object.defineProperty(e,"troubles",{get(){const r=this[s];if(r==null){const o=`@kosTroubleAware: Path property '${s}' is undefined on model ${this.id||"unknown"}. Returning empty troubles array.`;return this.logger&&typeof this.logger.warn=="function"?this.logger.warn(o):console.warn(o),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((o,n)=>n.rank-o.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(e,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(e,"troublesByType",{get(){return this.troubles.reduce(lc,{})},enumerable:!0,configurable:!0})}function Af(e,t){const s=e[rn];if(!s)return;const{containerProperty:r,includeMethods:o,includeGetters:n,modelsProperty:i,containerOptions:a,legacy:c}=s,u={...a,parentId:a.parentId||t},d=new Se(u);e[r]=d,e[Be]||(e[Be]={}),e[Be][r]=d,o&&(e.getModel=h=>d.getModel(h),e.addModel=h=>{d.addModel(h)},e.removeModel=h=>{d.removeModel(h)}),n&&(Object.defineProperty(e,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(e,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function Rf(e,t){const s=e.constructor.prototype[bt];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=t[o];if(!i){vo.warn(`Companion decorator configured but no parent model found at '${o}'`);return}if(e.getCompanionParent=()=>i,r==="composition")return;const a=["init","load","unload","ready","dispose","destroy","activate"],c=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace","getCompanionParent"],u=p=>{const b=i.constructor.prototype[ee]||{};return Object.values(b).some(w=>{const M=w==null?void 0:w.handler;return M===i[p]||M===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||c.includes(p)||n.includes(p)||u(p)||p in e,h=new Set;Object.getOwnPropertyNames(i).filter(p=>!d(p)).forEach(p=>h.add(p));let f=Object.getPrototypeOf(i);for(;f&&f!==Object.prototype;)Object.getOwnPropertyNames(f).filter(p=>!d(p)).forEach(p=>h.add(p)),f=Object.getPrototypeOf(f);for(const p of h)try{const b=i[p];typeof b=="function"?e[p]=(...w)=>b.apply(i,w):Object.defineProperty(e,p,{get:()=>i[p],set:w=>{i[p]=w},enumerable:!0,configurable:!0})}catch(b){vo.debug(`Skipping companion proxy for property ${p}:`,b)}}function Pf(e){try{return E.makeAutoObservable(e)}catch(t){return vo.error("Failed to make observable:",t),e}}const kf={construct(e,t){var c;const[s,r={}]=t,o=V.createContext(s);If(e,s,r);const i=!!e.prototype[sn]?null:m.createLogger({name:e.prototype.modelTypeId,group:((c=e[is])==null?void 0:c.group)??"kos-model"}),a=new e(s,r,{logger:i,kosContext:o});return Sf(a),Cf(a),Df(a),xf(a),Af(a,s),Rf(a,r),$f(a,s),Pf(a)}};function A(e){return t=>{var n,i;const s=t,r=typeof e=="string"?{modelTypeId:e,autoRegister:!1}:{autoRegister:!1,...e};s.prototype.modelTypeId=r.modelTypeId,s.prototype[Xo]=!0,(n=s.prototype)[ee]??(n[ee]={}),(i=s.prototype)[k]??(i[k]={}),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,kf);if(r.singleton!==void 0){let a;r.singleton?a=new Me({class:o,type:r.modelTypeId}):a=new me({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}const Lf=({topic:e,handler:t,websocket:s=!1,condition:r=()=>!0})=>o=>{o[ee]=o[ee]||{},Array.isArray(e)?e.forEach(n=>{o[ee][n]={websocket:s,handler:t,condition:r}}):o[ee][e]={websocket:s,handler:ka(o,E.action(t),200),condition:r}};function vc(e,t,s){const r={};if(!e.endsWith("/*"))return r;const o=e.slice(0,-2);if(t.startsWith(o)){const n=t.slice(o.length+1),i=s||"path";r[i]=n}return r}function wc(e){return e.endsWith("/*")}function U({topic:e,condition:t=(_,F)=>!0,transform:s=_=>_,websocket:r=!1,fos:o=!1,bridge:n=!1,skipParse:i=!1,lifecycle:a,destinationAddress:c,debounce:u,throttle:d,buffer:h,filter:f,once:p,replay:b,wildcardName:w,flow:M}){return(_,F,Q)=>{_[ee]=_[ee]||{};let O=Q.value;const W=typeof u=="number"?u:u==null?void 0:u.delay,B=typeof d=="number"?d:d==null?void 0:d.interval;W&&W>0?O=Ff(O,u):B&&B>0?O=Nf(O,d):h?O=Uf(O,h):p&&(O=jf(O));let J=t;if(f){const $e=t;J=(ui,di,Zr)=>f(Zr)?$e(ui,di,Zr):!1}const Ue={websocket:r,fos:o,bridge:n,handler:O,condition:J,transform:s,lifecycle:a,skipParse:i,destinationAddress:c,wildcardName:w,flow:M};Array.isArray(e)?e.forEach($e=>{_[ee][$e]=Ue}):_[ee][e]=Ue,b&&Bf(e,b.bufferSize)}}function Ff(e,t){const s=typeof t=="number"?t:t.delay,r=typeof t=="object"?t.discardIntermediate:!1;let o=null,n=[];return function(i){r?(o&&clearTimeout(o),o=setTimeout(()=>{e.call(this,i),o=null},s)):(n.push(i),o&&clearTimeout(o),o=setTimeout(()=>{const a=[...n];n=[],e.call(this,a),o=null},s))}}function Nf(e,t){const s=typeof t=="number"?t:t.interval,r=typeof t=="object"?t.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const u=[...i];i=[],e.call(this,u)}};return function(u){const d=Date.now(),h=d-o;r?h>=s?(o=d,e.call(this,u)):n||(n=setTimeout(()=>{o=Date.now(),e.call(this,u),n=null},s-h)):(i.push(u),h>=s?(o=d,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function Uf(e,t){const s=[];let r=null;const o=t.maxSize||1e3,n=i=>{s.length>0&&(e.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=o){r&&(clearTimeout(r),r=null),n(this);return}r||(r=setTimeout(()=>{n(this),r=null},t.time))}}function jf(e){let t=!1;return function(s){t||(t=!0,e.call(this,s))}}function Bf(e,t){(Array.isArray(e)?e:[e]).forEach(r=>{Go(r,t)})}function Ec(e,t){return`${Ko}${e}${t?`/${t}`:`/${e}`}`}function Mc(e){return`${Ko}${e}`}function no(e){const t=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of e){const i=E.when(o,()=>{t.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});t.push(i)}})}const Tc=5e3;class Kf extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const _c=(e,t,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} - ${s} timed out after ${e}ms`),a(new Kf(`${t.modelId} - ${t.modelTypeName} - ${s}`,t))},e)}),cancel:()=>{r&&clearTimeout(r)}}},Oc=e=>e.fsm.transitionTo(P.GO_ACTIVE,v.ACTIVE),Ic=e=>e.whenReady(),Sc=e=>e.fsm.transitionTo(P.LOAD,v.LOADED),Hf=e=>e.fsm.transitionTo(P.UNLOAD,v.UNLOADED),$c=e=>e.fsm.transitionTo(P.INITIALIZE,v.INITIALIZED);var nn=(e=>(e.ACTIVE="active",e.READY="ready",e.LOAD="load",e.UNLOAD="unload",e.INIT="init",e))(nn||{});const Ys={active:Oc,ready:Ic,load:Sc,init:$c},Cc=(e,t)=>{const s=t.id||t.modelType,r=vt({value:s,modelData:e.modelData,modelId:e.modelId});m.debug(`activating dependent model ${t.modelType} with id ${r}`);const o=Object.keys((t==null?void 0:t.options)||{}).reduce((i,a)=>{const c=t.options[a];return i[a]=vt({value:c,modelData:e.modelData,modelId:e.modelId}),i},{});return{dependentModel:I.getInstance().modelManager.createModelInstance(t.modelType,r,o),dataModelId:r}},Dc=(e,t=H.READY)=>{var o;const s=((o=e.modelData)==null?void 0:o[k])||{};return Object.keys(s).length===0?(m.debug(`${e.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===t).map(n=>{const i=s[n],{dependentModel:a,dataModelId:c}=Cc(e,i);e.modelData[n]=a.data,m.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const u=async(f,p,b)=>{var w;await((w=f.whenReady)==null?void 0:w.call(f)),m.debug(`dependent model ${p} with id ${b} - READY`)},{promise:d,cancel:h}=_c(Tc,e,e.status);return Promise.race([u(a.model,i.modelType,c).then(()=>{h()}).catch(f=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${c}:`,f),h()}),d])}).filter(n=>!!n)},xc=async(e,t,s,r)=>{if(m.debug(`Execute lifecycle with ${t.length} models`),t.length===0){m.debug(`${e.modelId} has no children. Returning`);return}if(!s){m.error(`${e.modelId} is not transitioning with a valid target ${s}`);return}const o=t.map(a=>{let c;return Ys[s]&&a?c=Ys[s](a):(a||m.error("model is undefined. This shouldn't happen"),Ys[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),i=(await Promise.allSettled(o.map(a=>{var d;const{promise:c,cancel:u}=_c(Tc,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{m.error(`Model ${a.modelId} - ${a.type} failed to transition to ${s}: ${h.message}`),u()}),c])}))).filter(a=>a.status==="rejected");i.length>0&&m.error(`Model ${e.modelId} had ${i.length} failed child models on ${r}`)},Ac=async(e,t,s)=>{await xc(e,e.getChildren().filter(r=>!!r),t,s)},zt=async(e,t)=>{const r=(await Promise.allSettled(Dc(e,t))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${t}`),m.error(r))},zf=e=>typeof e.toJSON=="function",ls=e=>e[k]!==void 0,an=e=>e.revision!==void 0&&e.index!==void 0,Rc=e=>{if(e){if(ls(e))return e;if(an(e))return e.data;if(e instanceof Map||e instanceof E.ObservableMap||e instanceof Set)return Array.from(e.values()).filter(ls);if(Array.isArray(e))return e.filter(ls)}};function Gf(e){const t=`KosModel(${e.modelTypeName}:${e.modelId})`;try{Object.defineProperty(e,Symbol.toStringTag,{value:t,configurable:!0})}catch{e.toString=()=>t}try{Object.defineProperty(e.constructor,"name",{value:`KosModel_${e.modelTypeName}`,configurable:!0})}catch{e.constructor.name=`KosModel_${e.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in e&&Object.defineProperty(e,r,{enumerable:!1});Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:e.modelId,type:e.modelTypeName,initialized:e.initialized,loaded:e.loaded,status:e.status,onlineStatus:e.onlineStatus,activeStatus:e.activeStatus,companions:(o=(r=e.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=e.getChildren)==null?void 0:n.call(e).map(i=>i.modelId),effects:!!e.effectManager,subs:!!e.subscriptionManager}}}),Vf(e.modelData,e.modelTypeName,e.modelId,e)}function Vf(e,t,s,r){Object.defineProperty(e,Symbol.toStringTag,{value:`KosModelData(${t}:${s})`,configurable:!0});try{Object.defineProperty(e.constructor,"name",{value:`${t}ModelData`,configurable:!0})}catch{e.constructor.name=`${t}ModelData`}Object.defineProperty(e,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[k]||{};return{id:s,type:t,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=e.toJSON)==null?void 0:u.call(e))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(e,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(e))if(!(n.startsWith("_")||typeof e[n]=="function"))try{const i=e[n];ls(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:an(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class Yf{constructor(t){this.model=t}resolve(){const t=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(t).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{V.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const t=((s=this.model.modelData)==null?void 0:s[Be])||{};return Object.keys(t).map(r=>Rc(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var t,s;return((s=(t=this.model.modelData)==null?void 0:t.getChildren)==null?void 0:s.call(t))||[]}}class qf{constructor(t){l(this,"companions",new E.ObservableMap);this.hostModel=t}add(t){this.companions.set(t.modelTypeName,t)}clear(){this.companions.clear()}get(t){return this.companions.get(t)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Wf{constructor(t,s,r,o){l(this,"disposers",[]);this.modelTypeName=t,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const t=((s=this.modelData)==null?void 0:s[Ze])||{};for(const r of Object.keys(t)){const{value:o,dependencies:n,options:i}=t[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),E.runInAction(()=>a())},u=n?E.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):E.autorun(c);this.disposers.push(u)}}disposeAll(){for(const t of this.disposers)try{t()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Qf=m.createLogger({name:"model-active-machine"}),Zf=e=>{const t=y.createMachine(v.INACTIVE,{[v.FAILED]:y.state(y.transition(P.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:y.state(y.transition(P.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:y.invoke(()=>(e.activeStatus=v.ACTIVATING,e.activate()),y.transition("done",v.ACTIVE,y.action(()=>{e.activeStatus=v.ACTIVE})),y.transition("error",v.FAILED,y.action(()=>{e.activeStatus=v.FAILED}))),[v.ACTIVE]:y.state(y.transition(P.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:y.invoke(()=>(e.activeStatus=v.DEACTIVATING,e.deactivate()),y.transition("done",v.INACTIVE,y.action(()=>{e.activeStatus=v.INACTIVE})),y.transition("error",v.FAILED,y.action(()=>{e.activeStatus=v.FAILED})))});return{service:y.interpret(t,r=>Qf.debug(r.machine.current)),machine:t}},bi=m.createLogger({name:"model-online-machine"}),Xf=e=>{const t=y.createMachine(v.OFFLINE,{[v.ONLINE]:y.state(y.transition(P.GO_OFFLINE,v.OFFLINE,y.action(async()=>{await e.offline(),e.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:y.state(y.transition(P.GO_ONLINE,v.ONLINE,y.action(async()=>{bi.debug(`Going online with model ${e.modelId}`),await e.online(),e.onlineStatus=v.ONLINE,await e.fsm.transitionTo(P.INITIALIZE,v.INITIALIZED)})))}),s=y.interpret(t,r=>bi.debug(r.machine.current));return{machine:t,service:s}},Jf=e=>{var r;const t=Zf(e).service,s=Xf(e).service;return y.createMachine(v.CREATING,{[v.CREATING]:y.state(y.transition(P.CREATE,v.CREATED)),[v.CREATED]:y.state(y.immediate(v.INITIALIZING)),[v.INITIALIZING]:y.invoke(()=>(X(()=>{e.status=v.INITIALIZING}),e.init()),y.transition("done",v.INITIALIZED,y.action(()=>{e.status=v.INITIALIZED})),y.transition("error",v.FAILED,y.action(()=>{m.error(`Model ${e.modelId} - ${e.modelTypeName} failed to initialize. Transitioning to FAILED state.`),e.status=v.FAILED}))),[v.INITIALIZED]:y.state(y.immediate(v.LOADING)),[v.LOADING]:y.invoke(()=>(X(()=>{e.status=v.LOADING}),e.load()),y.transition("done",v.LOADED,y.action(()=>{e.status=v.LOADED})),y.transition("error",v.FAILED,y.action(()=>{e.status=v.FAILED}))),[v.LOADED]:y.state(y.immediate(v.READYING),y.transition(P.UNLOAD,v.UNLOADING)),[v.RESETTING]:y.invoke(()=>{var o;return X(()=>{e.status=v.RESETTING}),(o=e.unload)==null||o.call(e),e.load()},y.transition("done",v.LOADED,y.action(()=>{e.status=v.LOADED}))),[v.READYING]:y.invoke(()=>(X(()=>{e.status=v.READYING}),e.ready()),y.transition("done",v.READY,y.action(()=>{X(()=>{e.status=v.READY}),s.send(P.GO_ONLINE)})),y.transition("error",v.FAILED,y.action(()=>{e.status=v.FAILED}))),[v.READY]:y.state(y.transition(P.UNLOAD,v.UNLOADED,y.action((r=e.unload)==null?void 0:r.bind(e))),y.transition(P.RESET,v.RESETTING),y.transition(P.GO_ONLINE,v.READY,y.action(()=>{s.send(P.GO_ONLINE)})),y.transition(P.GO_OFFLINE,v.READY,y.action(()=>{s.send(P.GO_OFFLINE)})),y.transition(P.GO_ACTIVE,v.READY,y.action(()=>{t.send(P.GO_ACTIVE)})),y.transition(P.GO_INACTIVE,v.READY,y.action(()=>{t.send(P.GO_INACTIVE)}))),[v.UNLOADED]:y.state(),[v.FAILED]:y.state()})},ep=m.createLogger({name:"kos-model-lifecycle"}),tp=e=>({service:y.interpret(Jf(e),s=>ep.debug(`state machine for model ${e.modelId}: ${s.machine.current});`))});class sp{constructor(t,s){l(this,"disposer");l(this,"service");this.model=t,this.log=s;const r=tp(t);this.service=r.service,this.service.send(P.CREATE)}get current(){return this.service.machine.current}async transitionTo(t,s,r=v.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${t} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=E.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${t}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(t)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(t){return[v.ACTIVE,v.INACTIVE].includes(t)?this.model.activeStatus:this.model.status}}const Pc="browser-router-model";class cn{constructor(t,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=t,this.logger=s}registerAll(){var s;if(!er(this.model))return;let t=this.model.__httpBrowserRouter;if(!t)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){t=o;break}}if(t||(t=(s=_e(Pc))==null?void 0:s.model),!t)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(t)}setRouter(t){this.router=t,this.registered||this.registerRoutes()}hasRoutes(){return er(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const t=oc(this.model);t.length!==0&&(this.logger.debug(`Registering ${t.length} HTTP routes`),t.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(t){const s=/\{PROP_([^}]+)\}/g;let r=t;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(t))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${t}`)}return r}registerRoute(t){if(!this.router)return;const s=this.model[t.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${t.handler}' not found on model`);return}const r=this.resolvePropKey(t.path);this.logger.debug(`Registering ${t.method} ${r} -> ${t.handler}`+(r!==t.path?` (resolved from ${t.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${t.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(t.method,r),this.router.use(t.method,r,o),this.registeredRoutes.push({method:t.method,path:r})}checkForDuplicateRoute(t,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===t&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${t} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let t=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);t+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${t} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function rp(e,t){if(!er(e))return;const s=_e(Pc);if(!(s!=null&&s.model))throw t.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new cn(e,t).setRouter(s.model)}class op{constructor(t){l(this,"queue",[]);this.log=t}enqueue(t){this.queue.push(t)}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const t of this.queue)try{t()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class np{constructor(t,s){l(this,"unsubscribers",[]);this.model=t,this.log=s}register(){const t=this.model.modelId,s=$("/kosCore/online",async()=>{this.log.debug(`Online event received for ${t}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${t} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(P.GO_ONLINE,v.ONLINE)}),r=$("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${t} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(P.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(t=>t()),this.unsubscribers=[]}}class ip{constructor(t){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=t,this.subscription={queue:[],resolvers:[],closed:!1};const s=$(t,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(t=>{this.subscription.closed?t({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{t({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(t=>{t(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(t){throw this.subscription.closed=!0,this.unsubscribe(),t}[Symbol.asyncIterator](){return this}}function vi(e){return new ip(e)}var kc=(e=>(e.GET="GET",e.PUT="PUT",e.POST="POST",e.DELETE="DELETE",e))(kc||{});const Lc=({path:e,requestId:t,method:s,destinationAddress:r})=>{let o=`${Sr}:${s}
|
|
2
2
|
`;return o+=`topic:${e}
|
|
3
3
|
`,o+=`${At}:${e}
|
|
4
4
|
`,o+=`${Is}:${t}
|
|
5
5
|
`,r&&(o+=`${Le}:${r}
|
|
6
|
-
`),o+=`${
|
|
6
|
+
`),o+=`${Oe}:kos.studio.request
|
|
7
7
|
`,o+=`
|
|
8
|
-
`,o},
|
|
9
|
-
`;return i+=`${
|
|
8
|
+
`,o},Fc=({path:e,requestId:t,method:s,destinationAddress:r,ordered:o,tracker:n})=>{let i=`${ta}:/http${e}
|
|
9
|
+
`;return i+=`${Sr}:${s}
|
|
10
10
|
`,i+=`${At}:${e}
|
|
11
|
-
`,i+=`${
|
|
11
|
+
`,i+=`${na}:${t}
|
|
12
12
|
`,r&&(i+=`${Le}:${r}
|
|
13
|
-
`),o&&(i+=`${
|
|
14
|
-
`),n&&(i+=`${
|
|
15
|
-
`),i+=`${
|
|
13
|
+
`),o&&(i+=`${jo}:true
|
|
14
|
+
`),n&&(i+=`${Bo}:${n}
|
|
15
|
+
`),i+=`${Oe}:fos.http.request
|
|
16
16
|
`,i+=`
|
|
17
|
-
`,i},
|
|
17
|
+
`,i},Nc=({path:e,requestId:t,method:s,destinationAddress:r,ordered:o,tracker:n,bridge:i,headers:a})=>{let c=`${Sr}:${s}
|
|
18
18
|
`;return c+=`${At}:${e}
|
|
19
19
|
`,c+=`${Is}:${t}
|
|
20
20
|
`,r&&(c+=`${Le}:${r}
|
|
21
|
-
`),o&&(c+=`${
|
|
22
|
-
`),n&&(c+=`${
|
|
21
|
+
`),o&&(c+=`${jo}:true
|
|
22
|
+
`),n&&(c+=`${Bo}:${n}
|
|
23
23
|
`),a&&Object.keys(a).forEach(u=>{c+=`${u}:${a[u]}
|
|
24
|
-
`}),c+=`${
|
|
24
|
+
`}),c+=`${Oe}:${i?"fos":"kos"}.http.request
|
|
25
25
|
`,c+=`
|
|
26
|
-
`,c},
|
|
26
|
+
`,c},Ge=(e,t)=>{let s=e;return t&&(s+=t),s};function Gt(e){const t={...e};return{append(s,r){t[s]=r},delete(s){delete t[s]},get(s){return t[s]},forEach(s){Object.keys(t).forEach(r=>s(t[r],r,this))},has(s){return Object.hasOwn(t,s)},set(s,r){t[s]=r},keys(){return Object.keys(t)},values(){return Object.values(t)},entries(){return Object.entries(t)}}}function Vt(e){let t=!1;return window.ReadableStream?new ReadableStream({start(r){function o(){return Promise.resolve({done:t,value:e}).then(({done:n,value:i})=>{if(n){r.close();return}r.enqueue(i),t=!0,o()})}o()}}):e}const Uc=({path:e,requestId:t,destinationAddress:s})=>{let r=`topic:${e}
|
|
27
27
|
`;return r+=`${At}:${e}
|
|
28
28
|
`,r+=`${Is}:${t}
|
|
29
29
|
`,r+=`${Le}:${s}
|
|
30
|
-
`,r+=`${
|
|
30
|
+
`,r+=`${Oe}:kos.studio.request
|
|
31
31
|
`,r+=`
|
|
32
|
-
`,r},
|
|
32
|
+
`,r},jc=({requestId:e,destinationAddress:t,requestType:s,headers:r})=>{let o=`${Is}:${e}
|
|
33
33
|
`;return o+=`${Le}:${t}
|
|
34
|
-
`,o+=`${
|
|
34
|
+
`,o+=`${Oe}:${s}
|
|
35
35
|
`,r&&Object.keys(r).forEach(n=>{o+=`${n}:${r[n]}
|
|
36
36
|
`}),o+=`
|
|
37
|
-
`,o},
|
|
37
|
+
`,o},ap=(e,t)=>{const s=e,r=Ge(jc(t),typeof s=="string"?s:JSON.stringify(s)),o=I.getInstance().transport.socket;o?(m.debug("Sending message",r),o.socket.send(r)):m.error("socket transport is not initialized")},Bc=({path:e,responseId:t,status:s,destinationAddress:r})=>{let o=`topic:${e}
|
|
38
38
|
`;return o+=`${At}:${e}
|
|
39
|
-
`,t&&(o+=`${
|
|
40
|
-
`),o+=`${
|
|
39
|
+
`,t&&(o+=`${$r}:${t}
|
|
40
|
+
`),o+=`${Uo}:${s}
|
|
41
41
|
`,o+=`${Le}:${r}
|
|
42
|
-
`,o+=`${
|
|
42
|
+
`,o+=`${Oe}:kos.studio.response
|
|
43
43
|
`,o+=`
|
|
44
|
-
`,o},
|
|
45
|
-
`;return t+=`${
|
|
44
|
+
`,o},cp=(e,t)=>{const s=e,r=Ge(Uc(t),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},lp=(e,t)=>{const s=t.responseId?{status:t.status,data:e}:e,r=Ge(Bc(t),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},Kc=({topic:e})=>{let t=`topic:${e}
|
|
45
|
+
`;return t+=`${Oe}:kos.broker.send
|
|
46
46
|
`,t+=`
|
|
47
|
-
`,t},
|
|
47
|
+
`,t},Hc=({responseId:e,destinationAddress:t,type:s,sourceAddress:r,status:o})=>{let n=`${$r}:${e}
|
|
48
48
|
`;return n+=`${Le}:${t}
|
|
49
|
-
`,n+=`${
|
|
50
|
-
`,n+=`${
|
|
51
|
-
`,n+=`${
|
|
52
|
-
`,n+=`${
|
|
53
|
-
`,n+=`${
|
|
49
|
+
`,n+=`${sa}:${r}
|
|
50
|
+
`,n+=`${Oe}:${s??"kos.message.request"}
|
|
51
|
+
`,n+=`${Uo}:${o}
|
|
52
|
+
`,n+=`${ra}:application/json
|
|
53
|
+
`,n+=`${oa}:no-cache
|
|
54
54
|
`,n+=`
|
|
55
|
-
`,n},
|
|
56
|
-
`;return t&&(o+=`${
|
|
55
|
+
`,n},zc=({topic:e,responseId:t,destinationAddress:s,type:r})=>{let o=`topic:${e}
|
|
56
|
+
`;return t&&(o+=`${$r}:${t}
|
|
57
57
|
`),o+=`${Le}:${s}
|
|
58
|
-
`,o+=`${
|
|
58
|
+
`,o+=`${Oe}:${r??"kos.message.request"}
|
|
59
59
|
`,o+=`
|
|
60
|
-
`,o},
|
|
60
|
+
`,o},up=({msg:e,options:t})=>{const s=e,r=Ge(Kc(t),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},Gc=({msg:e,options:t})=>{const s=e,r=Ge(zc(t),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},Vc=({msg:e,options:t})=>{const s=e,r=Ge(Hc(t),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},wo=(e,t)=>{try{return t?e.body??e:JSON.parse(e.body)}catch{return e.body||e}};class dp extends WebSocket{constructor(t){super(t)}}function wi(e){const t=`
|
|
61
61
|
|
|
62
62
|
`,s=`
|
|
63
|
-
`,r=/:(.*)/s,[o,n]=e.split(t).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}function
|
|
63
|
+
`,r=/:(.*)/s,[o,n]=e.split(t).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}function hp(e){const t=`
|
|
64
64
|
|
|
65
65
|
`,s=`
|
|
66
|
-
`,r=/:(.*)/s,[,o,n]=e.split(t).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}class
|
|
66
|
+
`,r=/:(.*)/s,[,o,n]=e.split(t).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}class ln{constructor({host:t,port:s,protocol:r,alias:o,onConnectionEstablished:n,onConnectionLost:i,Transport:a=dp}){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=t,this.port=s,this.protocol=r,this.onConnectionEstablished=n,this.onConnectionLost=i,this.alias=o,this.socket=new a(`${this.protocol}${this.host}:${this.port}/events`),this.socket.onmessage=this.onMessage.bind(this),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.oldSend=this.socket.send,this.connectionEstablished=!1,$("/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)}}),E.makeObservable(this,{connectionEstablished:E.observable})}addOfflineMessage(t){this.offlineMessages.push({msg:t})}processMessageEvent(t){const{data:s}=t;return wi(s)}onMessage(t){try{m.debug("webSocketTransport: onMessage received");const{headers:s,body:r}=this.processMessageEvent(t);m.wsReceive(t.data);const o=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(o){let n=r,i=s;if(o==="kos.sniffer.msg"){const{headers:a,body:c}=hp(t.data);n=c,i={...s,...a}}z(o,n,i)}}catch(s){m.error("onMessage exception",s.message,s.stack)}}onOpen(t){m.info("websocket connection opened"),this.socket=t.currentTarget,E.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 o;m.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),E.runInAction(()=>{this.connectionEstablished=!1}),m.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(t){var s,r;if(m.wsSend(t),window.kosLogEvents){const{headers:o,body:n}=
|
|
69
|
+
`),m.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;m.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),E.runInAction(()=>{this.connectionEstablished=!1}),m.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(t){var s,r;if(m.wsSend(t),window.kosLogEvents){const{headers:o,body:n}=wi(String(t));z(Ss.SEND,{headers:o,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:o,requestId:n}=window.kosTopicIntercept(t);if(o){t=`mocked:true
|
|
70
70
|
${t}`;const a={data:`mocked:true
|
|
71
|
-
${o(n)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,t)}else this.oldSend.call(this.socket,t)}}class
|
|
71
|
+
${o(n)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,t)}else this.oldSend.call(this.socket,t)}}class fp{constructor(t){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);C.debug(`called Bridge Transport with addr ${t}`);const s=this;globalThis.kosWindowWebsocketRecv=r=>{if(s.onmessage){const o={data:r};s.onmessage(o)}},C.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),C.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>C.debug("not implemented"),this.dispatchEvent=()=>C.debug("not implemented"),this.removeEventListener=()=>C.debug("not implemented")}close(){C.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const t=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(t),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(t){this.messageQueue.push(t),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(t){globalThis.kosWindowWebsocketSend(t)}get onmessage(){return this._onmessage}set onmessage(t){this._onmessage=t}get onopen(){return this._onopen}set onopen(t){this._onopen=t}get onclose(){return this._onclose}set onclose(t){this._onclose=t}get onerror(){return this._onerror}set onerror(t){this._onopen=t}}class pp extends ln{constructor({host:s,port:r,alias:o}){super({host:s,port:r,Transport:fp,alias:o,protocol:"kos://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class gp extends ln{constructor({host:s,port:r}){super({host:s,port:r,protocol:"ws://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class mp extends ln{constructor({host:s,port:r,protocol:o,onConnectionEstablished:n,onConnectionLost:i,alias:a}){super({host:s,port:r,onConnectionEstablished:n,onConnectionLost:i,alias:a,protocol:o});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}window.kosEnableMocks=process.env.KOS_MOCK_WS==="true";window.kosLogEvents=process.env.KOS_LOG_WS==="true";class Eo{static build({host:t,port:s,protocol:r,fos:o,alias:n,onConnectionEstablished:i,onConnectionLost:a}){return m.debug("initializing websocket connection"),m.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),m.warn(`fos: ${o?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!o?(m.warn("Using bridged message transport"),new pp({host:t,port:s,protocol:r,onConnectionEstablished:i,onConnectionLost:a,alias:n})):o?new gp({host:t,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a}):new mp({host:t,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a})}}const yp=ge();yp.fos&&(window.kosUseFos=!0);const Ei=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=Ei?parseInt(Ei):0;const Ye=C.getLogger("web-socket-transport");var Yc=(e=>(e.NOT_INITIALIZED="not_initialized",e.INITIALIZED="initialized",e.OFFLINE="OFFLINE",e.ONLINE="ONLINE",e))(Yc||{}),us=(e=>(e.CONNECTED="websocket.connected",e.DISCONNECTED="websocket.disconnected",e.RELOAD="websocket.reload",e))(us||{});class wt{constructor({host:t="localhost",port:s=8080,protocol:r="ws://",token:o,initialize:n,alias:i,fos:a}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"_token");l(this,"webSocketSupported",!!globalThis.WebSocket);l(this,"authorized");l(this,"alias");l(this,"socket");l(this,"fosSocket");l(this,"fosPort");l(this,"useFosTransport");this.host=t,this.port=s,this.protocol=r,this._token=o,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!a,this.fosPort=a==null?void 0:a.port,this.socket=void 0,this.fosSocket=void 0;let c=!1;E.makeObservable(this,{authorized:E.observable,socket:E.observable,fosSocket:E.observable,init:E.action,connectionEstablished:E.computed}),E.reaction(()=>this.connectionEstablished,u=>{u&&(Ye.warn("Connection Established"),z("websocket.connected","websocket.connected"),c&&z("websocket.reload","websocket.reload"),c=!0)}),n&&this.init()}get connectionEstablished(){return!this.webSocketSupported||!this.socket||this.useFosTransport&&!this.fosSocket?!1:this.useFosTransport&&this.fosSocket?this.socket.connectionEstablished&&this.fosSocket.connectionEstablished:!this.useFosTransport&&this.socket?this.socket.connectionEstablished:!1}init(){var t,s;if(m.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=Eo.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=Eo.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ye.error("Connection Lost"),z("websocket.disconnected","websocket.disconnected"),this.init()}}),globalThis.kosWindowWebsocketOpen){const r={currentTarget:this.socket.socket};(s=(t=this.socket.socket)==null?void 0:t.onopen)==null||s.call(t,r)}return this}_sendSubscriptionMessage(t,s,r=!1,o=!1,n){var f,p,b,w;Ye.debug(`${s} to topic ${t}`);const i=ge(),a=i==null?void 0:i.connId,c=n??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:${t}`:o?`type:fos.broker
|
|
73
73
|
cmd:${s}
|
|
74
74
|
${u}topics:${t}
|
|
75
75
|
`:`${u}type:kos.broker.${s}
|
|
76
76
|
|
|
77
|
-
["${t}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(b=this.socket)==null?void 0:b.connectionEstablished){const M=r?this.fosSocket:this.socket;(w=M==null?void 0:M.socket)==null||w.send(d)}else{Ye.debug("no connection adding to offline messages");const M=r?this.fosSocket:this.socket;M==null||M.addOfflineMessage(d)}}subscribeTopic({topic:t,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=$(t,s);return Ye.debug(`Topic ${t} currently has ${a} subscribers`),this._sendSubscriptionMessage(t,"subscribe",r,o,n),()=>{const{count:c}=i();Ye.debug(`Topic ${t} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(t,"unsubscribe",r,o,n)}}async whenReady(){const t=this;return this.webSocketSupported?(await E.when(()=>{var s,r;return!!((s=t.socket)!=null&&s.connectionEstablished)&&(!t.useFosTransport||!!((r=t.fosSocket)!=null&&r.connectionEstablished))&&t.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(t){this._token=t,this.init()}static host(t="localhost"){return this.getInstance().host=t,this}static port(t=8080){return this.getInstance().port=t,this}static alias(t){this.getInstance().alias=t}static getInstance(t=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:t,token:s,fos:r})}return this._instance}}l(wt,"_instance");class pp{constructor(t){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=t,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(t){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of t)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(t,s)}async*processSingleEvent(t){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(t))){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(t),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([t]):[t],this.updateProcessingStats([t])}}async*processBatchedEvents(t,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const 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 t)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(u);this.eventQueue.length>0;){const d=this.dequeueEvent();d&&n.push(d);const f=Date.now()-i;if(n.length>=r||f>=o){const p=await a();p!==void 0&&(yield p);break}}else{n.push(u);const h=Date.now()-i;if(n.length>=r||h>=o){const f=await a();f!==void 0&&(yield f)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(t){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(t,s);return this.config.filter.historySize&&(this.filterHistory.push(t),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const t=Date.now(),s=Math.floor(t/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const t=Date.now(),o=(Math.floor(t/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-t;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const t=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=t;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const t=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-t;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(t){if(this.eventQueue.push(t),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const t=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,t}updateProcessingStats(t){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+t.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?t.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(t){return this.activePromises.add(t),t.finally(()=>this.activePromises.delete(t)),t}getStats(){return{...this.stats}}}class gp{constructor(t,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);this.model=t,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(t){var o;const s=((o=this.modelData)==null?void 0:o[ee])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${t??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(t&&t!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.flow)this.subscribeWithFlowControl(i,c,a);else{const u=this.createHandler(c,i);this.subscribe(i,c,u,a===H.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const t of this.activatableDisposers)try{t()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const t=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${t.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 t)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(t,s,r,o){const n=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;if(t.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=wt.getInstance().subscribeTopic({topic:s,callback:r,fos:t.fos,bridge:t.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=$(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(t,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(t,r,s);if(this.model.isReady()){const u=vo(r,s.skipParse),d=s.transform(u);if(a&&s.condition(d,this.modelData,r))return this.callHandlerWithWildcard(s,d,c,r)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${t}`);const u=()=>{const d=vo(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)};this.offlineQueue.enqueue(u)}}catch(n){this.log.error(`Error handling subscription for ${t}`,n)}}}extractWildcardCapture(t,s,r){var n;if(!r.wildcardName||!yc(t))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return mc(t,o,r.wildcardName)}callHandlerWithWildcard(t,s,r,o){if(r&&Object.keys(r).length>0){const n={...o,wildcardCapture:r};return t.handler.call(this.modelData,s,n,this.modelData)}else return t.handler.call(this.modelData,s,o,this.modelData)}resolvePropKey(t){const s=/.*({PROP_(.+)})/;let r=t.includes("{MODEL_ID}")?t.replace("{MODEL_ID}",this.modelId):t;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}async subscribeWithFlowControl(t,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const o=new pp(t.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,t),i=this.startFlowProcessing(t,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===H.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(t,s,r,o){const n=new AbortController;try{let i;if(t.websocket){const a=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;wt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:t.fos,bridge:t.bridge,destinationAddress:a}),i=yi(s)}else i=yi(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(t,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${t}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c)}}catch(c){if(this.log.error(`Error in flow control handler for ${t}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(t,s,r){const o=t.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),t.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const t={};for(const[s,r]of this.flowControllers)t[s]=r.getStats();return t}}function ct(e,t){const s=`[Model:${t}]`;return{debug:(...r)=>e.debug(s,...r),info:(...r)=>e.info(s,...r),warn:(...r)=>e.warn(s,...r),error:(...r)=>e.error(s,...r)}}function mp(e){return!!(e!=null&&e[Ze])&&Object.keys(e[Ze]).length>0}function yp(e){return!!(e!=null&&e[ee])&&Object.keys(e[ee]).length>0}function bp(e){return!!(e!=null&&e[xe])&&e[xe].length>0}class vp{static createAll(t){const{modelId:s,modelTypeName:r,modelData:o}=t,n=rc.create({modelId:s,modelTypeName:r}),i=new Xf(t,ct(n,"fsm")),a=new ep(ct(n,"offline-queue")),c=new zf(t),u=new Hf(t),d={fsm:i,offlineQueue:a,companionManager:c,childResolver:u};if(mp(o)&&(d.effectManager=new Vf(r,s,o,ct(n,"effect"))),yp(o)){const h=ct(n,"subscription");d.subscriptionManager=new gp(t,o,s,a,h),d.onlineLifecycleManager=new tp(t,ct(n,"online"))}return bp(o)&&(d.httpRouteManager=new nn(o,ct(n,"http-routes"))),d}}const L=C.getLogger("kos-model"),wp="kos.extension.model.loader";class Vc{constructor({modelTypeName:t,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:t,this.modelTypeName=t,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const o=vp.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),E.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Bf(this)}get companionModels(){return this.companionManager}set status(t){this._status=t}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(t){this._activeStatus=t}get onlineStatus(){return this._onlineStatus}set onlineStatus(t){this._onlineStatus=t}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 t,s,r;L.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=G.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,o)),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw L.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var t,s,r;L.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await zt(this,H.ACTIVATE);try{const o=G.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,o)),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(r=this.subscriptionManager)==null||r.registerAll(H.ACTIVATE),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw L.debug(`Model ${this.modelId} failed to activate`),o}}async whenLoaded(){await oo([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{L.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await oo([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{L.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await oo([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{L.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,r;if(this.fsm.current===v.READY){L.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{L.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await zt(this,H.READY),await Cc(this,rn.READY,H.READY);const o=G.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.ready)==null?void 0:s.call(t,o)),this.offlineQueue.flush(),(r=this.subscriptionManager)==null||r.registerAll(H.READY),L.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};z(bc(this.modelTypeName,this.modelId),n),z(vc(this.modelTypeName),n)}catch(o){throw L.error(o),Error(o)}}async load(){var o,n,i,a,c;const t=this[bt];t&&await t.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED||this.fsm.current===v.LOADING){L.debug(`Model ${s} with id ${r} already loaded or loading`);return}L.debug(`Loading model ${s} with id ${r}`),await zt(this,H.LOAD);try{const u=G.getContext(r),d=`${wp}.${s}`,h=await S.loader.executeLoader(d,{});h&&(L.info(`Setting loaded context for ${r}, type: ${s}`),u==null||u.set(d,h)),await((n=(o=this.modelData)==null?void 0:o.load)==null?void 0:n.call(o,u)),X(()=>{this.loaded=!0}),L.debug(`Model ${s} with id ${r} successfully loaded`),(i=this.subscriptionManager)==null||i.registerAll(H.LOAD),(a=this.httpRouteManager)==null||a.registerAll(),(c=this.effectManager)==null||c.setup()}catch(u){throw L.error(`Model ${r} failed to load`,u),u}}async unload(){var t,s,r,o,n,i;L.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const a=this.getChildren().map(u=>{var d;return(d=u.unload)==null?void 0:d.call(u)}).filter(u=>!!u);await Promise.allSettled(a);const c=G.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.unload)==null?void 0:s.call(t,c)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(o=this.effectManager)==null||o.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll(),(i=this.httpRouteManager)==null||i.dispose()}catch(a){throw L.debug(`Model ${this.modelId} failed to unload`),a}}async init(){var n,i,a;const t=this[bt];t&&await t.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=G.getContext(s);L.debug(`Initializing model ${r} with id ${s}`),await zt(this,H.INIT);try{await((i=(n=this.modelData)==null?void 0:n.init)==null?void 0:i.call(n,o)),this.initialized=!0,L.debug(`Model ${r} with id ${s} initialized`),(a=this.onlineLifecycleManager)==null||a.register(),this.registerSubscribers(H.INIT)}catch(c){throw L.error(`Model ${s} failed to initialize`,c),c}}async registerSubscribers(t){var s;L.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,r;L.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=G.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,t))}async offline(){var s,r,o;L.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const t=G.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,t))}accept(t){t.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(t){this.companionManager.add(t)}clearCompanionModels(){this.companionManager.clear()}}const Gc=e=>typeof e=="function",wi=m.createLogger({name:"kos-model-instantiator"});class Ep{constructor(t,s){this.registry=t,this.cache=s}createModelInstance(t,s,r={}){const o=this.registry.models[t];if(!o)throw new Error(`No model registered for type ${t}`);const n=o.singleton?t:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){wi.debug(`Creating model instance: ${t} [${n}]`);const a=o.create?o.create({modelTypeId:t,id:n,options:r}):new o.class(n,r),c=new Vc({modelTypeName:t,id:n,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(n);if(!i)throw wi.error(`Model ${t} [${n}] not found in cache`),new Error(`Model ${t} [${n}] not found in cache`);return{model:i,data:i.modelData}}_createCompanionModels(t,s){var n;const r=t.modelTypeName,o=((n=this.registry.companionModels)==null?void 0:n[r])||[];for(const{type:i}of o){const a=Gc(i)?i(t.modelData,s):i;if(!a)continue;const c=`${a}-${t.modelId}`,u=this.createModelInstance(a,c,{data:s,companionParent:t.modelData,kosParentId:t.modelId});u!=null&&u.model&&(u.model[bt]=t,t.addCompanionModel(u.model))}}}let Mp=class{constructor(t){this._registry=t}get registry(){return this._registry}getModelTypeRegistry(t){const s=this.registry.models[t];if(!s)throw new Error(`No registration for model type ${t}`);return s}registerModel(t){const s=t.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...t.registration})}registerCompanionModel(t,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[t]??(o[t]=[]),this.registry.companionModels[t].some(n=>n.type===s)||this.registry.companionModels[t].push({type:s})}getModelSubscriptions(t){var s;return((s=this.getModelTypeRegistry(t))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(t){var r;const s=(r=this.getModelTypeRegistry(t))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${t}`);return s}getModelFactory(t){return Pt(t)}};const Yc=10,Ei=m.createLogger({name:"kos-model-manager"});class qc{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Qh,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=t=>{const s=this.getModelById(t);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=t=>{var r,o;const s=this.getModelById(t);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=t=>{var r;const s=this.getModelById(t);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(t,s){const r=this.getInstance(s);return r._registry=new Mp(t),r.cache=new Zh(t.preloadModels),r.instantiator=new Ep(t,r.cache),r}static getInstance(t){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(Ei.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(t=>(Ei.debug(`preloading ${t}`),typeof t=="string"?this.createModelInstance(t).model:this.createModelInstance(t.modelType,t.modelId,t.options).model))}get models(){return this.cache.models}getModelById(t){return this.cache.getModelById(t)}addModel(t){return this.cache.addModel(t)}removeModel(t){this.cache.removeModel(t.modelId)}hasModel(t){return this.cache.hasModel(t)}getModelsByType(t,s){return Array.from(this.models).filter(r=>r.modelTypeName===t).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(t){return this._registry.getModelSubscriptions(t)}getDataModelBuilder(t){return this._registry.getDataModelBuilder(t)}getModelFactory(t){return Pt(t)}addDependency(t,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(t,s)}removeDependency(t,s){this.dependencies.remove(t,s)}async reloadModel(t){if(t.id){const s=this.getModelById(t.id);s&&await s.fsm.transitionTo(P.RESET,v.RESETTING)}}async initiateDestroyModel(t){if(!t.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(t.id))return;const s=this.getModelById(t.id);s&&(this.cache.markForDeletion(s),Xa.addToDeletionQueue(t.id,setTimeout(()=>this.destroyModel(s),Yc)))}async destroyModel(t){var s;t!=null&&t.modelId&&this.dependencies.canDestroy(t.modelId)&&(await((s=t.unload)==null?void 0:s.call(t)),this.removeModel(t))}createModelInstance(t,s,r={}){return this.instantiator.createModelInstance(t,s,r)}registerCompanionModel(t,s){this._registry.registerCompanionModel(t,s)}registerModel(t){this._registry.registerModel(t)}}var Ys=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.RELOADING="reloading",e))(Ys||{}),ft=(e=>(e.CREATE="create",e.INITIALIZE="init",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.UNLOAD="unload",e.RELOAD="reload",e))(ft||{});const Tp=e=>{const t=y.createMachine("offline",{online:y.state(y.transition("go_offline","offline",y.action(()=>{e.offline(),E.runInAction(()=>{e.isOnline=!1})}))),offline:y.state(y.transition("go_online","online",y.action(()=>{e.online(),E.runInAction(()=>{e.isOnline=!0})})))}),s=y.interpret(t,n=>C.debug(n.machine.current)),r=y.createMachine({creating:y.state(y.transition("create","created")),created:y.state(y.immediate("initializing")),initializing:y.invoke(()=>e.init(),y.transition("done","initialized")),initialized:y.state(y.immediate("loading")),loading:y.invoke(()=>e.load(),y.transition("done","loaded")),loaded:y.state(y.immediate("readying"),y.transition("unload","unloading")),readying:y.invoke(()=>e.ready(),y.transition("done","ready",y.action(()=>{E.runInAction(()=>{e.status="ready"})}))),reloading:y.invoke(()=>e.reload(),y.transition("done","loading")),ready:y.state(y.transition("reload","reloading"),y.transition("unload","unloaded",y.action(e.unload.bind(e))),y.transition("go_online","ready",y.action(()=>{s.send("go_online")})),y.transition("go_offline","ready",y.action(()=>{s.send("go_offline")}))),unloaded:y.state()});return{service:y.interpret(r,n=>C.debug(n.machine.current)),online:s}},q=m.createLogger({name:"kos-core"}),_p=()=>{const e=ge(),t=e==null?void 0:e.alias,s=process.env.KOS_CONNECTION_ALIAS;return t||s||void 0},Ip=()=>{const e=window.location.protocol,t=ge(),s=t==null?void 0:t.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(e==="https:"?"wss://":"ws://")},Op=()=>{const e=window.location.hostname,t=process.env.KOS_HOST,s=ge(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??t??e},Sp=()=>{const e=window.location.port,t=process.env.KOS_PORT,s=ge(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??t??e},$p=(e,t)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{t?m.error(`Model ${t.modelId} - ${t.modelTypeName} preloading - timed out after ${e}ms`):m.error(`KOS Core preloading timed out after ${e}ms`),i(new Error(`Model ${t==null?void 0:t.modelId} - ${t==null?void 0:t.modelTypeName} - timed out after ${e}ms`))},e)}),cancel:()=>{s&&clearTimeout(s)}}},Mi=e=>typeof e.reload=="function",Cp=e=>typeof e.unload=="function";var Wc=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Wc||{});class O{constructor(t){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=t,this.loaded=!1,this.isOnline=!1,this.status=Ys.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,E.makeAutoObservable(this),$("token",a=>{a&&(this.transport.token=a.body)}),$(ls.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(ft.GO_ONLINE)}),$(ls.DISCONNECTED,async()=>{this.fsmService.service.send(ft.GO_OFFLINE)}),$("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),$("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),$(ls.RELOAD,()=>{q.warn("WebSocket requested reload"),this.fsmService.service.send(ft.RELOAD)}),$("/studio/project/reload",()=>{q.warn("Project requested reload"),this.fsmService.service.send(ft.RELOAD)});const s=wt.getInstance(),r=Op(),o=Sp(),n=Ip();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=_p()??t;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Tp(this),this.fsmService.service.send(ft.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var o,n,i,a;const t=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)Mi(c.modelData)&&(q.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),q.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Mi(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-t;setTimeout(()=>{E.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"),z("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){q.debug("KOS Core going offline"),z("/kosCore/offline","/kosCore/offline")}async unload(){var o;q.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,q.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Cp(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-t;setTimeout(()=>{E.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await E.when(()=>this.status===Ys.READY)}async ready(){q.debug("Readying KOS Core"),await this._transport.whenReady();const t=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(t.map(o=>{const{promise:n,cancel:i}=$p(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.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===Ys.READY}set transport(t){this._transport=t}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(t,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=t.extensions)!=null&&i.dataMapper&&Object.keys(t.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{S.dataMapper.registerDataMapper(u,p)}):S.dataMapper.registerDataMapper(u,d))}),(a=t.extensions)!=null&&a.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&S.propertyMapper.registerPropertyMapper(u,d)}),(c=t.extensions)!=null&&c.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&S.loader.registerLoader(u,d)}),x.model.getAll().forEach(([,u])=>{t.models={...t.models,...u.registration}}),t.models={...t.models,...x.model.getLegacyModels()},x.companion.getAll().forEach(([u,d])=>{t.companionModels={...t.companionModels},t.companionModels[u]=t.companionModels[u]||[];for(const h of d)t.companionModels[u].push({type:h})}),x.model.getPreloadModels().forEach(u=>{t.preloadModels.includes(u)||t.preloadModels.push(u)});const n=qc.create(t,s);return o.modelManager=n,o}static getInstance(t){return this._instance=window.KosCore,(!this._instance||t!=null&&t.reset)&&(window.KosCore=new this(t==null?void 0:t.connectionAlias),this._instance=window.KosCore),this._instance}}l(O,"_instance");function Eo(e){const t=new Uint8Array(e);let s="";for(let r=0;r<t.byteLength;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function Dp(e){const t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s.buffer}async function xp(e){return await e.arrayBuffer()}function Ap(e,t){return new Blob([e],{type:t})}async function Rp(e){const t={},s=[],r=[];e.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:Eo(i)})}else t[o]=n.toString();return{fields:t,files:s}}function Pp(e){return new ReadableStream({async start(){},async pull(t){await e(t)},cancel(){}})}async function kp(e){if(!e)return{data:"",contentType:"text/plain"};if(typeof e=="string")return{data:e,contentType:"text/plain"};if(e instanceof ArrayBuffer||e instanceof Uint8Array){let t;return e instanceof Uint8Array?(t=new ArrayBuffer(e.byteLength),new Uint8Array(t).set(e)):t=e,{data:Eo(t),contentType:"application/octet-stream",encoding:"base64"}}if(e instanceof Blob){const t=await xp(e);return{data:Eo(t),contentType:e.type||"application/octet-stream",encoding:"base64"}}if(e instanceof FormData){const t=await Rp(e);return{data:JSON.stringify(t),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Fs=m.createLogger({name:"kos-fetch"}),Lp=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Fp=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),Np=e=>e!=null&&e.studio?Rc:e!=null&&e.fos?Pc:kc,Up=async(e,t)=>{const s=O.getInstance().transport;await s.whenReady();const r=tt(),o=new URL(e),n=`${o.pathname}${o.search}`;Fs.debug(`path: ${n}`);const i=(t==null?void 0:t.timeout)||Lp,a=Np(t),c=await kp(t==null?void 0:t.body),u={};c.contentType&&(u["content-type"]=c.contentType),c.encoding&&(u["content-encoding"]=c.encoding);const d=Ve(a({path:n,requestId:r,method:(t==null?void 0:t.method)||"GET",destinationAddress:(t==null?void 0:t.destinationAddress)||"",ordered:t==null?void 0:t.ordered,tracker:t==null?void 0:t.tracker,bridge:t==null?void 0:t.bridge,headers:{...t==null?void 0:t.headers,...u}}),c.data);return new Promise(h=>{let f=null,p=null;if(t!=null&&t.signal){if(t.signal.aborted){h({headers:Vt({}),status:0,ok:!1,json:async()=>null,body:Gt(""),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}t.signal.addEventListener("abort",()=>{p&&clearTimeout(p),f&&f(),h({headers:Vt({}),status:0,ok:!1,json:async()=>null,body:Gt(""),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(()=>{Fs.error(`Timeout occurred - url: ${e}`),f&&f(),h({headers:Vt({}),status:404,ok:!1,json:async()=>null,body:Gt(""),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 b=$(r,M=>{p&&clearTimeout(p);const _=(M==null?void 0:M.headers)||{},F=_["content-type"]||"text/plain",Q=_["content-encoding"],D=(M==null?void 0:M.body)||"";let I=D;if(Q==="base64"&&D)try{I=Dp(D)}catch(B){Fs.error("Failed to decode base64 response",B)}const W={headers:Vt(_),status:_.status&&parseInt(_.status)||200,ok:_.status==="200",json:async()=>{try{if(typeof I=="string")return I.length?JSON.parse(I):null;{const J=new TextDecoder().decode(I);return J.length?JSON.parse(J):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof I=="string"?I:new TextDecoder().decode(I),arrayBuffer:async()=>I instanceof ArrayBuffer?I:new TextEncoder().encode(I).buffer,blob:async()=>I instanceof ArrayBuffer?Ap(I,F):new Blob([I],{type:F}),formData:async()=>{const B=new FormData;if(F==="multipart/form-data"&&typeof I=="string")try{const J=JSON.parse(I);J.fields&&Object.entries(J.fields).forEach(([Ue,$e])=>{B.append(Ue,$e)}),J.files&&Fs.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return B},body:t!=null&&t.stream?Pp(async B=>{if(I instanceof ArrayBuffer)B.enqueue(new Uint8Array(I));else{const J=new TextEncoder;B.enqueue(J.encode(I))}B.close()}):Gt(typeof I=="string"?I:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};b.unsubscribe(),Fp().then(()=>h(W))});f=b.unsubscribe;const w=t!=null&&t.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${t}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=Up;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const jp=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Bp{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(t){var r;if(t.id===void 0)throw new Error("rootModel must have an id");const s=O.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error(`Could not find rootModel with id: ${t.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(t){var r;if(this.visitedModels.has(t.modelId)){jp.info(`model ${t.modelId} already visited`);return}const s=!!this.visitModel(t.modelData,this);this.visitedModels.add(t.modelId),!s&&((r=t.getChildren)==null||r.call(t).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}const Qc=()=>({isMock:!1,URL:exports.BASE_URL}),Kp=m.createLogger({name:"kos-service-request"}),Hp="errUnknown";async function Ns(e,t,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((h,f)=>String(h).replace(`{${f}}`,r==null?void 0:r.path[f]),String(e)):String(e),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${h}=${r.query[h]}`).join("&"):"",a=`${Qc().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;Kp.debug(`fullUrl: ${a}`);const c={method:String(t).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const u=await exports.kosFetch(a,c);return u.status<200||u.status>=400?[`${u.statusText||Hp}`,null]:[null,(await u.json()).data]}function cn(){return{get:(e,t,s)=>Ns(e,"get",s,t),post:(e,t,s,r)=>Ns(e,"post",r,t,s),put:(e,t,s,r)=>Ns(e,"put",r,t,s),delete:(e,t,s,r)=>Ns(e,"delete",r,t,s)}}class Zc{constructor(){l(this,"middlewares",[])}use(t){this.middlewares.push(t)}async execute(t){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](t,r)};await this.middlewares[s](t,r)}}const zp=async(e,t)=>{const s=new Zc;t.forEach(o=>s.use(o));const r={data:e,result:{}};return await s.execute(r),r.result},Pt=e=>({type:e,build:(t,s)=>O.getInstance().modelManager.createModelInstance(e,t,s).data,buildAsync:async(t,s)=>{const r=O.getInstance().modelManager.createModelInstance(e,t,s);return await r.model.whenInitialized(),r.data}}),Vp=e=>{O.getInstance().modelManager.registerModel(e)},Gp=(e,t)=>{O.getInstance().modelManager.registerCompanionModel(e,t)},Ti="/kos/ui/internal/heartbeat/",Yp=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:r,beatTime:o})=>{const n=O.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${Ti}${e}`,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=o??2e3,f=window.setInterval(()=>{Kc({msg:{},options:{topic:`${Ti}${e}`,destinationAddress:t}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},b=()=>{p(),s&&s(),i.signal.removeEventListener("abort",b)};return i.signal.addEventListener("abort",b),{cleanUpHeartbeat:p}},Xc=(...e)=>t=>e.reduce((s,r)=>r(s),t),qp={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Wp(e,t){let s=1;const r={...qp,...t},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await e()}catch(c){if(m.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw c}throw new Error("All attempts failed")}const Qp=m.createLogger({name:"kos-service-request"}),ae=e=>({isMock:!1,URL:exports.BASE_URL}),Zp=(e,t,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d})=>{const h={method:"DELETE"};e&&(h.destinationAddress=e),o&&(h.tracker=o),kt(h,{ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d});const f=await s(n||`${t}/${r}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},kt=(e,{ordered:t,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i})=>(i&&(e.timeout=i),t&&(e.ordered=t),s&&(e.studio=s),r&&(e.fos=r),n&&(e.bridge=n),(o||o==="")&&(e.destinationAddress=o),e),Xp=(e,t,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,destinationAddress:u})=>{const d={method:"GET"};e&&(d.destinationAddress=e),kt(d,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const f=await s(r||t,d);if(!f.ok){let b;try{b=await f.json()}catch{}throw new pe(`There was a problem retrieving the model; returned status ${f.status}`,b)}return await f.json()},Jp=(e,t,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};e&&(h.destinationAddress=e),c&&(h.tracker=c),kt(h,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=r||t;Qp.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new pe(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},eg=(e,t,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};e&&(h.destinationAddress=e),kt(h,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,destinationAddress:d});const f=r||`${t}/${o}`,p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new pe(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class pe extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const _i=(e,t,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:u,timeout:d,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};e&&(f.destinationAddress=e),i&&(f.tracker=i),kt(f,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,destinationAddress:h});const p=await s(o||t,f);if(!p.ok){let w;try{w=await p.json()}catch{}throw new pe(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},Ii=(e="POST",t,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,destinationAddress:f})=>{const p={method:e};o&&(p.body=JSON.stringify(o)),t&&(p.destinationAddress=t),kt(p,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,destinationAddress:f});const b=await r(i||`${s}/${n}`,p);if(!b.ok){let M;try{M=await b.json()}catch{}throw new pe(`There was a problem modifying the model; returned status ${b.status}`,M)}return await b.json()},oe={build:({destinationAddress:e="",basePath:t,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:Xp(e,s||t,c),getModelById:eg(e,r||t,c),getOne:Jp(e,r||t,c),addModel:_i(e,n||t,c),deleteModel:Zp(e,o||t,c),modifyModel:Ii("POST",e,i||t,c),putModel:Ii("PUT",e,i||t,c),postModel:_i(e,n||t,c)}}},tg=tt(),Jc=()=>`kos-${tg}`,sg=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(Jc()),ln=async(e,t=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=$(e,i=>{C.debug(`recieved response for refId ${e}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${e} timed out. Cancelling.`))},t)}),rg=async(e,t,s)=>{const r=ln(s),o=await Promise.allSettled([e(t),r]);if(o[0].status==="fulfilled"){if(o[1].status==="rejected")throw Error(o[1].reason);if(o[0].value){if(o[1].value.error)throw Error(o[1].value.error);return o[0].value.data=o[1].value,o[0].value}}else throw Error(o[0].reason)},og=async({topic:e,msg:t,requestId:s})=>{const r=s??tt(),o=ln(r);z(e,t,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},de=new Map;class el{constructor(t){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=t,this._context=new E.ObservableMap({}),this._parent="",E.makeAutoObservable(this)}setParent(t){X(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=_e(this._parent))==null?void 0:t.model}get companionModels(){const t=_e(this._id);return t!=null&&t.model?dc(t.model):[]}get(t){var s,r;if(this._context.has(t))return this._context.get(t);if(this.companionModels.length>0){const o=this.companionModels.find(n=>{var i;return!n.id||!de.has(n.id)?!1:(i=de.get(n.id))==null?void 0:i.context.has(t)});if(o)return(s=de.get(o.id))==null?void 0:s.get(t)}if(this._parent)return(r=de.get(this._parent))==null?void 0:r.get(t)}set(t,s){this._context.set(t,s)}remove(t){this._context.delete(t)}clear(){this._context.clear()}}const G={createContext:(e,t)=>{const s=de.get(e)??new el(e);if(t){if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return de.set(e,s),s},getContext:e=>de.get(e),deleteContext:e=>{de.delete(e)},setParentContext:(e,t)=>{var s;if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);(s=de.get(e))==null||s.setParent(t)},rootContext:()=>de.get("root")};G.createContext("root");const ng=e=>G.getContext(e.id),no=m.createLogger({name:"kos-data-container"});class un{constructor(t){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=E.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1,this._optionsMap=(t==null?void 0:t.indexMap)||{};const s=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=E.observable.map(s),this.idx=Te(),E.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],r=new sn({container:this,key:s});this._index.set(t,r),this.idx[t]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((t,s)=>{var r;return t[s]=(r=this.index.get(s))==null?void 0:r.keys,t},{})}get revision(){return this._revision}addAll(t){E.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){E.runInAction(()=>{t.forEach(s=>this.removeModel(s))})}sortFn(t,s){const r=this._sortKey;return r?String(t[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){E.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const r=E.isObservable(t)?t:E.observable.object(t),o=this._disposerMap.get(t.id);o&&(o(),this._disposerMap.delete(t.id)),this._data.set(r.id||"",r),s||this.increment();const n=E.observe(r,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(r.id||"",n)}removeModel(t){this._data.delete(t),this.increment();const s=this._disposerMap.get(t);s&&(s(),this._disposerMap.delete(t))}updateModel(t){const s=E.observable.object(t);this._data.set(s.id||"",s),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(no.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const r=this.index.get(t);return r.index.has(s)?r.getByKey(s):(no.info(`key ${s} not found in ${t} index: ${Array.from(r.index.keys())}`),[])}else return no.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class ig{constructor({type:t,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=t,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 Ee(this.type)}}class ag{constructor({type:t,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=t,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 Ee(this.type)}}class tl{constructor(){l(this,"_token");E.makeAutoObservable(this),$("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class sl{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(t,s,...r){this.routes.push({method:t,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:t,path:s,parameters:o})}remove(t,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===t&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===t&&o.path===s)),r-this.routes.length}removeAllForPath(t){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==t),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==t),s-this.routes.length}getRoutes(){return this.routes.map(t=>({method:t.method,path:t.path}))}async handle(t,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(t.path),i={...t,params:n,query:o};for(const c of this.routes){const u=this.matchRoute(c.path,r);if(c.method===t.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(t){return t.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const t={};for(const s of this.openApiRoutes)t[s.path]||(t[s.path]={}),t[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:t}}extractPathParams(t){const[s,r]=t.split("?"),o=this.parseQueryParams(r);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:o,params:i}}return{path:s,query:o,params:{}}}matchRoute(t,s){const r=t.split("/").filter(Boolean),o=s.split("/").filter(Boolean);if(r.length!==o.length)return null;const n={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))n[r[i].slice(1)]=decodeURIComponent(o[i]);else if(r[i]!==o[i])return null;return n}parseQueryParams(t){return t?t.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const rl=m.createLogger({name:"intent-service"}),cg=e=>{Ko(`/kos/intent/${e.type}`)?z(`/kos/intent/${e.type}`,e.options,{"kos.intent.type":e.type}):rl.info(`No subscribers for intent ${e.type}. Intent not sent.`)},lg=async e=>new Promise(t=>{const{type:s,options:r}=e;if(Ko(`/kos/intent/${e.type}`)){const o=tt(),{unsubscribe:n}=$(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),t([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),t([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);z(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else rl.info(`No subscribers for intent ${e.type}. Intent not sent.`),t([null,{body:void 0,payload:void 0}])}),De=m.createLogger({name:"app-startup-service"});async function ol(e,t={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=t;if(e.length===0)return De.warn("No app IDs provided to waitForAppsToStart"),!0;De.debug(`Waiting for apps to start: ${e.join(", ")}`);try{const n=e.map(c=>`/kos/app/started/${c}`),i=await Vo(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>fy),[u,d]=await c.get("/api/kos/apps/started");return u?(De.error("Error fetching started apps:",u),[]):d}catch(c){De.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>e.every(u=>{const d=c.find(h=>h.appId===u);return!(!d||!d.started||o&&!d.postStarted)}),timeout:s}),a=e.filter(c=>{const u=i.find(d=>d.appId===c);return!!(!u||!u.started||o&&!u.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(De.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return De.info(`All apps started successfully: ${e.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${e.join(", ")}`;if(De.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function ug(e,t={}){return ol([e],t)}async function dg(e,t=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return e.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];e.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!t||(a==null?void 0:a.postStarted)===!0)})}catch(r){De.error("Failed to check app startup status:",r),e.forEach(o=>s[o]=!1)}return s}async function hg(){try{const e=await exports.kosFetch("kos:///api/kos/apps/started");if(!e.ok)return[];const t=await e.json();return(t==null?void 0:t.data)??[]}catch(e){return De.error("Failed to fetch started apps:",e),[]}}const Mo=E.when,dn=E.computed,X=E.runInAction,Y=E.autorun,nl=E.reaction,hn=E.observable,fn="Not Assigned",fg="kos.trouble.added",pg="kos.trouble.removed";var be=(e=>(e.TroubleRank="kos.trouble.rank.mapper",e.TroubleColor="kos.trouble.color.mapper",e.TroubleRole="kos.trouble.role.mapper",e))(be||{}),us=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(us||{});const il=m.createLogger({name:"config-bean-service",group:"Services"}),pn=exports.BASE_URL,al=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:gg,getOne:mg}=oe.build({destinationAddress:"",basePath:`${pn}/kos/config/`}),cl=async(e,t,s="/api/kos/config")=>(il.debug(`sending modify request for ConfigBean: ${e}`),gg({model:t,urlOverride:`${pn}${s}/${e}`})),ll=async(e,t="/api/kos/config")=>(il.debug(`sending get request for ConfigBean: ${e}`),await mg({urlOverride:`${pn}${t}/details/${e}/15`})),gn=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",Pr=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function ul(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:r}=s;return r&&(t={...t,...r}),t},{})}function dl(e,t="",s={}){for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const o=t?`${t}.${r}`:r;typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])?dl(e[r],o,s):s[o]=e[r]}return s}const hl=(e,t)=>{const s=e.details[0].bean||ul(e.details[0].scopes),r=dl(s);E.runInAction(()=>{const o={...r};t.props.setValues(o)})},fl=(e,t)=>{E.runInAction(()=>{e.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&gn(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&Pr(o)&&(o=Number(o),n=Number(n)),t.props[r]=o,t.prevProps[r]=n})})},pl=e=>Object.fromEntries(e.props.entries),yg=e=>t=>s=>e.build(t,s);var bg=Object.defineProperty,vg=Object.getOwnPropertyDescriptor,gl=(e,t,s,r)=>{for(var o=r>1?void 0:r?vg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&bg(t,s,o),o};function wg(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const mn="config-bean-model",Us=m.getLogger(mn),Eg=st("path");let tr=class{constructor(e,t){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,t),this.id=e,this.path=t.path,this.serviceBasePath=t.serviceBasePath;const{modifyConfigBean:s=cl,getConfigBean:r=ll}=t;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Te(),this.prevProps=Te()}get values(){return this.props.values}async ready(){Us.debug(`readying config bean ${this.path}`),Us.debug(`complete readying config bean ${this.path}`)}async load(){Us.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;hl(t,this),Us.debug(this.values);const s=e==null?void 0:e.data.details[0].schema;X(()=>{s&&(this._schema=s)})}}get schemaKeys(){var e;return Object.keys(((e=this._schema)==null?void 0:e.schema)||{})}getSchemaForProperty(e){var s,r;if(this.schemaKeys.includes(e))return(s=this._schema)==null?void 0:s.schema[e];const t=wg(this.schemaKeys,e);if(t)return(r=this._schema)==null?void 0:r.schema[t]}async updateProperty(e,t){this.props[e]=t,await this.updateConfigBean()}async updateConfigBean(){const e=pl(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){fl(e,this)}};gl([U({topic:`/kos/config/${Eg}`,websocket:!0})],tr.prototype,"handleConfigBeanUpdated",1);tr=gl([A(mn)],tr);const fs=new me({class:tr,type:mn}),kr=({path:e,lazy:t,serviceBasePath:s})=>(r,o)=>{r[k]=r[k]||{},r[k][o]={modelType:fs.type,id:`${fs.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:H.INIT,lazy:t}},{URL:ml}=ae(),{getOne:Mg,getAll:Tg}=oe.build({basePath:`${ml}/api/kos/regions/info`}),yl=async()=>{try{return await Mg({})}catch{return}},bl=async()=>{try{return await Tg({urlOverride:`${ml}/api/kos/regions`})}catch{return}},_g=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:yl,getRegions:bl},Symbol.toStringTag,{value:"Module"}));var le=(e=>(e[e.family=0]="family",e[e.scale=1]="scale",e[e.offset=2]="offset",e[e.decimals=3]="decimals",e[e.alias=4]="alias",e[e.system=5]="system",e))(le||{});const vl={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 Ig(e,t){const s=t.id,r=t.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{...vl});return{...e,...r}}function Og(e,t){const s=t.id,r=t.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...vl}}});return Object.keys(r).forEach(o=>{e[o]={...e[o],...r[o]}}),e}function Sg(e,t){const s=t.id,r=t.units.reduce((o,n)=>{const i=o[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),o[n.measure]=i,o},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(o=>{e[o]={...e[o],...r[o]}}),e}var $g=Object.defineProperty,Cg=Object.getOwnPropertyDescriptor,yn=(e,t,s,r)=>{for(var o=r>1?void 0:r?Cg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&$g(t,s,o),o};const qs="region-info-model",Ht=m.createLogger({name:"region-info-model"});let ps=class{constructor(e){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=e,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 e=this.regionSource.props.timeFormatId;if(!e)return"";const t=String(e),s=this.timeFormats[t];return s?String(s.id):""}get selectedTimeFormat(){const e=this.timeFormatId;return e?String(this.timeFormats[e].format):"HH:mm:ss"}get is12HourTimeFormat(){const e=this.timeFormatId;return e?this.timeFormats[e].ampm:!0}get dateFormatId(){const e=this.regionSource.props.dateFormatId;if(!e)return"";const t=String(e);return t?this.dateFormats[t].id:""}get selectedDateFormat(){const e=this.dateFormatId;return e?this.dateFormats[e].format:""}get selectedDateOrder(){const e=this.dateFormatId;return e?this.dateFormats[e].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(e=>({id:e,format:this.timeFormats[e].format,ampm:this.timeFormats[e].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(e=>({id:e,format:this.dateFormats[e].format,order:this.dateFormats[e].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(e=>({id:e,name:e}))}setSelectedTimeFormat(e){if(!this.timeFormatOptions.find(t=>t.id===e))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",e)}setSelectedDateFormat(e){if(!this.dateFormatOptions.find(t=>t.id===e))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",e)}setSelectedUnitSystem(e){if(!this.unitSystemOptions.find(t=>t.id===e))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",e)}getUnitSystem(e){if(!e)return this.defaultUnitSystem;const t=e==="drt"?"second":e,s=this.unitSystemMap[t];if(!s)throw Error(`No unit found with name: ${t}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[le.system]}getUnitMeasure(e){const t=e==="drt"?"second":e,s=this.unitSystemMap[t];if(!s)throw Error(`No unit found with name: ${t}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[le.family]}getDefaultUnitDecimalPlaces(e,t,s){if(!e||!t)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[e];if(!o)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[t.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${e} and unit system: ${t}. Unit system should come form list of unit systems: ${Object.keys(o).join(", ")}`);const i=n[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${e} and unit system: ${t}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[le.decimals]}getDefaultUnitForMeasure(e,t){if(!e||!t)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[e];if(!s)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[t.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${e} and unit system: ${t}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(e,t,s){if(t[le.family]!==s[le.family])throw new Error(`Cannot convert between units of different families: ${t[le.family]} and ${s[le.family]}`);const r=t[le.offset],o=t[le.scale],n=s[le.scale],i=s[le.offset],a=s[le.decimals];return((e-r)/(o/n)+i).toFixed(a)}convertByUnitName(e,t,s){const r=this.unitSystemMap[t],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${t} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(e,r,o)}convert(e,t,s){var a,c;if(t.unit&&s.unit)return this.convertByUnitName(e,t.unit,s.unit);const r=t.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];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||Ht.info("Could not find default unit for measure",s.measure)}if(!n&&t.measure&&t.system){const u=this.measureMap[t.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=u[t.system])==null?void 0:c.default,n||Ht.info("Could not find default unit for measure",t.measure)}return!n||!i?(Ht.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){Ht.debug("initializing region info")}async load(){Ht.debug("loading region info");const e=await bl();e&&(this.regions=e.data.map(s=>s.id),this.timeZoneMap=e.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=e.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const t=await yl();t&&(this.unitSystems=t.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=t.data.unitSystems.reduce(Ig,{}),this.measureMap=t.data.unitSystems.reduce(Og,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(Sg,{}),this.timeFormats=t.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=t.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var e,t;await((t=(e=this.regionSource).ready)==null?void 0:t.call(e))}};yn([kr({path:"kos:service:region:settings"})],ps.prototype,"regionSource",2);yn([kr({path:"kos:service:region"})],ps.prototype,"region",2);ps=yn([A(qs)],ps);const re={registration:{[qs]:{class:ps,singleton:!0}},type:qs,factory:ie.Singleton.create(qs)},sr=({source:e,defaultSystem:t="si",defaultMeasure:s})=>{let r={system:t,measure:s};return typeof e=="string"?r={...r,unit:e}:r={...r,...e},r},bn=(e,t,s)=>{const{model:r}=_e(re.type);if(!r)throw new Error("RegionInfo model not found");if(!er(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=sr({source:t}),i=sr({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(e,n,i)};function Oi(e,t,s){const r=t.toLowerCase().replace(/_/g,"-").replace(/s$/,""),o=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const n=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(o,{style:"unit",unit:r,unitDisplay:n,minimumFractionDigits:a,maximumFractionDigits:i}).format(e)}catch{return t}}const Dg=(e,t,s,r)=>{const o=bn(e,t,s),n=sr({source:t}),{model:i}=_e(re.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=sr({source:s||c,defaultMeasure:i.getUnitMeasure(n.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:o,unit:d||n.unit||"",display:Oi(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:Oi(o,d||n.unit||"",{...f,mode:"short"})}};function Si({start:e,end:t,count:s,decimals:r=0}){if(typeof e!="number"||typeof t!="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(e>=t)throw new Error("Start should be less than end.");const o=(t-e)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(e+i*o);n.push(a.toFixed(r))}return n}function $i({start:e,end:t,interval:s,decimals:r=0}){if(typeof e!="number"||typeof t!="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(e>=t)throw new Error("Start should be less than end.");const o=[];let n=e;for(;n<=t;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==t.toString()&&o.push(t.toString()),o}const lt=(e,t)=>s=>!e||!t?s:Pr(s)?bn(Number(s),e,t):s,xg=(e,t,s,r)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return Si(e.options).map(lt(s,r));if(e.options.type==="rangeInterval")return $i(e.options).map(lt(s,r));if(e.options.type==="list"){const{list:o}=e.options;return o.map(lt(s,r))}else{if(e.options.type==="unitSystemRangeCount"&&t)return Si(e.options.unitSystems[t]).map(lt(s,r));if(e.options.type==="unitSystemRangeInterval"&&t)return $i(e.options.unitSystems[t]).map(lt(s,r));if(e.options.type==="unitSystemList"&&t){const{list:o}=e.options.unitSystems[t];return o.map(lt(s,r))}}return[]},Ag=(e,t)=>{if(!((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options)))return e.options.type==="unitSystemRangeCount"&&t?{type:"rangeCount",...e.options.unitSystems[t]}:e.options.type==="unitSystemRangeInterval"&&t?{type:"rangeInterval",...e.options.unitSystems[t]}:e.options.type==="unitSystemList"&&t?{type:"list",...e.options.unitSystems[t]}:e.options.type==="unitSystemKeypad"&&t?{type:"keypad",...e.options.unitSystems[t]}:e.options};var Rg=Object.defineProperty,Pg=Object.getOwnPropertyDescriptor,vn=(e,t,s,r)=>{for(var o=r>1?void 0:r?Pg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Rg(t,s,o),o};function kg(e){return(e==null?void 0:e.type)==="enum"}function Lg(e){switch(e){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 e}}function Fg(e,t){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+e*1e3);return je.format(r,t)}const Ws="config-bean-prop-model",ut=m.createLogger({name:"config-bean-prop-model"}),Ng=st("path"),Ug=st("serviceBasePath");let gs=class{constructor(e,t){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=e,this.path=t.path,this.attribute=t.attribute,this.converter=t.converter,this.formatter=t.formatter,this.serviceBasePath=t.serviceBasePath,this.optionsExpander=t.optionsExpander}getDefaultUnitDecimalPlaces(e,t,s){if(!e)throw new Error("measure is required");if(!t)throw new Error("unitSystem is required");return al(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(e,t,s)}getDefaultUnitForMeasure(e,t){if(!e)throw new Error("measure is required");if(!t)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(e,t)}get schemaType(){const e=this.bean.getSchemaForProperty(this.attribute);return e!=null&&e.type?e.type:"String"}get schemaFormat(){const e=this.bean.getSchemaForProperty(this.attribute);return e!=null&&e.format?Lg(e.format):""}get options(){var i;const e=this.regionInfo.defaultUnitSystem,t=this.getConverter(),s=((i=t==null?void 0:t.to)==null?void 0:i.system)??e,r=this.bean.getSchemaForProperty(this.attribute),o=kg(r)?r.values:xg(r,s,t==null?void 0:t.from,t==null?void 0:t.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(e,t,s){const r=(e==null?void 0:e.measure)||s,o=(e==null?void 0:e.system)||t,n=e==null?void 0:e.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const e=this.regionInfo.defaultUnitSystem,t=this.getConverter();if(!t)throw Error("No converter defined");const s=t.measure,r=this.convertUnit(t.from,"si",s),o=this.convertUnit(t.to,e,s);return{backend:r,display:o}}set value(e){this.updateProperty(e)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const e=this.value,t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(e)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,t,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let u=String(e);return u=c.formatToParts(Number(e))[0].value,Number(u)}}catch(c){ut.info(`error formatting value ${e}`,c)}return Number(e).toFixed(i)}return e}get previousValue(){return this.getValue(!1)}getValue(e){const t=this.bean[e?"props":"prevProps"][this.attribute];if(typeof t=="boolean")return t;if(this.getConverter()&&!isNaN(t)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(t),r,o)}return t||""}async activate(){ut.debug(`activating config bean ${this.id}`)}get displayValue(){const e=this.value;if(typeof e=="boolean")return String(e);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return Fg(e,s)}if(!isNaN(e))try{const t=this.getConverter(),s=this.getFormatterOptions(t);if(s){let r=String(e);return r=s.format(Number(e)),r}}catch(t){ut.error(`error formatting value ${e}`,t)}return String(e)}get unit(){const e=this.getConverter();if(!isNaN(this.value)){const t=this.getFormatterOptions(e);if(t){const r=t.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(e)}}return this.getDefaultUnit(e)}get displayOptions(){var o;const e=this.bean.getSchemaForProperty(this.attribute),t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??t;return Ag(e,r)}getMeasureFromFormat(){const e=this.schemaFormat;return e?this.regionInfo.getUnitMeasure(e):""}getConverterFromFormat(){const e=this.getMeasureFromFormat();if(e){const t=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(e,t),measure:e}}return{}}getDefaultUnit(e){var r,o;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure;return s?((r=e==null?void 0:e.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=e==null?void 0:e.to)==null?void 0:o.system)||t):this.getConverterFromFormat().unit}getFormatterOptions(e){var n,i,a;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(e)}:null,u=this.formatter||c;if(u){let d=typeof u=="function"?u(((n=e==null?void 0:e.to)==null?void 0:n.system)||t):u;s&&(d={unit:this.getDefaultUnit(e),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=e==null?void 0:e.to)==null?void 0:i.system)||t,(a=e==null?void 0:e.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...d})}catch(h){ut.error(`error creating formatter ${d}. Returning the raw value`,h)}}else ut.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,u,d,h,f,p;const{unit:e,measure:t}=this.getConverterFromFormat(),s=e==="drt"?"second":e;if(this.converter){const b=(r=this.converter)==null?void 0:r.measure,w=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,M=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=b||w||M||t,F=((u=(c=this.converter)==null?void 0:c.to)==null?void 0:u.unit)||this.regionInfo.getDefaultUnitForMeasure(_,((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),Q=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(F),D=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:D,...this.converter.from},to:{...this.converter.to,unit:F,system:Q},measure:_}}if(s&&t){const b=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),M=this.regionInfo.getUnitSystem(b);return{measure:t,to:{unit:w===M?s:b}}}}async updateProperty(e){ut.debug(`updating property ${this.attribute} with value ${e}`);let t=e;if(this.getConverter()&&!isNaN(t)){const{backend:o,display:n}=this.getConverterUnits();t=this.regionInfo.convert(Number(t),n,o)}const r=Array.isArray(t)?JSON.stringify(t):String(t);await this.bean.updateProperty(this.attribute,r)}};vn([Rt({modelType:re.type})],gs.prototype,"regionInfo",2);vn([kr({path:Ng,serviceBasePath:Ug})],gs.prototype,"bean",2);gs=vn([A(Ws)],gs);const rt={registration:{[Ws]:{class:gs,singleton:!1}},type:Ws,factory:ie.Factory.create(Ws)};function jg(e){const{path:t,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=e,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[k]=u[k]||{},u[k][d]={modelType:rt.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:H.INIT,lazy:n}}}const wl="future-model",Lt=Pt(wl),Lr=m.createLogger({name:"future-service",group:"Services"}),{isMock:Bg,URL:Cs}=ae();var Ke=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Ke||{});const{getAll:Kg,modifyModel:Hg,addModel:zg,deleteModel:Vg,postModel:Gg}=oe.build({destinationAddress:"",basePath:`${Cs}/api/future`,mock:Bg}),Yg=async()=>await Kg({}),El=async(e,t="/api/kos/future")=>(Lr.info(`sending delete request for Future: ${e}`),await Vg({id:e,urlOverride:`${Cs}${t}/${e}`})),Ml=async(e,t="/api/kos/future")=>(Lr.info("sending add request for Future"),await zg({model:e,urlOverride:`${Cs}${t}`})),qg=async(e,t,s="/api/kos/future")=>(Lr.info(`sending modify request for Future: ${e}`),Hg({model:t,id:e,urlOverride:`${Cs}${s}/${e}`})),Tl=async(e,t="/api/kos/future")=>(Lr.info(`sending cancel request for Future: ${e}`),Gg({urlOverride:`${Cs}${t}/${e}/cancel`,ordered:!0,model:{}})),wn=e=>({id:String(e.id),progress:e.progress,remainingTimeMs:e.remainingTimeMs,endState:e.endState,reason:e.reason,clientData:e.clientData,reasonData:e.reasonData,note:e.note,tracker:e.tracker}),En=(e,t)=>{m.debug(`future dto ${e.id} end state ${e.endState}`),m.debug(`future model ${t.id} end state ${t.endState}`),t.endState?m.debug(`future model ${t.id} is already complete`):(m.debug(`updating future model ${t.id}`),E.runInAction(()=>{const s=wn(e);X(()=>{Object.keys(s).forEach(r=>{r==="id"?(t.futureId=s.id,s.tracker||(t.id=s.id)):r==="tracker"?t.id=s.tracker:t[r]=s[r]})})}))},_l=e=>t=>s=>e.build(String(t),s),Mn=e=>t=>Xc(wn,_l(e)(t.tracker||t.id))(t);var Wg=Object.defineProperty,Qg=Object.getOwnPropertyDescriptor,Il=(e,t,s,r)=>{for(var o=r>1?void 0:r?Qg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Wg(t,s,o),o};const io=m.getLogger(Lt.type);let rr=class{constructor(e,t,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,t),this.logger=s.logger,this.id=e,this.futureId=t.id,this.namespace=t.namespace||"kos",this._cancelFuture=Tl,Mo(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{io.info(`Future ${this.id} has completed with status ${this.status}`),Xe(this)})}async load(){io.debug(`loading Future ${this.id}`)}unload(){io.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Mo(()=>this.futureId!==fn),await this._cancelFuture(this.futureId,e)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const e=this.remainingTimeMs||-1;if(e<0)return"";const t={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(t))if(Math.abs(e)>=d){s=u,r=Math.round(e/d);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(e){this.logger.debug(`Future ${this.id} updated. future: ${e.id} endState: ${e.endState} progress: ${e.progress} remainingTimeMs: ${e.remainingTimeMs}`),En(e,this)}};Il([U({topic:`kos.future/${Zs}`})],rr.prototype,"handleFutureUpdated",1);rr=Il([A(Lt.type)],rr);const Ol=rr,Sl=cn();var Zg=Object.defineProperty,Xg=Object.getOwnPropertyDescriptor,$l=(e,t,s,r)=>{for(var o=r>1?void 0:r?Xg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Zg(t,s,o),o};const Cl="browser-router-model",Jg="kos.http.request",em="kos.http.response";let or=class{constructor(e,t,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=e,this.logger=s.logger,this.router=new sl}get id(){return this._id}async handleRequest(e,t){const s=t.headers["src-addr"],r=t.headers["dst-addr"],o=t.headers.url,n=t.headers.method,i=t.headers["request-id"],a={id:i,method:n,path:o,body:e};let c=200;const u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),Hc({msg:d,options:{responseId:i,destinationAddress:s,type:em,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(e,t,...s){this.router.use(e,t,...s)}remove(e,t){return this.router.remove(e,t)}removeAllForPath(e){return this.router.removeAllForPath(e)}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}`)}};$l([U({topic:Jg})],or.prototype,"handleRequest",1);or=$l([A(Cl)],or);const Tn=new Me({class:or,type:Cl}),Dl="future-container-model",He=Pt(Dl),xl=e=>Mn(Lt)(e),tm=e=>{const t=xl(e);return He.build(He.type,{}).addFutureModel(t),t},sm=e=>He.build(He.type,{}).getFuture(String(e)),Je={buildFutureModel:xl,initiateFuture:tm,getFuture:sm};var rm=Object.defineProperty,om=Object.getOwnPropertyDescriptor,_n=(e,t,s,r)=>{for(var o=r>1?void 0:r?om(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&rm(t,s,o),o};const js=m.getLogger(He.type);let ms=class{constructor(e,t,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=El,addFuture:o=Ml}=t;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=e,this._futures=new Se,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(e){return this._futures.getModel(e)}addFutureModel(e){this._futures.addModel(e)}removeFutureModel(e){this._futures.removeModel(e)}async removeFuture(e){try{await this._deleteFuture(e)}catch(t){js.error("error deleting a Future"),js.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const r=Mn(Lt)(s);return this.addFutureModel(r),r}}catch(t){throw js.error("error creating a Future"),js.error(t),t}}handleFutureUpdated(e,t){const s=Je.buildFutureModel(e);this.addFutureModel(s);const r=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${r}`),z(r,t.body,t.headers)}};_n([Oe],ms.prototype,"_futures",2);_n([U({topic:"kos.future"})],ms.prototype,"handleFutureUpdated",1);ms=_n([A(He.type)],ms);const Al=ms,{URL:Ds}=ae(),{getOne:nm,postModel:im,deleteModel:Rl}=oe.build({basePath:`${Ds}/api/keyVal`}),To=m.createLogger({name:"key-value-service",group:"Services"}),Pl=async(e,t)=>{await Rl({urlOverride:`${Ds}/api/keyVal/${e}/${t}`,id:t})},kl=async(e,t,s)=>{const r=await im({urlOverride:`${Ds}/api/keyVal/${e}/${t}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw To.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${e}`);return r.data},Ll=async(e="studio")=>{To.debug(`Retrieving all key-value data for namespace: ${e}`);const t=await nm({urlOverride:`${Ds}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw To.error("Failed to retrieve key-value data",t),new Error(`Failed to retrieve key-value data for namespace ${e}`);return t.data},am=async e=>{await Rl({urlOverride:`${Ds}/api/keyVal/${e}`,id:""})},cm=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Pl,deleteKeyValueNamespace:am,getKeyValue:Ll,updateKeyValue:kl},Symbol.toStringTag,{value:"Module"}));var lm=Object.defineProperty,um=Object.getOwnPropertyDescriptor,In=(e,t,s,r)=>{for(var o=r>1?void 0:r?um(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&lm(t,s,o),o};const Fl="key-value-model";let ys=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=e,this.logger=s.logger,this.data=Te(),this.namespace=t.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(e,t){this.logger.debug(`updating studio-state ${e} with value ${t}`),t!==void 0?(await kl(this.namespace,e,t),this.data[e]=t):(await Pl(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await Ll(this.namespace);this.data.setValues(e)}handleStateUpdate(e){e.namespace===this.namespace&&(this.data[e.key]=e.value)}handleStateDelete(e){e.namespace===this.namespace&&(this.data[e.key]=void 0)}};In([U({topic:"/keyVal/set"})],ys.prototype,"handleStateUpdate",1);In([U({topic:"/keyVal/remove"})],ys.prototype,"handleStateDelete",1);ys=In([A(Fl)],ys);const On=new me({class:ys,type:Fl});var he="INUMBER",Ft="IOP1",Nt="IOP2",Ut="IOP3",Ae="IVAR",et="IVARNAME",Et="IFUNCALL",Fr="IFUNDEF",ne="IEXPR",Sn="IEXPREVAL",ot="IMEMBER",Nr="IENDSTATEMENT",Mt="IARRAY";function R(e,t){this.type=e,this.value=t??0}R.prototype.toString=function(){switch(this.type){case he:case Ft:case Nt:case Ut:case Ae:case et:case Nr:return this.value;case Et:return"CALL "+this.value;case Fr:return"DEF "+this.value;case Mt:return"ARRAY "+this.value;case ot:return"."+this.value;default:return"Invalid Instruction"}};function Ur(e){return new R(Ft,e)}function Fe(e){return new R(Nt,e)}function Nl(e){return new R(Ut,e)}function _o(e,t,s,r,o){for(var n=[],i=[],a,c,u,d,h=0;h<e.length;h++){var f=e[h],p=f.type;if(p===he||p===et)Array.isArray(f.value)?n.push.apply(n,_o(f.value.map(function(b){return new R(he,b)}).concat(new R(Mt,f.value.length)),t,s,r,o)):n.push(f);else if(p===Ae&&o.hasOwnProperty(f.value))f=new R(he,o[f.value]),n.push(f);else if(p===Nt&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new R(he,d(a.value,c.value)),n.push(f);else if(p===Ut&&n.length>2)u=n.pop(),c=n.pop(),a=n.pop(),f.value==="?"?n.push(a.value?c.value:u.value):(d=r[f.value],f=new R(he,d(a.value,c.value,u.value)),n.push(f));else if(p===Ft&&n.length>0)a=n.pop(),d=t[f.value],f=new R(he,d(a.value)),n.push(f);else if(p===ne){for(;n.length>0;)i.push(n.shift());i.push(new R(ne,_o(f.value,t,s,r,o)))}else if(p===ot&&n.length>0)a=n.pop(),n.push(new R(he,a.value[f.value]));else{for(;n.length>0;)i.push(n.shift());i.push(f)}}for(;n.length>0;)i.push(n.shift());return i}function Ul(e,t,s){for(var r=[],o=0;o<e.length;o++){var n=e[o],i=n.type;if(i===Ae&&n.value===t)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===Ft?u=Ur(c.value):c.type===Nt?u=Fe(c.value):c.type===Ut?u=Nl(c.value):u=new R(c.type,c.value),r.push(u)}else i===ne?r.push(new R(ne,Ul(n.value,t,s))):r.push(n)}return r}function We(e,t,s){var r=[],o,n,i,a,c,u;if($n(e))return Ce(e,s);for(var d=e.length,h=0;h<d;h++){var f=e[h],p=f.type;if(p===he||p===et)r.push(f.value);else if(p===Nt)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!We(n,t,s):!1):f.value==="or"?r.push(o?!0:!!We(n,t,s)):f.value==="="?(a=t.binaryOps[f.value],r.push(a(o,We(n,t,s),s))):(a=t.binaryOps[f.value],r.push(a(Ce(o,s),Ce(n,s))));else if(p===Ut)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(We(o?n:i,t,s)):(a=t.ternaryOps[f.value],r.push(a(Ce(o,s),Ce(n,s),Ce(i,s))));else if(p===Ae)if(f.value in t.functions)r.push(t.functions[f.value]);else if(f.value in t.unaryOps&&t.parser.isOperatorEnabled(f.value))r.push(t.unaryOps[f.value]);else{var b=s[f.value];if(b!==void 0)r.push(b);else throw new Error("undefined variable: "+f.value)}else if(p===Ft)o=r.pop(),a=t.unaryOps[f.value],r.push(a(Ce(o,s)));else if(p===Et){for(u=f.value,c=[];u-- >0;)c.unshift(Ce(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===Fr)r.push(function(){for(var w=r.pop(),M=[],_=f.value;_-- >0;)M.unshift(r.pop());var F=r.pop(),Q=function(){for(var D=Object.assign({},s),I=0,W=M.length;I<W;I++)D[M[I]]=arguments[I];return We(w,t,D)};return Object.defineProperty(Q,"name",{value:F,writable:!1}),s[F]=Q,Q}());else if(p===ne)r.push(dm(f,t));else if(p===Sn)r.push(f);else if(p===ot)o=r.pop(),r.push(o[f.value]);else if(p===Nr)r.pop();else if(p===Mt){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:Ce(r[0],s)}function dm(e,t,s){return $n(e)?e:{type:Sn,value:function(r){return We(e.value,t,r)}}}function $n(e){return e&&e.type===Sn}function Ce(e,t){return $n(e)?e.value(t):e}function Cn(e,t){for(var s=[],r,o,n,i,a,c,u=0;u<e.length;u++){var d=e[u],h=d.type;if(h===he)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Ci).join(", ")+"]"):s.push(Ci(d.value));else if(h===Nt)o=s.pop(),r=s.pop(),i=d.value,t?i==="^"?s.push("Math.pow("+r+", "+o+")"):i==="and"?s.push("(!!"+r+" && !!"+o+")"):i==="or"?s.push("(!!"+r+" || !!"+o+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+o+")))"):i==="=="?s.push("("+r+" === "+o+")"):i==="!="?s.push("("+r+" !== "+o+")"):i==="["?s.push(r+"[("+o+") | 0]"):s.push("("+r+" "+i+" "+o+")"):i==="["?s.push(r+"["+o+"]"):s.push("("+r+" "+i+" "+o+")");else if(h===Ut)if(n=s.pop(),o=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+o+" : "+n+")");else throw new Error("invalid Expression");else if(h===Ae||h===et)s.push(d.value);else if(h===Ft)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):t?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===Et){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===Fr){for(o=s.pop(),c=d.value,a=[];c-- >0;)a.unshift(s.pop());r=s.pop(),t?s.push("("+r+" = function("+a.join(", ")+") { return "+o+" })"):s.push("("+r+"("+a.join(", ")+") = "+o+")")}else if(h===ot)r=s.pop(),s.push(r+"."+d.value);else if(h===Mt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ne)s.push("("+Cn(d.value,t)+")");else if(h!==Nr)throw new Error("invalid Expression")}return s.length>1&&(t?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Ci(e){return typeof e=="string"?JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):e}function gt(e,t){for(var s=0;s<e.length;s++)if(e[s]===t)return!0;return!1}function Dn(e,t,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<e.length;n++){var i=e[n];i.type===Ae||i.type===et?!r&&!gt(t,i.value)?t.push(i.value):(o!==null&&(gt(t,o)||t.push(o)),o=i.value):i.type===ot&&r&&o!==null?o+="."+i.value:i.type===ne?Dn(i.value,t,s):o!==null&&(gt(t,o)||t.push(o),o=null)}o!==null&&!gt(t,o)&&t.push(o)}function ve(e,t){this.tokens=e,this.parser=t,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.functions=t.functions}ve.prototype.simplify=function(e){return e=e||{},new ve(_o(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,e),this.parser)};ve.prototype.substitute=function(e,t){return t instanceof ve||(t=this.parser.parse(String(t))),new ve(Ul(this.tokens,e,t),this.parser)};ve.prototype.evaluate=function(e){return e=e||{},We(this.tokens,this,e)};ve.prototype.toString=function(){return Cn(this.tokens,!1)};ve.prototype.symbols=function(e){e=e||{};var t=[];return Dn(this.tokens,t,e),t};ve.prototype.variables=function(e){e=e||{};var t=[];Dn(this.tokens,t,e);var s=this.functions;return t.filter(function(r){return!(r in s)})};ve.prototype.toJSFunction=function(e,t){var s=this,r=new Function(e,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+Cn(this.simplify(t).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var bs="TEOF",N="TOP",jr="TNUMBER",jl="TSTRING",Re="TPAREN",Tt="TBRACKET",Br="TCOMMA",xn="TNAME",An="TSEMICOLON";function Bl(e,t,s){this.type=e,this.value=t,this.index=s}Bl.prototype.toString=function(){return this.type+": "+this.value};function V(e,t){this.pos=0,this.current=null,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.consts=e.consts,this.expression=t,this.savedPosition=0,this.savedCurrent=null,this.options=e.options,this.parser=e}V.prototype.newToken=function(e,t,s){return new Bl(e,t,s??this.pos)};V.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};V.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};V.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(bs,"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)+'"')};V.prototype.isString=function(){var e=!1,t=this.pos,s=this.expression.charAt(t);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,t+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(t+1,r);this.current=this.newToken(jl,this.unescape(o),t),e=!0;break}r=this.expression.indexOf(s,r+1)}return e};V.prototype.isParen=function(){var e=this.expression.charAt(this.pos);return e==="("||e===")"?(this.current=this.newToken(Re,e),this.pos++,!0):!1};V.prototype.isBracket=function(){var e=this.expression.charAt(this.pos);return(e==="["||e==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(Tt,e),this.pos++,!0):!1};V.prototype.isComma=function(){var e=this.expression.charAt(this.pos);return e===","?(this.current=this.newToken(Br,","),this.pos++,!0):!1};V.prototype.isSemicolon=function(){var e=this.expression.charAt(this.pos);return e===";"?(this.current=this.newToken(An,";"),this.pos++,!0):!1};V.prototype.isConst=function(){for(var e=this.pos,t=e;t<this.expression.length;t++){var s=this.expression.charAt(t);if(s.toUpperCase()===s.toLowerCase()&&(t===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(t>e){var r=this.expression.substring(e,t);if(r in this.consts)return this.current=this.newToken(jr,this.consts[r]),this.pos+=r.length,!0}return!1};V.prototype.isNamedOp=function(){for(var e=this.pos,t=e;t<this.expression.length;t++){var s=this.expression.charAt(t);if(s.toUpperCase()===s.toLowerCase()&&(t===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(t>e){var r=this.expression.substring(e,t);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(N,r),this.pos+=r.length,!0}return!1};V.prototype.isName=function(){for(var e=this.pos,t=e,s=!1;t<this.expression.length;t++){var r=this.expression.charAt(t);if(r.toUpperCase()===r.toLowerCase()){if(t===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(t===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(e,t);return this.current=this.newToken(xn,o),this.pos+=o.length,!0}return!1};V.prototype.isWhitespace=function(){for(var e=!1,t=this.expression.charAt(this.pos);(t===" "||t===" "||t===`
|
|
78
|
-
`||t==="\r")&&(e=!0,this.pos++,!(this.pos>=this.expression.length));)t=this.expression.charAt(this.pos);return e};var
|
|
79
|
-
`;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var o=e.substring(t+1,t+5);
|
|
80
|
-
`,s+1);while(s>=0&&s<this.pos);return{line:e,column:t}};V.prototype.parseError=function(e){var t=this.getCoordinates();throw new Error("parse error ["+t.line+":"+t.column+"]: "+e)};function j(e,t,s){this.parser=e,this.tokens=t,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}j.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};j.prototype.tokenMatches=function(e,t){return typeof t>"u"?!0:Array.isArray(t)?gt(t,e.value):typeof t=="function"?t(e):e.value===t};j.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};j.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};j.prototype.accept=function(e,t){return this.nextToken.type===e&&this.tokenMatches(this.nextToken,t)?(this.next(),!0):!1};j.prototype.expect=function(e,t){if(!this.accept(e,t)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(t||e))}};j.prototype.parseAtom=function(e){var t=this.tokens.unaryOps;function s(o){return o.value in t}if(this.accept(xn)||this.accept(N,s))e.push(new R(Ae,this.current.value));else if(this.accept(jr))e.push(new R(he,this.current.value));else if(this.accept(jl))e.push(new R(he,this.current.value));else if(this.accept(Re,"("))this.parseExpression(e),this.expect(Re,")");else if(this.accept(Tt,"["))if(this.accept(Tt,"]"))e.push(new R(Mt,0));else{var r=this.parseArrayList(e);e.push(new R(Mt,r))}else throw new Error("unexpected "+this.nextToken)};j.prototype.parseExpression=function(e){var t=[];this.parseUntilEndStatement(e,t)||(this.parseVariableAssignmentExpression(t),!this.parseUntilEndStatement(e,t)&&this.pushExpression(e,t))};j.prototype.pushExpression=function(e,t){for(var s=0,r=t.length;s<r;s++)e.push(t[s])};j.prototype.parseUntilEndStatement=function(e,t){return this.accept(An)?(this.nextToken&&this.nextToken.type!==bs&&!(this.nextToken.type===Re&&this.nextToken.value===")")&&t.push(new R(Nr)),this.nextToken.type!==bs&&this.parseExpression(t),e.push(new R(ne,t)),!0):!1};j.prototype.parseArrayList=function(e){for(var t=0;!this.accept(Tt,"]");)for(this.parseExpression(e),++t;this.accept(Br);)this.parseExpression(e),++t;return t};j.prototype.parseVariableAssignmentExpression=function(e){for(this.parseConditionalExpression(e);this.accept(N,"=");){var t=e.pop(),s=[],r=e.length-1;if(t.type===Et){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var o=0,n=t.value+1;o<n;o++){var i=r-o;e[i].type===Ae&&(e[i]=new R(et,e[i].value))}this.parseVariableAssignmentExpression(s),e.push(new R(ne,s)),e.push(new R(Fr,t.value));continue}if(t.type!==Ae&&t.type!==ot)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),e.push(new R(et,t.value)),e.push(new R(ne,s)),e.push(Fe("="))}};j.prototype.parseConditionalExpression=function(e){for(this.parseOrExpression(e);this.accept(N,"?");){var t=[],s=[];this.parseConditionalExpression(t),this.expect(N,":"),this.parseConditionalExpression(s),e.push(new R(ne,t)),e.push(new R(ne,s)),e.push(Nl("?"))}};j.prototype.parseOrExpression=function(e){for(this.parseAndExpression(e);this.accept(N,"or");){var t=[];this.parseAndExpression(t),e.push(new R(ne,t)),e.push(Fe("or"))}};j.prototype.parseAndExpression=function(e){for(this.parseComparison(e);this.accept(N,"and");){var t=[];this.parseComparison(t),e.push(new R(ne,t)),e.push(Fe("and"))}};var fm=["==","!=","<","<=",">=",">","in"];j.prototype.parseComparison=function(e){for(this.parseAddSub(e);this.accept(N,fm);){var t=this.current;this.parseAddSub(e),e.push(Fe(t.value))}};var pm=["+","-","||"];j.prototype.parseAddSub=function(e){for(this.parseTerm(e);this.accept(N,pm);){var t=this.current;this.parseTerm(e),e.push(Fe(t.value))}};var gm=["*","/","%"];j.prototype.parseTerm=function(e){for(this.parseFactor(e);this.accept(N,gm);){var t=this.current;this.parseFactor(e),e.push(Fe(t.value))}};j.prototype.parseFactor=function(e){var t=this.tokens.unaryOps;function s(o){return o.value in t}if(this.save(),this.accept(N,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===Re&&this.nextToken.value==="("){this.restore(),this.parseExponential(e);return}else if(this.nextToken.type===An||this.nextToken.type===Br||this.nextToken.type===bs||this.nextToken.type===Re&&this.nextToken.value===")"){this.restore(),this.parseAtom(e);return}}var r=this.current;this.parseFactor(e),e.push(Ur(r.value))}else this.parseExponential(e)};j.prototype.parseExponential=function(e){for(this.parsePostfixExpression(e);this.accept(N,"^");)this.parseFactor(e),e.push(Fe("^"))};j.prototype.parsePostfixExpression=function(e){for(this.parseFunctionCall(e);this.accept(N,"!");)e.push(Ur("!"))};j.prototype.parseFunctionCall=function(e){var t=this.tokens.unaryOps;function s(n){return n.value in t}if(this.accept(N,s)){var r=this.current;this.parseAtom(e),e.push(Ur(r.value))}else for(this.parseMemberExpression(e);this.accept(Re,"(");)if(this.accept(Re,")"))e.push(new R(Et,0));else{var o=this.parseArgumentList(e);e.push(new R(Et,o))}};j.prototype.parseArgumentList=function(e){for(var t=0;!this.accept(Re,")");)for(this.parseExpression(e),++t;this.accept(Br);)this.parseExpression(e),++t;return t};j.prototype.parseMemberExpression=function(e){for(this.parseAtom(e);this.accept(N,".")||this.accept(Tt,"[");){var t=this.current;if(t.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(xn),e.push(new R(ot,this.current.value))}else if(t.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(e),this.expect(Tt,"]"),e.push(Fe("["))}else throw new Error("unexpected symbol: "+t.value)}};function mm(e,t){return Number(e)+Number(t)}function ym(e,t){return e-t}function bm(e,t){return e*t}function vm(e,t){return e/t}function wm(e,t){return e%t}function Em(e,t){return Array.isArray(e)&&Array.isArray(t)?e.concat(t):""+e+t}function Mm(e,t){return e===t}function Tm(e,t){return e!==t}function _m(e,t){return e>t}function Im(e,t){return e<t}function Om(e,t){return e>=t}function Sm(e,t){return e<=t}function $m(e,t){return!!(e&&t)}function Cm(e,t){return!!(e||t)}function Dm(e,t){return gt(t,e)}function xm(e){return(Math.exp(e)-Math.exp(-e))/2}function Am(e){return(Math.exp(e)+Math.exp(-e))/2}function Rm(e){return e===1/0?1:e===-1/0?-1:(Math.exp(e)-Math.exp(-e))/(Math.exp(e)+Math.exp(-e))}function Pm(e){return e===-1/0?e:Math.log(e+Math.sqrt(e*e+1))}function km(e){return Math.log(e+Math.sqrt(e*e-1))}function Lm(e){return Math.log((1+e)/(1-e))/2}function Di(e){return Math.log(e)*Math.LOG10E}function Fm(e){return-e}function Nm(e){return!e}function Um(e){return e<0?Math.ceil(e):Math.floor(e)}function jm(e){return Math.random()*(e||1)}function xi(e){return Rn(e+1)}function Bm(e){return isFinite(e)&&e===Math.round(e)}var Km=4.7421875,ao=[.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 Rn(e){var t,s;if(Bm(e)){if(e<=0)return isFinite(e)?1/0:NaN;if(e>171)return 1/0;for(var r=e-2,o=e-1;r>1;)o*=r,r--;return o===0&&(o=1),o}if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*Rn(1-e));if(e>=171.35)return 1/0;if(e>85){var n=e*e,i=n*e,a=i*e,c=a*e;return Math.sqrt(2*Math.PI/e)*Math.pow(e/Math.E,e)*(1+1/(12*e)+1/(288*n)-139/(51840*i)-571/(2488320*a)+163879/(209018880*c)+5246819/(75246796800*c*e))}--e,s=ao[0];for(var u=1;u<ao.length;++u)s+=ao[u]/(e+u);return t=e+Km+.5,Math.sqrt(2*Math.PI)*Math.pow(t,e+.5)*Math.exp(-t)*s}function Hm(e){return Array.isArray(e)?e.length:String(e).length}function Ai(){for(var e=0,t=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),o;t<r?(o=t/r,e=e*o*o+1,t=r):r>0?(o=r/t,e+=o*o):e+=r}return t===1/0?1/0:t*Math.sqrt(e)}function Ri(e,t,s){return e?t:s}function zm(e,t){return typeof t>"u"||+t==0?Math.round(e):(e=+e,t=-+t,isNaN(e)||!(typeof t=="number"&&t%1===0)?NaN:(e=e.toString().split("e"),e=Math.round(+(e[0]+"e"+(e[1]?+e[1]-t:-t))),e=e.toString().split("e"),+(e[0]+"e"+(e[1]?+e[1]+t:t))))}function Vm(e,t,s){return s&&(s[e]=t),t}function Gm(e,t){return e[t|0]}function Ym(e){return arguments.length===1&&Array.isArray(e)?Math.max.apply(Math,e):Math.max.apply(Math,arguments)}function qm(e){return arguments.length===1&&Array.isArray(e)?Math.min.apply(Math,e):Math.min.apply(Math,arguments)}function Wm(e,t){if(typeof e!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(t))throw new Error("Second argument to map is not an array");return t.map(function(s,r){return e(s,r)})}function Qm(e,t,s){if(typeof e!="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,o,n){return e(r,o,n)},t)}function Zm(e,t){if(typeof e!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(t))throw new Error("Second argument to filter is not an array");return t.filter(function(s,r){return e(s,r)})}function Xm(e,t){if(!(Array.isArray(t)||typeof t=="string"))throw new Error("Second argument to indexOf is not a string or array");return t.indexOf(e)}function Jm(e,t){if(!Array.isArray(t))throw new Error("Second argument to join is not an array");return t.join(e)}function ey(e){return(e>0)-(e<0)||+e}var Pi=1/3;function ty(e){return e<0?-Math.pow(-e,Pi):Math.pow(e,Pi)}function sy(e){return Math.exp(e)-1}function ry(e){return Math.log(1+e)}function oy(e){return Math.log(e)/Math.LN2}function nt(e){this.options=e||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||xm,cosh:Math.cosh||Am,tanh:Math.tanh||Rm,asinh:Math.asinh||Pm,acosh:Math.acosh||km,atanh:Math.atanh||Lm,sqrt:Math.sqrt,cbrt:Math.cbrt||ty,log:Math.log,log2:Math.log2||oy,ln:Math.log,lg:Math.log10||Di,log10:Math.log10||Di,expm1:Math.expm1||sy,log1p:Math.log1p||ry,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||Um,"-":Fm,"+":Number,exp:Math.exp,not:Nm,length:Hm,"!":xi,sign:Math.sign||ey},this.binaryOps={"+":mm,"-":ym,"*":bm,"/":vm,"%":wm,"^":Math.pow,"||":Em,"==":Mm,"!=":Tm,">":_m,"<":Im,">=":Om,"<=":Sm,and:$m,or:Cm,in:Dm,"=":Vm,"[":Gm},this.ternaryOps={"?":Ri},this.functions={random:jm,fac:xi,min:qm,max:Ym,hypot:Math.hypot||Ai,pyt:Math.hypot||Ai,pow:Math.pow,atan2:Math.atan2,if:Ri,gamma:Rn,roundTo:zm,map:Wm,fold:Qm,filter:Zm,indexOf:Xm,join:Jm},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}nt.prototype.parse=function(e){var t=[],s=new j(this,new V(this,e),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(t),s.expect(bs,"EOF"),new ve(t,this)};nt.prototype.evaluate=function(e,t){return this.parse(e).evaluate(t)};var Kl=new nt;nt.parse=function(e){return Kl.parse(e)};nt.evaluate=function(e,t){return Kl.parse(e).evaluate(t)};var ki={"+":"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 ny(e){return ki.hasOwnProperty(e)?ki[e]:e}nt.prototype.isOperatorEnabled=function(e){var t=ny(e),s=this.options.operators||{};return!(t in s)||!!s[t]};var iy=Object.defineProperty,ay=Object.getOwnPropertyDescriptor,cy=(e,t,s)=>t in e?iy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,ly=(e,t,s,r)=>{for(var o=r>1?void 0:r?ay(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o},uy=(e,t,s)=>(cy(e,t+"",s),s);const dy="kos-expression-evaluator-model";class hy{constructor(t,s,r,o){l(this,"name");l(this,"expression");l(this,"expr");l(this,"getContextData",null);l(this,"_lastResult",{value:void 0});this.name=t,this.expression=s,this.expr=r,this.getContextData=o,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(t){this._lastResult=t}evaluate(t){try{return{value:this.expr.evaluate(t),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let nr=class{constructor(e,t,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=e,this.logger=s.logger,this._data=Te(),this._results=Te(),this.parser=new nt}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(e){this._data.setValues(e),X(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(e,t){this._data[e]=t}updateNestedValue(e,t){const s=e.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${e}" - cannot be empty`);return}let o=this._data;for(const n of s)(o[n]===void 0||o[n]===null)&&(o[n]={}),o=o[n];o[r]=t,this.logger.debug(`Updated nested context value "${e}" to:`,t)}addModelToContext(e,t){this._data[e]=t}addExpression(e,t){try{const s=this.parser.parse(t),r=new hy(e,t,s,()=>this.data);this._expressions.set(e,r),this.evaluateExpression(e),this.logger.debug(`Added expression "${e}": ${t}`)}catch(s){throw this.logger.error(`Failed to parse expression "${e}"`,s),s}}removeExpression(e){const t=this._expressions.delete(e);return t?(delete this._results[e],this.logger.debug(`Removed expression "${e}"`)):this.logger.warn(`Attempted to remove non-existent expression "${e}". Available expressions: [${this.expressionNames.join(", ")}]`),t}getExpression(e){const t=this._expressions.get(e);return t||this.logger.warn(`Expression "${e}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),t}getExpressionValue(e){const t=this._expressions.get(e);if(!t){this.logger.warn(`Expression "${e}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return t.result}getCachedExpressionValue(e){const t=this._expressions.get(e);if(t)return t.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(t=>{this._expressions.get(t)&&this.evaluateExpression(t)})}evaluateExpression(e){this.logger.debug(`Evaluating expression: ${String(e)}`);const t=this._expressions.get(e);if(!t){this.logger.warn(`Expression "${String(e)}" not found`);return}const s=t.evaluate(this.data);this.logger.debug(`Expression "${String(e)}" evaluated to:`,s);const r=t.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(e)}" result changed from`,r,"to",s),t.updateResult(s),this.updateResult(e,s))}updateResult(e,t){this.logger.debug(`ExpressionEvaluator.updateResult called for "${e}":`,t),X(()=>{this._results[e]=t})}createExpression(e){const t=tt();return this.addExpression(t,e),t}};uy(nr,"Registration");nr=ly([A({modelTypeId:dy,singleton:!1})],nr);const Hl=nr.Registration,Ne=cn(),fy=Object.freeze(Object.defineProperty({__proto__:null,default:Ne},Symbol.toStringTag,{value:"Module"})),py=m.createLogger({name:"kos-log-manager-service",group:"Services"}),gy="/api/kos/logs/overrides",zl=async()=>(py.debug("sending GET for kos-log-manager"),await Ne.get(gy)),my=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:zl},Symbol.toStringTag,{value:"Module"}));var yy=Object.defineProperty,by=Object.getOwnPropertyDescriptor,Kr=(e,t,s,r)=>{for(var o=r>1?void 0:r?by(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&yy(t,s,o),o};const Vl="kos-log-manager-model",vy="/kos/logs/override/add/*",wy="/kos/logs/override/remove/*",Ey=e=>{if(typeof e=="string")return e;if(typeof e=="number")switch(e){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 _t=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=e,this.logger=s.logger,this._overrides=new un}updateModel(e){}resolveLoggers(){const e=m.getLoggers(),s=Object.entries(e).map(([r,o])=>({name:r,level:Ey(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(e,t){const s=Object.values(this.resolveLoggers());return t==null||t.send(s),s}setLogLevels(e){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(e.name)).forEach(r=>{const o=m.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(e.level)});const s=m.getLoggers()[e.name];if(!s){this.logger.debug(`Logger ${e.name} not found`);return}s.setLevel(e.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(e){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(e.name)).forEach(r=>{const o=m.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=m.getLoggers()[e.name];s||this.logger.debug(`Logger ${e.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(e,t){var s;this.logger.debug(`Override received for node type ${((s=t.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...e,id:e.name}),this.setLogLevels(e)}handleOverrideRemoved(e){this._overrides.removeModel(e.name),this.resetLogLevels(e)}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[e,t]=await zl();if(e){this.logger.error("Failed to load log overrides",e);return}const s=(t==null?void 0:t.filter(r=>{var o;return((o=r.type)==null?void 0:o.toUpperCase())==="UI"}).map(r=>({name:r.name??"",type:r.type??"",level:r.level??"info",id:r.name||""})))??[];this._overrides.addAll(s),s.forEach(r=>{this.setLogLevels(r)})}};Kr([ec("/api/kos/ui/loggers")],_t.prototype,"getAllLoggers",1);Kr([U({topic:vy,websocket:!0,wildcardName:"nodeType"})],_t.prototype,"handleOverrideAdded",1);Kr([U({topic:wy,websocket:!0,wildcardName:"nodeType"})],_t.prototype,"handleOverrideRemoved",1);_t=Kr([A(Vl)],_t);const Gl=new Me({class:_t,type:Vl}),{URL:xs}=ae(),{postModel:Pn,getOne:My}=oe.build({basePath:`${xs}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const Yl=async e=>{const t=await Pn({model:e,urlOverride:`${xs}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},ql=async e=>{const t=await Pn({model:e,urlOverride:`${xs}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Wl=async e=>{const t=await Pn({model:{},urlOverride:`${xs}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},Ql=async()=>{const e=await My({urlOverride:`${xs}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},Ty=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Ql,setDate:ql,setTime:Yl,setTimezone:Wl},Symbol.toStringTag,{value:"Module"}));var _y=Object.defineProperty,Iy=Object.getOwnPropertyDescriptor,Hr=(e,t,s,r)=>{for(var o=r>1?void 0:r?Iy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&_y(t,s,o),o};const Yt="kos-time-model",Oy="/kos/time/time",Sy="/kos/time/day",$y="/kos/time/timezone";let It=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=e,this.logger=s.logger,this.timezone=""}async updateSystemTime(e){await Yl(e)}async updateSystemDate(e){await ql(e)}async updateSystemTimezone(e){await Wl(e)}handleTimeChange(){z(us.TIME_CHANGE,{})}handleDayChange(){z(us.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),z(us.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await Ql();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};Hr([U({topic:Oy,websocket:!0})],It.prototype,"handleTimeChange",1);Hr([U({topic:Sy,websocket:!0})],It.prototype,"handleDayChange",1);Hr([U({topic:$y,websocket:!0})],It.prototype,"handleTimeZoneChange",1);It=Hr([A(Yt)],It);const ir={registration:{[Yt]:{class:It,singleton:!0}},type:Yt,predicate:Ee(Yt),factory:ie.Singleton.create(Yt)};var Cy=Object.defineProperty,Dy=Object.getOwnPropertyDescriptor,Zl=(e,t,s,r)=>{for(var o=r>1?void 0:r?Dy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Cy(t,s,o),o};const Xl="log-block-container-model";let ar=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e,sortKey:"blockNum"})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};Zl([Oe],ar.prototype,"_models",2);ar=Zl([A(Xl)],ar);const xy=m.createLogger({name:"log-stream-container-service",group:"Services"}),Jl=()=>{var r;const e=ge(),s=(e==null?void 0:e.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},jt=Jl(),Ay="/api/kos/logs/node/{nodeId}/streams",eu=async()=>(xy.debug("sending GET for log-stream-container"),await Ne.get(Ay,{path:{nodeId:"primary"}},{destinationAddress:jt})),tu=async(e,t="primary")=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:jt})},su=async e=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:jt})},Ry=async()=>{await Ne.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:jt})},ru=async e=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:jt}),ou=async(e,t)=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:jt}),Py=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Ry,getKosConnectionId:Jl,getLogStreamBlock:ou,getLogStreamBlocks:ru,getLogStreams:eu,subscribeToLogStream:tu,unsubscribeFromLogStream:su},Symbol.toStringTag,{value:"Module"}));var ky=Object.getOwnPropertyDescriptor,Ly=(e,t,s,r)=>{for(var o=r>1?void 0:r?ky(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const nu="log-block-model";let Io=class{constructor(e,t,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=e,this.logger=s.logger,this.nodeId=t.nodeId,this.stream=t.stream,this.blockNum=t.blockNum,this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount,this.lines=[],this.inc=0}async syncLines(){const[e,t]=await ou(this.stream,this.blockNum);if(e){this.logger.error(`Failed to get log block ${this.blockNum}`);return}t&&this.addLines(t.lines,!0)}updateModel(e){this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount}addLines(e,t){const s=t?[]:this.lines;this.lines=[...s,...e],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};Io=Ly([A(nu)],Io);const vs=new me({class:Io,type:nu}),zr=new me({class:ar,type:Xl});zr.addRelatedModel(vs);var Fy=Object.defineProperty,Ny=Object.getOwnPropertyDescriptor,iu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Ny(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Fy(t,s,o),o};const au="log-stream-model";let cr=class{constructor(e,t,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=e,this.logger=s.logger,this.currentBlockId="",this.name=t.name,this.nodeId=t.nodeId,this.isResetting=!0,this._blocks=zr.instance(`${e}-blocks`).options({}).build()}get firstLineNum(){const e=this.populated[0];return e?e.startLineNum:0}get currentBlock(){const e=this.currentBlockId;return this._blocks.getModel(e)}get populated(){return this._blocks.data.filter(e=>e.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((e,t)=>e+t.lineCount,0)}accept(e){e.visit(this)}updateBlock(e){var r;let t=this._blocks.models.getModel(`${e.stream}-block-${e.blockNum}`);const s={nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)};t||(t=vs.instance(`${e.stream}-block-${e.blockNum}`).options(s).build(),this._blocks.addModel(t)),t&&t.updateModel(s),(!this.currentBlock||e.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}addBlock(e){var s;const t=vs.instance(`${e.stream}-block-${e.blockNum}`).options({nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)}).build();this._blocks.addModel(t),(!this.currentBlock||e.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}removeBlock(e){this._blocks.models.removeModel(`${this.name}-block-${e}`)}async subscribe(){await tu(this.name)}async unsubscribe(){await su(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const t of this._blocks.models.data)t.lines=[];const e=this._blocks.data[this._blocks.data.length-1];e&&await e.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[e,t]=await ru(this.name);if(e){this.logger.error(`Error loading log stream: ${e}`);return}if(t)for(const r of t)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 e;this.shouldStop=!0,(e=this.generatorInstance)==null||e.next(),console.log("Requested generator stop.")}async*streamLogs(){const e=[];let t=null,s=0,r=this.currentBlockId;const o=nl(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(r!==(n==null?void 0:n.blockId))r=n==null?void 0:n.blockId,s=0,e.push(...i.lines);else{const a=i.lines.slice(s);e.push(...a),s+=a.length}t&&(t(),t=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(e.length===0&&await new Promise(n=>t=n);e.length>0;)yield e.shift()}finally{o()}}};iu([Oe],cr.prototype,"_blocks",2);cr=iu([A(au)],cr);const ds=new me({class:cr,type:au});var Uy=Object.defineProperty,jy=Object.getOwnPropertyDescriptor,it=(e,t,s,r)=>{for(var o=r>1?void 0:r?jy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Uy(t,s,o),o};const cu="log-stream-container-model",By="/kos/logs/subscription/addBlock/*",Ky="/kos/logs/subscription/updateBlock/*",Hy="/kos/logs/subscription/removeBlock/*",zy="/kos/logs/subscription/lines/*",lu="/kos/logs/streams/add/*";let Pe=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e}),this.selectedStream=void 0}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}updateModel(e){}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}updateSelectedStream(e){this.selectedStream=e}handleStreamAdded(e){this.logger.debug(`Received topic: ${lu}`);const t=e.stream,s=ds.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.addBlock(e)}handleRemoveBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.removeBlock(e.blockNum)}handleUpdateBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.updateBlock(e)}handleLogLine(e,t){var o;this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&((o=r.currentBlock)==null||o.addLines(e.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(e){const t=ds.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(t),await t.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[e,t]=await eu();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const r=ds.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};it([Oe],Pe.prototype,"_models",2);it([U({topic:[lu],websocket:!0})],Pe.prototype,"handleStreamAdded",1);it([U({topic:[By],websocket:!0})],Pe.prototype,"handleAddBlock",1);it([U({topic:[Hy],websocket:!0})],Pe.prototype,"handleRemoveBlock",1);it([U({topic:[Ky],websocket:!0})],Pe.prototype,"handleUpdateBlock",1);it([U({topic:[zy],websocket:!0})],Pe.prototype,"handleLogLine",1);Pe=it([A(cu)],Pe);const As=new Me({class:Pe,type:cu});As.addRelatedModel(ds);As.addRelatedModel(zr);As.addRelatedModel(vs);const Vy=e=>e.rank!==void 0,Gy=e=>e.visibleRole!==void 0,Yy=e=>e.color!==void 0,qy=e=>{const t=e.info;return Vy(t)?t.rank:0},Wy=e=>{const t=e.info;return Yy(t)?t.color:"orange"},Qy=e=>{const t=e.info;return Gy(t)?t.visibleRole:"TECHNICIAN"},{URL:Vr}=ae(),{getAll:Zy,postModel:uu}=oe.build({basePath:`${Vr}/api/kos/troubles`}),du=async e=>await Zy({urlOverride:`${Vr}${e}`}),hu=async(e,t="/api/kos/troubles",s)=>{try{const r=await uu({model:{},urlOverride:`${Vr}${t}/resolve/${e}`,tracker:s});return r!=null&&r.data&&Je.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve trouble"};return Je.initiateFuture(o),o}},Xy=async(e,t="/api/kos/troubles",s)=>{try{const r=await uu({model:e,urlOverride:`${Vr}${t}/resolve/`,tracker:s});return r!=null&&r.data&&Je.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve troubles"};return Je.initiateFuture(o),o}},Jy=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Xy,getTroubles:du,resolveTrouble:hu},Symbol.toStringTag,{value:"Module"})),lr="troubleDataMapper",Bs=new Map;Ss(lr,{register:(e,t)=>{var s;Bs.has(e)||Bs.set(e,[]),(s=Bs.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Bs.get(e);if(!s)return{...t.data};const r=s.map(i=>i(t));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:m.info(`Trouble mapper ${e} failed: ${a.reason}`),i),{...t.data})}});const Rs="troubleMapper",Ks=new Map;Ss(Rs,{register:(e,t)=>{var s;Ks.has(e)||Ks.set(e,[]),(s=Ks.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Ks.get(e);if(!s)return[];const r=s.map(i=>i(t)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${e} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});S[Rs].register("nozzle",async e=>[e.data.nozzlePath]);S[Rs].register("path",async e=>[e.data.path]);const eb=async e=>{const t=new Set,s=e.ifaces,r=s==null?void 0:s.map(n=>S[Rs].execute(n,e));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},fu=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>S[lr].execute(i,e)),r=S[lr].execute(e.type,e);s.push(r);const n=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...e.data,...n}};class tb{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class sb{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class dt{static getHandler(t){switch(t){case"ResolvableTrouble":return new tb;case"BlockPumpTrouble":return new sb;default:return}}}var rb=Object.defineProperty,ob=Object.getOwnPropertyDescriptor,pu=(e,t,s,r)=>{for(var o=r>1?void 0:r?ob(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&rb(t,s,o),o};const qt="trouble-model";function Hs(e){return typeof e.shouldDefer=="boolean"}let ur=class{constructor(e,{resolvable:t,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:u,createTime:d,role:h,color:f,servicePath:p,...b},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=e,this.logger=w.logger,this.type=c,this._troubleId=o,this._resolvable=!!t,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=n,this.data={},Object.assign(this.data,b),this.futureHandler=new Rr(this)}getTitleWithContext(e){var s,r;const t=e?(r=(s=dt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[e]:dt.getHandler(this.type);return(t==null?void 0:t.title)||"Trouble"}getSubtitleWithContext(e){var s,r;const t=e?(r=(s=dt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[e]:dt.getHandler(this.type);return(t==null?void 0:t.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var e;return((e=dt.getHandler(this.type))==null?void 0:e.title)||"Trouble"}get subtitle(){var e;return((e=dt.getHandler(this.type))==null?void 0:e.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await fu(this)}get deferredCompanion(){const e=yo(this.id,t=>Hs(t));if(e&&Hs(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=yo(this.id,t=>Hs(t));return e&&Hs(e.modelData)?e.modelData.shouldDefer:!1}clearDefer(){var e;(e=this.deferredCompanion)==null||e.clearDefer()}defer(){var e;(e=this.deferredCompanion)==null||e.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(e){var t;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){(t=this.deferredCompanion)==null||t.defer();return}return await hu(this._troubleId,this.servicePath,e)}};pu([Xn()],ur.prototype,"resolve",1);ur=pu([A(qt)],ur);const ws={registration:{[qt]:{class:ur,singleton:!1}},type:qt,predicate:Ee(qt),factory:ie.Factory.create(qt)};var gu=Object.defineProperty,nb=Object.getOwnPropertyDescriptor,ib=(e,t,s)=>t in e?gu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,kn=(e,t,s,r)=>{for(var o=r>1?void 0:r?nb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&gu(t,s,o),o},ab=(e,t,s)=>(ib(e,t+"",s),s);function Li(e){return S.propertyMapper.hasMapper(be.TroubleRank)?S.propertyMapper.executeMapper(be.TroubleRank,e):qy(e)}function Fi(e){return(S.propertyMapper.hasMapper(be.TroubleColor)?S.propertyMapper.executeMapper(be.TroubleColor,e):Wy(e)).toLowerCase()}function Ni(e){return(S.propertyMapper.hasMapper(be.TroubleRole)?S.propertyMapper.executeMapper(be.TroubleRole,e):Qy(e)).toLowerCase()}const cb="trouble-container-model";class fe{}l(fe,"INDEX_TROUBLES_BY_IFACE","byIface"),l(fe,"INDEX_TROUBLES_BY_TYPE","byType"),l(fe,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(fe,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(fe,"SORT_KEY_RANK","rank"),l(fe,"TROUBLES_DEFERRED","true");let Ot=class{constructor(e,t){l(this,"id");l(this,"servicePath","/api/kos/troubles");this.id=e,this.servicePath=t.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");const e=await du(this.servicePath);try{e==null||e.data.forEach(t=>{const s={...t,servicePath:this.servicePath,rank:Li(t),color:Fi(t),role:Ni(t),id:String(t.id)},r=ws.factory(`trouble-${t.id}`)(s);this.troubles.addModel(r)})}catch(t){throw this.logger.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&Xe(s)}handleTroubleAdded(e){const t={...e,servicePath:this.servicePath,rank:Li(e),color:Fi(e),role:Ni(e),id:String(e.id)};if(t.role==="NONE")return;const s=ws.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};ab(Ot,"Registration");kn([U({topic:"/kos/trouble/remove",websocket:!0,lifecycle:H.INIT})],Ot.prototype,"handleTroubleRemoved",1);kn([U({topic:"/kos/trouble/add",websocket:!0})],Ot.prototype,"handleTroubleAdded",1);Ot=kn([A({modelTypeId:cb,singleton:!0}),oc(),Ja({containerProperty:"troubles",containerOptions:{indexMap:{[fe.INDEX_TROUBLES_BY_IFACE]:eb,[fe.INDEX_TROUBLES_BY_TYPE]:"type",[fe.INDEX_TROUBLES_BY_GROUP]:"group",[fe.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:fe.SORT_KEY_RANK}})],Ot);const St=Ot.Registration,{URL:mu}=ae(),{getAll:lb}=oe.build({basePath:`${mu}/api/kos/ota`}),Ui=m.createLogger({name:"ota-service",group:"Services"}),ub=async()=>{Ui.debug("sending GET request to /api/kos/ota/artifacts");const e=await lb({urlOverride:`${mu}/api/kos/ota/artifacts`});return Ui.debug("getArtifacts - response:",e),e==null?void 0:e.data};var db=Object.defineProperty,hb=Object.getOwnPropertyDescriptor,Gr=(e,t,s,r)=>{for(var o=r>1?void 0:r?hb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&db(t,s,o),o};const yu="ota-model",fb=e=>{let t=null;for(const s in e){const r=e[s],o=r.lastUpdateTime;(!t||t.lastUpdateTime<o)&&(t=r)}return t},co=e=>{const t=e.artifactInfo,s=fb(e.requests),r=(t==null?void 0:t.identifier)||(s==null?void 0:s.kabId);if(!r)return;let o;switch(e.status){case"INSTALLED":o="ready";break;case"INVALID":o="error";break;case"MISSING":o=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":o="pending"}const n=t===void 0;return{id:r,manifest:n,label:t==null?void 0:t.version,name:t==null?void 0:t.name,status:o,error:o==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:o==="error"?s==null?void 0:s.errorCount:0,progress:o==="downloading"&&s&&!n?s.currentSize/(t==null?void 0:t.size)*100:void 0,size:t==null?void 0:t.size}};let $t=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"data",new un);l(this,"troubleContainer");this.id=e,this.logger=s.logger}get downloadInProgressTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:t[0]}get updatePendingTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:t[0]}get pausedDueToErrorsTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:t[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var e;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(e=this.updatePendingTrouble)==null||e.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const e=await ub();e&&e.forEach(t=>{const s=co(t);s&&this.data.addModel(s)})}catch(e){this.logger.error(`loading ota ${this.id} - error:`,e)}}async handleAllArtifacts(e){this.logger.debug("handleAllArtifacts:",e),await this.data.clear();try{e.forEach(t=>{const s=co(t);s&&this.data.addModel(s)})}catch(t){this.logger.error(`handleAllArtifacts ${this.id} - error:`,t)}}handleChangedArtifacts(e){this.logger.debug("handleChangedArtifacts:",e);try{e.forEach(t=>{const s=co(t);s&&this.data.updateModel(s)})}catch(t){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,t)}}};Gr([Rt({modelType:St.type})],$t.prototype,"troubleContainer",2);Gr([U({topic:"/kos/ota/artifacts/all",websocket:!0})],$t.prototype,"handleAllArtifacts",1);Gr([U({topic:"/kos/ota/artifacts/changed",websocket:!0})],$t.prototype,"handleChangedArtifacts",1);$t=Gr([A(yu)],$t);const dr=new Me({class:$t,type:yu});function pb(e){let t;const s=async(...r)=>{t&&t.abort(),t=new AbortController;const o=t;try{return await e(...r,o.signal)}finally{t===o&&(t=void 0)}};return s.cancel=()=>{t&&(t.abort(),t=void 0)},s.getController=()=>t,s.isActive=()=>!!t,s}const lo=m.createLogger({name:"software-info-service",group:"Services"}),Ln=async e=>{lo.debug("sending GET for software-info");const[t,s]=await Sl.get("/api/kos/manifest/info",void 0,{signal:e});if(!s)throw e!=null&&e.aborted?(lo.debug("Request was aborted"),new pe("Request was aborted")):(lo.error("Failed to fetch software-info",t),new pe("Failed to fetch software-info"));return s},gb=pb(Ln),mb=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Ln,getSoftwareInfosWithCancel:gb},Symbol.toStringTag,{value:"Module"}));var yb=Object.getOwnPropertyDescriptor,bb=(e,t,s,r)=>{for(var o=r>1?void 0:r?yb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Wt="software-info-model";let Oo=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=e,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(e,t){return e.reduce((s,r)=>(s[r[t]]=[...s[r[t]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const e=await Ln(),t=(e==null?void 0:e.nodes)||{};X(()=>{const r=Object.keys(t).map(o=>t[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(e){e instanceof pe&&this.logger.error("Failed to fetch software-info",e)}}};Oo=bb([A(Wt)],Oo);const hr={registration:{[Wt]:{class:Oo,singleton:!1}},type:Wt,predicate:Ee(Wt),factory:ie.Factory.create(Wt)},{URL:bu}=ae(),{getOne:vb}=oe.build({basePath:`${bu}/api/kos/state`}),wb=m.createLogger({name:"state-bean-service",group:"Services"}),vu=async({path:e})=>(wb.debug("sending GET for state-bean"),await vb({urlOverride:`${bu}/api/kos/state/${e}`})),Eb=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:vu},Symbol.toStringTag,{value:"Module"}));var Mb=Object.defineProperty,Tb=Object.getOwnPropertyDescriptor,wu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Tb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Mb(t,s,o),o};const Qt="state-bean-model",_b=st("path");let fr=class{constructor(e,t,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=e,this.logger=s.logger,this.props=hn.map(new Map),mo(t,this)}updateModel(e){mo(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let r=s;typeof r=="string"&&gn(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&Pr(r)&&(r=Number(r)),this.props.set(t,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(e){Object.entries(e).forEach(([t,s])=>{this.props.set(t,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const e=await vu({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};wu([U({topic:`/kos/state/${_b}`,websocket:!0})],fr.prototype,"handleConfigBeanUpdated",1);fr=wu([A(Qt)],fr);const Es={registration:{[Qt]:{class:fr,singleton:!1}},type:Qt,predicate:Ee(Qt),factory:ie.Factory.create(Qt)};var Ib=Object.defineProperty,Ob=Object.getOwnPropertyDescriptor,Eu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Ob(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ib(t,s,o),o};const Zt="state-prop-model",ji=st("path");let pr=class{constructor(e,t,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=e,this.logger=s.logger,this.path=t.path,this.attribute=t.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 e;return((e=this.value)==null?void 0:e.toString())??""}};Eu([Rt({modelType:Es.type,id:`state-bean-${ji}`,options:{path:ji}})],pr.prototype,"stateBean",2);pr=Eu([A(Zt)],pr);const Fn={registration:{[Zt]:{class:pr,singleton:!1}},type:Zt,predicate:Ee(Zt),factory:ie.Factory.create(Zt)},{URL:Sb}=ae(),{getAll:$b}=oe.build({basePath:`${Sb}/api/state-prop`}),Cb=m.createLogger({name:"state-prop-service",group:"Services"}),Db=async()=>(Cb.debug("sending GET for state-prop"),await $b({})),xb=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Db},Symbol.toStringTag,{value:"Module"})),{URL:Nn}=ae(),{getOne:Mu}=oe.build({basePath:`${Nn}/api/translation`}),hs=m.createLogger({name:"translation-service",group:"Services"}),Ab=()=>{const e=window.location.origin,t=ge();return(t==null?void 0:t.host)||e},Tu=async(e,t)=>{hs.debug(`Loading translations from: ${e}`);const s=t??Ab();try{const r=await fetch(`${s}${e}`);return r.status!==200?(hs.warn(`Failed to fetch translations at ${e}: ${r.status}`),{}):await r.json()}catch(r){throw hs.error("Error fetching translations",r),r}},Rb=async()=>{hs.debug("Getting system localization descriptor");const e=await Mu({urlOverride:`${Nn}/api/system/kos/localization`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get localization descriptor ${e==null?void 0:e.status}`);return e.data},_u=e=>async()=>{hs.debug(`Getting KOS localization descriptor for context: ${e}`);const t=await Mu({urlOverride:`${Nn}/api/kos/localization/contexts`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${t==null?void 0:t.status}`);return t.data[e]},Iu="langResolver";var Pb=Object.getOwnPropertyDescriptor,kb=(e,t,s,r)=>{for(var o=r>1?void 0:r?Pb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Xt="translation-model";function Lb(e){const t=typeof e=="string",s=t?!1:!!(e!=null&&e.data)&&typeof(e==null?void 0:e.data)!="string",r=t?e:e==null?void 0:e.defaultValue,o=t||e==null?void 0:e.context,n=t?void 0:s?e==null?void 0:e.data:e;return{isBasicOptions:t,defaultValue:r,context:o,data:n}}function Ou(e,t=""){return Object.keys(e).reduce((s,r)=>{const o=t?`${t}.${r}`:r;if(typeof e[r]=="object"&&e[r]!==null){const n=Ou(e[r],o);return{...s,...n}}else return{...s,[o]:e[r]}},{})}function Su(e,t){const s={...e};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(typeof t[r]=="object"&&t[r]!==null&&typeof e[r]=="object"&&e[r]!==null?s[r]=Su(e[r],t[r]):s[r]=t[r]);return s}const So=(e,t)=>{const s=/__(.*?)__/g,r=e.replace(s,(o,n)=>Object.prototype.hasOwnProperty.call(t||{},n.trim())?t==null?void 0:t[n.trim()]:o);return r===e?r:s.test(r)?So(r,t):r},zs=(e,t,s)=>{const r=/{{(.*?)}}/g,n=So(e,t).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return So(n,t)},Bi=(e,t)=>{if(t.includes(":")){const[s,r]=t.split(":");return{namespace:s,key:r}}else return{namespace:e,key:t}};let $o=class{constructor(e,t,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=e,this.defaultLocale=t.defaultLocale||"en",this.currentLocale=t.currentLocale||"en",this.namespace=t.namespace,this.descriptor=t.descriptor,this.rootUrl=t.rootUrl,this.data={},this.resolver=t.resolver||s.kosContext.get(Iu),this.bundleResolver=t.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(e){const t=this.descriptor[e];if(!e||!t)return[this.defaultLocale];if(!this.defaultLocale&&!t.fallbacks)return[e];let s=t.fallbacks||[this.defaultLocale];return s.includes(e)||(s=[e,...s]),s}async loadTranslations(){const e=this.getTranslationLocales(this.currentLocale).reverse(),t=e.map(r=>{if(this.bundleResolver){const o=G.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return Tu(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(t);X(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${e[i]}`,n.value),n.value&&(o=Su(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),o),{});this.data=Ou(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=Bi(this.namespace,e);if(t!==this.namespace){const r=this.context.getModel(t);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(e,t){if(!e)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=Lb(t),{namespace:n,key:i}=Bi(this.namespace,e),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,t):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>zs(u,this.data,o)):zs(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[a];return Array.isArray(c)?c.map(u=>zs(u,this.data,o)):zs(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=E.reaction(()=>this.currentLocale,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};$o=kb([xr(),A(Xt)],$o);const gr={registration:{[Xt]:{class:$o,singleton:!1}},type:Xt,predicate:Ee(Xt),factory:ie.Factory.create(Xt)};var Fb=Object.defineProperty,Nb=Object.getOwnPropertyDescriptor,$u=(e,t,s,r)=>{for(var o=r>1?void 0:r?Nb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Fb(t,s,o),o};const Jt="translation-container-model",Ub=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function jb(e,t){const s=this.descriptor.namespaces[e];if(!s)throw new Error("namespace "+e+" not found in descriptor");const r=s.basePath,o=s.locales[t].file;return Ub([r,o])}let mr=class{constructor(e,t,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=e,this.lang=t.lang||"en",this.descriptor=t.descriptor,this._defaultNamespace=t.defaultNamespace,this.descriptorUrl=t.descriptorUrl,this.rootUrl=t.rootUrl,this.resolver=t.resolver||jb.bind(this),s.kosContext.set(Iu,this.resolver),this.logger=s.logger,this._models=new Se({parentId:e})}set currentLocale(e){this.lang=e,this.models.data.forEach(t=>{t.currentLocale=e})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(e){return this.logger.debug("getting model "+e),this._models.getModel("translation-"+e)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const e of this.namespaces){const t=this.resolveNamespace(e);await ue(t)}}resolveNamespace(e){var s;if((s=this.descriptor.namespaces)==null?void 0:s[e]){const r=Object.keys(this.descriptor.namespaces[e].locales)[0],o=this.descriptor.namespaces[e].locales[r].defaultLocale,n=gr.factory("translation-"+e)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[e].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(e)||X(()=>{this.namespaces.push(e)}),n}else{this.logger.warn("namespace "+e+" not found in descriptor");const r=gr.factory("translation-"+e)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug("initializing translation-container container "+this.id)}async load(){this.logger.debug("loading translation-container container "+this.id)}};$u([Oe],mr.prototype,"_models",2);mr=$u([A(Jt)],mr);const ke={registration:{[Jt]:{class:mr,singleton:!0}},type:Jt,predicate:Ee(Jt),factory:ie.Singleton.create(Jt)},Bb={set(e,t){const s=G.getContext(ke.type);s&&s.set(e,t)},get(e){const t=G.getContext(ke.type);return t==null?void 0:t.get(e)}},Cu={async init(e){const t=ke.factory(e);return await ue(t),{translations:t}}};function Kb(e){return(e==null?void 0:e.troubles)!==void 0&&(e==null?void 0:e.troubles)instanceof Array&&(e==null?void 0:e.troublesByType)!==void 0&&typeof(e==null?void 0:e.troublesByType)=="object"}const Du="kos-ws-event",Un=Pt(Du);var Hb=Object.defineProperty,zb=Object.getOwnPropertyDescriptor,jn=(e,t,s,r)=>{for(var o=r>1?void 0:r?zb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Hb(t,s,o),o};const Vb=({headers:e,body:t})=>Object.entries(e).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+t;exports.WsEventModel=class{constructor(t){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=t,this.events=E.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(t,s){this.processEvent(s,!0)}handleReceiveEvent(t,s){this.processEvent(s)}processEvent(t,s=!1){m.debug("kos event received");const{body:r,headers:o}=t.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:Vb({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};jn([U({topic:[Os.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);jn([U({topic:[Os.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=jn([A(Un.type)],exports.WsEventModel);const Ki=ge(),Gb=Ki.debug==="true"||Ki.debug===!0,Yb="/api/system/canvas",xu=async(e,t)=>{const s=t||Yb,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Gb?"false":"true"},body:e})},qb=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:xu},Symbol.toStringTag,{value:"Module"}));function Hi(e,t,s){{const r=e.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var Wb=Object.defineProperty,Qb=Object.getOwnPropertyDescriptor,Au=(e,t,s,r)=>{for(var o=r>1?void 0:r?Qb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Wb(t,s,o),o};const Ru="canvas-renderer-model";function uo(e){return typeof e.onDone=="function"}let yr=class{constructor(e,t,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=e,this.logger=s.logger,this.width=t.width??50,this.height=t.height??30,this.fps=t.fps??10,this.durationMs=t.durationMs??null,this.apiPath=t.apiPath??"/api/system/canvas",this.endpointName=t.endpoint}set onFrame(e){this._onFrame=e}set renderer(e){var t,s;this._renderer&&(this.stopStreaming(),(s=(t=this._renderer).dispose)==null||s.call(t)),this._renderer=e,this.isStreaming&&this.startStreaming()}setClearOnComplete(e){this._clearOnComplete=e}sendDataFrame(e,t){xu(e,t)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const e=this.isOneShotDone();this.stopStreaming(!e)});return}}handleFrame(e){var s;const t=Hi(e);this.sendDataFrame(t,this.apiPath),(s=this._onFrame)==null||s.call(this,t)}stopStreaming(e=!0){var t,s;this.logger.debug(`stopStreaming called with clearCanvas=${e}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(t=this._renderer)==null?void 0:t.pause)==null||s.call(t),e&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const e=this.width>0?this.width:50,t=this.height>0?this.height:30;if(e>0&&t>0){const r=e*t*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=Hi(o);this.logger.debug(`Sending clear frame: ${e}x${t}, apiPath: ${this.apiPath}`),this.sendDataFrame(n,this.apiPath),(s=this._onFrame)==null||s.call(this,n)}}isOneShotDone(){var e,t;return uo(this._renderer)&&((t=(e=this._renderer).isOneShot)==null?void 0:t.call(e))===!0&&this._renderer.isOneShotDone}startStreaming(){var e,t,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(),(t=(e=this._renderer).play)==null||t.call(e);const o=uo(this._renderer);uo(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),z("/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 n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,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),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(e,t)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),t.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(e,t)=>{this.startStreaming(),t.send({status:"OK"})})}};Au([Rt({modelType:Tn.type})],yr.prototype,"router",2);yr=Au([A(Ru)],yr);const Bn=new me({class:yr,type:Ru});class Pu{constructor({src:t}){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=t,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(t,s){this.canvas.width=t,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,t,s)}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}onDone(t){this.doneCallback=t}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}}class Zb{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 t=this.canvas.getContext("webgl");if(!t)throw new Error("WebGL not supported");this.gl=t}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}readPixels(t=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(t*s*4);this.gl.readPixels(0,0,t,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const o=new Uint8ClampedArray(r.length);for(let n=0;n<s;n++){const i=n*t*4,a=(s-1-n)*t*4;o.set(r.subarray(i,i+t*4),a)}return o}}class Xb extends Zb{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
|
|
77
|
+
["${t}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(b=this.socket)==null?void 0:b.connectionEstablished){const M=r?this.fosSocket:this.socket;(w=M==null?void 0:M.socket)==null||w.send(d)}else{Ye.debug("no connection adding to offline messages");const M=r?this.fosSocket:this.socket;M==null||M.addOfflineMessage(d)}}subscribeTopic({topic:t,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=$(t,s);return Ye.debug(`Topic ${t} currently has ${a} subscribers`),this._sendSubscriptionMessage(t,"subscribe",r,o,n),()=>{const{count:c}=i();Ye.debug(`Topic ${t} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(t,"unsubscribe",r,o,n)}}async whenReady(){const t=this;return this.webSocketSupported?(await E.when(()=>{var s,r;return!!((s=t.socket)!=null&&s.connectionEstablished)&&(!t.useFosTransport||!!((r=t.fosSocket)!=null&&r.connectionEstablished))&&t.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(t){this._token=t,this.init()}static host(t="localhost"){return this.getInstance().host=t,this}static port(t=8080){return this.getInstance().port=t,this}static alias(t){this.getInstance().alias=t}static getInstance(t=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:t,token:s,fos:r})}return this._instance}}l(wt,"_instance");class bp{constructor(t){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=t,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(t){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of t)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(t,s)}async*processSingleEvent(t){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(t))){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(t),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([t]):[t],this.updateProcessingStats([t])}}async*processBatchedEvents(t,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const 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 t)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(u);this.eventQueue.length>0;){const d=this.dequeueEvent();d&&n.push(d);const f=Date.now()-i;if(n.length>=r||f>=o){const p=await a();p!==void 0&&(yield p);break}}else{n.push(u);const h=Date.now()-i;if(n.length>=r||h>=o){const f=await a();f!==void 0&&(yield f)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(t){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(t,s);return this.config.filter.historySize&&(this.filterHistory.push(t),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const t=Date.now(),s=Math.floor(t/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const t=Date.now(),o=(Math.floor(t/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-t;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const t=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=t;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const t=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-t;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(t){if(this.eventQueue.push(t),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const t=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,t}updateProcessingStats(t){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+t.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?t.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(t){return this.activePromises.add(t),t.finally(()=>this.activePromises.delete(t)),t}getStats(){return{...this.stats}}}class vp{constructor(t,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);this.model=t,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(t){var o;const s=((o=this.modelData)==null?void 0:o[ee])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${t??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(t&&t!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.flow)this.subscribeWithFlowControl(i,c,a);else{const u=this.createHandler(c,i);this.subscribe(i,c,u,a===H.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const t of this.activatableDisposers)try{t()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const t=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${t.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 t)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(t,s,r,o){const n=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;if(t.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=wt.getInstance().subscribeTopic({topic:s,callback:r,fos:t.fos,bridge:t.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=$(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(t,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(t,r,s);if(this.model.isReady()){const u=wo(r,s.skipParse),d=s.transform(u);if(a&&s.condition(d,this.modelData,r))return this.callHandlerWithWildcard(s,d,c,r)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${t}`);const u=()=>{const d=wo(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)};this.offlineQueue.enqueue(u)}}catch(n){this.log.error(`Error handling subscription for ${t}`,n)}}}extractWildcardCapture(t,s,r){var n;if(!r.wildcardName||!wc(t))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return vc(t,o,r.wildcardName)}callHandlerWithWildcard(t,s,r,o){if(r&&Object.keys(r).length>0){const n={...o,wildcardCapture:r};return t.handler.call(this.modelData,s,n,this.modelData)}else return t.handler.call(this.modelData,s,o,this.modelData)}resolvePropKey(t){const s=/.*({PROP_(.+)})/;let r=t.includes("{MODEL_ID}")?t.replace("{MODEL_ID}",this.modelId):t;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}async subscribeWithFlowControl(t,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const o=new bp(t.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,t),i=this.startFlowProcessing(t,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===H.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(t,s,r,o){const n=new AbortController;try{let i;if(t.websocket){const a=t.destinationAddress?this.resolvePropKey(t.destinationAddress):null;wt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:t.fos,bridge:t.bridge,destinationAddress:a}),i=vi(s)}else i=vi(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(t,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${t}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c)}}catch(c){if(this.log.error(`Error in flow control handler for ${t}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(t,s,r){const o=t.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),t.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const t={};for(const[s,r]of this.flowControllers)t[s]=r.getStats();return t}}function ct(e,t){const s=`[Model:${t}]`;return{debug:(...r)=>e.debug(s,...r),info:(...r)=>e.info(s,...r),warn:(...r)=>e.warn(s,...r),error:(...r)=>e.error(s,...r)}}function wp(e){return!!(e!=null&&e[Ze])&&Object.keys(e[Ze]).length>0}function Ep(e){return!!(e!=null&&e[ee])&&Object.keys(e[ee]).length>0}function Mp(e){return!!(e!=null&&e[xe])&&e[xe].length>0}class Tp{static createAll(t){const{modelId:s,modelTypeName:r,modelData:o}=t,n=nc.create({modelId:s,modelTypeName:r}),i=new sp(t,ct(n,"fsm")),a=new op(ct(n,"offline-queue")),c=new qf(t),u=new Yf(t),d={fsm:i,offlineQueue:a,companionManager:c,childResolver:u};if(wp(o)&&(d.effectManager=new Wf(r,s,o,ct(n,"effect"))),Ep(o)){const h=ct(n,"subscription");d.subscriptionManager=new vp(t,o,s,a,h),d.onlineLifecycleManager=new np(t,ct(n,"online"))}return Mp(o)&&(d.httpRouteManager=new cn(o,ct(n,"http-routes"))),d}}const L=C.getLogger("kos-model"),_p="kos.extension.model.loader";class qc{constructor({modelTypeName:t,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:t,this.modelTypeName=t,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const o=Tp.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),E.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Gf(this)}get companionModels(){return this.companionManager}set status(t){this._status=t}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(t){this._activeStatus=t}get onlineStatus(){return this._onlineStatus}set onlineStatus(t){this._onlineStatus=t}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 t,s,r;L.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=V.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.deactivate)==null?void 0:s.call(t,o)),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw L.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var t,s,r;L.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await zt(this,H.ACTIVATE);try{const o=V.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.activate)==null?void 0:s.call(t,o)),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(r=this.subscriptionManager)==null||r.registerAll(H.ACTIVATE),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw L.debug(`Model ${this.modelId} failed to activate`),o}}async whenLoaded(){await no([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{L.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await no([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{L.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await no([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{L.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var t,s,r;if(this.fsm.current===v.READY){L.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{L.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await zt(this,H.READY),await Ac(this,nn.READY,H.READY);const o=V.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.ready)==null?void 0:s.call(t,o)),this.offlineQueue.flush(),(r=this.subscriptionManager)==null||r.registerAll(H.READY),L.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};z(Ec(this.modelTypeName,this.modelId),n),z(Mc(this.modelTypeName),n)}catch(o){throw L.error(o),Error(o)}}async load(){var o,n,i,a,c;const t=this[bt];t&&await t.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED||this.fsm.current===v.LOADING){L.debug(`Model ${s} with id ${r} already loaded or loading`);return}L.debug(`Loading model ${s} with id ${r}`),await zt(this,H.LOAD);try{const u=V.getContext(r),d=`${_p}.${s}`,h=await S.loader.executeLoader(d,{});h&&(L.info(`Setting loaded context for ${r}, type: ${s}`),u==null||u.set(d,h)),await((n=(o=this.modelData)==null?void 0:o.load)==null?void 0:n.call(o,u)),X(()=>{this.loaded=!0}),L.debug(`Model ${s} with id ${r} successfully loaded`),(i=this.subscriptionManager)==null||i.registerAll(H.LOAD),(a=this.httpRouteManager)==null||a.registerAll(),(c=this.effectManager)==null||c.setup()}catch(u){throw L.error(`Model ${r} failed to load`,u),u}}async unload(){var t,s,r,o,n,i;L.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const a=this.getChildren().map(u=>{var d;return(d=u.unload)==null?void 0:d.call(u)}).filter(u=>!!u);await Promise.allSettled(a);const c=V.getContext(this.modelId);await((s=(t=this.modelData)==null?void 0:t.unload)==null?void 0:s.call(t,c)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(o=this.effectManager)==null||o.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll(),(i=this.httpRouteManager)==null||i.dispose()}catch(a){throw L.debug(`Model ${this.modelId} failed to unload`),a}}async init(){var n,i,a;const t=this[bt];t&&await t.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=V.getContext(s);L.debug(`Initializing model ${r} with id ${s}`),await zt(this,H.INIT);try{await((i=(n=this.modelData)==null?void 0:n.init)==null?void 0:i.call(n,o)),this.initialized=!0,L.debug(`Model ${r} with id ${s} initialized`),(a=this.onlineLifecycleManager)==null||a.register(),this.registerSubscribers(H.INIT)}catch(c){throw L.error(`Model ${s} failed to initialize`,c),c}}async registerSubscribers(t){var s;L.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(t)}async online(){var s,r;L.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const t=V.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,t))}async offline(){var s,r,o;L.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const t=V.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,t))}accept(t){t.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(t){this.companionManager.add(t)}clearCompanionModels(){this.companionManager.clear()}}const Wc=e=>typeof e=="function",Mi=m.createLogger({name:"kos-model-instantiator"});class Op{constructor(t,s){this.registry=t,this.cache=s}createModelInstance(t,s,r={}){const o=this.registry.models[t];if(!o)throw new Error(`No model registered for type ${t}`);const n=o.singleton?t:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Mi.debug(`Creating model instance: ${t} [${n}]`);const a=o.create?o.create({modelTypeId:t,id:n,options:r}):new o.class(n,r),c=new qc({modelTypeName:t,id:n,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(n);if(!i)throw Mi.error(`Model ${t} [${n}] not found in cache`),new Error(`Model ${t} [${n}] not found in cache`);return{model:i,data:i.modelData}}_createCompanionModels(t,s){var n;const r=t.modelTypeName,o=((n=this.registry.companionModels)==null?void 0:n[r])||[];for(const{type:i}of o){const a=Wc(i)?i(t.modelData,s):i;if(!a)continue;const c=`${a}-${t.modelId}`,u=this.createModelInstance(a,c,{data:s,companionParent:t.modelData,kosParentId:t.modelId});u!=null&&u.model&&(u.model[bt]=t,t.addCompanionModel(u.model))}}}let Ip=class{constructor(t){this._registry=t}get registry(){return this._registry}getModelTypeRegistry(t){const s=this.registry.models[t];if(!s)throw new Error(`No registration for model type ${t}`);return s}registerModel(t){const s=t.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...t.registration})}registerCompanionModel(t,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[t]??(o[t]=[]),this.registry.companionModels[t].some(n=>n.type===s)||this.registry.companionModels[t].push({type:s})}getModelSubscriptions(t){var s;return((s=this.getModelTypeRegistry(t))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(t){var r;const s=(r=this.getModelTypeRegistry(t))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${t}`);return s}getModelFactory(t){return Pt(t)}};const Qc=10,Ti=m.createLogger({name:"kos-model-manager"});class Zc{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Jh,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=t=>{const s=this.getModelById(t);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=t=>{var r,o;const s=this.getModelById(t);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=t=>{var r;const s=this.getModelById(t);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(t,s){const r=this.getInstance(s);return r._registry=new Ip(t),r.cache=new ef(t.preloadModels),r.instantiator=new Op(t,r.cache),r}static getInstance(t){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||t)&&(Ti.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(t=>(Ti.debug(`preloading ${t}`),typeof t=="string"?this.createModelInstance(t).model:this.createModelInstance(t.modelType,t.modelId,t.options).model))}get models(){return this.cache.models}getModelById(t){return this.cache.getModelById(t)}addModel(t){return this.cache.addModel(t)}removeModel(t){this.cache.removeModel(t.modelId)}hasModel(t){return this.cache.hasModel(t)}getModelsByType(t,s){return Array.from(this.models).filter(r=>r.modelTypeName===t).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(t){return this._registry.getModelSubscriptions(t)}getDataModelBuilder(t){return this._registry.getDataModelBuilder(t)}getModelFactory(t){return Pt(t)}addDependency(t,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(t,s)}removeDependency(t,s){this.dependencies.remove(t,s)}async reloadModel(t){if(t.id){const s=this.getModelById(t.id);s&&await s.fsm.transitionTo(P.RESET,v.RESETTING)}}async initiateDestroyModel(t){if(!t.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(t.id))return;const s=this.getModelById(t.id);s&&(this.cache.markForDeletion(s),ec.addToDeletionQueue(t.id,setTimeout(()=>this.destroyModel(s),Qc)))}async destroyModel(t){var s;t!=null&&t.modelId&&this.dependencies.canDestroy(t.modelId)&&(await((s=t.unload)==null?void 0:s.call(t)),this.removeModel(t))}createModelInstance(t,s,r={}){return this.instantiator.createModelInstance(t,s,r)}registerCompanionModel(t,s){this._registry.registerCompanionModel(t,s)}registerModel(t){this._registry.registerModel(t)}}var qs=(e=>(e.CREATING="creating",e.CREATED="created",e.INITIALIZING="initializing",e.INITIALIZED="initialized",e.LOADING="loading",e.LOADED="loaded",e.ONLINE="online",e.READYING="readying",e.READY="ready",e.OFFLINE="offline",e.UNLOADING="unloading",e.UNLOADED="unloaded",e.RELOADING="reloading",e))(qs||{}),ft=(e=>(e.CREATE="create",e.INITIALIZE="init",e.READY="ready",e.GO_ONLINE="go_online",e.GO_OFFLINE="go_offline",e.UNLOAD="unload",e.RELOAD="reload",e))(ft||{});const Sp=e=>{const t=y.createMachine("offline",{online:y.state(y.transition("go_offline","offline",y.action(()=>{e.offline(),E.runInAction(()=>{e.isOnline=!1})}))),offline:y.state(y.transition("go_online","online",y.action(()=>{e.online(),E.runInAction(()=>{e.isOnline=!0})})))}),s=y.interpret(t,n=>C.debug(n.machine.current)),r=y.createMachine({creating:y.state(y.transition("create","created")),created:y.state(y.immediate("initializing")),initializing:y.invoke(()=>e.init(),y.transition("done","initialized")),initialized:y.state(y.immediate("loading")),loading:y.invoke(()=>e.load(),y.transition("done","loaded")),loaded:y.state(y.immediate("readying"),y.transition("unload","unloading")),readying:y.invoke(()=>e.ready(),y.transition("done","ready",y.action(()=>{E.runInAction(()=>{e.status="ready"})}))),reloading:y.invoke(()=>e.reload(),y.transition("done","loading")),ready:y.state(y.transition("reload","reloading"),y.transition("unload","unloaded",y.action(e.unload.bind(e))),y.transition("go_online","ready",y.action(()=>{s.send("go_online")})),y.transition("go_offline","ready",y.action(()=>{s.send("go_offline")}))),unloaded:y.state()});return{service:y.interpret(r,n=>C.debug(n.machine.current)),online:s}},q=m.createLogger({name:"kos-core"}),$p=()=>{const e=ge(),t=e==null?void 0:e.alias,s=process.env.KOS_CONNECTION_ALIAS;return t||s||void 0},Cp=()=>{const e=window.location.protocol,t=ge(),s=t==null?void 0:t.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(e==="https:"?"wss://":"ws://")},Dp=()=>{const e=window.location.hostname,t=process.env.KOS_HOST,s=ge(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??t??e},xp=()=>{const e=window.location.port,t=process.env.KOS_PORT,s=ge(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??t??e},Ap=(e,t)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{t?m.error(`Model ${t.modelId} - ${t.modelTypeName} preloading - timed out after ${e}ms`):m.error(`KOS Core preloading timed out after ${e}ms`),i(new Error(`Model ${t==null?void 0:t.modelId} - ${t==null?void 0:t.modelTypeName} - timed out after ${e}ms`))},e)}),cancel:()=>{s&&clearTimeout(s)}}},_i=e=>typeof e.reload=="function",Rp=e=>typeof e.unload=="function";var Xc=(e=>(e.LOGGED_IN="logged_in",e.LOGGED_OUT="logged_out",e))(Xc||{});class I{constructor(t){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=t,this.loaded=!1,this.isOnline=!1,this.status=qs.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,E.makeAutoObservable(this),$("token",a=>{a&&(this.transport.token=a.body)}),$(us.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(ft.GO_ONLINE)}),$(us.DISCONNECTED,async()=>{this.fsmService.service.send(ft.GO_OFFLINE)}),$("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),$("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),$(us.RELOAD,()=>{q.warn("WebSocket requested reload"),this.fsmService.service.send(ft.RELOAD)}),$("/studio/project/reload",()=>{q.warn("Project requested reload"),this.fsmService.service.send(ft.RELOAD)});const s=wt.getInstance(),r=Dp(),o=xp(),n=Cp();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=$p()??t;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Sp(this),this.fsmService.service.send(ft.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var o,n,i,a;const t=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)_i(c.modelData)&&(q.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),q.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&_i(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-t;setTimeout(()=>{E.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"),z("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){q.debug("KOS Core going offline"),z("/kosCore/offline","/kosCore/offline")}async unload(){var o;q.debug("Unloading KOS Core");const t=Date.now();this._unloading=!0,q.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Rp(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-t;setTimeout(()=>{E.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await E.when(()=>this.status===qs.READY)}async ready(){q.debug("Readying KOS Core"),await this._transport.whenReady();const t=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(t.map(o=>{const{promise:n,cancel:i}=Ap(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.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===qs.READY}set transport(t){this._transport=t}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(t,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=t.extensions)!=null&&i.dataMapper&&Object.keys(t.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=t.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{S.dataMapper.registerDataMapper(u,p)}):S.dataMapper.registerDataMapper(u,d))}),(a=t.extensions)!=null&&a.propertyMapper&&Object.keys(t.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=t.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&S.propertyMapper.registerPropertyMapper(u,d)}),(c=t.extensions)!=null&&c.contextLoader&&Object.keys(t.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=t.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&S.loader.registerLoader(u,d)}),x.model.getAll().forEach(([,u])=>{t.models={...t.models,...u.registration}}),t.models={...t.models,...x.model.getLegacyModels()},x.companion.getAll().forEach(([u,d])=>{t.companionModels={...t.companionModels},t.companionModels[u]=t.companionModels[u]||[];for(const h of d)t.companionModels[u].push({type:h})}),x.model.getPreloadModels().forEach(u=>{t.preloadModels.includes(u)||t.preloadModels.push(u)});const n=Zc.create(t,s);return o.modelManager=n,o}static getInstance(t){return this._instance=window.KosCore,(!this._instance||t!=null&&t.reset)&&(window.KosCore=new this(t==null?void 0:t.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function Mo(e){const t=new Uint8Array(e);let s="";for(let r=0;r<t.byteLength;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function Pp(e){const t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s.buffer}async function kp(e){return await e.arrayBuffer()}function Lp(e,t){return new Blob([e],{type:t})}async function Fp(e){const t={},s=[],r=[];e.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:Mo(i)})}else t[o]=n.toString();return{fields:t,files:s}}function Np(e){return new ReadableStream({async start(){},async pull(t){await e(t)},cancel(){}})}async function Up(e){if(!e)return{data:"",contentType:"text/plain"};if(typeof e=="string")return{data:e,contentType:"text/plain"};if(e instanceof ArrayBuffer||e instanceof Uint8Array){let t;return e instanceof Uint8Array?(t=new ArrayBuffer(e.byteLength),new Uint8Array(t).set(e)):t=e,{data:Mo(t),contentType:"application/octet-stream",encoding:"base64"}}if(e instanceof Blob){const t=await kp(e);return{data:Mo(t),contentType:e.type||"application/octet-stream",encoding:"base64"}}if(e instanceof FormData){const t=await Fp(e);return{data:JSON.stringify(t),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Ns=m.createLogger({name:"kos-fetch"}),jp=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Bp=()=>new Promise(e=>{setTimeout(()=>{e(!0)},0)}),Kp=e=>e!=null&&e.studio?Lc:e!=null&&e.fos?Fc:Nc,Hp=async(e,t)=>{const s=I.getInstance().transport;await s.whenReady();const r=tt(),o=new URL(e),n=`${o.pathname}${o.search}`;Ns.debug(`path: ${n}`);const i=(t==null?void 0:t.timeout)||jp,a=Kp(t),c=await Up(t==null?void 0:t.body),u={};c.contentType&&(u["content-type"]=c.contentType),c.encoding&&(u["content-encoding"]=c.encoding);const d=Ge(a({path:n,requestId:r,method:(t==null?void 0:t.method)||"GET",destinationAddress:(t==null?void 0:t.destinationAddress)||"",ordered:t==null?void 0:t.ordered,tracker:t==null?void 0:t.tracker,bridge:t==null?void 0:t.bridge,headers:{...t==null?void 0:t.headers,...u}}),c.data);return new Promise(h=>{let f=null,p=null;if(t!=null&&t.signal){if(t.signal.aborted){h({headers:Gt({}),status:0,ok:!1,json:async()=>null,body:Vt(""),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}t.signal.addEventListener("abort",()=>{p&&clearTimeout(p),f&&f(),h({headers:Gt({}),status:0,ok:!1,json:async()=>null,body:Vt(""),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(()=>{Ns.error(`Timeout occurred - url: ${e}`),f&&f(),h({headers:Gt({}),status:404,ok:!1,json:async()=>null,body:Vt(""),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 b=$(r,M=>{p&&clearTimeout(p);const _=(M==null?void 0:M.headers)||{},F=_["content-type"]||"text/plain",Q=_["content-encoding"],D=(M==null?void 0:M.body)||"";let O=D;if(Q==="base64"&&D)try{O=Pp(D)}catch(B){Ns.error("Failed to decode base64 response",B)}const W={headers:Gt(_),status:_.status&&parseInt(_.status)||200,ok:_.status==="200",json:async()=>{try{if(typeof O=="string")return O.length?JSON.parse(O):null;{const J=new TextDecoder().decode(O);return J.length?JSON.parse(J):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof O=="string"?O:new TextDecoder().decode(O),arrayBuffer:async()=>O instanceof ArrayBuffer?O:new TextEncoder().encode(O).buffer,blob:async()=>O instanceof ArrayBuffer?Lp(O,F):new Blob([O],{type:F}),formData:async()=>{const B=new FormData;if(F==="multipart/form-data"&&typeof O=="string")try{const J=JSON.parse(O);J.fields&&Object.entries(J.fields).forEach(([Ue,$e])=>{B.append(Ue,$e)}),J.files&&Ns.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return B},body:t!=null&&t.stream?Np(async B=>{if(O instanceof ArrayBuffer)B.enqueue(new Uint8Array(O));else{const J=new TextEncoder;B.enqueue(J.encode(O))}B.close()}):Vt(typeof O=="string"?O:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};b.unsubscribe(),Bp().then(()=>h(W))});f=b.unsubscribe;const w=t!=null&&t.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${t}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=Hp;if(process.env.KOS_MOCK_FETCH==="true"){const e=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${e}`}const zp=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Gp{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(t){var r;if(t.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error(`Could not find rootModel with id: ${t.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(t){var r;if(this.visitedModels.has(t.modelId)){zp.info(`model ${t.modelId} already visited`);return}const s=!!this.visitModel(t.modelData,this);this.visitedModels.add(t.modelId),!s&&((r=t.getChildren)==null||r.call(t).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}const Jc=()=>({isMock:!1,URL:exports.BASE_URL}),Vp=m.createLogger({name:"kos-service-request"}),Yp="errUnknown";async function Us(e,t,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((h,f)=>String(h).replace(`{${f}}`,r==null?void 0:r.path[f]),String(e)):String(e),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${h}=${r.query[h]}`).join("&"):"",a=`${Jc().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;Vp.debug(`fullUrl: ${a}`);const c={method:String(t).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const u=await exports.kosFetch(a,c);return u.status<200||u.status>=400?[`${u.statusText||Yp}`,null]:[null,(await u.json()).data]}function un(){return{get:(e,t,s)=>Us(e,"get",s,t),post:(e,t,s,r)=>Us(e,"post",r,t,s),put:(e,t,s,r)=>Us(e,"put",r,t,s),delete:(e,t,s,r)=>Us(e,"delete",r,t,s)}}class el{constructor(){l(this,"middlewares",[])}use(t){this.middlewares.push(t)}async execute(t){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](t,r)};await this.middlewares[s](t,r)}}const qp=async(e,t)=>{const s=new el;t.forEach(o=>s.use(o));const r={data:e,result:{}};return await s.execute(r),r.result},Pt=e=>({type:e,build:(t,s)=>I.getInstance().modelManager.createModelInstance(e,t,s).data,buildAsync:async(t,s)=>{const r=I.getInstance().modelManager.createModelInstance(e,t,s);return await r.model.whenInitialized(),r.data}}),Wp=e=>{I.getInstance().modelManager.registerModel(e)},Qp=(e,t)=>{I.getInstance().modelManager.registerCompanionModel(e,t)},Oi="/kos/ui/internal/heartbeat/",Zp=({relationshipId:e,destinationAddress:t,onAbort:s,waitTime:r,beatTime:o})=>{const n=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${Oi}${e}`,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=o??2e3,f=window.setInterval(()=>{Gc({msg:{},options:{topic:`${Oi}${e}`,destinationAddress:t}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},b=()=>{p(),s&&s(),i.signal.removeEventListener("abort",b)};return i.signal.addEventListener("abort",b),{cleanUpHeartbeat:p}},tl=(...e)=>t=>e.reduce((s,r)=>r(s),t),Xp={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Jp(e,t){let s=1;const r={...Xp,...t},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await e()}catch(c){if(m.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw c}throw new Error("All attempts failed")}const eg=m.createLogger({name:"kos-service-request"}),ae=e=>({isMock:!1,URL:exports.BASE_URL}),tg=(e,t,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d})=>{const h={method:"DELETE"};e&&(h.destinationAddress=e),o&&(h.tracker=o),kt(h,{ordered:i,studio:a,fos:c,bridge:u,destinationAddress:d});const f=await s(n||`${t}/${r}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},kt=(e,{ordered:t,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i})=>(i&&(e.timeout=i),t&&(e.ordered=t),s&&(e.studio=s),r&&(e.fos=r),n&&(e.bridge=n),(o||o==="")&&(e.destinationAddress=o),e),sg=(e,t,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,destinationAddress:u})=>{const d={method:"GET"};e&&(d.destinationAddress=e),kt(d,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const f=await s(r||t,d);if(!f.ok){let b;try{b=await f.json()}catch{}throw new pe(`There was a problem retrieving the model; returned status ${f.status}`,b)}return await f.json()},rg=(e,t,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};e&&(h.destinationAddress=e),c&&(h.tracker=c),kt(h,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=r||t;eg.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new pe(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},og=(e,t,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:u,destinationAddress:d})=>{const h={method:"GET"};e&&(h.destinationAddress=e),kt(h,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,destinationAddress:d});const f=r||`${t}/${o}`,p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new pe(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class pe extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Ii=(e,t,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:u,timeout:d,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};e&&(f.destinationAddress=e),i&&(f.tracker=i),kt(f,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,destinationAddress:h});const p=await s(o||t,f);if(!p.ok){let w;try{w=await p.json()}catch{}throw new pe(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},Si=(e="POST",t,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,destinationAddress:f})=>{const p={method:e};o&&(p.body=JSON.stringify(o)),t&&(p.destinationAddress=t),kt(p,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,destinationAddress:f});const b=await r(i||`${s}/${n}`,p);if(!b.ok){let M;try{M=await b.json()}catch{}throw new pe(`There was a problem modifying the model; returned status ${b.status}`,M)}return await b.json()},oe={build:({destinationAddress:e="",basePath:t,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:sg(e,s||t,c),getModelById:og(e,r||t,c),getOne:rg(e,r||t,c),addModel:Ii(e,n||t,c),deleteModel:tg(e,o||t,c),modifyModel:Si("POST",e,i||t,c),putModel:Si("PUT",e,i||t,c),postModel:Ii(e,n||t,c)}}},ng=tt(),sl=()=>`kos-${ng}`,ig=e=>!!e&&!e.includes("VM_SERVICE")&&e.startsWith(sl()),dn=async(e,t=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=$(e,i=>{C.debug(`recieved response for refId ${e}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${e} timed out. Cancelling.`))},t)}),ag=async(e,t,s)=>{const r=dn(s),o=await Promise.allSettled([e(t),r]);if(o[0].status==="fulfilled"){if(o[1].status==="rejected")throw Error(o[1].reason);if(o[0].value){if(o[1].value.error)throw Error(o[1].value.error);return o[0].value.data=o[1].value,o[0].value}}else throw Error(o[0].reason)},cg=async({topic:e,msg:t,requestId:s})=>{const r=s??tt(),o=dn(r);z(e,t,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},de=new Map;class rl{constructor(t){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=t,this._context=new E.ObservableMap({}),this._parent="",E.makeAutoObservable(this)}setParent(t){X(()=>{this._parent=t})}get id(){return this._id}get context(){return this._context}get parentModel(){var t;if(this._parent)return(t=_e(this._parent))==null?void 0:t.model}get companionModels(){const t=_e(this._id);return t!=null&&t.model?pc(t.model):[]}get(t){var s,r;if(this._context.has(t))return this._context.get(t);if(this.companionModels.length>0){const o=this.companionModels.find(n=>{var i;return!n.id||!de.has(n.id)?!1:(i=de.get(n.id))==null?void 0:i.context.has(t)});if(o)return(s=de.get(o.id))==null?void 0:s.get(t)}if(this._parent)return(r=de.get(this._parent))==null?void 0:r.get(t)}set(t,s){this._context.set(t,s)}remove(t){this._context.delete(t)}clear(){this._context.clear()}}const V={createContext:(e,t)=>{const s=de.get(e)??new rl(e);if(t){if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);s.setParent(t)}else e!=="root"&&s.setParent("root");return de.set(e,s),s},getContext:e=>de.get(e),deleteContext:e=>{de.delete(e)},setParentContext:(e,t)=>{var s;if(!de.has(t))throw new Error(`Parent context ${t} does not exist`);(s=de.get(e))==null||s.setParent(t)},rootContext:()=>de.get("root")};V.createContext("root");const lg=e=>V.getContext(e.id),io=m.createLogger({name:"kos-data-container"});class hn{constructor(t){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=E.observable.map(new Map),this._sortKey=t==null?void 0:t.sortKey,this._revision=1,this._optionsMap=(t==null?void 0:t.indexMap)||{};const s=t!=null&&t.indexMap?Object.keys(t.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=E.observable.map(s),this.idx=Te(),E.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(t=>{const s=this._optionsMap[t],r=new on({container:this,key:s});this._index.set(t,r),this.idx[t]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((t,s)=>{var r;return t[s]=(r=this.index.get(s))==null?void 0:r.keys,t},{})}get revision(){return this._revision}addAll(t){E.runInAction(()=>{t.forEach(s=>this.addModel(s))})}removeAll(t){E.runInAction(()=>{t.forEach(s=>this.removeModel(s))})}sortFn(t,s){const r=this._sortKey;return r?String(t[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const t=Array.from(this._data.values());return this._sortKey&&t.sort(this.sortFn.bind(this)),t}increment(){E.runInAction(()=>{this._revision=this._revision+1})}addModel(t,s){const r=E.isObservable(t)?t:E.observable.object(t),o=this._disposerMap.get(t.id);o&&(o(),this._disposerMap.delete(t.id)),this._data.set(r.id||"",r),s||this.increment();const n=E.observe(r,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(r.id||"",n)}removeModel(t){this._data.delete(t),this.increment();const s=this._disposerMap.get(t);s&&(s(),this._disposerMap.delete(t))}updateModel(t){const s=E.observable.object(t);this._data.set(s.id||"",s),this.increment()}getModel(t){return this._data.get(t)}getIndexKeys(t){return this.index.has(t)?this.index.get(t).keys??[]:(io.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(t,s){if(this.index.has(t)){const r=this.index.get(t);return r.index.has(s)?r.getByKey(s):(io.info(`key ${s} not found in ${t} index: ${Array.from(r.index.keys())}`),[])}else return io.info(`index ${t} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(t,s){return this.data.filter(t,s)}sort(t){return this.data.sort(t)}map(t,s){return this.data.map(t,s)}forEach(t,s){this.data.forEach(t,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class ug{constructor({type:t,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=t,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 Ee(this.type)}}class dg{constructor({type:t,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=t,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 Ee(this.type)}}class ol{constructor(){l(this,"_token");E.makeAutoObservable(this),$("token",t=>{this.token=t==null?void 0:t.body})}get token(){return this._token}set token(t){this._token=t}}class nl{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(t,s,...r){this.routes.push({method:t,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:t,path:s,parameters:o})}remove(t,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===t&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===t&&o.path===s)),r-this.routes.length}removeAllForPath(t){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==t),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==t),s-this.routes.length}getRoutes(){return this.routes.map(t=>({method:t.method,path:t.path}))}async handle(t,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(t.path),i={...t,params:n,query:o};for(const c of this.routes){const u=this.matchRoute(c.path,r);if(c.method===t.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(t){return t.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const t={};for(const s of this.openApiRoutes)t[s.path]||(t[s.path]={}),t[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:t}}extractPathParams(t){const[s,r]=t.split("?"),o=this.parseQueryParams(r);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:o,params:i}}return{path:s,query:o,params:{}}}matchRoute(t,s){const r=t.split("/").filter(Boolean),o=s.split("/").filter(Boolean);if(r.length!==o.length)return null;const n={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))n[r[i].slice(1)]=decodeURIComponent(o[i]);else if(r[i]!==o[i])return null;return n}parseQueryParams(t){return t?t.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const il=m.createLogger({name:"intent-service"}),hg=e=>{Ho(`/kos/intent/${e.type}`)?z(`/kos/intent/${e.type}`,e.options,{"kos.intent.type":e.type}):il.info(`No subscribers for intent ${e.type}. Intent not sent.`)},fg=async e=>new Promise(t=>{const{type:s,options:r}=e;if(Ho(`/kos/intent/${e.type}`)){const o=tt(),{unsubscribe:n}=$(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),t([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),t([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);z(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else il.info(`No subscribers for intent ${e.type}. Intent not sent.`),t([null,{body:void 0,payload:void 0}])}),De=m.createLogger({name:"app-startup-service"});async function al(e,t={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=t;if(e.length===0)return De.warn("No app IDs provided to waitForAppsToStart"),!0;De.debug(`Waiting for apps to start: ${e.join(", ")}`);try{const n=e.map(c=>`/kos/app/started/${c}`),i=await Vo(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>yy),[u,d]=await c.get("/api/kos/apps/started");return u?(De.error("Error fetching started apps:",u),[]):d}catch(c){De.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>e.every(u=>{const d=c.find(h=>h.appId===u);return!(!d||!d.started||o&&!d.postStarted)}),timeout:s}),a=e.filter(c=>{const u=i.find(d=>d.appId===c);return!!(!u||!u.started||o&&!u.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(De.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return De.info(`All apps started successfully: ${e.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${e.join(", ")}`;if(De.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function pg(e,t={}){return al([e],t)}async function gg(e,t=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return e.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];e.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!t||(a==null?void 0:a.postStarted)===!0)})}catch(r){De.error("Failed to check app startup status:",r),e.forEach(o=>s[o]=!1)}return s}async function mg(){try{const e=await exports.kosFetch("kos:///api/kos/apps/started");if(!e.ok)return[];const t=await e.json();return(t==null?void 0:t.data)??[]}catch(e){return De.error("Failed to fetch started apps:",e),[]}}const To=E.when,fn=E.computed,X=E.runInAction,Y=E.autorun,cl=E.reaction,pn=E.observable,gn="Not Assigned",yg="kos.trouble.added",bg="kos.trouble.removed";var be=(e=>(e.TroubleRank="kos.trouble.rank.mapper",e.TroubleColor="kos.trouble.color.mapper",e.TroubleRole="kos.trouble.role.mapper",e))(be||{}),ds=(e=>(e.TIME_CHANGE="/kos/internal/time/time",e.DAY_CHANGE="/kos/internal/time/day",e.TIMEZONE_CHANGE="/kos/internal/time/timezone",e))(ds||{});const ll=m.createLogger({name:"config-bean-service",group:"Services"}),mn=exports.BASE_URL,ul=e=>(e==null?void 0:e.decimals)!==void 0,{postModel:vg,getOne:wg}=oe.build({destinationAddress:"",basePath:`${mn}/kos/config/`}),dl=async(e,t,s="/api/kos/config")=>(ll.debug(`sending modify request for ConfigBean: ${e}`),vg({model:t,urlOverride:`${mn}${s}/${e}`})),hl=async(e,t="/api/kos/config")=>(ll.debug(`sending get request for ConfigBean: ${e}`),await wg({urlOverride:`${mn}${t}/details/${e}/15`})),yn=e=>e.toLowerCase()==="true"||e.toLowerCase()==="false",kr=e=>{try{const t=Number(e);return!isNaN(t)}catch{return!1}};function fl(e=[]){return e.reverse().reduce((t,s)=>{const{overrides:r}=s;return r&&(t={...t,...r}),t},{})}function pl(e,t="",s={}){for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const o=t?`${t}.${r}`:r;typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])?pl(e[r],o,s):s[o]=e[r]}return s}const gl=(e,t)=>{const s=e.details[0].bean||fl(e.details[0].scopes),r=pl(s);E.runInAction(()=>{const o={...r};t.props.setValues(o)})},ml=(e,t)=>{E.runInAction(()=>{e.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&yn(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&kr(o)&&(o=Number(o),n=Number(n)),t.props[r]=o,t.prevProps[r]=n})})},yl=e=>Object.fromEntries(e.props.entries),Eg=e=>t=>s=>e.build(t,s);var Mg=Object.defineProperty,Tg=Object.getOwnPropertyDescriptor,bl=(e,t,s,r)=>{for(var o=r>1?void 0:r?Tg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Mg(t,s,o),o};function _g(e,t){for(const s of e)if(new RegExp(`^${s}$`).test(t))return s}const bn="config-bean-model",js=m.getLogger(bn),Og=st("path");let sr=class{constructor(e,t){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,t),this.id=e,this.path=t.path,this.serviceBasePath=t.serviceBasePath;const{modifyConfigBean:s=dl,getConfigBean:r=hl}=t;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Te(),this.prevProps=Te()}get values(){return this.props.values}async ready(){js.debug(`readying config bean ${this.path}`),js.debug(`complete readying config bean ${this.path}`)}async load(){js.debug(`loading config bean ${this.path}`);const e=await this._getConfigBean(this.path,this.serviceBasePath);if(e!=null&&e.data){const t=e.data;gl(t,this),js.debug(this.values);const s=e==null?void 0:e.data.details[0].schema;X(()=>{s&&(this._schema=s)})}}get schemaKeys(){var e;return Object.keys(((e=this._schema)==null?void 0:e.schema)||{})}getSchemaForProperty(e){var s,r;if(this.schemaKeys.includes(e))return(s=this._schema)==null?void 0:s.schema[e];const t=_g(this.schemaKeys,e);if(t)return(r=this._schema)==null?void 0:r.schema[t]}async updateProperty(e,t){this.props[e]=t,await this.updateConfigBean()}async updateConfigBean(){const e=yl(this);await this._modifyConfigBean(this.path,e,this.serviceBasePath)}handleConfigBeanUpdated(e){ml(e,this)}};bl([U({topic:`/kos/config/${Og}`,websocket:!0})],sr.prototype,"handleConfigBeanUpdated",1);sr=bl([A(bn)],sr);const ps=new me({class:sr,type:bn}),Lr=({path:e,lazy:t,serviceBasePath:s})=>(r,o)=>{r[k]=r[k]||{},r[k][o]={modelType:ps.type,id:`${ps.type}-${e}`,options:{path:e,serviceBasePath:s},lifecycle:H.INIT,lazy:t}},{URL:vl}=ae(),{getOne:Ig,getAll:Sg}=oe.build({basePath:`${vl}/api/kos/regions/info`}),wl=async()=>{try{return await Ig({})}catch{return}},El=async()=>{try{return await Sg({urlOverride:`${vl}/api/kos/regions`})}catch{return}},$g=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:wl,getRegions:El},Symbol.toStringTag,{value:"Module"}));var le=(e=>(e[e.family=0]="family",e[e.scale=1]="scale",e[e.offset=2]="offset",e[e.decimals=3]="decimals",e[e.alias=4]="alias",e[e.system=5]="system",e))(le||{});const Ml={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 Cg(e,t){const s=t.id,r=t.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{...Ml});return{...e,...r}}function Dg(e,t){const s=t.id,r=t.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...Ml}}});return Object.keys(r).forEach(o=>{e[o]={...e[o],...r[o]}}),e}function xg(e,t){const s=t.id,r=t.units.reduce((o,n)=>{const i=o[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),o[n.measure]=i,o},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(o=>{e[o]={...e[o],...r[o]}}),e}var Ag=Object.defineProperty,Rg=Object.getOwnPropertyDescriptor,vn=(e,t,s,r)=>{for(var o=r>1?void 0:r?Rg(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ag(t,s,o),o};const Ws="region-info-model",Ht=m.createLogger({name:"region-info-model"});let gs=class{constructor(e){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=e,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 e=this.regionSource.props.timeFormatId;if(!e)return"";const t=String(e),s=this.timeFormats[t];return s?String(s.id):""}get selectedTimeFormat(){const e=this.timeFormatId;return e?String(this.timeFormats[e].format):"HH:mm:ss"}get is12HourTimeFormat(){const e=this.timeFormatId;return e?this.timeFormats[e].ampm:!0}get dateFormatId(){const e=this.regionSource.props.dateFormatId;if(!e)return"";const t=String(e);return t?this.dateFormats[t].id:""}get selectedDateFormat(){const e=this.dateFormatId;return e?this.dateFormats[e].format:""}get selectedDateOrder(){const e=this.dateFormatId;return e?this.dateFormats[e].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(e=>({id:e,format:this.timeFormats[e].format,ampm:this.timeFormats[e].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(e=>({id:e,format:this.dateFormats[e].format,order:this.dateFormats[e].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(e=>({id:e,name:e}))}setSelectedTimeFormat(e){if(!this.timeFormatOptions.find(t=>t.id===e))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",e)}setSelectedDateFormat(e){if(!this.dateFormatOptions.find(t=>t.id===e))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",e)}setSelectedUnitSystem(e){if(!this.unitSystemOptions.find(t=>t.id===e))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(t=>t.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",e)}getUnitSystem(e){if(!e)return this.defaultUnitSystem;const t=e==="drt"?"second":e,s=this.unitSystemMap[t];if(!s)throw Error(`No unit found with name: ${t}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[le.system]}getUnitMeasure(e){const t=e==="drt"?"second":e,s=this.unitSystemMap[t];if(!s)throw Error(`No unit found with name: ${t}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[le.family]}getDefaultUnitDecimalPlaces(e,t,s){if(!e||!t)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[e];if(!o)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[t.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${e} and unit system: ${t}. Unit system should come form list of unit systems: ${Object.keys(o).join(", ")}`);const i=n[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${e} and unit system: ${t}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[le.decimals]}getDefaultUnitForMeasure(e,t){if(!e||!t)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[e];if(!s)throw Error(`No unit systems found for measure: ${e}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[t.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${e} and unit system: ${t}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(e,t,s){if(t[le.family]!==s[le.family])throw new Error(`Cannot convert between units of different families: ${t[le.family]} and ${s[le.family]}`);const r=t[le.offset],o=t[le.scale],n=s[le.scale],i=s[le.offset],a=s[le.decimals];return((e-r)/(o/n)+i).toFixed(a)}convertByUnitName(e,t,s){const r=this.unitSystemMap[t],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${t} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(e,r,o)}convert(e,t,s){var a,c;if(t.unit&&s.unit)return this.convertByUnitName(e,t.unit,s.unit);const r=t.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];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||Ht.info("Could not find default unit for measure",s.measure)}if(!n&&t.measure&&t.system){const u=this.measureMap[t.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=u[t.system])==null?void 0:c.default,n||Ht.info("Could not find default unit for measure",t.measure)}return!n||!i?(Ht.warn("Could not find unit to convert to or from. Return value as is"),String(e)):this.convertByUnit(e,n,i)}async init(){Ht.debug("initializing region info")}async load(){Ht.debug("loading region info");const e=await El();e&&(this.regions=e.data.map(s=>s.id),this.timeZoneMap=e.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=e.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const t=await wl();t&&(this.unitSystems=t.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=t.data.unitSystems.reduce(Cg,{}),this.measureMap=t.data.unitSystems.reduce(Dg,{}),this.defaultMeasureMap=t.data.unitSystems.reduce(xg,{}),this.timeFormats=t.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=t.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var e,t;await((t=(e=this.regionSource).ready)==null?void 0:t.call(e))}};vn([Lr({path:"kos:service:region:settings"})],gs.prototype,"regionSource",2);vn([Lr({path:"kos:service:region"})],gs.prototype,"region",2);gs=vn([A(Ws)],gs);const re={registration:{[Ws]:{class:gs,singleton:!0}},type:Ws,factory:ie.Singleton.create(Ws)},rr=({source:e,defaultSystem:t="si",defaultMeasure:s})=>{let r={system:t,measure:s};return typeof e=="string"?r={...r,unit:e}:r={...r,...e},r},wn=(e,t,s)=>{const{model:r}=_e(re.type);if(!r)throw new Error("RegionInfo model not found");if(!tr(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=rr({source:t}),i=rr({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(e,n,i)};function $i(e,t,s){const r=t.toLowerCase().replace(/_/g,"-").replace(/s$/,""),o=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const n=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(o,{style:"unit",unit:r,unitDisplay:n,minimumFractionDigits:a,maximumFractionDigits:i}).format(e)}catch{return t}}const Pg=(e,t,s,r)=>{const o=wn(e,t,s),n=rr({source:t}),{model:i}=_e(re.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=rr({source:s||c,defaultMeasure:i.getUnitMeasure(n.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:o,unit:d||n.unit||"",display:$i(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:$i(o,d||n.unit||"",{...f,mode:"short"})}};function Ci({start:e,end:t,count:s,decimals:r=0}){if(typeof e!="number"||typeof t!="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(e>=t)throw new Error("Start should be less than end.");const o=(t-e)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(e+i*o);n.push(a.toFixed(r))}return n}function Di({start:e,end:t,interval:s,decimals:r=0}){if(typeof e!="number"||typeof t!="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(e>=t)throw new Error("Start should be less than end.");const o=[];let n=e;for(;n<=t;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==t.toString()&&o.push(t.toString()),o}const lt=(e,t)=>s=>!e||!t?s:kr(s)?wn(Number(s),e,t):s,kg=(e,t,s,r)=>{if((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options))return[];if(e.options.type==="rangeCount")return Ci(e.options).map(lt(s,r));if(e.options.type==="rangeInterval")return Di(e.options).map(lt(s,r));if(e.options.type==="list"){const{list:o}=e.options;return o.map(lt(s,r))}else{if(e.options.type==="unitSystemRangeCount"&&t)return Ci(e.options.unitSystems[t]).map(lt(s,r));if(e.options.type==="unitSystemRangeInterval"&&t)return Di(e.options.unitSystems[t]).map(lt(s,r));if(e.options.type==="unitSystemList"&&t){const{list:o}=e.options.unitSystems[t];return o.map(lt(s,r))}}return[]},Lg=(e,t)=>{if(!((e==null?void 0:e.type)==="enum"||!(e!=null&&e.options)))return e.options.type==="unitSystemRangeCount"&&t?{type:"rangeCount",...e.options.unitSystems[t]}:e.options.type==="unitSystemRangeInterval"&&t?{type:"rangeInterval",...e.options.unitSystems[t]}:e.options.type==="unitSystemList"&&t?{type:"list",...e.options.unitSystems[t]}:e.options.type==="unitSystemKeypad"&&t?{type:"keypad",...e.options.unitSystems[t]}:e.options};var Fg=Object.defineProperty,Ng=Object.getOwnPropertyDescriptor,En=(e,t,s,r)=>{for(var o=r>1?void 0:r?Ng(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Fg(t,s,o),o};function Ug(e){return(e==null?void 0:e.type)==="enum"}function jg(e){switch(e){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 e}}function Bg(e,t){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+e*1e3);return je.format(r,t)}const Qs="config-bean-prop-model",ut=m.createLogger({name:"config-bean-prop-model"}),Kg=st("path"),Hg=st("serviceBasePath");let ms=class{constructor(e,t){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=e,this.path=t.path,this.attribute=t.attribute,this.converter=t.converter,this.formatter=t.formatter,this.serviceBasePath=t.serviceBasePath,this.optionsExpander=t.optionsExpander}getDefaultUnitDecimalPlaces(e,t,s){if(!e)throw new Error("measure is required");if(!t)throw new Error("unitSystem is required");return ul(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(e,t,s)}getDefaultUnitForMeasure(e,t){if(!e)throw new Error("measure is required");if(!t)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(e,t)}get schemaType(){const e=this.bean.getSchemaForProperty(this.attribute);return e!=null&&e.type?e.type:"String"}get schemaFormat(){const e=this.bean.getSchemaForProperty(this.attribute);return e!=null&&e.format?jg(e.format):""}get options(){var i;const e=this.regionInfo.defaultUnitSystem,t=this.getConverter(),s=((i=t==null?void 0:t.to)==null?void 0:i.system)??e,r=this.bean.getSchemaForProperty(this.attribute),o=Ug(r)?r.values:kg(r,s,t==null?void 0:t.from,t==null?void 0:t.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(e,t,s){const r=(e==null?void 0:e.measure)||s,o=(e==null?void 0:e.system)||t,n=e==null?void 0:e.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const e=this.regionInfo.defaultUnitSystem,t=this.getConverter();if(!t)throw Error("No converter defined");const s=t.measure,r=this.convertUnit(t.from,"si",s),o=this.convertUnit(t.to,e,s);return{backend:r,display:o}}set value(e){this.updateProperty(e)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const e=this.value,t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(e)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,t,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let u=String(e);return u=c.formatToParts(Number(e))[0].value,Number(u)}}catch(c){ut.info(`error formatting value ${e}`,c)}return Number(e).toFixed(i)}return e}get previousValue(){return this.getValue(!1)}getValue(e){const t=this.bean[e?"props":"prevProps"][this.attribute];if(typeof t=="boolean")return t;if(this.getConverter()&&!isNaN(t)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(t),r,o)}return t||""}async activate(){ut.debug(`activating config bean ${this.id}`)}get displayValue(){const e=this.value;if(typeof e=="boolean")return String(e);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return Bg(e,s)}if(!isNaN(e))try{const t=this.getConverter(),s=this.getFormatterOptions(t);if(s){let r=String(e);return r=s.format(Number(e)),r}}catch(t){ut.error(`error formatting value ${e}`,t)}return String(e)}get unit(){const e=this.getConverter();if(!isNaN(this.value)){const t=this.getFormatterOptions(e);if(t){const r=t.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(e)}}return this.getDefaultUnit(e)}get displayOptions(){var o;const e=this.bean.getSchemaForProperty(this.attribute),t=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??t;return Lg(e,r)}getMeasureFromFormat(){const e=this.schemaFormat;return e?this.regionInfo.getUnitMeasure(e):""}getConverterFromFormat(){const e=this.getMeasureFromFormat();if(e){const t=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(e,t),measure:e}}return{}}getDefaultUnit(e){var r,o;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure;return s?((r=e==null?void 0:e.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=e==null?void 0:e.to)==null?void 0:o.system)||t):this.getConverterFromFormat().unit}getFormatterOptions(e){var n,i,a;const t=this.regionInfo.defaultUnitSystem,s=e==null?void 0:e.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(e)}:null,u=this.formatter||c;if(u){let d=typeof u=="function"?u(((n=e==null?void 0:e.to)==null?void 0:n.system)||t):u;s&&(d={unit:this.getDefaultUnit(e),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=e==null?void 0:e.to)==null?void 0:i.system)||t,(a=e==null?void 0:e.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...d})}catch(h){ut.error(`error creating formatter ${d}. Returning the raw value`,h)}}else ut.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,u,d,h,f,p;const{unit:e,measure:t}=this.getConverterFromFormat(),s=e==="drt"?"second":e;if(this.converter){const b=(r=this.converter)==null?void 0:r.measure,w=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,M=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=b||w||M||t,F=((u=(c=this.converter)==null?void 0:c.to)==null?void 0:u.unit)||this.regionInfo.getDefaultUnitForMeasure(_,((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),Q=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(F),D=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:D,...this.converter.from},to:{...this.converter.to,unit:F,system:Q},measure:_}}if(s&&t){const b=this.regionInfo.getDefaultUnitForMeasure(t,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),M=this.regionInfo.getUnitSystem(b);return{measure:t,to:{unit:w===M?s:b}}}}async updateProperty(e){ut.debug(`updating property ${this.attribute} with value ${e}`);let t=e;if(this.getConverter()&&!isNaN(t)){const{backend:o,display:n}=this.getConverterUnits();t=this.regionInfo.convert(Number(t),n,o)}const r=Array.isArray(t)?JSON.stringify(t):String(t);await this.bean.updateProperty(this.attribute,r)}};En([Rt({modelType:re.type})],ms.prototype,"regionInfo",2);En([Lr({path:Kg,serviceBasePath:Hg})],ms.prototype,"bean",2);ms=En([A(Qs)],ms);const rt={registration:{[Qs]:{class:ms,singleton:!1}},type:Qs,factory:ie.Factory.create(Qs)};function zg(e){const{path:t,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=e,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[k]=u[k]||{},u[k][d]={modelType:rt.type,id:`${t}-${s}`,options:{path:t,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:H.INIT,lazy:n}}}const Tl="future-model",Lt=Pt(Tl),Fr=m.createLogger({name:"future-service",group:"Services"}),{isMock:Gg,URL:Ds}=ae();var Ke=(e=>(e.Success="SUCCESS",e.Fail="FAIL",e.Aborted="ABORT",e.Canceled="CANCEL",e))(Ke||{});const{getAll:Vg,modifyModel:Yg,addModel:qg,deleteModel:Wg,postModel:Qg}=oe.build({destinationAddress:"",basePath:`${Ds}/api/future`,mock:Gg}),Zg=async()=>await Vg({}),_l=async(e,t="/api/kos/future")=>(Fr.info(`sending delete request for Future: ${e}`),await Wg({id:e,urlOverride:`${Ds}${t}/${e}`})),Ol=async(e,t="/api/kos/future")=>(Fr.info("sending add request for Future"),await qg({model:e,urlOverride:`${Ds}${t}`})),Xg=async(e,t,s="/api/kos/future")=>(Fr.info(`sending modify request for Future: ${e}`),Yg({model:t,id:e,urlOverride:`${Ds}${s}/${e}`})),Il=async(e,t="/api/kos/future")=>(Fr.info(`sending cancel request for Future: ${e}`),Qg({urlOverride:`${Ds}${t}/${e}/cancel`,ordered:!0,model:{}})),Mn=e=>({id:String(e.id),progress:e.progress,remainingTimeMs:e.remainingTimeMs,endState:e.endState,reason:e.reason,clientData:e.clientData,reasonData:e.reasonData,note:e.note,tracker:e.tracker}),Tn=(e,t)=>{m.debug(`future dto ${e.id} end state ${e.endState}`),m.debug(`future model ${t.id} end state ${t.endState}`),t.endState?m.debug(`future model ${t.id} is already complete`):(m.debug(`updating future model ${t.id}`),E.runInAction(()=>{const s=Mn(e);X(()=>{Object.keys(s).forEach(r=>{r==="id"?(t.futureId=s.id,s.tracker||(t.id=s.id)):r==="tracker"?t.id=s.tracker:t[r]=s[r]})})}))},Sl=e=>t=>s=>e.build(String(t),s),_n=e=>t=>tl(Mn,Sl(e)(t.tracker||t.id))(t);var Jg=Object.defineProperty,em=Object.getOwnPropertyDescriptor,$l=(e,t,s,r)=>{for(var o=r>1?void 0:r?em(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Jg(t,s,o),o};const ao=m.getLogger(Lt.type);let or=class{constructor(e,t,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,t),this.logger=s.logger,this.id=e,this.futureId=t.id,this.namespace=t.namespace||"kos",this._cancelFuture=Il,To(()=>this.status===Ke.Success||this.status===Ke.Fail,()=>{ao.info(`Future ${this.id} has completed with status ${this.status}`),Xe(this)})}async load(){ao.debug(`loading Future ${this.id}`)}unload(){ao.info(`unloading Future ${this.id}`)}async cancelFuture(){const e=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await To(()=>this.futureId!==gn),await this._cancelFuture(this.futureId,e)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const e=this.remainingTimeMs||-1;if(e<0)return"";const t={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(t))if(Math.abs(e)>=d){s=u,r=Math.round(e/d);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(e){this.logger.debug(`Future ${this.id} updated. future: ${e.id} endState: ${e.endState} progress: ${e.progress} remainingTimeMs: ${e.remainingTimeMs}`),Tn(e,this)}};$l([U({topic:`kos.future/${Xs}`})],or.prototype,"handleFutureUpdated",1);or=$l([A(Lt.type)],or);const Cl=or,Dl=un();var tm=Object.defineProperty,sm=Object.getOwnPropertyDescriptor,xl=(e,t,s,r)=>{for(var o=r>1?void 0:r?sm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&tm(t,s,o),o};const Al="browser-router-model",rm="kos.http.request",om="kos.http.response";let nr=class{constructor(e,t,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=e,this.logger=s.logger,this.router=new nl}get id(){return this._id}async handleRequest(e,t){const s=t.headers["src-addr"],r=t.headers["dst-addr"],o=t.headers.url,n=t.headers.method,i=t.headers["request-id"],a={id:i,method:n,path:o,body:e};let c=200;const u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),Vc({msg:d,options:{responseId:i,destinationAddress:s,type:om,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(e,t,...s){this.router.use(e,t,...s)}remove(e,t){return this.router.remove(e,t)}removeAllForPath(e){return this.router.removeAllForPath(e)}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}`)}};xl([U({topic:rm})],nr.prototype,"handleRequest",1);nr=xl([A(Al)],nr);const On=new Me({class:nr,type:Al}),Rl="future-container-model",He=Pt(Rl),Pl=e=>_n(Lt)(e),nm=e=>{const t=Pl(e);return He.build(He.type,{}).addFutureModel(t),t},im=e=>He.build(He.type,{}).getFuture(String(e)),Je={buildFutureModel:Pl,initiateFuture:nm,getFuture:im};var am=Object.defineProperty,cm=Object.getOwnPropertyDescriptor,In=(e,t,s,r)=>{for(var o=r>1?void 0:r?cm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&am(t,s,o),o};const Bs=m.getLogger(He.type);let ys=class{constructor(e,t,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=_l,addFuture:o=Ol}=t;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=e,this._futures=new Se,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(e){return this._futures.getModel(e)}addFutureModel(e){this._futures.addModel(e)}removeFutureModel(e){this._futures.removeModel(e)}async removeFuture(e){try{await this._deleteFuture(e)}catch(t){Bs.error("error deleting a Future"),Bs.error(t)}}async createFuture(e){try{const t=await this._addFuture(e),s=t==null?void 0:t.data;if(s){const r=_n(Lt)(s);return this.addFutureModel(r),r}}catch(t){throw Bs.error("error creating a Future"),Bs.error(t),t}}handleFutureUpdated(e,t){const s=Je.buildFutureModel(e);this.addFutureModel(s);const r=`kos.future/${e.tracker||e.id}`;this.logger.debug(`publishing future update to ${r}`),z(r,t.body,t.headers)}};In([Ie],ys.prototype,"_futures",2);In([U({topic:"kos.future"})],ys.prototype,"handleFutureUpdated",1);ys=In([A(He.type)],ys);const kl=ys,{URL:xs}=ae(),{getOne:lm,postModel:um,deleteModel:Ll}=oe.build({basePath:`${xs}/api/keyVal`}),_o=m.createLogger({name:"key-value-service",group:"Services"}),Fl=async(e,t)=>{await Ll({urlOverride:`${xs}/api/keyVal/${e}/${t}`,id:t})},Nl=async(e,t,s)=>{const r=await um({urlOverride:`${xs}/api/keyVal/${e}/${t}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw _o.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${e}`);return r.data},Ul=async(e="studio")=>{_o.debug(`Retrieving all key-value data for namespace: ${e}`);const t=await lm({urlOverride:`${xs}/api/keyVal/${e}`});if((t==null?void 0:t.status)!==200)throw _o.error("Failed to retrieve key-value data",t),new Error(`Failed to retrieve key-value data for namespace ${e}`);return t.data},dm=async e=>{await Ll({urlOverride:`${xs}/api/keyVal/${e}`,id:""})},hm=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Fl,deleteKeyValueNamespace:dm,getKeyValue:Ul,updateKeyValue:Nl},Symbol.toStringTag,{value:"Module"}));var fm=Object.defineProperty,pm=Object.getOwnPropertyDescriptor,Sn=(e,t,s,r)=>{for(var o=r>1?void 0:r?pm(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&fm(t,s,o),o};const jl="key-value-model";let bs=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=e,this.logger=s.logger,this.data=Te(),this.namespace=t.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(e,t){this.logger.debug(`updating studio-state ${e} with value ${t}`),t!==void 0?(await Nl(this.namespace,e,t),this.data[e]=t):(await Fl(this.namespace,e),this.data[e]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const e=await Ul(this.namespace);this.data.setValues(e)}handleStateUpdate(e){e.namespace===this.namespace&&(this.data[e.key]=e.value)}handleStateDelete(e){e.namespace===this.namespace&&(this.data[e.key]=void 0)}};Sn([U({topic:"/keyVal/set"})],bs.prototype,"handleStateUpdate",1);Sn([U({topic:"/keyVal/remove"})],bs.prototype,"handleStateDelete",1);bs=Sn([A(jl)],bs);const $n=new me({class:bs,type:jl});var he="INUMBER",Ft="IOP1",Nt="IOP2",Ut="IOP3",Ae="IVAR",et="IVARNAME",Et="IFUNCALL",Nr="IFUNDEF",ne="IEXPR",Cn="IEXPREVAL",ot="IMEMBER",Ur="IENDSTATEMENT",Mt="IARRAY";function R(e,t){this.type=e,this.value=t??0}R.prototype.toString=function(){switch(this.type){case he:case Ft:case Nt:case Ut:case Ae:case et:case Ur:return this.value;case Et:return"CALL "+this.value;case Nr:return"DEF "+this.value;case Mt:return"ARRAY "+this.value;case ot:return"."+this.value;default:return"Invalid Instruction"}};function jr(e){return new R(Ft,e)}function Fe(e){return new R(Nt,e)}function Bl(e){return new R(Ut,e)}function Oo(e,t,s,r,o){for(var n=[],i=[],a,c,u,d,h=0;h<e.length;h++){var f=e[h],p=f.type;if(p===he||p===et)Array.isArray(f.value)?n.push.apply(n,Oo(f.value.map(function(b){return new R(he,b)}).concat(new R(Mt,f.value.length)),t,s,r,o)):n.push(f);else if(p===Ae&&o.hasOwnProperty(f.value))f=new R(he,o[f.value]),n.push(f);else if(p===Nt&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new R(he,d(a.value,c.value)),n.push(f);else if(p===Ut&&n.length>2)u=n.pop(),c=n.pop(),a=n.pop(),f.value==="?"?n.push(a.value?c.value:u.value):(d=r[f.value],f=new R(he,d(a.value,c.value,u.value)),n.push(f));else if(p===Ft&&n.length>0)a=n.pop(),d=t[f.value],f=new R(he,d(a.value)),n.push(f);else if(p===ne){for(;n.length>0;)i.push(n.shift());i.push(new R(ne,Oo(f.value,t,s,r,o)))}else if(p===ot&&n.length>0)a=n.pop(),n.push(new R(he,a.value[f.value]));else{for(;n.length>0;)i.push(n.shift());i.push(f)}}for(;n.length>0;)i.push(n.shift());return i}function Kl(e,t,s){for(var r=[],o=0;o<e.length;o++){var n=e[o],i=n.type;if(i===Ae&&n.value===t)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===Ft?u=jr(c.value):c.type===Nt?u=Fe(c.value):c.type===Ut?u=Bl(c.value):u=new R(c.type,c.value),r.push(u)}else i===ne?r.push(new R(ne,Kl(n.value,t,s))):r.push(n)}return r}function We(e,t,s){var r=[],o,n,i,a,c,u;if(Dn(e))return Ce(e,s);for(var d=e.length,h=0;h<d;h++){var f=e[h],p=f.type;if(p===he||p===et)r.push(f.value);else if(p===Nt)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!We(n,t,s):!1):f.value==="or"?r.push(o?!0:!!We(n,t,s)):f.value==="="?(a=t.binaryOps[f.value],r.push(a(o,We(n,t,s),s))):(a=t.binaryOps[f.value],r.push(a(Ce(o,s),Ce(n,s))));else if(p===Ut)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(We(o?n:i,t,s)):(a=t.ternaryOps[f.value],r.push(a(Ce(o,s),Ce(n,s),Ce(i,s))));else if(p===Ae)if(f.value in t.functions)r.push(t.functions[f.value]);else if(f.value in t.unaryOps&&t.parser.isOperatorEnabled(f.value))r.push(t.unaryOps[f.value]);else{var b=s[f.value];if(b!==void 0)r.push(b);else throw new Error("undefined variable: "+f.value)}else if(p===Ft)o=r.pop(),a=t.unaryOps[f.value],r.push(a(Ce(o,s)));else if(p===Et){for(u=f.value,c=[];u-- >0;)c.unshift(Ce(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===Nr)r.push(function(){for(var w=r.pop(),M=[],_=f.value;_-- >0;)M.unshift(r.pop());var F=r.pop(),Q=function(){for(var D=Object.assign({},s),O=0,W=M.length;O<W;O++)D[M[O]]=arguments[O];return We(w,t,D)};return Object.defineProperty(Q,"name",{value:F,writable:!1}),s[F]=Q,Q}());else if(p===ne)r.push(gm(f,t));else if(p===Cn)r.push(f);else if(p===ot)o=r.pop(),r.push(o[f.value]);else if(p===Ur)r.pop();else if(p===Mt){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:Ce(r[0],s)}function gm(e,t,s){return Dn(e)?e:{type:Cn,value:function(r){return We(e.value,t,r)}}}function Dn(e){return e&&e.type===Cn}function Ce(e,t){return Dn(e)?e.value(t):e}function xn(e,t){for(var s=[],r,o,n,i,a,c,u=0;u<e.length;u++){var d=e[u],h=d.type;if(h===he)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(xi).join(", ")+"]"):s.push(xi(d.value));else if(h===Nt)o=s.pop(),r=s.pop(),i=d.value,t?i==="^"?s.push("Math.pow("+r+", "+o+")"):i==="and"?s.push("(!!"+r+" && !!"+o+")"):i==="or"?s.push("(!!"+r+" || !!"+o+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+o+")))"):i==="=="?s.push("("+r+" === "+o+")"):i==="!="?s.push("("+r+" !== "+o+")"):i==="["?s.push(r+"[("+o+") | 0]"):s.push("("+r+" "+i+" "+o+")"):i==="["?s.push(r+"["+o+"]"):s.push("("+r+" "+i+" "+o+")");else if(h===Ut)if(n=s.pop(),o=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+o+" : "+n+")");else throw new Error("invalid Expression");else if(h===Ae||h===et)s.push(d.value);else if(h===Ft)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):t?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===Et){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===Nr){for(o=s.pop(),c=d.value,a=[];c-- >0;)a.unshift(s.pop());r=s.pop(),t?s.push("("+r+" = function("+a.join(", ")+") { return "+o+" })"):s.push("("+r+"("+a.join(", ")+") = "+o+")")}else if(h===ot)r=s.pop(),s.push(r+"."+d.value);else if(h===Mt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ne)s.push("("+xn(d.value,t)+")");else if(h!==Ur)throw new Error("invalid Expression")}return s.length>1&&(t?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function xi(e){return typeof e=="string"?JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):e}function gt(e,t){for(var s=0;s<e.length;s++)if(e[s]===t)return!0;return!1}function An(e,t,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<e.length;n++){var i=e[n];i.type===Ae||i.type===et?!r&&!gt(t,i.value)?t.push(i.value):(o!==null&&(gt(t,o)||t.push(o)),o=i.value):i.type===ot&&r&&o!==null?o+="."+i.value:i.type===ne?An(i.value,t,s):o!==null&&(gt(t,o)||t.push(o),o=null)}o!==null&&!gt(t,o)&&t.push(o)}function ve(e,t){this.tokens=e,this.parser=t,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.functions=t.functions}ve.prototype.simplify=function(e){return e=e||{},new ve(Oo(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,e),this.parser)};ve.prototype.substitute=function(e,t){return t instanceof ve||(t=this.parser.parse(String(t))),new ve(Kl(this.tokens,e,t),this.parser)};ve.prototype.evaluate=function(e){return e=e||{},We(this.tokens,this,e)};ve.prototype.toString=function(){return xn(this.tokens,!1)};ve.prototype.symbols=function(e){e=e||{};var t=[];return An(this.tokens,t,e),t};ve.prototype.variables=function(e){e=e||{};var t=[];An(this.tokens,t,e);var s=this.functions;return t.filter(function(r){return!(r in s)})};ve.prototype.toJSFunction=function(e,t){var s=this,r=new Function(e,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+xn(this.simplify(t).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var vs="TEOF",N="TOP",Br="TNUMBER",Hl="TSTRING",Re="TPAREN",Tt="TBRACKET",Kr="TCOMMA",Rn="TNAME",Pn="TSEMICOLON";function zl(e,t,s){this.type=e,this.value=t,this.index=s}zl.prototype.toString=function(){return this.type+": "+this.value};function G(e,t){this.pos=0,this.current=null,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.consts=e.consts,this.expression=t,this.savedPosition=0,this.savedCurrent=null,this.options=e.options,this.parser=e}G.prototype.newToken=function(e,t,s){return new zl(e,t,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(vs,"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 e=!1,t=this.pos,s=this.expression.charAt(t);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,t+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(t+1,r);this.current=this.newToken(Hl,this.unescape(o),t),e=!0;break}r=this.expression.indexOf(s,r+1)}return e};G.prototype.isParen=function(){var e=this.expression.charAt(this.pos);return e==="("||e===")"?(this.current=this.newToken(Re,e),this.pos++,!0):!1};G.prototype.isBracket=function(){var e=this.expression.charAt(this.pos);return(e==="["||e==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(Tt,e),this.pos++,!0):!1};G.prototype.isComma=function(){var e=this.expression.charAt(this.pos);return e===","?(this.current=this.newToken(Kr,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var e=this.expression.charAt(this.pos);return e===";"?(this.current=this.newToken(Pn,";"),this.pos++,!0):!1};G.prototype.isConst=function(){for(var e=this.pos,t=e;t<this.expression.length;t++){var s=this.expression.charAt(t);if(s.toUpperCase()===s.toLowerCase()&&(t===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(t>e){var r=this.expression.substring(e,t);if(r in this.consts)return this.current=this.newToken(Br,this.consts[r]),this.pos+=r.length,!0}return!1};G.prototype.isNamedOp=function(){for(var e=this.pos,t=e;t<this.expression.length;t++){var s=this.expression.charAt(t);if(s.toUpperCase()===s.toLowerCase()&&(t===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(t>e){var r=this.expression.substring(e,t);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(N,r),this.pos+=r.length,!0}return!1};G.prototype.isName=function(){for(var e=this.pos,t=e,s=!1;t<this.expression.length;t++){var r=this.expression.charAt(t);if(r.toUpperCase()===r.toLowerCase()){if(t===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(t===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(e,t);return this.current=this.newToken(Rn,o),this.pos+=o.length,!0}return!1};G.prototype.isWhitespace=function(){for(var e=!1,t=this.expression.charAt(this.pos);(t===" "||t===" "||t===`
|
|
78
|
+
`||t==="\r")&&(e=!0,this.pos++,!(this.pos>=this.expression.length));)t=this.expression.charAt(this.pos);return e};var mm=/^[0-9a-f]{4}$/i;G.prototype.unescape=function(e){var t=e.indexOf("\\");if(t<0)return e;for(var s=e.substring(0,t);t>=0;){var r=e.charAt(++t);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 o=e.substring(t+1,t+5);mm.test(o)||this.parseError("Illegal escape sequence: \\u"+o),s+=String.fromCharCode(parseInt(o,16)),t+=4;break;default:throw this.parseError('Illegal escape sequence: "\\'+r+'"')}++t;var n=e.indexOf("\\",t);s+=e.substring(t,n<0?e.length:n),t=n}return s};G.prototype.isComment=function(){var e=this.expression.charAt(this.pos);return e==="/"&&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 e=this.pos;if(e>=this.expression.length-2||this.expression.charAt(e)!=="0")return!1;++e;var t,s;if(this.expression.charAt(e)==="x")t=16,s=/^[0-9a-f]$/i,++e;else if(this.expression.charAt(e)==="b")t=2,s=/^[01]$/i,++e;else return!1;for(var r=!1,o=e;e<this.expression.length;){var n=this.expression.charAt(e);if(s.test(n))e++,r=!0;else break}return r&&(this.current=this.newToken(Br,parseInt(this.expression.substring(o,e),t)),this.pos=e),r};G.prototype.isNumber=function(){for(var e=!1,t=this.pos,s=t,r=t,o=!1,n=!1,i;t<this.expression.length&&(i=this.expression.charAt(t),i>="0"&&i<="9"||!o&&i===".");)i==="."?o=!0:n=!0,t++,e=n;if(e&&(r=t),i==="e"||i==="E"){t++;for(var a=!0,c=!1;t<this.expression.length;){if(i=this.expression.charAt(t),a&&(i==="+"||i==="-"))a=!1;else if(i>="0"&&i<="9")c=!0,a=!1;else break;t++}c||(t=r)}return e?(this.current=this.newToken(Br,parseFloat(this.expression.substring(s,t))),this.pos=t):this.pos=r,e};G.prototype.isOperator=function(){var e=this.pos,t=this.expression.charAt(this.pos);if(t==="+"||t==="-"||t==="*"||t==="/"||t==="%"||t==="^"||t==="?"||t===":"||t===".")this.current=this.newToken(N,t);else if(t==="∙"||t==="•")this.current=this.newToken(N,"*");else if(t===">")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(N,">="),this.pos++):this.current=this.newToken(N,">");else if(t==="<")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(N,"<="),this.pos++):this.current=this.newToken(N,"<");else if(t==="|")if(this.expression.charAt(this.pos+1)==="|")this.current=this.newToken(N,"||"),this.pos++;else return!1;else if(t==="=")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(N,"=="),this.pos++):this.current=this.newToken(N,t);else if(t==="!")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(N,"!="),this.pos++):this.current=this.newToken(N,t);else return!1;return this.pos++,this.isOperatorEnabled(this.current.value)?!0:(this.pos=e,!1)};G.prototype.isOperatorEnabled=function(e){return this.parser.isOperatorEnabled(e)};G.prototype.getCoordinates=function(){var e=0,t,s=-1;do e++,t=this.pos-s,s=this.expression.indexOf(`
|
|
80
|
+
`,s+1);while(s>=0&&s<this.pos);return{line:e,column:t}};G.prototype.parseError=function(e){var t=this.getCoordinates();throw new Error("parse error ["+t.line+":"+t.column+"]: "+e)};function j(e,t,s){this.parser=e,this.tokens=t,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}j.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};j.prototype.tokenMatches=function(e,t){return typeof t>"u"?!0:Array.isArray(t)?gt(t,e.value):typeof t=="function"?t(e):e.value===t};j.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};j.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};j.prototype.accept=function(e,t){return this.nextToken.type===e&&this.tokenMatches(this.nextToken,t)?(this.next(),!0):!1};j.prototype.expect=function(e,t){if(!this.accept(e,t)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(t||e))}};j.prototype.parseAtom=function(e){var t=this.tokens.unaryOps;function s(o){return o.value in t}if(this.accept(Rn)||this.accept(N,s))e.push(new R(Ae,this.current.value));else if(this.accept(Br))e.push(new R(he,this.current.value));else if(this.accept(Hl))e.push(new R(he,this.current.value));else if(this.accept(Re,"("))this.parseExpression(e),this.expect(Re,")");else if(this.accept(Tt,"["))if(this.accept(Tt,"]"))e.push(new R(Mt,0));else{var r=this.parseArrayList(e);e.push(new R(Mt,r))}else throw new Error("unexpected "+this.nextToken)};j.prototype.parseExpression=function(e){var t=[];this.parseUntilEndStatement(e,t)||(this.parseVariableAssignmentExpression(t),!this.parseUntilEndStatement(e,t)&&this.pushExpression(e,t))};j.prototype.pushExpression=function(e,t){for(var s=0,r=t.length;s<r;s++)e.push(t[s])};j.prototype.parseUntilEndStatement=function(e,t){return this.accept(Pn)?(this.nextToken&&this.nextToken.type!==vs&&!(this.nextToken.type===Re&&this.nextToken.value===")")&&t.push(new R(Ur)),this.nextToken.type!==vs&&this.parseExpression(t),e.push(new R(ne,t)),!0):!1};j.prototype.parseArrayList=function(e){for(var t=0;!this.accept(Tt,"]");)for(this.parseExpression(e),++t;this.accept(Kr);)this.parseExpression(e),++t;return t};j.prototype.parseVariableAssignmentExpression=function(e){for(this.parseConditionalExpression(e);this.accept(N,"=");){var t=e.pop(),s=[],r=e.length-1;if(t.type===Et){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var o=0,n=t.value+1;o<n;o++){var i=r-o;e[i].type===Ae&&(e[i]=new R(et,e[i].value))}this.parseVariableAssignmentExpression(s),e.push(new R(ne,s)),e.push(new R(Nr,t.value));continue}if(t.type!==Ae&&t.type!==ot)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),e.push(new R(et,t.value)),e.push(new R(ne,s)),e.push(Fe("="))}};j.prototype.parseConditionalExpression=function(e){for(this.parseOrExpression(e);this.accept(N,"?");){var t=[],s=[];this.parseConditionalExpression(t),this.expect(N,":"),this.parseConditionalExpression(s),e.push(new R(ne,t)),e.push(new R(ne,s)),e.push(Bl("?"))}};j.prototype.parseOrExpression=function(e){for(this.parseAndExpression(e);this.accept(N,"or");){var t=[];this.parseAndExpression(t),e.push(new R(ne,t)),e.push(Fe("or"))}};j.prototype.parseAndExpression=function(e){for(this.parseComparison(e);this.accept(N,"and");){var t=[];this.parseComparison(t),e.push(new R(ne,t)),e.push(Fe("and"))}};var ym=["==","!=","<","<=",">=",">","in"];j.prototype.parseComparison=function(e){for(this.parseAddSub(e);this.accept(N,ym);){var t=this.current;this.parseAddSub(e),e.push(Fe(t.value))}};var bm=["+","-","||"];j.prototype.parseAddSub=function(e){for(this.parseTerm(e);this.accept(N,bm);){var t=this.current;this.parseTerm(e),e.push(Fe(t.value))}};var vm=["*","/","%"];j.prototype.parseTerm=function(e){for(this.parseFactor(e);this.accept(N,vm);){var t=this.current;this.parseFactor(e),e.push(Fe(t.value))}};j.prototype.parseFactor=function(e){var t=this.tokens.unaryOps;function s(o){return o.value in t}if(this.save(),this.accept(N,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===Re&&this.nextToken.value==="("){this.restore(),this.parseExponential(e);return}else if(this.nextToken.type===Pn||this.nextToken.type===Kr||this.nextToken.type===vs||this.nextToken.type===Re&&this.nextToken.value===")"){this.restore(),this.parseAtom(e);return}}var r=this.current;this.parseFactor(e),e.push(jr(r.value))}else this.parseExponential(e)};j.prototype.parseExponential=function(e){for(this.parsePostfixExpression(e);this.accept(N,"^");)this.parseFactor(e),e.push(Fe("^"))};j.prototype.parsePostfixExpression=function(e){for(this.parseFunctionCall(e);this.accept(N,"!");)e.push(jr("!"))};j.prototype.parseFunctionCall=function(e){var t=this.tokens.unaryOps;function s(n){return n.value in t}if(this.accept(N,s)){var r=this.current;this.parseAtom(e),e.push(jr(r.value))}else for(this.parseMemberExpression(e);this.accept(Re,"(");)if(this.accept(Re,")"))e.push(new R(Et,0));else{var o=this.parseArgumentList(e);e.push(new R(Et,o))}};j.prototype.parseArgumentList=function(e){for(var t=0;!this.accept(Re,")");)for(this.parseExpression(e),++t;this.accept(Kr);)this.parseExpression(e),++t;return t};j.prototype.parseMemberExpression=function(e){for(this.parseAtom(e);this.accept(N,".")||this.accept(Tt,"[");){var t=this.current;if(t.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(Rn),e.push(new R(ot,this.current.value))}else if(t.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(e),this.expect(Tt,"]"),e.push(Fe("["))}else throw new Error("unexpected symbol: "+t.value)}};function wm(e,t){return Number(e)+Number(t)}function Em(e,t){return e-t}function Mm(e,t){return e*t}function Tm(e,t){return e/t}function _m(e,t){return e%t}function Om(e,t){return Array.isArray(e)&&Array.isArray(t)?e.concat(t):""+e+t}function Im(e,t){return e===t}function Sm(e,t){return e!==t}function $m(e,t){return e>t}function Cm(e,t){return e<t}function Dm(e,t){return e>=t}function xm(e,t){return e<=t}function Am(e,t){return!!(e&&t)}function Rm(e,t){return!!(e||t)}function Pm(e,t){return gt(t,e)}function km(e){return(Math.exp(e)-Math.exp(-e))/2}function Lm(e){return(Math.exp(e)+Math.exp(-e))/2}function Fm(e){return e===1/0?1:e===-1/0?-1:(Math.exp(e)-Math.exp(-e))/(Math.exp(e)+Math.exp(-e))}function Nm(e){return e===-1/0?e:Math.log(e+Math.sqrt(e*e+1))}function Um(e){return Math.log(e+Math.sqrt(e*e-1))}function jm(e){return Math.log((1+e)/(1-e))/2}function Ai(e){return Math.log(e)*Math.LOG10E}function Bm(e){return-e}function Km(e){return!e}function Hm(e){return e<0?Math.ceil(e):Math.floor(e)}function zm(e){return Math.random()*(e||1)}function Ri(e){return kn(e+1)}function Gm(e){return isFinite(e)&&e===Math.round(e)}var Vm=4.7421875,co=[.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 kn(e){var t,s;if(Gm(e)){if(e<=0)return isFinite(e)?1/0:NaN;if(e>171)return 1/0;for(var r=e-2,o=e-1;r>1;)o*=r,r--;return o===0&&(o=1),o}if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*kn(1-e));if(e>=171.35)return 1/0;if(e>85){var n=e*e,i=n*e,a=i*e,c=a*e;return Math.sqrt(2*Math.PI/e)*Math.pow(e/Math.E,e)*(1+1/(12*e)+1/(288*n)-139/(51840*i)-571/(2488320*a)+163879/(209018880*c)+5246819/(75246796800*c*e))}--e,s=co[0];for(var u=1;u<co.length;++u)s+=co[u]/(e+u);return t=e+Vm+.5,Math.sqrt(2*Math.PI)*Math.pow(t,e+.5)*Math.exp(-t)*s}function Ym(e){return Array.isArray(e)?e.length:String(e).length}function Pi(){for(var e=0,t=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),o;t<r?(o=t/r,e=e*o*o+1,t=r):r>0?(o=r/t,e+=o*o):e+=r}return t===1/0?1/0:t*Math.sqrt(e)}function ki(e,t,s){return e?t:s}function qm(e,t){return typeof t>"u"||+t==0?Math.round(e):(e=+e,t=-+t,isNaN(e)||!(typeof t=="number"&&t%1===0)?NaN:(e=e.toString().split("e"),e=Math.round(+(e[0]+"e"+(e[1]?+e[1]-t:-t))),e=e.toString().split("e"),+(e[0]+"e"+(e[1]?+e[1]+t:t))))}function Wm(e,t,s){return s&&(s[e]=t),t}function Qm(e,t){return e[t|0]}function Zm(e){return arguments.length===1&&Array.isArray(e)?Math.max.apply(Math,e):Math.max.apply(Math,arguments)}function Xm(e){return arguments.length===1&&Array.isArray(e)?Math.min.apply(Math,e):Math.min.apply(Math,arguments)}function Jm(e,t){if(typeof e!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(t))throw new Error("Second argument to map is not an array");return t.map(function(s,r){return e(s,r)})}function ey(e,t,s){if(typeof e!="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,o,n){return e(r,o,n)},t)}function ty(e,t){if(typeof e!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(t))throw new Error("Second argument to filter is not an array");return t.filter(function(s,r){return e(s,r)})}function sy(e,t){if(!(Array.isArray(t)||typeof t=="string"))throw new Error("Second argument to indexOf is not a string or array");return t.indexOf(e)}function ry(e,t){if(!Array.isArray(t))throw new Error("Second argument to join is not an array");return t.join(e)}function oy(e){return(e>0)-(e<0)||+e}var Li=1/3;function ny(e){return e<0?-Math.pow(-e,Li):Math.pow(e,Li)}function iy(e){return Math.exp(e)-1}function ay(e){return Math.log(1+e)}function cy(e){return Math.log(e)/Math.LN2}function nt(e){this.options=e||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||km,cosh:Math.cosh||Lm,tanh:Math.tanh||Fm,asinh:Math.asinh||Nm,acosh:Math.acosh||Um,atanh:Math.atanh||jm,sqrt:Math.sqrt,cbrt:Math.cbrt||ny,log:Math.log,log2:Math.log2||cy,ln:Math.log,lg:Math.log10||Ai,log10:Math.log10||Ai,expm1:Math.expm1||iy,log1p:Math.log1p||ay,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||Hm,"-":Bm,"+":Number,exp:Math.exp,not:Km,length:Ym,"!":Ri,sign:Math.sign||oy},this.binaryOps={"+":wm,"-":Em,"*":Mm,"/":Tm,"%":_m,"^":Math.pow,"||":Om,"==":Im,"!=":Sm,">":$m,"<":Cm,">=":Dm,"<=":xm,and:Am,or:Rm,in:Pm,"=":Wm,"[":Qm},this.ternaryOps={"?":ki},this.functions={random:zm,fac:Ri,min:Xm,max:Zm,hypot:Math.hypot||Pi,pyt:Math.hypot||Pi,pow:Math.pow,atan2:Math.atan2,if:ki,gamma:kn,roundTo:qm,map:Jm,fold:ey,filter:ty,indexOf:sy,join:ry},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}nt.prototype.parse=function(e){var t=[],s=new j(this,new G(this,e),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(t),s.expect(vs,"EOF"),new ve(t,this)};nt.prototype.evaluate=function(e,t){return this.parse(e).evaluate(t)};var Gl=new nt;nt.parse=function(e){return Gl.parse(e)};nt.evaluate=function(e,t){return Gl.parse(e).evaluate(t)};var Fi={"+":"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 ly(e){return Fi.hasOwnProperty(e)?Fi[e]:e}nt.prototype.isOperatorEnabled=function(e){var t=ly(e),s=this.options.operators||{};return!(t in s)||!!s[t]};var uy=Object.defineProperty,dy=Object.getOwnPropertyDescriptor,hy=(e,t,s)=>t in e?uy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,fy=(e,t,s,r)=>{for(var o=r>1?void 0:r?dy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o},py=(e,t,s)=>(hy(e,t+"",s),s);const gy="kos-expression-evaluator-model";class my{constructor(t,s,r,o){l(this,"name");l(this,"expression");l(this,"expr");l(this,"getContextData",null);l(this,"_lastResult",{value:void 0});this.name=t,this.expression=s,this.expr=r,this.getContextData=o,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(t){this._lastResult=t}evaluate(t){try{return{value:this.expr.evaluate(t),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let ir=class{constructor(e,t,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=e,this.logger=s.logger,this._data=Te(),this._results=Te(),this.parser=new nt}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(e){this._data.setValues(e),X(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(e,t){this._data[e]=t}updateNestedValue(e,t){const s=e.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${e}" - cannot be empty`);return}let o=this._data;for(const n of s)(o[n]===void 0||o[n]===null)&&(o[n]={}),o=o[n];o[r]=t,this.logger.debug(`Updated nested context value "${e}" to:`,t)}addModelToContext(e,t){this._data[e]=t}addExpression(e,t){try{const s=this.parser.parse(t),r=new my(e,t,s,()=>this.data);this._expressions.set(e,r),this.evaluateExpression(e),this.logger.debug(`Added expression "${e}": ${t}`)}catch(s){throw this.logger.error(`Failed to parse expression "${e}"`,s),s}}removeExpression(e){const t=this._expressions.delete(e);return t?(delete this._results[e],this.logger.debug(`Removed expression "${e}"`)):this.logger.warn(`Attempted to remove non-existent expression "${e}". Available expressions: [${this.expressionNames.join(", ")}]`),t}getExpression(e){const t=this._expressions.get(e);return t||this.logger.warn(`Expression "${e}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),t}getExpressionValue(e){const t=this._expressions.get(e);if(!t){this.logger.warn(`Expression "${e}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return t.result}getCachedExpressionValue(e){const t=this._expressions.get(e);if(t)return t.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(t=>{this._expressions.get(t)&&this.evaluateExpression(t)})}evaluateExpression(e){this.logger.debug(`Evaluating expression: ${String(e)}`);const t=this._expressions.get(e);if(!t){this.logger.warn(`Expression "${String(e)}" not found`);return}const s=t.evaluate(this.data);this.logger.debug(`Expression "${String(e)}" evaluated to:`,s);const r=t.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(e)}" result changed from`,r,"to",s),t.updateResult(s),this.updateResult(e,s))}updateResult(e,t){this.logger.debug(`ExpressionEvaluator.updateResult called for "${e}":`,t),X(()=>{this._results[e]=t})}createExpression(e){const t=tt();return this.addExpression(t,e),t}};py(ir,"Registration");ir=fy([A({modelTypeId:gy,singleton:!1})],ir);const Vl=ir.Registration,Ne=un(),yy=Object.freeze(Object.defineProperty({__proto__:null,default:Ne},Symbol.toStringTag,{value:"Module"})),by=m.createLogger({name:"kos-log-manager-service",group:"Services"}),vy="/api/kos/logs/overrides",Yl=async()=>(by.debug("sending GET for kos-log-manager"),await Ne.get(vy)),wy=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:Yl},Symbol.toStringTag,{value:"Module"}));var Ey=Object.defineProperty,My=Object.getOwnPropertyDescriptor,Hr=(e,t,s,r)=>{for(var o=r>1?void 0:r?My(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ey(t,s,o),o};const ql="kos-log-manager-model",Ty="/kos/logs/override/add/*",_y="/kos/logs/override/remove/*",Oy=e=>{if(typeof e=="string")return e;if(typeof e=="number")switch(e){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 _t=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=e,this.logger=s.logger,this._overrides=new hn}updateModel(e){}resolveLoggers(){const e=m.getLoggers(),s=Object.entries(e).map(([r,o])=>({name:r,level:Oy(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(e,t){const s=Object.values(this.resolveLoggers());return t==null||t.send(s),s}setLogLevels(e){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(e.name)).forEach(r=>{const o=m.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(e.level)});const s=m.getLoggers()[e.name];if(!s){this.logger.debug(`Logger ${e.name} not found`);return}s.setLevel(e.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(e){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(e.name)).forEach(r=>{const o=m.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=m.getLoggers()[e.name];s||this.logger.debug(`Logger ${e.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(e,t){var s;this.logger.debug(`Override received for node type ${((s=t.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...e,id:e.name}),this.setLogLevels(e)}handleOverrideRemoved(e){this._overrides.removeModel(e.name),this.resetLogLevels(e)}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[e,t]=await Yl();if(e){this.logger.error("Failed to load log overrides",e);return}const s=(t==null?void 0:t.filter(r=>{var o;return((o=r.type)==null?void 0:o.toUpperCase())==="UI"}).map(r=>({name:r.name??"",type:r.type??"",level:r.level??"info",id:r.name||""})))??[];this._overrides.addAll(s),s.forEach(r=>{this.setLogLevels(r)})}};Hr([sc("/api/kos/ui/loggers")],_t.prototype,"getAllLoggers",1);Hr([U({topic:Ty,websocket:!0,wildcardName:"nodeType"})],_t.prototype,"handleOverrideAdded",1);Hr([U({topic:_y,websocket:!0,wildcardName:"nodeType"})],_t.prototype,"handleOverrideRemoved",1);_t=Hr([A(ql)],_t);const Wl=new Me({class:_t,type:ql}),{URL:As}=ae(),{postModel:Ln,getOne:Iy}=oe.build({basePath:`${As}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const Ql=async e=>{const t=await Ln({model:e,urlOverride:`${As}/api/kos/time/time`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Zl=async e=>{const t=await Ln({model:e,urlOverride:`${As}/api/kos/time/date`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set time");return t.data},Xl=async e=>{const t=await Ln({model:{},urlOverride:`${As}/api/kos/time/timezone?tz=${e}`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data},Jl=async()=>{const e=await Iy({urlOverride:`${As}/api/kos/time/timezone`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data.timeZone},Sy=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Jl,setDate:Zl,setTime:Ql,setTimezone:Xl},Symbol.toStringTag,{value:"Module"}));var $y=Object.defineProperty,Cy=Object.getOwnPropertyDescriptor,zr=(e,t,s,r)=>{for(var o=r>1?void 0:r?Cy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&$y(t,s,o),o};const Yt="kos-time-model",Dy="/kos/time/time",xy="/kos/time/day",Ay="/kos/time/timezone";let Ot=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=e,this.logger=s.logger,this.timezone=""}async updateSystemTime(e){await Ql(e)}async updateSystemDate(e){await Zl(e)}async updateSystemTimezone(e){await Xl(e)}handleTimeChange(){z(ds.TIME_CHANGE,{})}handleDayChange(){z(ds.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),z(ds.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const e=await Jl();this.setTimezone(e)}setTimezone(e){this.timezone=e}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};zr([U({topic:Dy,websocket:!0})],Ot.prototype,"handleTimeChange",1);zr([U({topic:xy,websocket:!0})],Ot.prototype,"handleDayChange",1);zr([U({topic:Ay,websocket:!0})],Ot.prototype,"handleTimeZoneChange",1);Ot=zr([A(Yt)],Ot);const ar={registration:{[Yt]:{class:Ot,singleton:!0}},type:Yt,predicate:Ee(Yt),factory:ie.Singleton.create(Yt)};var Ry=Object.defineProperty,Py=Object.getOwnPropertyDescriptor,eu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Py(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ry(t,s,o),o};const tu="log-block-container-model";let cr=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e,sortKey:"blockNum"})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};eu([Ie],cr.prototype,"_models",2);cr=eu([A(tu)],cr);const ky=m.createLogger({name:"log-stream-container-service",group:"Services"}),su=()=>{var r;const e=ge(),s=(e==null?void 0:e.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},jt=su(),Ly="/api/kos/logs/node/{nodeId}/streams",ru=async()=>(ky.debug("sending GET for log-stream-container"),await Ne.get(Ly,{path:{nodeId:"primary"}},{destinationAddress:jt})),ou=async(e,t="primary")=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:t,stream:e}},void 0,{destinationAddress:jt})},nu=async e=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:e}},void 0,{destinationAddress:jt})},Fy=async()=>{await Ne.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:jt})},iu=async e=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:e}},{destinationAddress:jt}),au=async(e,t)=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:e,blockId:t}},{destinationAddress:jt}),Ny=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Fy,getKosConnectionId:su,getLogStreamBlock:au,getLogStreamBlocks:iu,getLogStreams:ru,subscribeToLogStream:ou,unsubscribeFromLogStream:nu},Symbol.toStringTag,{value:"Module"}));var Uy=Object.getOwnPropertyDescriptor,jy=(e,t,s,r)=>{for(var o=r>1?void 0:r?Uy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const cu="log-block-model";let Io=class{constructor(e,t,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=e,this.logger=s.logger,this.nodeId=t.nodeId,this.stream=t.stream,this.blockNum=t.blockNum,this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount,this.lines=[],this.inc=0}async syncLines(){const[e,t]=await au(this.stream,this.blockNum);if(e){this.logger.error(`Failed to get log block ${this.blockNum}`);return}t&&this.addLines(t.lines,!0)}updateModel(e){this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount}addLines(e,t){const s=t?[]:this.lines;this.lines=[...s,...e],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};Io=jy([A(cu)],Io);const ws=new me({class:Io,type:cu}),Gr=new me({class:cr,type:tu});Gr.addRelatedModel(ws);var By=Object.defineProperty,Ky=Object.getOwnPropertyDescriptor,lu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Ky(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&By(t,s,o),o};const uu="log-stream-model";let lr=class{constructor(e,t,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=e,this.logger=s.logger,this.currentBlockId="",this.name=t.name,this.nodeId=t.nodeId,this.isResetting=!0,this._blocks=Gr.instance(`${e}-blocks`).options({}).build()}get firstLineNum(){const e=this.populated[0];return e?e.startLineNum:0}get currentBlock(){const e=this.currentBlockId;return this._blocks.getModel(e)}get populated(){return this._blocks.data.filter(e=>e.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((e,t)=>e+t.lineCount,0)}accept(e){e.visit(this)}updateBlock(e){var r;let t=this._blocks.models.getModel(`${e.stream}-block-${e.blockNum}`);const s={nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)};t||(t=ws.instance(`${e.stream}-block-${e.blockNum}`).options(s).build(),this._blocks.addModel(t)),t&&t.updateModel(s),(!this.currentBlock||e.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}addBlock(e){var s;const t=ws.instance(`${e.stream}-block-${e.blockNum}`).options({nodeId:e.nodeId,blockNum:e.blockNum,endLineNum:e.endLineNum,lineCount:e.lineCount,startLineNum:e.startLineNum,stream:this.name,endTime:new Date(e.endTime),startTime:new Date(e.startTime)}).build();this._blocks.addModel(t),(!this.currentBlock||e.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${e.stream}-block-${e.blockNum}`)}removeBlock(e){this._blocks.models.removeModel(`${this.name}-block-${e}`)}async subscribe(){await ou(this.name)}async unsubscribe(){await nu(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const t of this._blocks.models.data)t.lines=[];const e=this._blocks.data[this._blocks.data.length-1];e&&await e.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[e,t]=await iu(this.name);if(e){this.logger.error(`Error loading log stream: ${e}`);return}if(t)for(const r of t)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 e;this.shouldStop=!0,(e=this.generatorInstance)==null||e.next(),console.log("Requested generator stop.")}async*streamLogs(){const e=[];let t=null,s=0,r=this.currentBlockId;const o=cl(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(r!==(n==null?void 0:n.blockId))r=n==null?void 0:n.blockId,s=0,e.push(...i.lines);else{const a=i.lines.slice(s);e.push(...a),s+=a.length}t&&(t(),t=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(e.length===0&&await new Promise(n=>t=n);e.length>0;)yield e.shift()}finally{o()}}};lu([Ie],lr.prototype,"_blocks",2);lr=lu([A(uu)],lr);const hs=new me({class:lr,type:uu});var Hy=Object.defineProperty,zy=Object.getOwnPropertyDescriptor,it=(e,t,s,r)=>{for(var o=r>1?void 0:r?zy(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Hy(t,s,o),o};const du="log-stream-container-model",Gy="/kos/logs/subscription/addBlock/*",Vy="/kos/logs/subscription/updateBlock/*",Yy="/kos/logs/subscription/removeBlock/*",qy="/kos/logs/subscription/lines/*",hu="/kos/logs/streams/add/*";let Pe=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e}),this.selectedStream=void 0}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}updateModel(e){}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}updateSelectedStream(e){this.selectedStream=e}handleStreamAdded(e){this.logger.debug(`Received topic: ${hu}`);const t=e.stream,s=hs.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.addBlock(e)}handleRemoveBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.removeBlock(e.blockNum)}handleUpdateBlock(e,t){this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&r.updateBlock(e)}handleLogLine(e,t){var o;this.logger.debug(`Received topic: ${t.headers.topic}`);const s=e.stream,r=this.models.getModel(s);r&&((o=r.currentBlock)==null||o.addLines(e.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(e){const t=hs.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(t),await t.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[e,t]=await ru();if(e){this.logger.error(`Error loading log-streams: ${e}`);return}t&&t.forEach(s=>{const r=hs.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};it([Ie],Pe.prototype,"_models",2);it([U({topic:[hu],websocket:!0})],Pe.prototype,"handleStreamAdded",1);it([U({topic:[Gy],websocket:!0})],Pe.prototype,"handleAddBlock",1);it([U({topic:[Yy],websocket:!0})],Pe.prototype,"handleRemoveBlock",1);it([U({topic:[Vy],websocket:!0})],Pe.prototype,"handleUpdateBlock",1);it([U({topic:[qy],websocket:!0})],Pe.prototype,"handleLogLine",1);Pe=it([A(du)],Pe);const Rs=new Me({class:Pe,type:du});Rs.addRelatedModel(hs);Rs.addRelatedModel(Gr);Rs.addRelatedModel(ws);const Wy=e=>e.rank!==void 0,Qy=e=>e.visibleRole!==void 0,Zy=e=>e.color!==void 0,Xy=e=>{const t=e.info;return Wy(t)?t.rank:0},Jy=e=>{const t=e.info;return Zy(t)?t.color:"orange"},eb=e=>{const t=e.info;return Qy(t)?t.visibleRole:"TECHNICIAN"},{URL:Vr}=ae(),{getAll:tb,postModel:fu}=oe.build({basePath:`${Vr}/api/kos/troubles`}),pu=async e=>await tb({urlOverride:`${Vr}${e}`}),gu=async(e,t="/api/kos/troubles",s)=>{try{const r=await fu({model:{},urlOverride:`${Vr}${t}/resolve/${e}`,tracker:s});return r!=null&&r.data&&Je.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve trouble"};return Je.initiateFuture(o),o}},sb=async(e,t="/api/kos/troubles",s)=>{try{const r=await fu({model:e,urlOverride:`${Vr}${t}/resolve/`,tracker:s});return r!=null&&r.data&&Je.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ke.Fail,tracker:s,reason:"Failed to resolve troubles"};return Je.initiateFuture(o),o}},rb=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:sb,getTroubles:pu,resolveTrouble:gu},Symbol.toStringTag,{value:"Module"})),ur="troubleDataMapper",Ks=new Map;$s(ur,{register:(e,t)=>{var s;Ks.has(e)||Ks.set(e,[]),(s=Ks.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Ks.get(e);if(!s)return{...t.data};const r=s.map(i=>i(t));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:m.info(`Trouble mapper ${e} failed: ${a.reason}`),i),{...t.data})}});const Ps="troubleMapper",Hs=new Map;$s(Ps,{register:(e,t)=>{var s;Hs.has(e)||Hs.set(e,[]),(s=Hs.get(e))==null||s.push(t)},execute:async(e,t)=>{const s=Hs.get(e);if(!s)return[];const r=s.map(i=>i(t)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${e} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});S[Ps].register("nozzle",async e=>[e.data.nozzlePath]);S[Ps].register("path",async e=>[e.data.path]);const ob=async e=>{const t=new Set,s=e.ifaces,r=s==null?void 0:s.map(n=>S[Ps].execute(n,e));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>t.add(i))}),Array.from(t)},mu=async e=>{const t=e.ifaces,s=t==null?void 0:t.map(i=>S[ur].execute(i,e)),r=S[ur].execute(e.type,e);s.push(r);const n=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...e.data,...n}};class nb{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class ib{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class dt{static getHandler(t){switch(t){case"ResolvableTrouble":return new nb;case"BlockPumpTrouble":return new ib;default:return}}}var ab=Object.defineProperty,cb=Object.getOwnPropertyDescriptor,yu=(e,t,s,r)=>{for(var o=r>1?void 0:r?cb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&ab(t,s,o),o};const qt="trouble-model";function zs(e){return typeof e.shouldDefer=="boolean"}let dr=class{constructor(e,{resolvable:t,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:u,createTime:d,role:h,color:f,servicePath:p,...b},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=e,this.logger=w.logger,this.type=c,this._troubleId=o,this._resolvable=!!t,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=n,this.data={},Object.assign(this.data,b),this.futureHandler=new Pr(this)}getTitleWithContext(e){var s,r;const t=e?(r=(s=dt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[e]:dt.getHandler(this.type);return(t==null?void 0:t.title)||"Trouble"}getSubtitleWithContext(e){var s,r;const t=e?(r=(s=dt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[e]:dt.getHandler(this.type);return(t==null?void 0:t.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var e;return((e=dt.getHandler(this.type))==null?void 0:e.title)||"Trouble"}get subtitle(){var e;return((e=dt.getHandler(this.type))==null?void 0:e.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await mu(this)}get deferredCompanion(){const e=bo(this.id,t=>zs(t));if(e&&zs(e.modelData))return e.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const e=bo(this.id,t=>zs(t));return e&&zs(e.modelData)?e.modelData.shouldDefer:!1}clearDefer(){var e;(e=this.deferredCompanion)==null||e.clearDefer()}defer(){var e;(e=this.deferredCompanion)==null||e.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(e){var t;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){(t=this.deferredCompanion)==null||t.defer();return}return await gu(this._troubleId,this.servicePath,e)}};yu([ei()],dr.prototype,"resolve",1);dr=yu([A(qt)],dr);const Es={registration:{[qt]:{class:dr,singleton:!1}},type:qt,predicate:Ee(qt),factory:ie.Factory.create(qt)};var bu=Object.defineProperty,lb=Object.getOwnPropertyDescriptor,ub=(e,t,s)=>t in e?bu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Fn=(e,t,s,r)=>{for(var o=r>1?void 0:r?lb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&bu(t,s,o),o},db=(e,t,s)=>(ub(e,t+"",s),s);function Ni(e){return S.propertyMapper.hasMapper(be.TroubleRank)?S.propertyMapper.executeMapper(be.TroubleRank,e):Xy(e)}function Ui(e){return(S.propertyMapper.hasMapper(be.TroubleColor)?S.propertyMapper.executeMapper(be.TroubleColor,e):Jy(e)).toLowerCase()}function ji(e){return(S.propertyMapper.hasMapper(be.TroubleRole)?S.propertyMapper.executeMapper(be.TroubleRole,e):eb(e)).toLowerCase()}const hb="trouble-container-model";class fe{}l(fe,"INDEX_TROUBLES_BY_IFACE","byIface"),l(fe,"INDEX_TROUBLES_BY_TYPE","byType"),l(fe,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(fe,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(fe,"SORT_KEY_RANK","rank"),l(fe,"TROUBLES_DEFERRED","true");let It=class{constructor(e,t){l(this,"id");l(this,"servicePath","/api/kos/troubles");this.id=e,this.servicePath=t.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");const e=await pu(this.servicePath);try{e==null||e.data.forEach(t=>{const s={...t,servicePath:this.servicePath,rank:Ni(t),color:Ui(t),role:ji(t),id:String(t.id)},r=Es.factory(`trouble-${t.id}`)(s);this.troubles.addModel(r)})}catch(t){throw this.logger.error(t),t}}handleTroubleRemoved(e){const t=`trouble-${e}`,s=this.troubles.getModel(t);this.troubles.removeModel(t),s&&Xe(s)}handleTroubleAdded(e){const t={...e,servicePath:this.servicePath,rank:Ni(e),color:Ui(e),role:ji(e),id:String(e.id)};if(t.role==="NONE")return;const s=Es.factory(`trouble-${e.id}`)(t);this.troubles.addModel(s)}};db(It,"Registration");Fn([U({topic:"/kos/trouble/remove",websocket:!0,lifecycle:H.INIT})],It.prototype,"handleTroubleRemoved",1);Fn([U({topic:"/kos/trouble/add",websocket:!0})],It.prototype,"handleTroubleAdded",1);It=Fn([A({modelTypeId:hb,singleton:!0}),ic(),tc({containerProperty:"troubles",containerOptions:{indexMap:{[fe.INDEX_TROUBLES_BY_IFACE]:ob,[fe.INDEX_TROUBLES_BY_TYPE]:"type",[fe.INDEX_TROUBLES_BY_GROUP]:"group",[fe.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:fe.SORT_KEY_RANK}})],It);const St=It.Registration,{URL:vu}=ae(),{getAll:fb}=oe.build({basePath:`${vu}/api/kos/ota`}),Bi=m.createLogger({name:"ota-service",group:"Services"}),pb=async()=>{Bi.debug("sending GET request to /api/kos/ota/artifacts");const e=await fb({urlOverride:`${vu}/api/kos/ota/artifacts`});return Bi.debug("getArtifacts - response:",e),e==null?void 0:e.data};var gb=Object.defineProperty,mb=Object.getOwnPropertyDescriptor,Yr=(e,t,s,r)=>{for(var o=r>1?void 0:r?mb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&gb(t,s,o),o};const wu="ota-model",yb=e=>{let t=null;for(const s in e){const r=e[s],o=r.lastUpdateTime;(!t||t.lastUpdateTime<o)&&(t=r)}return t},lo=e=>{const t=e.artifactInfo,s=yb(e.requests),r=(t==null?void 0:t.identifier)||(s==null?void 0:s.kabId);if(!r)return;let o;switch(e.status){case"INSTALLED":o="ready";break;case"INVALID":o="error";break;case"MISSING":o=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":o="pending"}const n=t===void 0;return{id:r,manifest:n,label:t==null?void 0:t.version,name:t==null?void 0:t.name,status:o,error:o==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:o==="error"?s==null?void 0:s.errorCount:0,progress:o==="downloading"&&s&&!n?s.currentSize/(t==null?void 0:t.size)*100:void 0,size:t==null?void 0:t.size}};let $t=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"data",new hn);l(this,"troubleContainer");this.id=e,this.logger=s.logger}get downloadInProgressTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:t[0]}get updatePendingTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:t[0]}get pausedDueToErrorsTrouble(){var t;return(t=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:t[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var e;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(e=this.updatePendingTrouble)==null||e.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const e=await pb();e&&e.forEach(t=>{const s=lo(t);s&&this.data.addModel(s)})}catch(e){this.logger.error(`loading ota ${this.id} - error:`,e)}}async handleAllArtifacts(e){this.logger.debug("handleAllArtifacts:",e),await this.data.clear();try{e.forEach(t=>{const s=lo(t);s&&this.data.addModel(s)})}catch(t){this.logger.error(`handleAllArtifacts ${this.id} - error:`,t)}}handleChangedArtifacts(e){this.logger.debug("handleChangedArtifacts:",e);try{e.forEach(t=>{const s=lo(t);s&&this.data.updateModel(s)})}catch(t){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,t)}}};Yr([Rt({modelType:St.type})],$t.prototype,"troubleContainer",2);Yr([U({topic:"/kos/ota/artifacts/all",websocket:!0})],$t.prototype,"handleAllArtifacts",1);Yr([U({topic:"/kos/ota/artifacts/changed",websocket:!0})],$t.prototype,"handleChangedArtifacts",1);$t=Yr([A(wu)],$t);const hr=new Me({class:$t,type:wu});function bb(e){let t;const s=async(...r)=>{t&&t.abort(),t=new AbortController;const o=t;try{return await e(...r,o.signal)}finally{t===o&&(t=void 0)}};return s.cancel=()=>{t&&(t.abort(),t=void 0)},s.getController=()=>t,s.isActive=()=>!!t,s}const uo=m.createLogger({name:"software-info-service",group:"Services"}),Nn=async e=>{uo.debug("sending GET for software-info");const[t,s]=await Dl.get("/api/kos/manifest/info",void 0,{signal:e});if(!s)throw e!=null&&e.aborted?(uo.debug("Request was aborted"),new pe("Request was aborted")):(uo.error("Failed to fetch software-info",t),new pe("Failed to fetch software-info"));return s},vb=bb(Nn),wb=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Nn,getSoftwareInfosWithCancel:vb},Symbol.toStringTag,{value:"Module"}));var Eb=Object.getOwnPropertyDescriptor,Mb=(e,t,s,r)=>{for(var o=r>1?void 0:r?Eb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Wt="software-info-model";let So=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=e,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(e,t){return e.reduce((s,r)=>(s[r[t]]=[...s[r[t]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const e=await Nn(),t=(e==null?void 0:e.nodes)||{};X(()=>{const r=Object.keys(t).map(o=>t[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(e){e instanceof pe&&this.logger.error("Failed to fetch software-info",e)}}};So=Mb([A(Wt)],So);const fr={registration:{[Wt]:{class:So,singleton:!1}},type:Wt,predicate:Ee(Wt),factory:ie.Factory.create(Wt)},{URL:Eu}=ae(),{getOne:Tb}=oe.build({basePath:`${Eu}/api/kos/state`}),_b=m.createLogger({name:"state-bean-service",group:"Services"}),Mu=async({path:e})=>(_b.debug("sending GET for state-bean"),await Tb({urlOverride:`${Eu}/api/kos/state/${e}`})),Ob=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Mu},Symbol.toStringTag,{value:"Module"}));var Ib=Object.defineProperty,Sb=Object.getOwnPropertyDescriptor,Tu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Sb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ib(t,s,o),o};const Qt="state-bean-model",$b=st("path");let pr=class{constructor(e,t,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=e,this.logger=s.logger,this.props=pn.map(new Map),yo(t,this)}updateModel(e){yo(e,this)}handleConfigBeanUpdated(e){Object.entries(e).forEach(([t,s])=>{let r=s;typeof r=="string"&&yn(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&kr(r)&&(r=Number(r)),this.props.set(t,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(e){Object.entries(e).forEach(([t,s])=>{this.props.set(t,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const e=await Mu({path:this.path});e!=null&&e.data&&this.updateProps(e.data)}};Tu([U({topic:`/kos/state/${$b}`,websocket:!0})],pr.prototype,"handleConfigBeanUpdated",1);pr=Tu([A(Qt)],pr);const Ms={registration:{[Qt]:{class:pr,singleton:!1}},type:Qt,predicate:Ee(Qt),factory:ie.Factory.create(Qt)};var Cb=Object.defineProperty,Db=Object.getOwnPropertyDescriptor,_u=(e,t,s,r)=>{for(var o=r>1?void 0:r?Db(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Cb(t,s,o),o};const Zt="state-prop-model",Ki=st("path");let gr=class{constructor(e,t,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=e,this.logger=s.logger,this.path=t.path,this.attribute=t.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 e;return((e=this.value)==null?void 0:e.toString())??""}};_u([Rt({modelType:Ms.type,id:`state-bean-${Ki}`,options:{path:Ki}})],gr.prototype,"stateBean",2);gr=_u([A(Zt)],gr);const Un={registration:{[Zt]:{class:gr,singleton:!1}},type:Zt,predicate:Ee(Zt),factory:ie.Factory.create(Zt)},{URL:xb}=ae(),{getAll:Ab}=oe.build({basePath:`${xb}/api/state-prop`}),Rb=m.createLogger({name:"state-prop-service",group:"Services"}),Pb=async()=>(Rb.debug("sending GET for state-prop"),await Ab({})),kb=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Pb},Symbol.toStringTag,{value:"Module"})),{URL:jn}=ae(),{getOne:Ou}=oe.build({basePath:`${jn}/api/translation`}),fs=m.createLogger({name:"translation-service",group:"Services"}),Lb=()=>{const e=window.location.origin,t=ge();return(t==null?void 0:t.host)||e},Iu=async(e,t)=>{fs.debug(`Loading translations from: ${e}`);const s=t??Lb();try{const r=await fetch(`${s}${e}`);return r.status!==200?(fs.warn(`Failed to fetch translations at ${e}: ${r.status}`),{}):await r.json()}catch(r){throw fs.error("Error fetching translations",r),r}},Fb=async()=>{fs.debug("Getting system localization descriptor");const e=await Ou({urlOverride:`${jn}/api/system/kos/localization`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get localization descriptor ${e==null?void 0:e.status}`);return e.data},Su=e=>async()=>{fs.debug(`Getting KOS localization descriptor for context: ${e}`);const t=await Ou({urlOverride:`${jn}/api/kos/localization/contexts`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${t==null?void 0:t.status}`);return t.data[e]},$u="langResolver";var Nb=Object.getOwnPropertyDescriptor,Ub=(e,t,s,r)=>{for(var o=r>1?void 0:r?Nb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Xt="translation-model";function jb(e){const t=typeof e=="string",s=t?!1:!!(e!=null&&e.data)&&typeof(e==null?void 0:e.data)!="string",r=t?e:e==null?void 0:e.defaultValue,o=t||e==null?void 0:e.context,n=t?void 0:s?e==null?void 0:e.data:e;return{isBasicOptions:t,defaultValue:r,context:o,data:n}}function Cu(e,t=""){return Object.keys(e).reduce((s,r)=>{const o=t?`${t}.${r}`:r;if(typeof e[r]=="object"&&e[r]!==null){const n=Cu(e[r],o);return{...s,...n}}else return{...s,[o]:e[r]}},{})}function Du(e,t){const s={...e};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(typeof t[r]=="object"&&t[r]!==null&&typeof e[r]=="object"&&e[r]!==null?s[r]=Du(e[r],t[r]):s[r]=t[r]);return s}const $o=(e,t)=>{const s=/__(.*?)__/g,r=e.replace(s,(o,n)=>Object.prototype.hasOwnProperty.call(t||{},n.trim())?t==null?void 0:t[n.trim()]:o);return r===e?r:s.test(r)?$o(r,t):r},Gs=(e,t,s)=>{const r=/{{(.*?)}}/g,n=$o(e,t).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return $o(n,t)},Hi=(e,t)=>{if(t.includes(":")){const[s,r]=t.split(":");return{namespace:s,key:r}}else return{namespace:e,key:t}};let Co=class{constructor(e,t,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=e,this.defaultLocale=t.defaultLocale||"en",this.currentLocale=t.currentLocale||"en",this.namespace=t.namespace,this.descriptor=t.descriptor,this.rootUrl=t.rootUrl,this.data={},this.resolver=t.resolver||s.kosContext.get($u),this.bundleResolver=t.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(e){const t=this.descriptor[e];if(!e||!t)return[this.defaultLocale];if(!this.defaultLocale&&!t.fallbacks)return[e];let s=t.fallbacks||[this.defaultLocale];return s.includes(e)||(s=[e,...s]),s}async loadTranslations(){const e=this.getTranslationLocales(this.currentLocale).reverse(),t=e.map(r=>{if(this.bundleResolver){const o=V.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return Iu(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(t);X(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${e[i]}`,n.value),n.value&&(o=Du(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${e[i]}`),o),{});this.data=Cu(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(e){const{namespace:t,key:s}=Hi(this.namespace,e);if(t!==this.namespace){const r=this.context.getModel(t);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(e,t){if(!e)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=jb(t),{namespace:n,key:i}=Hi(this.namespace,e),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,t):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>Gs(u,this.data,o)):Gs(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[a];return Array.isArray(c)?c.map(u=>Gs(u,this.data,o)):Gs(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=E.reaction(()=>this.currentLocale,(e,t)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${t} to ${e}`),this.loadTranslations()})}};Co=Ub([Ar(),A(Xt)],Co);const mr={registration:{[Xt]:{class:Co,singleton:!1}},type:Xt,predicate:Ee(Xt),factory:ie.Factory.create(Xt)};var Bb=Object.defineProperty,Kb=Object.getOwnPropertyDescriptor,xu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Kb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Bb(t,s,o),o};const Jt="translation-container-model",Hb=(e,t="/")=>e.join(t).replace(new RegExp(t+"{1,}","g"),t);function zb(e,t){const s=this.descriptor.namespaces[e];if(!s)throw new Error("namespace "+e+" not found in descriptor");const r=s.basePath,o=s.locales[t].file;return Hb([r,o])}let yr=class{constructor(e,t,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=e,this.lang=t.lang||"en",this.descriptor=t.descriptor,this._defaultNamespace=t.defaultNamespace,this.descriptorUrl=t.descriptorUrl,this.rootUrl=t.rootUrl,this.resolver=t.resolver||zb.bind(this),s.kosContext.set($u,this.resolver),this.logger=s.logger,this._models=new Se({parentId:e})}set currentLocale(e){this.lang=e,this.models.data.forEach(t=>{t.currentLocale=e})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(e){return this.logger.debug("getting model "+e),this._models.getModel("translation-"+e)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const e of this.namespaces){const t=this.resolveNamespace(e);await ue(t)}}resolveNamespace(e){var s;if((s=this.descriptor.namespaces)==null?void 0:s[e]){const r=Object.keys(this.descriptor.namespaces[e].locales)[0],o=this.descriptor.namespaces[e].locales[r].defaultLocale,n=mr.factory("translation-"+e)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[e].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(e)||X(()=>{this.namespaces.push(e)}),n}else{this.logger.warn("namespace "+e+" not found in descriptor");const r=mr.factory("translation-"+e)({kosParentId:this.id,namespace:e,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug("initializing translation-container container "+this.id)}async load(){this.logger.debug("loading translation-container container "+this.id)}};xu([Ie],yr.prototype,"_models",2);yr=xu([A(Jt)],yr);const ke={registration:{[Jt]:{class:yr,singleton:!0}},type:Jt,predicate:Ee(Jt),factory:ie.Singleton.create(Jt)},Gb={set(e,t){const s=V.getContext(ke.type);s&&s.set(e,t)},get(e){const t=V.getContext(ke.type);return t==null?void 0:t.get(e)}},Au={async init(e){const t=ke.factory(e);return await ue(t),{translations:t}}};function Vb(e){return(e==null?void 0:e.troubles)!==void 0&&(e==null?void 0:e.troubles)instanceof Array&&(e==null?void 0:e.troublesByType)!==void 0&&typeof(e==null?void 0:e.troublesByType)=="object"}const Ru="kos-ws-event",Bn=Pt(Ru);var Yb=Object.defineProperty,qb=Object.getOwnPropertyDescriptor,Kn=(e,t,s,r)=>{for(var o=r>1?void 0:r?qb(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Yb(t,s,o),o};const Wb=({headers:e,body:t})=>Object.entries(e).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+t;exports.WsEventModel=class{constructor(t){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=t,this.events=E.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(t,s){this.processEvent(s,!0)}handleReceiveEvent(t,s){this.processEvent(s)}processEvent(t,s=!1){m.debug("kos event received");const{body:r,headers:o}=t.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:Wb({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};Kn([U({topic:[Ss.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Kn([U({topic:[Ss.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Kn([A(Bn.type)],exports.WsEventModel);const zi=ge(),Qb=zi.debug==="true"||zi.debug===!0,Zb="/api/system/canvas",Pu=async(e,t)=>{const s=t||Zb,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Qb?"false":"true"},body:e})},Xb=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Pu},Symbol.toStringTag,{value:"Module"}));function Gi(e,t,s){{const r=e.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var Jb=Object.defineProperty,ev=Object.getOwnPropertyDescriptor,ku=(e,t,s,r)=>{for(var o=r>1?void 0:r?ev(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Jb(t,s,o),o};const Lu="canvas-renderer-model";function ho(e){return typeof e.onDone=="function"}let br=class{constructor(e,t,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=e,this.logger=s.logger,this.width=t.width??50,this.height=t.height??30,this.fps=t.fps??10,this.durationMs=t.durationMs??null,this.apiPath=t.apiPath??"/api/system/canvas",this.endpointName=t.endpoint}set onFrame(e){this._onFrame=e}set renderer(e){var t,s;this._renderer&&(this.stopStreaming(),(s=(t=this._renderer).dispose)==null||s.call(t)),this._renderer=e,this.isStreaming&&this.startStreaming()}setClearOnComplete(e){this._clearOnComplete=e}sendDataFrame(e,t){Pu(e,t)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const e=this.isOneShotDone();this.stopStreaming(!e)});return}}handleFrame(e){var s;const t=Gi(e);this.sendDataFrame(t,this.apiPath),(s=this._onFrame)==null||s.call(this,t)}stopStreaming(e=!0){var t,s;this.logger.debug(`stopStreaming called with clearCanvas=${e}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(t=this._renderer)==null?void 0:t.pause)==null||s.call(t),e&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const e=this.width>0?this.width:50,t=this.height>0?this.height:30;if(e>0&&t>0){const r=e*t*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=Gi(o);this.logger.debug(`Sending clear frame: ${e}x${t}, apiPath: ${this.apiPath}`),this.sendDataFrame(n,this.apiPath),(s=this._onFrame)==null||s.call(this,n)}}isOneShotDone(){var e,t;return ho(this._renderer)&&((t=(e=this._renderer).isOneShot)==null?void 0:t.call(e))===!0&&this._renderer.isOneShotDone}startStreaming(){var e,t,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(),(t=(e=this._renderer).play)==null||t.call(e);const o=ho(this._renderer);ho(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),z("/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 n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,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),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(e,t)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),t.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(e,t)=>{this.startStreaming(),t.send({status:"OK"})})}};ku([Rt({modelType:On.type})],br.prototype,"router",2);br=ku([A(Lu)],br);const Hn=new me({class:br,type:Lu});class Fu{constructor({src:t}){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=t,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(t,s){this.canvas.width=t,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,t,s)}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}onDone(t){this.doneCallback=t}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}}class tv{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 t=this.canvas.getContext("webgl");if(!t)throw new Error("WebGL not supported");this.gl=t}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}readPixels(t=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(t*s*4);this.gl.readPixels(0,0,t,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const o=new Uint8ClampedArray(r.length);for(let n=0;n<s;n++){const i=n*t*4,a=(s-1-n)*t*4;o.set(r.subarray(i,i+t*4),a)}return o}}class sv extends tv{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
|
|
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:${t}
|
|
|
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,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class at{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const t=this.canvas.getContext("2d");if(!t)throw new Error("2D canvas not supported");this.ctx=t}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}}function Kn(e){class t extends e{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(o){this.doneCallback=o}signalDoneIfNeeded(){var o;this.oneShotDone||((o=this.doneCallback)==null||o.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return t}const Jb=Kn(at);class ev extends Jb{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();l(this,"offset",0);l(this,"speed");l(this,"colors");l(this,"direction");l(this,"loop");this.colors=s,this.direction=r,this.speed=o,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,r){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const o=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(o,0,n,0),a=1/(this.colors.length-1);this.colors.forEach((c,u)=>{i.addColorStop(u*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const tv=Kn(at);class ku extends tv{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 sv extends Pu{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 rv(e){const t=e.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(t))throw new Error(`Invalid hex color: ${e}`);let s,r,o;return t.length===3?(s=parseInt(t[0]+t[0],16),r=parseInt(t[1]+t[1],16),o=parseInt(t[2]+t[2],16)):(s=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),o=parseInt(t.substring(4,6),16)),{r:s,g:r,b:o}}function Lu(e){return typeof e=="string"?rv(e):e}function br(e){const t=Lu(e);return`rgb(${t.r},${t.g},${t.b})`}class ov extends at{constructor(s={}){super();l(this,"columns",[]);l(this,"fallChance");l(this,"speed");l(this,"baseColor");l(this,"trailColors");this.speed=s.speed??1,this.fallChance=s.fallChance??.7,s.baseColor?this.baseColor=Lu(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let o=0;o<=5;o++){const n=1-o/5*.6;r.push({r:Math.floor(this.baseColor.r*n),g:Math.floor(this.baseColor.g*n),b:Math.floor(this.baseColor.b*n)})}return r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const c=this.columns[a];let u=0,d=0,h=0;if(i===c)u=this.baseColor.r,d=this.baseColor.g,h=this.baseColor.b;else if(i<c&&i>c-this.trailColors.length){const p=c-i;if(p<this.trailColors.length){const b=this.trailColors[p];u=b.r,d=b.g,h=b.b}}const f=(i*s+a)*4;n[f]=u,n[f+1]=d,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(o,0,0)}}class nv{constructor(t,s){l(this,"baseRenderer");l(this,"overlayIcons",new Map);l(this,"overlayConfigs");l(this,"loadedIcons",new Set);l(this,"canvas");l(this,"ctx");l(this,"persistOverlaysOnComplete");l(this,"baseRendererCompleted",!1);l(this,"completionCallback",null);l(this,"hasSignaledCompletion",!1);this.baseRenderer=s(t.baseRenderer.type,t.baseRenderer.data),this.overlayConfigs=t.overlays,this.persistOverlaysOnComplete=t.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const t of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(t.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${t.src}`,r)},s.src=t.src,this.overlayIcons.set(t.src,s)}}calculateOverlayPosition(t,s,r){let o,n;if(typeof t.position=="string")switch(t.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-t.size)/2,n=0;break;case"top-right":o=s-t.size,n=0;break;case"center-left":o=0,n=(r-t.size)/2;break;case"center":o=(s-t.size)/2,n=(r-t.size)/2;break;case"center-right":o=s-t.size,n=(r-t.size)/2;break;case"bottom-left":o=0,n=r-t.size;break;case"bottom-center":o=(s-t.size)/2,n=r-t.size;break;case"bottom-right":o=s-t.size,n=r-t.size;break;default:o=0,n=0}else o=t.position.x,n=t.position.y;return t.offset&&(o+=t.offset.x||0,n+=t.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(t,s){if(this.canvas.width=t,this.canvas.height=s,this.ctx.clearRect(0,0,t,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(t,s);else{this.baseRenderer.renderFrame(t,s);const r=this.baseRenderer.readPixels(t,s);if(r&&r.length>0){const o=new ImageData(r,t,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(t,s)}}renderOverlays(t,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const o=this.overlayIcons.get(r.src);if(!o||!this.loadedIcons.has(r.src))continue;const n=this.calculateOverlayPosition(r,t,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(o,n.x,n.y,r.size,r.size),this.ctx.restore()}}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(t){this.completionCallback=t,this.hasSignaledCompletion&&t()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class Fu extends at{constructor(s){super();l(this,"img");l(this,"loaded",!1);l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"colorOverride");l(this,"originalSvgData",null);l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);this.img=new Image,this.img.crossOrigin="anonymous",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,this.colorOverride=s.colorOverride,this.colorOverride&&s.src.toLowerCase().includes(".svg")?this.loadAndProcessSvg(s.src):this.img.src=s.src,this.img.onload=()=>{this.loaded=!0},this.img.onerror=r=>{console.error("Failed to load image:",r)}}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(!this.loaded||this.completed)return;if(this.isPaused){this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.ctx.drawImage(this.img,0,0,s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":this.position+=d;break;case"right":this.position+=d;break;case"up":this.position+=d;break;case"down":this.position+=d;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(s,r,o,i)}drawScrollingImage(s,r,o,n){var h,f,p,b,w,M,_,F,Q;const i=this.img.width/this.img.height;let a,c;((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((b=this.scrollConfig)==null?void 0:b.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r);let u,d;switch(o==="left"||o==="right"?(u=0,((M=this.scrollConfig)==null?void 0:M.offsetY)==="center"||((_=this.scrollConfig)==null?void 0:_.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((F=this.scrollConfig)==null?void 0:F.offsetX)==="center"||((Q=this.scrollConfig)==null?void 0:Q.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),o){case"left":{const D=s-this.position;if(D<s&&D>-a&&this.ctx.drawImage(this.img,D,d,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>n){const I=D+a+n;I<s&&this.ctx.drawImage(this.img,I,d,a,c)}break}case"right":{const D=-a+this.position;if(D>-a&&D<s&&this.ctx.drawImage(this.img,D,d,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-a>-a){const I=D-a-n;I<s&&this.ctx.drawImage(this.img,I,d,a,c)}break}case"up":{const D=r-this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,u,D,a,c),this.loopConfig&&this.pauseDuration===0&&D+c+n<r){const I=D+c+n;I>-c&&this.ctx.drawImage(this.img,u,I,a,c)}break}case"down":{const D=-c+this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,u,D,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-c>-c){const I=D-c-n;I<r&&this.ctx.drawImage(this.img,u,I,a,c)}break}}}checkScrollCompletion(s,r,o,n){var h,f,p,b,w;if(!this.isPlaying)return;const i=this.img.width/this.img.height;let a,c;switch(((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((b=this.scrollConfig)==null?void 0:b.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r),o){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let u=!1;const d=1;switch(o){case"left":u=s-this.position<-a-d;break;case"right":u=-a+this.position>s+d;break;case"up":u=r-this.position<-c-d;break;case"down":u=-c+this.position>r+d;break}u&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}async loadAndProcessSvg(s){try{const o=await(await fetch(s)).text();this.originalSvgData=o;const n=this.applySvgColorOverride(o),i=`data:image/svg+xml;base64,${btoa(n)}`;this.img.src=i}catch(r){console.error("Failed to load and process SVG:",r),this.img.src=s}}applySvgColorOverride(s){if(!this.colorOverride)return s;const r=br(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 iv extends at{constructor(s){super();l(this,"text");l(this,"lines");l(this,"fontSize");l(this,"fontFamily");l(this,"lineHeight");l(this,"textColor");l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);l(this,"textWidth",0);l(this,"textHeight",0);l(this,"lineWidths",[]);l(this,"textMeasured",!1);this.text=s.text,this.lines=s.text.split(`
|
|
115
|
-
`),this.fontSize=s.fontSize??8,this.lineHeight=s.lineHeight??this.fontSize+2,this.fontFamily=s.fontFamily??"monospace, 'Lucida Console', 'Courier New', Courier",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,s.color?this.textColor=br(s.color):this.textColor="rgb(255,255,255)"}measureText(){if(this.textMeasured)return;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.lineWidths=[];let s=0;for(const r of this.lines){const n=this.ctx.measureText(r).width;this.lineWidths.push(n),s=Math.max(s,n)}this.textWidth=s,this.textHeight=this.lines.length*this.lineHeight,this.textMeasured=!0}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0,this.textMeasured=!1,this.lineWidths=[]}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(this.canvas.width=s,this.canvas.height=r,this.measureText(),this.completed)return;if(this.isPaused){this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.drawStaticText(s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":case"right":case"up":case"down":this.position+=d;break}}this.drawScrollingText(s,r,o,i),this.checkScrollCompletion(s,r,o)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const o=this.textHeight;let n=(r-o)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],c=this.lineWidths[i],u=(s-c)/2,d=n+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,o,n){var c,u,d,h;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";let i,a;o==="left"||o==="right"?(i=0,((c=this.scrollConfig)==null?void 0:c.offsetY)==="center"||((u=this.scrollConfig)==null?void 0:u.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((d=this.scrollConfig)==null?void 0:d.offsetX)==="center"||((h=this.scrollConfig)==null?void 0:h.offsetX)===void 0?(i=s/2,this.ctx.textAlign="center"):(i=this.scrollConfig.offsetX,this.ctx.textAlign="left"),a=0),this.drawMultiLineScrollText(o,s,r,n,i,a)}drawMultiLineScrollText(s,r,o,n,i,a){switch(s){case"left":{const c=r-this.position;if(c<r&&c>-this.textWidth&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&this.position>n){const u=c+this.textWidth+n;u<r&&this.drawTextBlock(u,a,"left")}break}case"right":{const c=-this.textWidth+this.position;if(c>-this.textWidth&&c<r&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textWidth>-this.textWidth){const u=c-this.textWidth-n;u<r&&this.drawTextBlock(u,a,"left")}break}case"up":{const c=o-this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c+this.textHeight+n<o){const u=c+this.textHeight+n;u>-this.textHeight&&this.drawTextBlock(i,u,"center")}break}case"down":{const c=-this.textHeight+this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textHeight>-this.textHeight){const u=c-this.textHeight-n;u<o&&this.drawTextBlock(i,u,"center")}break}}}drawTextBlock(s,r,o){for(let n=0;n<this.lines.length;n++){const i=this.lines[n],a=this.lineWidths[n];let c;o==="center"?c=s-a/2:c=s;const u=r+n*this.lineHeight;this.ctx.fillText(i,c,u)}}checkScrollCompletion(s,r,o){if(!this.isPlaying)return;let n=!1;const i=1;switch(o){case"left":n=s-this.position<-this.textWidth-i;break;case"right":n=-this.textWidth+this.position>s+i;break;case"up":n=r-this.position<-this.textHeight-i;break;case"down":n=-this.textHeight+this.position>r+i;break}n&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}dispose(){this.completionCallback=null}}class av{constructor(t){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=t.patterns,this.loopConfig=t.loop??!1,this.transitionDuration=t.transitionDuration??0,this.patternOverrides=t.patternOverrides??{},this.patternStore=t.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var n,i,a,c;const t=this.patterns[this.currentPatternIndex],s=this.patternStore.get(t);if(!s){console.warn(`Pattern "${t}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[t]??{},o={...s.data,...r};try{this.currentRenderer=vr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(c=(a=this.currentRenderer).play)==null||c.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(u){console.error(`Failed to create renderer for pattern "${t}":`,u),this.moveToNextPattern()}}isDoneAware(t){return typeof(t==null?void 0:t.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var t,s;(s=(t=this.currentRenderer)==null?void 0:t.play)==null||s.call(t)}pause(){var t,s;(s=(t=this.currentRenderer)==null?void 0:t.pause)==null||s.call(t)}renderFrame(t,s){this.width=t,this.height=s,this.canvas.width=t,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(t,s)}readPixels(t,s){return this.currentRenderer?this.currentRenderer.readPixels(t,s):this.ctx.getImageData(0,0,t,s).data}onDone(t){this.completionCallback=t}isOneShot(){var t,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(t=this.currentRenderer).isOneShot)==null?void 0:s.call(t))??!1:!0:!1}dispose(){var t,s;this.currentRenderer&&((s=(t=this.currentRenderer).dispose)==null||s.call(t)),this.completionCallback=null}setPatternStore(t){this.patternStore=t,this.patterns.length>0&&this.loadCurrentPattern()}}const cv=Kn(at);class lv extends cv{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=br(r)}setColor(s){this.color=br(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 uv extends at{constructor({minHue:s=0,maxHue:r=360,speed:o=1}={}){super();l(this,"offset",0);l(this,"minHue");l(this,"maxHue");l(this,"speed");this.minHue=s,this.maxHue=r,this.speed=o}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,r,o){let n,i,a;if(r===0)n=i=a=o;else{const c=(h,f,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?h+(f-h)*6*p:p<.5?f:p<.6666666666666666?h+(f-h)*(.6666666666666666-p)*6:h),u=o<.5?o*(1+r):o+r-o*r,d=2*o-u;n=c(d,u,s+1/3),i=c(d,u,s),a=c(d,u,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let c=0;c<s;c++){const u=(c+this.offset)%s/s,d=this.minHue/360+u*((this.maxHue-this.minHue)/360),[h,f,p]=this.hslToRgb(d,1,.5);n[i++]=h,n[i++]=f,n[i++]=p,n[i++]=255}this.ctx.putImageData(o,0,0)}}const zi=new Map;Ss(te,{register(e,t){zi.set(e,t)},execute(e,t){const s=zi.get(e);return s?new s(t):null}});S.canvas.registerRenderer("video",sv);S.canvas.registerRenderer("video-basic",Pu);S[te].register("image-static",ku);S[te].register("image-scrolling",Fu);const dv=class{constructor(e){var t;return(t=e.scroll)!=null&&t.enabled?new Fu(e):new ku(e)}};S[te].register("image",dv);S[te].register("color",lv);S[te].register("matrix",ov);S[te].register("sweep",uv);S[te].register("gradient",ev);S[te].register("drop",Xb);S[te].register("sequence",av);S[te].register("text",iv);const hv=class{constructor(e){const t=(s,r)=>{const o=vr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new nv(e,t)}};S[te].register("overlay",hv);const vr=({mode:e,data:t})=>{const s=S[te].execute(e,t);if(s)return s;throw new Error(`Unknown mode: ${e}`)};var fv=Object.defineProperty,pv=Object.getOwnPropertyDescriptor,Bt=(e,t,s,r)=>{for(var o=r>1?void 0:r?pv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&fv(t,s,o),o};const Nu="canvas-dispatcher-model";function gv(e){if(e=e.replace(/^#/,""),e.length===3&&(e=e.split("").map(s=>s+s).join("")),e.length!==6)return null;const t=parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}}let ze=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=e,this.logger=s.logger,this._endpointRenderers=new Se}addNamedEndpoint(e,t){this._endpointRenderers.getModel(e)&&this.logger.warn(`Endpoint "${e}" already exists. Overwriting.`);const s=Bn.instance(e).options({apiPath:t.apiPath,width:t.width,height:t.height,fps:t.fps,durationMs:t.durationMs??null,endpoint:e}).build();return this._endpointRenderers.addModel(s),s}addContent(e,t){this._content.has(e)&&this.logger.warn(`Content "${e}" already exists. Overwriting.`),this._content.set(e,t)}addPattern(e,t){this._patterns.has(e)&&this.logger.warn(`Pattern "${e}" already exists. Overwriting.`),this._patterns.set(e,t)}async handlePatternsPost(e,t){var o,n;const s=e.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=t.status)==null||o.call(t,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(n=t.status)==null||n.call(t,200).send({status:"OK"})}async handlePatternApplication(e,t){var u,d,h;const s=e.params.pattern,r=e.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(u=t.status)==null||u.call(t,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=t.status)==null||d.call(t,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=e.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=vr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=t.status)==null||h.call(t,200).send({status:"OK"})}async handleColorApplication(e,t){var u,d,h;const s=e.params.color,r=gv(s);if(!r){(u=t.status)==null||u.call(t,400).send({error:"Invalid color format"});return}const o=e.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(d=t.status)==null||d.call(t,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=vr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=t.status)==null||h.call(t,200).send({status:"OK"})}async handleEndpointCreation(e,t){var r,o;const s=e.body;if(!s.apiPath||!s.id){(r=t.status)==null||r.call(t,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=t.status)==null||o.call(t,200).send({status:"OK"})}async load(e){var s;const t=e==null?void 0:e.get(Ct.loader);t&&((s=t.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};Bt([Oe],ze.prototype,"_endpointRenderers",2);Bt([$s("/api/ui/canvas/patterns")],ze.prototype,"handlePatternsPost",1);Bt([$s("/api/ui/canvas/pattern/:endpoint/:pattern")],ze.prototype,"handlePatternApplication",1);Bt([$s("/api/ui/canvas/color/:endpoint/:color")],ze.prototype,"handleColorApplication",1);Bt([$s("/api/ui/canvas/endpoint")],ze.prototype,"handleEndpointCreation",1);ze=Bt([A(Nu)],ze);const Ct=new Me({class:ze,type:Nu}),{URL:Hn}=ae(),{getOne:Uu}=oe.build({basePath:`${Hn}/api/device`}),wr=m.createLogger({name:"device-service",group:"Services"}),ju=async()=>{wr.debug("sending GET for device serial number");try{const e=await Uu({urlOverride:`${Hn}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof pe)return wr.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Bu=async()=>{wr.debug("sending GET for device details");try{const e=await Uu({urlOverride:`${Hn}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof pe)return wr.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},mv=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Bu,getSerialNumber:ju},Symbol.toStringTag,{value:"Module"}));var yv=Object.defineProperty,bv=Object.getOwnPropertyDescriptor,Ku=(e,t,s,r)=>{for(var o=r>1?void 0:r?bv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&yv(t,s,o),o};const Hu="device-model",vv="/kos/criticalData/changed",wv="/kos/criticalData/available";let Er=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=e,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[e]=this.nodeId.split("-");return e}get nodeName(){const[,e]=this.nodeId.split("-");return e}updateModel(e){this._serialNumber=e.serialNumber??"unassigned",this._name=e.name??"unassigned",this._nodeId=e.nodeId??"unassigned"}async loadDeviceData(){const[e,t]=await Bu();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}if(t){const{name:s,nodeId:r}=t;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[e,t]=await ju();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}this.updateModel({serialNumber:t,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};Ku([U({topic:[vv,wv],websocket:!0})],Er.prototype,"handleCriticalDataChanged",1);Er=Ku([A(Hu)],Er);const Mr=new Me({class:Er,type:Hu});var Ev=Object.getOwnPropertyDescriptor,Mv=(e,t,s,r)=>{for(var o=r>1?void 0:r?Ev(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const zu="network-interface-model";let Co=class{constructor(e,t,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=e,this.logger=s.logger,this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}updateModel(e){this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};Co=Mv([A(zu)],Co);const zn=new me({class:Co,type:zu}),{URL:Tv}=ae(),{getAll:_v}=oe.build({basePath:`${Tv}/api/kos/network/interfaces`}),Vi=m.createLogger({name:"network-interface-service",group:"Services"}),Vu=async()=>{Vi.debug("sending GET for copy-logs");try{const e=await _v({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof pe)return Vi.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Iv=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Vu},Symbol.toStringTag,{value:"Module"}));var Ov=Object.defineProperty,Sv=Object.getOwnPropertyDescriptor,Gu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Sv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ov(t,s,o),o};const Yu="network-interface-container-model";let Tr=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e,indexMap:{byCategory:"category"}})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[e,t]=await Vu();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const r=zn.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Gu([Oe],Tr.prototype,"_models",2);Tr=Gu([A(Yu)],Tr);const Ms=new Me({class:Tr,type:Yu});Ms.addRelatedModel(zn);const{URL:$v}=ae(),{getAll:Cv}=oe.build({basePath:`${$v}/api/kos/storage/devices`}),Gi=m.createLogger({name:"storage-device-service",group:"Services"}),qu=async()=>{Gi.debug("sending GET for storage-device");const e=await Cv({});return!(e!=null&&e.data)||e.status!==200?(Gi.error("Failed to retrieve storage-device data",e),[]):e.data},Dv=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:qu},Symbol.toStringTag,{value:"Module"}));var xv=Object.getOwnPropertyDescriptor,Av=(e,t,s,r)=>{for(var o=r>1?void 0:r?xv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Wu="storage-device-model";let Do=class{constructor(e,t,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=e,this.logger=s.logger,this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}updateModel(e){this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};Do=Av([xr(),A(Wu)],Do);const _r=new me({class:Do,type:Wu});var Rv=Object.defineProperty,Pv=Object.getOwnPropertyDescriptor,Vn=(e,t,s,r)=>{for(var o=r>1?void 0:r?Pv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Rv(t,s,o),o};const Qu="storage-device-container-model",kv="/kos/storage";let Ts=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(e){this._models.data.filter(s=>!e.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),e.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=_r.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await qu()).forEach(t=>{const s={...t,kosParentId:this.id},r=_r.instance(t.id).options(s).build();this.addModel(r)})}};Vn([Oe],Ts.prototype,"_models",2);Vn([U({topic:kv,websocket:!0})],Ts.prototype,"handleStorageAvailability",1);Ts=Vn([A(Qu)],Ts);const Dt=new Me({class:Ts,type:Qu});Dt.addRelatedModel(_r);const{URL:Gn}=ae(),{getAll:Lv,postModel:Fv}=oe.build({basePath:`${Gn}/api/kos/update/available`}),Yi=m.createLogger({name:"usb-update-service",group:"Services"}),Zu=async()=>{Yi.debug("sending GET for usb-update");const e=await Lv({urlOverride:`${Gn}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(Yi.error("Failed to retrieve usb-update data",e),[]):e.data},Xu=async(e,t,s)=>{const r=await Fv({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${Gn}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},Nv=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Zu,installUpdate:Xu},Symbol.toStringTag,{value:"Module"}));var Uv=Object.defineProperty,jv=Object.getOwnPropertyDescriptor,Ju=(e,t,s,r)=>{for(var o=r>1?void 0:r?jv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Uv(t,s,o),o};const ed="usb-update-model";let Ir=class{constructor(e,t,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=e,this.logger=s.logger,this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes,this.futureHandler=new Rr(this)}updateModel(e){this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(e){if(!e)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),Xu(this.manifestId,this.deviceId,e)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};Ju([Xn()],Ir.prototype,"install",1);Ir=Ju([A(ed)],Ir);const Yn=new me({class:Ir,type:ed});var Bv=Object.defineProperty,Kv=Object.getOwnPropertyDescriptor,Yr=(e,t,s,r)=>{for(var o=r>1?void 0:r?Kv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Bv(t,s,o),o};const td="usb-update-container-model";let xt=class{constructor(e,t,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(e){this._activeUpdate=e}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const e=await Zu();X(()=>{const t=e.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!t.includes(s.id)).forEach(s=>this.removeModel(s.id)),e.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=Yn.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(o)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var e;(e=this.disposer)==null||e.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};Yr([Rt({modelType:Dt.type})],xt.prototype,"storageService",2);Yr([Oe],xt.prototype,"_models",2);Yr([nc({dependencies:e=>[e.isUsbInserted]})],xt.prototype,"usbInsertedEffect",1);xt=Yr([A(td)],xt);const _s=new Me({class:xt,type:td});_s.addRelatedModel(Yn);const Hv=()=>({...{[Lt.type]:{class:Ol},[He.type]:{class:Al,singleton:!0},...re.registration,...rt.registration,...St.registration,...gr.registration,...ke.registration,[Un.type]:{class:exports.WsEventModel,singleton:!0},...Es.registration,...Fn.registration,...ir.registration}}),qn=Hv(),zv={models:qn,preloadModels:[]},qi=!0,sd=e=>()=>{const t=qn;return fc(xo)(ws).model(St).model(Dt).model(_s).model(Mr).model(dr).model(fs).model(hr).model(On).model(Ms).model(Ct).model(Bn).model(Hl).model(Tn,qi).model(As).model(Gl,qi),Object.keys(t).forEach(s=>{const r=t[s];hc(xo)(s,r)}),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e)}},we={};we.core={models:sd(we)};we.preload=x.model.preloadModel(we);we.model=x.model.register(we);we.companion=x.companion.register(we);we.legacy=x.model.registerLegacyModel(we);const xo=we;class Vv{registerTroubleRankMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleRank,t),this}registerTroubleRoleMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleRole,t),this}registerTroubleColorMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleColor,t),this}registerModelLoader(t,s){S.loader.registerLoader(t,s)}registerCanvasPatternLoader(t){S.loader.registerLoader(Ct.loader,t)}}const Gv=async(e,t)=>{const s=On.instance(e).options({}).build(),r=t?`${t}-`:"";return await ue(s),{getState:o=>s.data[`${r}${o}`],updateState:async(o,n)=>{await s.updateState(`${r}${o}`,n)},clean:async()=>{for(const o of s.data.keys)await s.updateState(`${r}${o}`,void 0)},unsubscribe:()=>{Xe(s)}}},rd="kos:service:region",od="regionId",Yv=`${rd}-${od}`,nd=async e=>{const t=rt.factory(Yv)({path:rd,attribute:od});await ue(t),t.updateProperty(e)},Wn="/kos-timer-event",Qn="/kos-timer-event/tick",Zn="defaultTimerEnd",es=m.createLogger({name:"timer-manager"}),qv=e=>e.updateProperty!==void 0;class id{constructor(t,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=t;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,qv(s)&&Y(()=>{m.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:Zn}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){es.debug(`Timer ${this.name} already started`);return}(this.state==="inactive"||this.state==="paused")&&(this.state="active",this.timer=setInterval(()=>this.updateTimer(),1e3))}pause(){this.timer&&(es.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(t){this.timeout=t,this.restart()}addTimeoutAction(t){const s=t.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=t.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=t.action:this.timeoutActions.get(s).push(t)}removeTimeoutAction(t){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==t);o.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,o)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(t){this.timeoutActions.has(t)&&this.timeoutActions.get(t).forEach(s=>{var r;es.debug(`Executing timer action ${s.name} at ${t}`),(r=s.action)==null||r.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(es.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){z(`${Qn}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(t){z(Wn,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const ts=new Map,ht=(e,t)=>{const s=ts.get(e);if(!s){es.error(`Timer ${e} not found`);return}t(s)},ad={createRelativeTimer(e,t,s){const r=new Date,o=Math.round((t.getTime()-r.getTime())/1e3);return this.createTimer(e,o,s)},createTimer(e,t=60,s){if(ts.has(e))return ts.get(e);const r=new id(e,t,s);return ts.set(e,r),r},getTimer(e){return ts.get(e)},clearTimer(e){ht(e,t=>t.pause())},restartTimer(e){ht(e,t=>t.restart())},resetTimer(e){ht(e,t=>t.reset())},addTimeoutAction(e,t){ht(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){ht(e,s=>s.removeTimeoutAction(t))},startTimer(e){ht(e,t=>t.start())}},cd="kos:service:region:settings",ld="timeZone",Wv=`${cd}-${ld}`,Ao=async e=>{const t=rt.factory(Wv)({path:cd,attribute:ld});await ue(t),t.updateProperty(e)},Qv=e=>!e||!e.data;function Xn(e={}){const{alias:t,namespace:s,abortController:r=!1}=e;return(o,n,i)=>{o[os]=o[os]||{};const a=i.value,c=async function(...u){const d=tt();m.debug(`Calling future service ${n} with tracker ${d}`);let h,f;r&&(h=new AbortController);const p=Je.initiateFuture({tracker:d,id:fn});s&&(p.namespace=s),m.debug(`waiting for future ${p.id} to be ready`),await ue(p),m.debug(`future ${p.id} is ready`),X(()=>{m.debug(`Adding future ${p.id} to futureHandler`),this.futureHandler.addFuture(p,t)}),r&&h&&(f=Y(()=>{(p.status==="CANCELLED"||p.endState===Ke.Canceled)&&(m.debug(`Future ${p.id} cancelled, aborting request`),h==null||h.abort())}),h.signal.addEventListener("abort",async()=>{if(p.status!=="CANCELLED"&&p.endState!==Ke.Canceled&&!p.endState){m.debug(`AbortController aborted, cancelling future ${p.id}`);try{await p.cancelFuture()}catch(w){m.error(`Failed to cancel future ${p.id}:`,w)}}},{once:!0}));const b=()=>{f&&(f(),f=void 0)};try{const w=[...u];if(r&&h){const F=w[w.length-1];F&&typeof F=="object"&&"aborted"in F?w[w.length-1]=h.signal:w.push(h.signal)}w.push(d);const M=await a.apply(this,w);m.debug(`received future response for ${d}`,M);const _=Qv(M)?M:M==null?void 0:M.data;return _?(_.progress=1,m.debug("mapping future response to future model"),p.endState?m.debug(`future ${p.id} has already completed. Not updating the model`):En(_,p)):this.futureHandler.removeFuture(t),b(),_}catch(w){if(b(),r&&(h!=null&&h.signal.aborted)){const M=new Error("Operation cancelled");throw m.debug(`Operation ${n} was cancelled`),M}throw m.error(w),w}};o[os][n]={handler:c}}}const Zv=({path:e})=>(t,s)=>{t[k]=t[k]||{},t[k][s]={modelType:Es.type,id:`${Es.type}-${e}`,options:{path:e},lifecycle:H.INIT}};function Xv(e){const{path:t,attribute:s}=e;return(r,o)=>{r[k]=r[k]||{},r[k][o]={modelType:Fn.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:H.INIT}}}const mt=m.createLogger({name:"services",group:"Services"}),Jv=async(e,t)=>ud(e,t,`${exports.BASE_URL}/api/server/login`),ud=async(e,t,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:e,password:t})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},ew=async e=>dd(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),dd=async(e,t=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${t}?email=${e}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},tw=async(e,t)=>hd(e,t,`${exports.BASE_URL}/api/server/resetPassword`),hd=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{mt.debug(`resetting password with token ${e} and password ${t.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t})});if(mt.debug(`password reset returned status ${r.status}`),!r.ok){mt.error(`password reset failed with message ${r.statusText}`);const n=await r.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await r.json()},sw=async(e,t,s)=>fd(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),fd=async(e,t,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{mt.debug(`accepting invite with token ${e} and password ${t.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t,name:s})});if(mt.debug(`invitation accept returned status ${o.status}`),!o.ok){mt.error(`invite failed with message ${o.statusText}`);const i=await o.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await o.json()};function rw(e,t,s,r){const o=e instanceof Promise?{promise:e,abortController:t,cancelFuture:s,future:r}:e,{promise:n,abortController:i,cancelFuture:a,future:c}=o,u=n;let d=0,h="PENDING",f=!0;const p=new Set;let b;return c&&typeof c=="object"&&(b=E.autorun(()=>{const w=c.progress||0,M=c.status||"PENDING",_=!c.endState;(w!==d||M!==h||_!==f)&&(d=w,h=M,f=_,p.forEach(F=>{try{F(d,h)}catch(Q){console.warn("Progress callback error:",Q)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(w=>{try{w(d,h)}catch(M){console.warn("Progress callback error:",M)}})),b&&b(),p.clear()}),u.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",p.forEach(w=>{try{w(d,h)}catch(M){console.warn("Progress callback error:",M)}}),b&&b()},u.getController=()=>i,u.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(u,"progress",{get:()=>d,enumerable:!0}),Object.defineProperty(u,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(u,"isRunning",{get:()=>f,enumerable:!0}),u.onProgressUpdate=w=>(p.add(w),w(d,h),()=>p.delete(w)),u}const ow=qe.keyframes`
|
|
114
|
+
`,i=this.compileShader(r.VERTEX_SHADER,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class at{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const t=this.canvas.getContext("2d");if(!t)throw new Error("2D canvas not supported");this.ctx=t}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(t){const s=performance.now();return s-this.lastUpdate>=t?(this.lastUpdate=s,!0):!1}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}}function zn(e){class t extends e{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(o){this.doneCallback=o}signalDoneIfNeeded(){var o;this.oneShotDone||((o=this.doneCallback)==null||o.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return t}const rv=zn(at);class ov extends rv{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();l(this,"offset",0);l(this,"speed");l(this,"colors");l(this,"direction");l(this,"loop");this.colors=s,this.direction=r,this.speed=o,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,r){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const o=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(o,0,n,0),a=1/(this.colors.length-1);this.colors.forEach((c,u)=>{i.addColorStop(u*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const nv=zn(at);class Nu extends nv{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 iv extends Fu{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 av(e){const t=e.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(t))throw new Error(`Invalid hex color: ${e}`);let s,r,o;return t.length===3?(s=parseInt(t[0]+t[0],16),r=parseInt(t[1]+t[1],16),o=parseInt(t[2]+t[2],16)):(s=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),o=parseInt(t.substring(4,6),16)),{r:s,g:r,b:o}}function Uu(e){return typeof e=="string"?av(e):e}function vr(e){const t=Uu(e);return`rgb(${t.r},${t.g},${t.b})`}class cv extends at{constructor(s={}){super();l(this,"columns",[]);l(this,"fallChance");l(this,"speed");l(this,"baseColor");l(this,"trailColors");this.speed=s.speed??1,this.fallChance=s.fallChance??.7,s.baseColor?this.baseColor=Uu(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let o=0;o<=5;o++){const n=1-o/5*.6;r.push({r:Math.floor(this.baseColor.r*n),g:Math.floor(this.baseColor.g*n),b:Math.floor(this.baseColor.b*n)})}return r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const c=this.columns[a];let u=0,d=0,h=0;if(i===c)u=this.baseColor.r,d=this.baseColor.g,h=this.baseColor.b;else if(i<c&&i>c-this.trailColors.length){const p=c-i;if(p<this.trailColors.length){const b=this.trailColors[p];u=b.r,d=b.g,h=b.b}}const f=(i*s+a)*4;n[f]=u,n[f+1]=d,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(o,0,0)}}class lv{constructor(t,s){l(this,"baseRenderer");l(this,"overlayIcons",new Map);l(this,"overlayConfigs");l(this,"loadedIcons",new Set);l(this,"canvas");l(this,"ctx");l(this,"persistOverlaysOnComplete");l(this,"baseRendererCompleted",!1);l(this,"completionCallback",null);l(this,"hasSignaledCompletion",!1);this.baseRenderer=s(t.baseRenderer.type,t.baseRenderer.data),this.overlayConfigs=t.overlays,this.persistOverlaysOnComplete=t.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const t of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(t.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${t.src}`,r)},s.src=t.src,this.overlayIcons.set(t.src,s)}}calculateOverlayPosition(t,s,r){let o,n;if(typeof t.position=="string")switch(t.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-t.size)/2,n=0;break;case"top-right":o=s-t.size,n=0;break;case"center-left":o=0,n=(r-t.size)/2;break;case"center":o=(s-t.size)/2,n=(r-t.size)/2;break;case"center-right":o=s-t.size,n=(r-t.size)/2;break;case"bottom-left":o=0,n=r-t.size;break;case"bottom-center":o=(s-t.size)/2,n=r-t.size;break;case"bottom-right":o=s-t.size,n=r-t.size;break;default:o=0,n=0}else o=t.position.x,n=t.position.y;return t.offset&&(o+=t.offset.x||0,n+=t.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(t,s){if(this.canvas.width=t,this.canvas.height=s,this.ctx.clearRect(0,0,t,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(t,s);else{this.baseRenderer.renderFrame(t,s);const r=this.baseRenderer.readPixels(t,s);if(r&&r.length>0){const o=new ImageData(r,t,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(t,s)}}renderOverlays(t,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const o=this.overlayIcons.get(r.src);if(!o||!this.loadedIcons.has(r.src))continue;const n=this.calculateOverlayPosition(r,t,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(o,n.x,n.y,r.size,r.size),this.ctx.restore()}}readPixels(t,s){return this.ctx.getImageData(0,0,t,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(t){this.completionCallback=t,this.hasSignaledCompletion&&t()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class ju extends at{constructor(s){super();l(this,"img");l(this,"loaded",!1);l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"colorOverride");l(this,"originalSvgData",null);l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);this.img=new Image,this.img.crossOrigin="anonymous",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,this.colorOverride=s.colorOverride,this.colorOverride&&s.src.toLowerCase().includes(".svg")?this.loadAndProcessSvg(s.src):this.img.src=s.src,this.img.onload=()=>{this.loaded=!0},this.img.onerror=r=>{console.error("Failed to load image:",r)}}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(!this.loaded||this.completed)return;if(this.isPaused){this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.ctx.drawImage(this.img,0,0,s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":this.position+=d;break;case"right":this.position+=d;break;case"up":this.position+=d;break;case"down":this.position+=d;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(s,r,o,i)}drawScrollingImage(s,r,o,n){var h,f,p,b,w,M,_,F,Q;const i=this.img.width/this.img.height;let a,c;((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((b=this.scrollConfig)==null?void 0:b.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r);let u,d;switch(o==="left"||o==="right"?(u=0,((M=this.scrollConfig)==null?void 0:M.offsetY)==="center"||((_=this.scrollConfig)==null?void 0:_.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((F=this.scrollConfig)==null?void 0:F.offsetX)==="center"||((Q=this.scrollConfig)==null?void 0:Q.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),o){case"left":{const D=s-this.position;if(D<s&&D>-a&&this.ctx.drawImage(this.img,D,d,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>n){const O=D+a+n;O<s&&this.ctx.drawImage(this.img,O,d,a,c)}break}case"right":{const D=-a+this.position;if(D>-a&&D<s&&this.ctx.drawImage(this.img,D,d,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-a>-a){const O=D-a-n;O<s&&this.ctx.drawImage(this.img,O,d,a,c)}break}case"up":{const D=r-this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,u,D,a,c),this.loopConfig&&this.pauseDuration===0&&D+c+n<r){const O=D+c+n;O>-c&&this.ctx.drawImage(this.img,u,O,a,c)}break}case"down":{const D=-c+this.position;if(D>-c&&D<r&&this.ctx.drawImage(this.img,u,D,a,c),this.loopConfig&&this.pauseDuration===0&&D-n-c>-c){const O=D-c-n;O<r&&this.ctx.drawImage(this.img,u,O,a,c)}break}}}checkScrollCompletion(s,r,o,n){var h,f,p,b,w;if(!this.isPlaying)return;const i=this.img.width/this.img.height;let a,c;switch(((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((b=this.scrollConfig)==null?void 0:b.width)||s,c=((w=this.scrollConfig)==null?void 0:w.height)||r),o){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let u=!1;const d=1;switch(o){case"left":u=s-this.position<-a-d;break;case"right":u=-a+this.position>s+d;break;case"up":u=r-this.position<-c-d;break;case"down":u=-c+this.position>r+d;break}u&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}async loadAndProcessSvg(s){try{const o=await(await fetch(s)).text();this.originalSvgData=o;const n=this.applySvgColorOverride(o),i=`data:image/svg+xml;base64,${btoa(n)}`;this.img.src=i}catch(r){console.error("Failed to load and process SVG:",r),this.img.src=s}}applySvgColorOverride(s){if(!this.colorOverride)return s;const r=vr(this.colorOverride);return s.replace(/fill\s*=\s*["'][^"']*["']/gi,`fill="${r}"`).replace(/fill\s*:\s*[^;"]*/gi,`fill:${r}`).replace(/stroke\s*=\s*["'][^"']*["']/gi,`stroke="${r}"`).replace(/stroke\s*:\s*[^;"]*/gi,`stroke:${r}`)}dispose(){this.img.removeAttribute("src"),this.completionCallback=null,this.originalSvgData=null}}class uv extends at{constructor(s){super();l(this,"text");l(this,"lines");l(this,"fontSize");l(this,"fontFamily");l(this,"lineHeight");l(this,"textColor");l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);l(this,"textWidth",0);l(this,"textHeight",0);l(this,"lineWidths",[]);l(this,"textMeasured",!1);this.text=s.text,this.lines=s.text.split(`
|
|
115
|
+
`),this.fontSize=s.fontSize??8,this.lineHeight=s.lineHeight??this.fontSize+2,this.fontFamily=s.fontFamily??"monospace, 'Lucida Console', 'Courier New', Courier",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,s.color?this.textColor=vr(s.color):this.textColor="rgb(255,255,255)"}measureText(){if(this.textMeasured)return;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.lineWidths=[];let s=0;for(const r of this.lines){const n=this.ctx.measureText(r).width;this.lineWidths.push(n),s=Math.max(s,n)}this.textWidth=s,this.textHeight=this.lines.length*this.lineHeight,this.textMeasured=!0}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0,this.textMeasured=!1,this.lineWidths=[]}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(this.canvas.width=s,this.canvas.height=r,this.measureText(),this.completed)return;if(this.isPaused){this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.drawStaticText(s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":case"right":case"up":case"down":this.position+=d;break}}this.drawScrollingText(s,r,o,i),this.checkScrollCompletion(s,r,o)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const o=this.textHeight;let n=(r-o)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],c=this.lineWidths[i],u=(s-c)/2,d=n+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,o,n){var c,u,d,h;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";let i,a;o==="left"||o==="right"?(i=0,((c=this.scrollConfig)==null?void 0:c.offsetY)==="center"||((u=this.scrollConfig)==null?void 0:u.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((d=this.scrollConfig)==null?void 0:d.offsetX)==="center"||((h=this.scrollConfig)==null?void 0:h.offsetX)===void 0?(i=s/2,this.ctx.textAlign="center"):(i=this.scrollConfig.offsetX,this.ctx.textAlign="left"),a=0),this.drawMultiLineScrollText(o,s,r,n,i,a)}drawMultiLineScrollText(s,r,o,n,i,a){switch(s){case"left":{const c=r-this.position;if(c<r&&c>-this.textWidth&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&this.position>n){const u=c+this.textWidth+n;u<r&&this.drawTextBlock(u,a,"left")}break}case"right":{const c=-this.textWidth+this.position;if(c>-this.textWidth&&c<r&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textWidth>-this.textWidth){const u=c-this.textWidth-n;u<r&&this.drawTextBlock(u,a,"left")}break}case"up":{const c=o-this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c+this.textHeight+n<o){const u=c+this.textHeight+n;u>-this.textHeight&&this.drawTextBlock(i,u,"center")}break}case"down":{const c=-this.textHeight+this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textHeight>-this.textHeight){const u=c-this.textHeight-n;u<o&&this.drawTextBlock(i,u,"center")}break}}}drawTextBlock(s,r,o){for(let n=0;n<this.lines.length;n++){const i=this.lines[n],a=this.lineWidths[n];let c;o==="center"?c=s-a/2:c=s;const u=r+n*this.lineHeight;this.ctx.fillText(i,c,u)}}checkScrollCompletion(s,r,o){if(!this.isPlaying)return;let n=!1;const i=1;switch(o){case"left":n=s-this.position<-this.textWidth-i;break;case"right":n=-this.textWidth+this.position>s+i;break;case"up":n=r-this.position<-this.textHeight-i;break;case"down":n=-this.textHeight+this.position>r+i;break}n&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}dispose(){this.completionCallback=null}}class dv{constructor(t){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=t.patterns,this.loopConfig=t.loop??!1,this.transitionDuration=t.transitionDuration??0,this.patternOverrides=t.patternOverrides??{},this.patternStore=t.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var n,i,a,c;const t=this.patterns[this.currentPatternIndex],s=this.patternStore.get(t);if(!s){console.warn(`Pattern "${t}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[t]??{},o={...s.data,...r};try{this.currentRenderer=wr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(c=(a=this.currentRenderer).play)==null||c.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(u){console.error(`Failed to create renderer for pattern "${t}":`,u),this.moveToNextPattern()}}isDoneAware(t){return typeof(t==null?void 0:t.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var t,s;(s=(t=this.currentRenderer)==null?void 0:t.play)==null||s.call(t)}pause(){var t,s;(s=(t=this.currentRenderer)==null?void 0:t.pause)==null||s.call(t)}renderFrame(t,s){this.width=t,this.height=s,this.canvas.width=t,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(t,s)}readPixels(t,s){return this.currentRenderer?this.currentRenderer.readPixels(t,s):this.ctx.getImageData(0,0,t,s).data}onDone(t){this.completionCallback=t}isOneShot(){var t,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(t=this.currentRenderer).isOneShot)==null?void 0:s.call(t))??!1:!0:!1}dispose(){var t,s;this.currentRenderer&&((s=(t=this.currentRenderer).dispose)==null||s.call(t)),this.completionCallback=null}setPatternStore(t){this.patternStore=t,this.patterns.length>0&&this.loadCurrentPattern()}}const hv=zn(at);class fv extends hv{constructor(s={r:0,g:0,b:0}){super();l(this,"color");let r;s.color!==void 0?r=s.color:s.r!==void 0&&s.g!==void 0&&s.b!==void 0?r={r:s.r,g:s.g,b:s.b}:r={r:0,g:0,b:0},this.color=vr(r)}setColor(s){this.color=vr(s),this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,r){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,r),this.signalDoneIfNeeded())}}class pv extends at{constructor({minHue:s=0,maxHue:r=360,speed:o=1}={}){super();l(this,"offset",0);l(this,"minHue");l(this,"maxHue");l(this,"speed");this.minHue=s,this.maxHue=r,this.speed=o}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,r,o){let n,i,a;if(r===0)n=i=a=o;else{const c=(h,f,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?h+(f-h)*6*p:p<.5?f:p<.6666666666666666?h+(f-h)*(.6666666666666666-p)*6:h),u=o<.5?o*(1+r):o+r-o*r,d=2*o-u;n=c(d,u,s+1/3),i=c(d,u,s),a=c(d,u,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let c=0;c<s;c++){const u=(c+this.offset)%s/s,d=this.minHue/360+u*((this.maxHue-this.minHue)/360),[h,f,p]=this.hslToRgb(d,1,.5);n[i++]=h,n[i++]=f,n[i++]=p,n[i++]=255}this.ctx.putImageData(o,0,0)}}const Vi=new Map;$s(te,{register(e,t){Vi.set(e,t)},execute(e,t){const s=Vi.get(e);return s?new s(t):null}});S.canvas.registerRenderer("video",iv);S.canvas.registerRenderer("video-basic",Fu);S[te].register("image-static",Nu);S[te].register("image-scrolling",ju);const gv=class{constructor(e){var t;return(t=e.scroll)!=null&&t.enabled?new ju(e):new Nu(e)}};S[te].register("image",gv);S[te].register("color",fv);S[te].register("matrix",cv);S[te].register("sweep",pv);S[te].register("gradient",ov);S[te].register("drop",sv);S[te].register("sequence",dv);S[te].register("text",uv);const mv=class{constructor(e){const t=(s,r)=>{const o=wr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new lv(e,t)}};S[te].register("overlay",mv);const wr=({mode:e,data:t})=>{const s=S[te].execute(e,t);if(s)return s;throw new Error(`Unknown mode: ${e}`)};var yv=Object.defineProperty,bv=Object.getOwnPropertyDescriptor,Bt=(e,t,s,r)=>{for(var o=r>1?void 0:r?bv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&yv(t,s,o),o};const Bu="canvas-dispatcher-model";function vv(e){if(e=e.replace(/^#/,""),e.length===3&&(e=e.split("").map(s=>s+s).join("")),e.length!==6)return null;const t=parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}}let ze=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=e,this.logger=s.logger,this._endpointRenderers=new Se}addNamedEndpoint(e,t){this._endpointRenderers.getModel(e)&&this.logger.warn(`Endpoint "${e}" already exists. Overwriting.`);const s=Hn.instance(e).options({apiPath:t.apiPath,width:t.width,height:t.height,fps:t.fps,durationMs:t.durationMs??null,endpoint:e}).build();return this._endpointRenderers.addModel(s),s}addContent(e,t){this._content.has(e)&&this.logger.warn(`Content "${e}" already exists. Overwriting.`),this._content.set(e,t)}addPattern(e,t){this._patterns.has(e)&&this.logger.warn(`Pattern "${e}" already exists. Overwriting.`),this._patterns.set(e,t)}async handlePatternsPost(e,t){var o,n;const s=e.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=t.status)==null||o.call(t,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(n=t.status)==null||n.call(t,200).send({status:"OK"})}async handlePatternApplication(e,t){var u,d,h;const s=e.params.pattern,r=e.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(u=t.status)==null||u.call(t,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=t.status)==null||d.call(t,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=e.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=wr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=t.status)==null||h.call(t,200).send({status:"OK"})}async handleColorApplication(e,t){var u,d,h;const s=e.params.color,r=vv(s);if(!r){(u=t.status)==null||u.call(t,400).send({error:"Invalid color format"});return}const o=e.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(d=t.status)==null||d.call(t,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=wr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=t.status)==null||h.call(t,200).send({status:"OK"})}async handleEndpointCreation(e,t){var r,o;const s=e.body;if(!s.apiPath||!s.id){(r=t.status)==null||r.call(t,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=t.status)==null||o.call(t,200).send({status:"OK"})}async load(e){var s;const t=e==null?void 0:e.get(Ct.loader);t&&((s=t.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};Bt([Ie],ze.prototype,"_endpointRenderers",2);Bt([Cs("/api/ui/canvas/patterns")],ze.prototype,"handlePatternsPost",1);Bt([Cs("/api/ui/canvas/pattern/:endpoint/:pattern")],ze.prototype,"handlePatternApplication",1);Bt([Cs("/api/ui/canvas/color/:endpoint/:color")],ze.prototype,"handleColorApplication",1);Bt([Cs("/api/ui/canvas/endpoint")],ze.prototype,"handleEndpointCreation",1);ze=Bt([A(Bu)],ze);const Ct=new Me({class:ze,type:Bu}),{URL:Gn}=ae(),{getOne:Ku}=oe.build({basePath:`${Gn}/api/device`}),Er=m.createLogger({name:"device-service",group:"Services"}),Hu=async()=>{Er.debug("sending GET for device serial number");try{const e=await Ku({urlOverride:`${Gn}/api/kos/device/serialNumber`});return[void 0,e==null?void 0:e.data.serialNumber]}catch(e){if(e instanceof pe)return Er.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},zu=async()=>{Er.debug("sending GET for device details");try{const e=await Ku({urlOverride:`${Gn}/api/kos/device`});return e?[void 0,e.data]:["unknownError",void 0]}catch(e){if(e instanceof pe)return Er.error(`Error fetching device serial number: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},wv=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:zu,getSerialNumber:Hu},Symbol.toStringTag,{value:"Module"}));var Ev=Object.defineProperty,Mv=Object.getOwnPropertyDescriptor,Gu=(e,t,s,r)=>{for(var o=r>1?void 0:r?Mv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Ev(t,s,o),o};const Vu="device-model",Tv="/kos/criticalData/changed",_v="/kos/criticalData/available";let Mr=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=e,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[e]=this.nodeId.split("-");return e}get nodeName(){const[,e]=this.nodeId.split("-");return e}updateModel(e){this._serialNumber=e.serialNumber??"unassigned",this._name=e.name??"unassigned",this._nodeId=e.nodeId??"unassigned"}async loadDeviceData(){const[e,t]=await zu();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}if(t){const{name:s,nodeId:r}=t;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[e,t]=await Hu();if(e){this.logger.error(`Error fetching device serial number: ${e}`);return}this.updateModel({serialNumber:t,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};Gu([U({topic:[Tv,_v],websocket:!0})],Mr.prototype,"handleCriticalDataChanged",1);Mr=Gu([A(Vu)],Mr);const Tr=new Me({class:Mr,type:Vu});var Ov=Object.getOwnPropertyDescriptor,Iv=(e,t,s,r)=>{for(var o=r>1?void 0:r?Ov(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Yu="network-interface-model";let Do=class{constructor(e,t,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=e,this.logger=s.logger,this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}updateModel(e){this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};Do=Iv([A(Yu)],Do);const Vn=new me({class:Do,type:Yu}),{URL:Sv}=ae(),{getAll:$v}=oe.build({basePath:`${Sv}/api/kos/network/interfaces`}),Yi=m.createLogger({name:"network-interface-service",group:"Services"}),qu=async()=>{Yi.debug("sending GET for copy-logs");try{const e=await $v({});return[void 0,e==null?void 0:e.data]}catch(e){if(e instanceof pe)return Yi.error(`Error fetching log file size: ${e.payload.error}`),[e.payload.error,void 0]}return["unknownError",void 0]},Cv=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:qu},Symbol.toStringTag,{value:"Module"}));var Dv=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,Wu=(e,t,s,r)=>{for(var o=r>1?void 0:r?xv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Dv(t,s,o),o};const Qu="network-interface-container-model";let _r=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e,indexMap:{byCategory:"category"}})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[e,t]=await qu();if(e){this.logger.error(`Error loading network interfaces: ${e}`);return}t&&t.forEach(s=>{const r=Vn.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Wu([Ie],_r.prototype,"_models",2);_r=Wu([A(Qu)],_r);const Ts=new Me({class:_r,type:Qu});Ts.addRelatedModel(Vn);const{URL:Av}=ae(),{getAll:Rv}=oe.build({basePath:`${Av}/api/kos/storage/devices`}),qi=m.createLogger({name:"storage-device-service",group:"Services"}),Zu=async()=>{qi.debug("sending GET for storage-device");const e=await Rv({});return!(e!=null&&e.data)||e.status!==200?(qi.error("Failed to retrieve storage-device data",e),[]):e.data},Pv=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Zu},Symbol.toStringTag,{value:"Module"}));var kv=Object.getOwnPropertyDescriptor,Lv=(e,t,s,r)=>{for(var o=r>1?void 0:r?kv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const Xu="storage-device-model";let xo=class{constructor(e,t,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=e,this.logger=s.logger,this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}updateModel(e){this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};xo=Lv([Ar(),A(Xu)],xo);const Or=new me({class:xo,type:Xu});var Fv=Object.defineProperty,Nv=Object.getOwnPropertyDescriptor,Yn=(e,t,s,r)=>{for(var o=r>1?void 0:r?Nv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Fv(t,s,o),o};const Ju="storage-device-container-model",Uv="/kos/storage";let _s=class{constructor(e,t,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(e){this._models.data.filter(s=>!e.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),e.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=Or.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Zu()).forEach(t=>{const s={...t,kosParentId:this.id},r=Or.instance(t.id).options(s).build();this.addModel(r)})}};Yn([Ie],_s.prototype,"_models",2);Yn([U({topic:Uv,websocket:!0})],_s.prototype,"handleStorageAvailability",1);_s=Yn([A(Ju)],_s);const Dt=new Me({class:_s,type:Ju});Dt.addRelatedModel(Or);const{URL:qn}=ae(),{getAll:jv,postModel:Bv}=oe.build({basePath:`${qn}/api/kos/update/available`}),Wi=m.createLogger({name:"usb-update-service",group:"Services"}),ed=async()=>{Wi.debug("sending GET for usb-update");const e=await jv({urlOverride:`${qn}/api/kos/update/available`});return!(e!=null&&e.data)||(e==null?void 0:e.status)!==200?(Wi.error("Failed to retrieve usb-update data",e),[]):e.data},td=async(e,t,s)=>{const r=await Bv({model:{manifestId:e,deviceId:t},tracker:s,urlOverride:`${qn}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},Kv=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:ed,installUpdate:td},Symbol.toStringTag,{value:"Module"}));var Hv=Object.defineProperty,zv=Object.getOwnPropertyDescriptor,sd=(e,t,s,r)=>{for(var o=r>1?void 0:r?zv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Hv(t,s,o),o};const rd="usb-update-model";let Ir=class{constructor(e,t,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=e,this.logger=s.logger,this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes,this.futureHandler=new Pr(this)}updateModel(e){this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(e){if(!e)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),td(this.manifestId,this.deviceId,e)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};sd([ei()],Ir.prototype,"install",1);Ir=sd([A(rd)],Ir);const Wn=new me({class:Ir,type:rd});var Gv=Object.defineProperty,Vv=Object.getOwnPropertyDescriptor,qr=(e,t,s,r)=>{for(var o=r>1?void 0:r?Vv(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=(r?i(t,s,o):i(o))||o);return r&&o&&Gv(t,s,o),o};const od="usb-update-container-model";let xt=class{constructor(e,t,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=e,this.logger=s.logger,this._models=new Se({parentId:e})}getModel(e){return this._models.getModel(e)}get models(){return this._models}get data(){return this._models.data}addModel(e){this._models.addModel(e)}removeModel(e){this._models.removeModel(e)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(e){this._activeUpdate=e}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const e=await ed();X(()=>{const t=e.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!t.includes(s.id)).forEach(s=>this.removeModel(s.id)),e.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=Wn.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(o)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var e;(e=this.disposer)==null||e.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};qr([Rt({modelType:Dt.type})],xt.prototype,"storageService",2);qr([Ie],xt.prototype,"_models",2);qr([ac({dependencies:e=>[e.isUsbInserted]})],xt.prototype,"usbInsertedEffect",1);xt=qr([A(od)],xt);const Os=new Me({class:xt,type:od});Os.addRelatedModel(Wn);const Yv=()=>({...{[Lt.type]:{class:Cl},[He.type]:{class:kl,singleton:!0},...re.registration,...rt.registration,...St.registration,...mr.registration,...ke.registration,[Bn.type]:{class:exports.WsEventModel,singleton:!0},...Ms.registration,...Un.registration,...ar.registration}}),Qn=Yv(),qv={models:Qn,preloadModels:[]},Qi=!0,nd=e=>()=>{const t=Qn;return mc(Ao)(Es).model(St).model(Dt).model(Os).model(Tr).model(hr).model(ps).model(fr).model($n).model(Ts).model(Ct).model(Hn).model(Vl).model(On,Qi).model(Rs).model(Wl,Qi),Object.keys(t).forEach(s=>{const r=t[s];gc(Ao)(s,r)}),{preload:x.model.preloadModel(e),model:x.model.register(e),companion:x.companion.register(e),legacy:x.model.registerLegacyModel(e)}},we={};we.core={models:nd(we)};we.preload=x.model.preloadModel(we);we.model=x.model.register(we);we.companion=x.companion.register(we);we.legacy=x.model.registerLegacyModel(we);const Ao=we;class Wv{registerTroubleRankMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleRank,t),this}registerTroubleRoleMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleRole,t),this}registerTroubleColorMapper(t){return S.propertyMapper.registerPropertyMapper(be.TroubleColor,t),this}registerModelLoader(t,s){S.loader.registerLoader(t,s)}registerCanvasPatternLoader(t){S.loader.registerLoader(Ct.loader,t)}}const Qv=async(e,t)=>{const s=$n.instance(e).options({}).build(),r=t?`${t}-`:"";return await ue(s),{getState:o=>s.data[`${r}${o}`],updateState:async(o,n)=>{await s.updateState(`${r}${o}`,n)},clean:async()=>{for(const o of s.data.keys)await s.updateState(`${r}${o}`,void 0)},unsubscribe:()=>{Xe(s)}}},id="kos:service:region",ad="regionId",Zv=`${id}-${ad}`,cd=async e=>{const t=rt.factory(Zv)({path:id,attribute:ad});await ue(t),t.updateProperty(e)},Zn="/kos-timer-event",Xn="/kos-timer-event/tick",Jn="defaultTimerEnd",es=m.createLogger({name:"timer-manager"}),Xv=e=>e.updateProperty!==void 0;class ld{constructor(t,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=t;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,Xv(s)&&Y(()=>{m.info(`Updating config value timer ${t} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:Jn}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){es.debug(`Timer ${this.name} already started`);return}(this.state==="inactive"||this.state==="paused")&&(this.state="active",this.timer=setInterval(()=>this.updateTimer(),1e3))}pause(){this.timer&&(es.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(t){this.timeout=t,this.restart()}addTimeoutAction(t){const s=t.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=t.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=t.action:this.timeoutActions.get(s).push(t)}removeTimeoutAction(t){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==t);o.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,o)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(t){this.timeoutActions.has(t)&&this.timeoutActions.get(t).forEach(s=>{var r;es.debug(`Executing timer action ${s.name} at ${t}`),(r=s.action)==null||r.call(s,s.name,t),this.notifyTimeoutAction(s),s.singleUse&&(es.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){z(`${Xn}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(t){z(Zn,{name:this.name,action:t.name,remainingTime:this.remainingTime})}}const ts=new Map,ht=(e,t)=>{const s=ts.get(e);if(!s){es.error(`Timer ${e} not found`);return}t(s)},ud={createRelativeTimer(e,t,s){const r=new Date,o=Math.round((t.getTime()-r.getTime())/1e3);return this.createTimer(e,o,s)},createTimer(e,t=60,s){if(ts.has(e))return ts.get(e);const r=new ld(e,t,s);return ts.set(e,r),r},getTimer(e){return ts.get(e)},clearTimer(e){ht(e,t=>t.pause())},restartTimer(e){ht(e,t=>t.restart())},resetTimer(e){ht(e,t=>t.reset())},addTimeoutAction(e,t){ht(e,s=>s.addTimeoutAction(t))},removeTimeoutAction(e,t){ht(e,s=>s.removeTimeoutAction(t))},startTimer(e){ht(e,t=>t.start())}},dd="kos:service:region:settings",hd="timeZone",Jv=`${dd}-${hd}`,Ro=async e=>{const t=rt.factory(Jv)({path:dd,attribute:hd});await ue(t),t.updateProperty(e)},ew=e=>!e||!e.data;function ei(e={}){const{alias:t,namespace:s,abortController:r=!1}=e;return(o,n,i)=>{o[os]=o[os]||{},t&&(o[as]=o[as]||new Map,o[as].set(n,t));const a=i.value,c=async function(...u){const d=tt();m.debug(`Calling future service ${n} with tracker ${d}`);let h,f;r&&(h=new AbortController);const p=Je.initiateFuture({tracker:d,id:gn});s&&(p.namespace=s),m.debug(`waiting for future ${p.id} to be ready`),await ue(p),m.debug(`future ${p.id} is ready`),X(()=>{m.debug(`Adding future ${p.id} to futureHandler`),this.futureHandler.addFuture(p,t)}),r&&h&&(f=Y(()=>{(p.status==="CANCELLED"||p.endState===Ke.Canceled)&&(m.debug(`Future ${p.id} cancelled, aborting request`),h==null||h.abort())}),h.signal.addEventListener("abort",async()=>{if(p.status!=="CANCELLED"&&p.endState!==Ke.Canceled&&!p.endState){m.debug(`AbortController aborted, cancelling future ${p.id}`);try{await p.cancelFuture()}catch(w){m.error(`Failed to cancel future ${p.id}:`,w)}}},{once:!0}));const b=()=>{f&&(f(),f=void 0)};try{const w=[...u];if(r&&h){const F=w[w.length-1];F&&typeof F=="object"&&"aborted"in F?w[w.length-1]=h.signal:w.push(h.signal)}w.push(d);const M=await a.apply(this,w);m.debug(`received future response for ${d}`,M);const _=ew(M)?M:M==null?void 0:M.data;return _?(_.progress=1,m.debug("mapping future response to future model"),p.endState?m.debug(`future ${p.id} has already completed. Not updating the model`):Tn(_,p)):this.futureHandler.removeFuture(t),b(),_}catch(w){if(b(),r&&(h!=null&&h.signal.aborted)){const M=new Error("Operation cancelled");throw m.debug(`Operation ${n} was cancelled`),M}throw m.error(w),w}};o[os][n]={handler:c}}}const tw=({path:e})=>(t,s)=>{t[k]=t[k]||{},t[k][s]={modelType:Ms.type,id:`${Ms.type}-${e}`,options:{path:e},lifecycle:H.INIT}};function sw(e){const{path:t,attribute:s}=e;return(r,o)=>{r[k]=r[k]||{},r[k][o]={modelType:Un.type,id:`${t}-${s}`,options:{path:t,attribute:s},lifecycle:H.INIT}}}const mt=m.createLogger({name:"services",group:"Services"}),rw=async(e,t)=>fd(e,t,`${exports.BASE_URL}/api/server/login`),fd=async(e,t,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:e,password:t})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},ow=async e=>pd(e,`${exports.BASE_URL}/api/server/startPasswordReset`,""),pd=async(e,t=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${t}?email=${e}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},nw=async(e,t)=>gd(e,t,`${exports.BASE_URL}/api/server/resetPassword`),gd=async(e,t,s=`${exports.BASE_URL}/api/resetPassword`)=>{mt.debug(`resetting password with token ${e} and password ${t.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t})});if(mt.debug(`password reset returned status ${r.status}`),!r.ok){mt.error(`password reset failed with message ${r.statusText}`);const n=await r.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await r.json()},iw=async(e,t,s)=>md(e,t,s,`${exports.BASE_URL}/api/server/acceptInvite`),md=async(e,t,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{mt.debug(`accepting invite with token ${e} and password ${t.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:e,password:t,name:s})});if(mt.debug(`invitation accept returned status ${o.status}`),!o.ok){mt.error(`invite failed with message ${o.statusText}`);const i=await o.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await o.json()};function aw(e,t,s,r){const o=e instanceof Promise?{promise:e,abortController:t,cancelFuture:s,future:r}:e,{promise:n,abortController:i,cancelFuture:a,future:c}=o,u=n;let d=0,h="PENDING",f=!0;const p=new Set;let b;return c&&typeof c=="object"&&(b=E.autorun(()=>{const w=c.progress||0,M=c.status||"PENDING",_=!c.endState;(w!==d||M!==h||_!==f)&&(d=w,h=M,f=_,p.forEach(F=>{try{F(d,h)}catch(Q){console.warn("Progress callback error:",Q)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(w=>{try{w(d,h)}catch(M){console.warn("Progress callback error:",M)}})),b&&b(),p.clear()}),u.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",p.forEach(w=>{try{w(d,h)}catch(M){console.warn("Progress callback error:",M)}}),b&&b()},u.getController=()=>i,u.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(u,"progress",{get:()=>d,enumerable:!0}),Object.defineProperty(u,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(u,"isRunning",{get:()=>f,enumerable:!0}),u.onProgressUpdate=w=>(p.add(w),w(d,h),()=>p.delete(w)),u}const cw=qe.keyframes`
|
|
116
116
|
0% {
|
|
117
117
|
left: -90px;
|
|
118
118
|
color: #eee;
|
|
@@ -124,13 +124,13 @@ ${u}topics:${t}
|
|
|
124
124
|
left: 90px;
|
|
125
125
|
color: #eee;
|
|
126
126
|
}
|
|
127
|
-
`,
|
|
127
|
+
`,lw=qe.css`
|
|
128
128
|
font-size: 100px;
|
|
129
129
|
margin-top: -80px;
|
|
130
130
|
position: relative;
|
|
131
|
-
animation: ${
|
|
131
|
+
animation: ${cw} ease-in-out infinite alternate;
|
|
132
132
|
animation-duration: 1.2s;
|
|
133
|
-
`,
|
|
133
|
+
`,uw=({children:e})=>ea.createPortal(e,document.body);function yd({message:e="Wait a moment while we load your app.",theme:t="light"}){return T.jsx(uw,{children:T.jsxs(dw,{theme:t,children:[e,T.jsx("div",{css:lw,children:"."})]})})}const dw=Fo.div`
|
|
134
134
|
padding-inline: 20px;
|
|
135
135
|
width: 100%;
|
|
136
136
|
height: 100vh;
|
|
@@ -144,7 +144,7 @@ ${u}topics:${t}
|
|
|
144
144
|
left: 0;
|
|
145
145
|
color: ${({theme:e})=>e==="light"?"black":"white"};
|
|
146
146
|
z-index: 10000;
|
|
147
|
-
`;class
|
|
147
|
+
`;class bd extends g.Component{constructor(t){super(t),this.state={error:null,errorInfo:null}}componentDidCatch(t,s){this.setState({error:t,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 hw={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},fw=({value:e=0,title:t,status:s="normal",subtitle:r})=>{const o=qe.css`
|
|
148
148
|
display: flex;
|
|
149
149
|
flex-direction: column;
|
|
150
150
|
`,n=qe.css`
|
|
@@ -164,7 +164,7 @@ ${u}topics:${t}
|
|
|
164
164
|
`,a=qe.css`
|
|
165
165
|
width: ${e}%;
|
|
166
166
|
height: 35px;
|
|
167
|
-
background-color: ${
|
|
167
|
+
background-color: ${hw[s]};
|
|
168
168
|
text-align: center;
|
|
169
169
|
line-height: 32px;
|
|
170
170
|
color: black;
|
|
@@ -182,7 +182,7 @@ ${u}topics:${t}
|
|
|
182
182
|
transform: translateX(100%) scaleX(0.5);
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
|
-
`;return T.jsxs("div",{css:o,children:[T.jsxs("div",{css:n,children:[T.jsx("div",{css:i,children:t}),T.jsx("div",{css:[a,e<0?c:""]})]}),T.jsx("div",{children:r})]})},
|
|
185
|
+
`;return T.jsxs("div",{css:o,children:[T.jsxs("div",{css:n,children:[T.jsx("div",{css:i,children:t}),T.jsx("div",{css:[a,e<0?c:""]})]}),T.jsx("div",{children:r})]})},pw={setModel:()=>!1},Wr=g.createContext(pw),gw=()=>{const e=g.useContext(Wr);if(e==null)throw new Error("useModels must be used within a KosModelProvider");return e.model},vd=({children:e})=>{const[t,s]=g.useState(),r=g.useCallback(o=>(s(o),!0),[s]);return T.jsx(Wr.Provider,{value:{model:t,setModel:r},children:e})},wd=m.createLogger({name:"kos-model-hierarchy-context"}),mw={models:[],addModel:()=>{wd.debug("Default implementation being used. Do Nothing.")}},Qr=g.createContext(mw),yw=({children:e})=>{const[t,s]=g.useState([]),r=g.useCallback(o=>{t.includes(o)||(wd.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[t]);return T.jsx(Qr.Provider,{value:{models:t,addModel:r},children:e})},bw=()=>!0,Ed=e=>{const t=g.useContext(Qr);if(!t)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(e==null?void 0:e.filter)||bw;return g.useMemo(()=>t.models.filter(s),[t.models,s])},vw=e=>Ed({filter:s=>{const r=_e(s.id);return(r==null?void 0:r.type)===e}})[0],ww=m.createLogger({name:"kos-model-loader"}),Ew=()=>T.jsx("div",{}),Md=({fallback:e,children:t,...s})=>T.jsx(vd,{children:T.jsx(bd,{fallback:e,children:T.jsx(g.Suspense,{children:T.jsx(Td,{...s,children:t})})})}),Td=e=>{const[t,s]=g.useState(),[r,o]=g.useState(!1),{setModel:n}=g.useContext(Wr),i=g.useContext(Qr);if(g.useEffect(()=>{e.model&&(s(e.model),n(e.model),o(!0),i&&i.addModel(e.model))},[i,e.model,n]),e.error)throw ww.error(e.error),new Error(e.error);const a=e.loading||T.jsx(Ew,{});return T.jsx(T.Fragment,{children:t&&r?e.children:a})},Zs={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},_d=g.createContext(Zs),Mw=({translations:e=Zs,children:t})=>{const s={header:{...Zs.header,...e.header},createModal:{...Zs.createModal,...e.createModal}};return T.jsx(_d.Provider,{value:s,children:t})};function Tw(e,t){const s=I.create(e,!1,t),r=s.whenReady().then(()=>s);return Yo(r)}const Od=g.createContext(void 0),_w=(e={models:{},preloadModels:[]},t)=>{const s=Tw(e,t),r=({children:o})=>{const n=s.read(),[i,a]=g.useState(n.isOnline);return g.useEffect(()=>{const c=Y(()=>{a(n.isOnline)});return()=>{c()}},[n]),T.jsx(Od.Provider,{value:{kosCore:n,online:i},children:o})};return{KosCoreContextProvider:No.observer(r)}},Id=()=>{const e=g.useContext(Od);if(e===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return e},Ow=8,Iw=(e=0)=>new Promise(t=>{setTimeout(()=>{t(!0)},2**e*10)}),Qe=new Map;function Sw(e,t){if(Qe.has(e)){const s=Qe.get(e);if(s.status==="finished"){const r=I.getInstance().modelManager.getModelById(e);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=t().then(()=>{Qe.set(e,{status:"finished",key:e})},o=>{throw Qe.set(e,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Qe.set(e,r),s}}function $w(e,t){return Sw(e,t)}async function Cw(e,t){const{modelId:s,factory:r,modelType:o,options:n,activate:i}=t;let a=0;await e.whenReady();let c;if(n){const d=typeof o=="string"?e.modelManager.getModelFactory(o):r;if(!d)throw Error("No Factory Specified. Cannot create a new instance");c=d.build(s,n)}const u=e.modelManager.getModelById(s);if(!u){if(a>Ow)throw Error(`KOS Model ${s} has not been found`);await Iw(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=e=>{const{modelId:t,modelType:s,activate:r,destroyOnUnmount:o}=e,n=Id(),[i,a]=g.useState(!1),[c,u]=g.useState(),{kosModel:d,model:h}=$w(t||s||"",()=>Cw(n.kosCore,e));return g.useEffect(()=>{async function f(){try{return await n.kosCore.whenReady(),r&&await(d==null?void 0:d.fsm.transitionTo(P.GO_ACTIVE,v.ACTIVE)),a(!0),d}catch(b){u(b.message)}}let p;return n.kosCore&&t&&f().then(b=>{p=Y(()=>{const w=(b==null?void 0:b.status)===v.READY;a(w)})}).catch(b=>{console.error(b)}),()=>{if(r){if(h!=null&&h.id){const b=n.kosCore.modelManager.getModelById(h.id);b==null||b.fsm.transitionTo(P.GO_INACTIVE,v.INACTIVE).then(()=>{if(o){const w=h.id;Xe(h).then(()=>{Qe.delete(w),p==null||p()})}})}}else o&&h&&Xe(h).then(()=>{Qe.delete(t),p==null||p()})}},[r,o,n.kosCore,d,h,t]),{model:h,ready:i,error:c,status:{model:h,ready:i,error:c},KosModelLoader:Md}},ti=()=>{const e=ar.type;return Z({modelId:e,modelType:ar.type,options:{}})},si=g.createContext(void 0),Dw=({children:e})=>{const{model:t,ready:s}=ti(),r=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return T.jsx(si.Provider,{value:r,children:e})},xw=()=>{const e=g.useContext(si);if(!e)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return e},ri=()=>{const e=fr.type;return Z({modelId:e,modelType:fr.type,options:{}})};function Aw(e){return()=>t=>{const{model:s,status:r,KosModelLoader:o}=ri();return T.jsx(o,{...r,children:T.jsx(e,{...t,softwareInfo:s})})}}const oi=g.createContext(void 0),Rw=({children:e})=>{const{model:t,ready:s}=ri(),r=g.useMemo(()=>s&&t?{model:t}:{},[s,t]);return T.jsx(oi.Provider,{value:r,children:e})},Pw=()=>{const e=g.useContext(oi);if(!e)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return e},Sd=new ol,$d=g.createContext(Sd);function kw({children:e}){return T.jsx($d.Provider,{value:Sd,children:e})}const ni=g.createContext(void 0),Lw=()=>{const e=window.location.origin,t=ge();return(t==null?void 0:t.host)||e},Fw=({children:e,appContext:t,locale:s="en",resolver:r,rootUrl:o,descriptorResolver:n})=>{const[i,a]=g.useState(!1),[c,u]=g.useState(),[d,h]=g.useState(),f=o||Lw(),p=g.useMemo(()=>t??"app/system",[t]);g.useEffect(()=>{async function M(){const F=(Array.isArray(p)?p:[p]).map(W=>(n||Su(W))()),O=(await Promise.allSettled(F)).map(W=>{if(W.status==="rejected"){m.warn("Failed to load localization descriptor",W.reason);return}return W.value}).filter(W=>!!W).reverse().reduce((W,B)=>{const J=B.path;return Object.keys(B.namespaces).forEach(Ue=>{const $e=B.namespaces[Ue];$e.basePath=J}),{...W,namespaces:{...W.namespaces,...B.namespaces}}},{});u(O)}M()},[p,n]),g.useEffect(()=>{async function M(){if(c){const _=f,{translations:F}=await Au.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:_});h(F),a(!0)}}M()},[s,c,r,f]);const b=g.useMemo(()=>i?{setLocale:M=>{d&&(d.currentLocale=M)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,d]),w=i?e:null;return T.jsx(ni.Provider,{value:b,children:w})},Nw=()=>{const e=g.useContext(ni);if(!e)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return e},Uw=()=>{const e=Ct.type;return Z({modelId:e,modelType:Ct.type,options:{}})};function jw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Uw();return T.jsx(o,{...r,children:T.jsx(e,{...t,canvasDispatcher:s})})}}const Bw=(e,t,s)=>{const r=atob(e),o=new Uint8ClampedArray(t*s*4);for(let n=0,i=0;n<r.length&&i<o.length;n+=3,i+=4)o[i]=r.charCodeAt(n),o[i+1]=r.charCodeAt(n+1),o[i+2]=r.charCodeAt(n+2),o[i+3]=255;return o};function Kw({ctx:e,format:t,dataString:s,width:r,height:o,pixelSize:n}){const i=Bw(s,r,o),a=new ImageData(i,r,o),c=document.createElement("canvas");c.width=r,c.height=o;const u=c.getContext("2d");u==null||u.putImageData(a,0,0),e.imageSmoothingEnabled=!1,e.clearRect(0,0,r*n,o*n),e.drawImage(c,0,0,r*n,o*n)}const Hw=m.createLogger({name:"canvas-streamer"});Hw.debug("main-view component loaded");const fo=10,Cd=No.observer(({canvasDispatcher:e,height:t=30,width:s=50,defaultFps:r=10,showPreview:o=!1,name:n,apiPath:i="/api/system/canvas"})=>{const a=g.useRef(null),[c,u]=g.useState();g.useEffect(()=>{const h=e.addNamedEndpoint(n,{apiPath:i,fps:r,width:s,height:t,id:n});u(h)},[e]);const d=g.useCallback(h=>{if(a.current&&o){const f=a.current.getContext("2d");f&&Kw({ctx:f,format:"base64",dataString:h,height:t,width:s,pixelSize:fo})}},[s,t,o]);return g.useEffect(()=>{c&&(c.onFrame=d,c.width=s,c.height=t,c.fps=r)},[c,d,s,t,r]),o&&ea.createPortal(T.jsx(Gw,{children:T.jsx(Vw,{children:T.jsx("canvas",{ref:a,width:s*fo,height:t*fo,style:{border:"1px solid black"}})})}),document.body)}),zw=jw(Cd),Gw=Fo.div`
|
|
186
186
|
display: flex;
|
|
187
187
|
flex-direction: column;
|
|
188
188
|
gap: 8px;
|
|
@@ -190,9 +190,9 @@ ${u}topics:${t}
|
|
|
190
190
|
width: 100%;
|
|
191
191
|
justify-content: space-between;
|
|
192
192
|
align-items: center;
|
|
193
|
-
`,
|
|
193
|
+
`,Vw=Fo.div`
|
|
194
194
|
display: flex;
|
|
195
195
|
flex-direction: column;
|
|
196
196
|
align-items: center;
|
|
197
|
-
`,Sd=()=>{const e=Mr.type;return Z({modelId:e,modelType:Mr.type,options:{}})};function Hw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Sd();return T.jsx(o,{...r,children:T.jsx(e,{...t,device:s})})}}function zw(e,t,s){const r=new Promise(o=>{O.getInstance().whenReady().then(()=>{const{model:n}=O.getInstance().modelManager.createModelInstance(e,t??e,s);return n.whenReady().then(()=>{o(n.modelData)})})});return Go(r)}function Vw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Jn();return T.jsx(o,{...r,children:T.jsx(e,{...t,kosTime:s})})}}const $d=()=>{const e=Ms.type;return Z({modelId:e,modelType:Ms.type,options:{}})};function Gw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=$d();return T.jsx(o,{...r,children:T.jsx(e,{...t,networkInterfaceContainer:s})})}}const Cd=()=>{const e=dr.type;return Z({modelId:e,modelType:dr.type,options:{}})};function Yw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Cd();return T.jsx(o,{...r,children:T.jsx(e,{...t,oTA:s})})}}function qw(e,t){g.useEffect(()=>{function s(o){e.current&&!e.current.contains(o.target)&&t()}function r(o){o.key==="Escape"&&t()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[e,t])}function Ww(e){const t=g.useRef(null),s=e.onAlert;return qw(t,s),T.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const Qw=e=>{var u;const{stateProp:t}=e,[s,r]=g.useState((u=e.stateProp)==null?void 0:u.value),[o,n]=g.useState(!1),[i,a]=g.useState(void 0);return g.useEffect(()=>{async function d(h){try{h&&(await ue(h),n(!0))}catch(f){a(f.message)}}d(t)},[t]),g.useEffect(()=>{const d=Y(()=>{t&&o&&r(t.value)});return()=>{d()}},[o,t]),[s,{ready:o,error:i}]},Dd=()=>{const[e,t]=g.useState(!1),[s,r]=g.useState([]),o=Dt.type,n=Z({modelId:o,modelType:Dt.type,options:{}});return g.useEffect(()=>{const i=Y(()=>{var a,c;t(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:e,devices:s}};function Zw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Dd();return T.jsx(o,{...r,children:T.jsx(e,{...t,storageDeviceContainer:s})})}}const fo=m.createLogger({name:"use-timer"}),Xw=({timerName:e,onTimerExpired:t,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=ad.getTimer(e);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${e} does not exist.`);return}const u=$(Wn,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===e&&(f===Zn?t({name:h,action:f,remainingTime:p,timer:n}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:p,timer:n}))});return o&&n.start(),()=>{u.unsubscribe()}},[o,t,r,e,n]),g.useEffect(()=>{if(!n||!s)return;const u=`${Qn}/${e}`,d=$(u,h=>{const{name:f,remainingTime:p}=h==null?void 0:h.body;f===e&&s({name:f,remainingTime:p,timer:n})});return()=>{d.unsubscribe()}},[s,e,n]);const i=g.useCallback(()=>{n?n.start():fo.warn(`Timer with name ${e} does not exist.`)},[n,e]),a=g.useCallback(()=>{n?n.reset():fo.warn(`Timer with name ${e} does not exist.`)},[n,e]),c=g.useCallback(()=>{n?n.pause():fo.warn(`Timer with name ${e} does not exist.`)},[n,e]);return{timer:n,start:i,reset:a,pause:c}},Jw=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},eE=e=>e instanceof RegExp,tE=e=>typeof e=="string",sE=(e,t,s)=>{if(e===""||t==="")return e;let r=t;eE(r)||(r=new RegExp("("+Jw(r)+")","gi"));const o=e.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},xd=(e,t,s)=>{let r=e;return Array.isArray(r)||(r=[r]),r.flatMap(o=>tE(o)?sE(o,t,s):o)};function rE(e,t){let s=e;return Object.entries(t).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=xd(s,n,(i,a)=>o.type==="br"?T.jsx("br",{}):g.cloneElement(o,{key:`${r}-${a}`},i))}),s}const oE=e=>{const{i18nKey:t,t:s,defaults:r,components:o,values:n={},context:i}=e,a=s(t,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=rE(a,o||{});return T.jsx("span",{className:e.className,children:c})},pt=new Map;function nE(e,t){if(pt.has(e)){const s=pt.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(o=>{pt.set(e,{status:"finished",result:o})},o=>{throw pt.set(e,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw pt.set(e,r),s}}function Ro(e,t){return nE(e,t)}const iE=async()=>{const e=await lc(ke.type);return await ue(e.model),e.model},aE=async(e,t,s)=>{const r=e.resolveNamespace(t);await ue(r);for(const o of s){const n=e.resolveNamespace(o);await ue(n),pt.set(o,{status:"finished",result:n})}return r},cE=(e,t)=>{const s=[e].flat(),[r,...o]=s,n=Ro(ke.type,iE),i=s.join("__"),a=Ro(i,()=>aE(n,r,o)),c=g.useMemo(()=>({exists:d=>{const h=t!=null&&t.keyPrefix?`${t.keyPrefix}.${d}`:d;return a?a.exists(h):!1}}),[t==null?void 0:t.keyPrefix,a]);return{t:g.useCallback((d,h)=>{const f=t!=null&&t.keyPrefix?`${t.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(m.debug(`Translation model ${e} not ready for key: ${f}`),f)},[t==null?void 0:t.keyPrefix,e,a]),i18n:c}},Ad=()=>{const e=ke.type;return Z({modelId:e,modelType:ke.type,options:{}})};function lE(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Ad();return T.jsx(o,{...r,children:T.jsx(e,{...t,translationContainer:s})})}}const uE=e=>Z({modelId:e,modelType:ws.type}),oi=()=>Z({modelId:St.type,modelType:St.type,options:{}}),dE=({troubleType:e,condition:t})=>{const{model:s}=oi(),[r,o]=g.useState(!1),[n,i]=g.useState([]),a=g.useCallback(()=>{var c,u;return n.length>0&&((c=n[0])!=null&&c.resolvable)?(u=n[0])==null?void 0:u.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>Y(()=>{const u=(e?s==null?void 0:s.troubles.getIndexByKey("byType",e):s==null?void 0:s.troubles.data)||[],d=t?u.filter(t):u;o(d.length>0),i(d)}),[t,s,e]),[r,a,n.length>0?n[0]:void 0,n]};function hE(e){return t=>{const{model:s,status:r,KosModelLoader:o}=oi();return T.jsx(o,{...r,children:T.jsx(e,{...t,troubleContainer:s})})}}const Rd=()=>{const e=_s.type,t=Z({modelId:e,modelType:_s.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=g.useState(!1),[o,n]=g.useState(!1),[i,a]=g.useState([]);return g.useEffect(()=>{const c=Y(()=>{var u,d,h;r(((u=t.model)==null?void 0:u.isUsbInserted)??!1),n(((d=t.model)==null?void 0:d.hasAvailableUpdates)??!1),a(((h=t.model)==null?void 0:h.data)??[])});return()=>{c()}},[t.model]),{...t,inserted:s,updateAvailable:o,updates:i}};function fE(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Rd();return T.jsx(o,{...r,children:T.jsx(e,{...t,usbUpdateContainer:s})})}}const pE=({path:e,propKey:t})=>{const{status:s}=Z({modelType:fs.type,modelId:e,options:{path:e}}),[r,o]=g.useState(!1),[n,i]=g.useState(),[a,c]=g.useState(""),[u,d]=g.useState(),h=f=>{n&&t&&n.updateProperty(t,f)};return g.useEffect(()=>{var f;s.model&&i(s.model),s.model&&t&&((f=s.model)!=null&&f.props.has(t)?c(s.model.props[t]):d(`property ${t} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,t]),g.useEffect(()=>{t&&E.autorun(()=>{const f=n==null?void 0:n.props[t];c(f||"")})},[n,t]),{config:n,ready:r,value:a,error:u,updateValue:h}},gE=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},Pd=({configProperty:e,optionsTransformer:t})=>{const[s,r]=g.useState(!1),[o,n]=g.useState(""),[i,a]=g.useReducer(gE,{value:String(e==null?void 0:e.value),displayValue:e==null?void 0:e.displayValue,significantValue:e==null?void 0:e.significantValue,unit:e==null?void 0:e.unit,options:e==null?void 0:e.options,mappedOptions:[],updateProperty:e==null?void 0:e.updateProperty,displayOptions:e==null?void 0:e.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&&(e==null||e.updateProperty(d))},[e]);return g.useEffect(()=>{async function u(d){try{d&&(await ue(d),r(!0))}catch(h){n(h.message)}}u(e)},[e]),g.useEffect(()=>{const u=Y(()=>{if(e&&s){let d=[];t&&(d=t(e.options)),a({type:"UPDATE",payload:{value:String(e.value),displayValue:e.displayValue,significantValue:e.significantValue,unit:e.unit,options:e.options,mappedOptions:d,updateProperty:e.updateProperty,displayOptions:e==null?void 0:e.displayOptions}})}});return()=>{u()}},[e,t,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:t?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function mE(e,t){const s=t??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return e===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[e]??0}function yE(e,t){return new Date(e,t,0).getDate()}function kd(e,t){const s=mE(t,e),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function Ld(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function Fd(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function Nd(e,t=[2018,2028]){const s=Fd(t);return e==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function ni(e="numeric",t="en-US"){const s=new Intl.DateTimeFormat(t,{month:e,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function bE({locale:e="en-US",year:t,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(t,i,r),c=new Intl.DateTimeFormat(e,{month:o.month}).format(a),u=new Intl.DateTimeFormat(e,{year:o.year}).format(a),d=new Intl.DateTimeFormat(e,{day:o.day}).format(a);return n?n=="MMDDYY"?`${c} ${d} ${u}`:n==="DDMMYY"?`${d} ${c} ${u}`:n==="YYMMDD"?`${u} ${c} ${d}`:`${u} ${d} ${c}`:new Intl.DateTimeFormat(e,o).format(a)}function ye(e){return e.toString().length===2?new Date(Date.parse(`01 Jan 20${e}`)).getFullYear():e}function vE(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function Ud(e,t,s){const r=ye(t),o=new Date(r,e,1).getDay(),n=new Date(r,e+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function ss(e,t,s){const r=t-1,o=new Date(e,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function rs(e,t){return new Date(e,t,0).getDate()}function jd(e="en-US",t="short"){const s=new Intl.DateTimeFormat(e,{weekday:t}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function Bd({locale:e="en-US",year:t=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:o=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=ii(n,r),u=Kd(n,r,e),d=Hd(i,e),h=zd(i,e),f=ai(t,s),p=Vd(t,s,e,o),b=qd(s,t,p),w=Gd(e,a);return{daysArray:f,monthsArray:d,yearsArray:c,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:b,dayNamesArray:w}}function ii(e="long",t=[2018,2028]){return g.useMemo(()=>Nd(e,t),[e,t])}function Kd(e="long",t=[2018,2028],s="en-US"){const r=ii(e,t);return g.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function Hd(e,t="en-US"){return g.useMemo(()=>ni(e,t),[e,t])}function zd(e,t="en-US"){const s=g.useMemo(()=>Ld(),[]),r=g.useMemo(()=>ni(e,t),[e,t]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function ai(e,t){const s=ye(e);return g.useMemo(()=>kd(s,t),[t,s])}const wE=(e,t,s,r=[])=>{const o=new Date(e,t,s).getDay();return r.length>0&&r.includes(o)};function Vd(e,t,s="en-US",r=[]){const o=ai(e,t);return g.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:wE(e,t,i,r)})),[r,s,t,o,e])}function Gd(e="en-US",t="short"){return g.useMemo(()=>jd(e,t),[e,t])}function Yd({year:e=new Date().getFullYear(),month:t=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=t,n=new Date(e,o,s);return{formattedDate:je.format(n,r)}}function qd(e,t,s){return g.useMemo(()=>Ud(e,t,s),[e,t,s])}var Wd=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(Wd||{});function EE({locale:e="en-US",date:{year:t=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:o="long",monthFormat:n="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:u=[]}={}}){const[d,h]=g.useState(t),[f,p]=g.useState(c),[b,w]=g.useState(s),[M,_]=g.useState(r);g.useEffect(()=>{h(t)},[t]),g.useEffect(()=>{w(s)},[s]),g.useEffect(()=>{_(r)},[r]);const{yearsArray:F,yearsOptionsArray:Q,monthsArray:D,monthsOptionsArray:I,daysArray:W,daysOptionsArray:B,calendarDayArray:J,dayNamesArray:Ue}=Bd({locale:e,year:d,yearRange:f,month:b,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:$e}=Yd({year:d,month:b,day:M,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:w,setDay:_,nextMonth:()=>{const se=b<11?ye(d):ye(d+1),ce=b<11?b+1:0;if(!ss(se,ce,M)){const Ge=rs(se,ce);_(Ge)}ce===0&&h(se),w(ce)},previousMonth:()=>{const se=ye(b===0?d-1:d),ce=b===0?11:b-1;if(!ss(se,ce,M)){const Ge=rs(se,ce);_(Ge)}ce===11&&h(se),w(ce)},nextYear:()=>{const se=d<f[1]?d+1:f[0],ce=ye(se);if(ss(ce,b,M))h(se);else{const Ge=rs(ye(d+1),b);_(Ge),h(se)}},previousYear:()=>{const se=d>f[0]?d-1:f[0],ce=ye(se);if(ss(ce,b,M))h(se);else{const Ge=rs(ye(d-1),b);_(Ge),h(se)}}},dateState:{year:d,yearRange:f,month:b,day:M,yearsArray:F,yearsOptionsArray:Q,monthsArray:D,monthsOptionsArray:I,daysArray:W,daysOptionsArray:B,calendarDayNames:Ue,calendarDayArray:J,formattedDate:$e}}}function Qd({date:e=new Date,dateFormat:t,timeFormat:s,options:r={}}){const[o,n]=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 e=="string"?je.parseISO(e):e;return g.useEffect(()=>{c?a(""):t?a(je.format(h,t)):d&&a(je.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[c,e,t,h,u,d]),g.useEffect(()=>{s?n(je.format(h,s)):d&&n(je.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[e,s,h,u,d]),{formattedDate:i,formattedTime:o}}const Zd=({secondsFromMidnight:e=0})=>{const[t,s]=g.useState(0),[r,o]=g.useState(0),[n,i]=g.useState(0),[a,c]=g.useState(new Date),{formattedTime:u}=Qd({date:a,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const d=Number(e),h=Math.floor(d/3600),f=Math.floor(d%3600/60),p=d%60;s(h),o(f),i(p);const b=new Date;b.setHours(0,0,0,0);const w=new Date(b.getTime()+d*1e3);c(new Date(w))},[e]),{hours:t,minutes:r,seconds:n,formattedTime:u,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},ME=({configProperty:e})=>{const{value:t}=Pd({configProperty:e}),s=parseInt(t||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=Zd({secondsFromMidnight:s}),c=g.useRef();return g.useEffect(()=>{const u=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{e&&e.updateProperty(u.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[e,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function TE(e,t={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=t;g.useEffect(()=>{const o=()=>{try{e({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[e,s,r])}const _E=e=>T.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),IE=(e=_E)=>{const[t,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=Y(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{c()}},[n,i,e]),g.useEffect(()=>{const c=Y(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&o({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{c()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const a=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&&(n==null||n.setSelectedDateFormat(u))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(c=>c.id))??[],regionModel:n,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:t}}},OE=e=>T.jsx("option",{title:e,value:e,children:e},e),Xd="kos:service:region:settings",Jd="timeZone",SE=`${Xd}-${Jd}`,$E=(e=OE)=>{const[t,s]=g.useState([]),[r,o]=g.useState(""),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=rt.factory(SE)({path:Xd,attribute:Jd});g.useEffect(()=>{const u=Y(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&Ao(n==null?void 0:n.timeZones[0])});return()=>{u()}},[n,i,e]),g.useEffect(()=>{const u=Y(()=>{o(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&&Ao(d)},[]);return{options:t,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:t}}},eh="kos:service:region",th="regionId",CE=`${eh}-${th}`,DE=e=>T.jsx("option",{title:e,value:e,children:e},e),sh=(e=DE)=>{const[t,s]=g.useState([]),[r,o]=g.useState("factory"),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=rt.factory(CE)({path:eh,attribute:th});g.useEffect(()=>{const u=Y(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{u()}},[n,i,e]),g.useEffect(()=>{const u=Y(()=>{o(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&&nd(d)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:t}}},xE=e=>T.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),AE=(e=xE)=>{const[t,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=Y(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{c()}},[n,i,e]),g.useEffect(()=>{const c=Y(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&o({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{c()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const a=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&&(n==null||n.setSelectedTimeFormat(u))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(c=>c.id))??[],regionModel:n,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:t}}},RE=(e,t)=>g.useMemo(()=>dn(e),t),PE={config:{attributes:!0,childList:!0,subtree:!0}};function kE(e,t,s=PE){const[r,o]=g.useState(null);g.useEffect(()=>{if(!t||typeof t!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(t);o(n)},[t,s,o]),g.useEffect(()=>{if(!r)return()=>{};if(!e)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(e,n)}catch(i){m.error(i)}return()=>{r&&r.disconnect()}},[r,e,s])}const rh={validateStart:function(e){return!0},validateStop:function(e){const t=e.event.currentTarget.getBoundingClientRect(),[s,r]=e.xy;return s<t.left||s>t.right||r<t.top||r>t.bottom}},po=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function LE({onPressed:e,onRelease:t,intersectionStrategy:s=rh}){const r=g.useRef(!1),o=ph.useGesture({onDragStart:c=>{po.info("onDragStart",c.type),s.validateStart(c)&&(e&&e(),r.current=!0)},onDrag:c=>{po.info("onDrag",c.type),r.current&&s.validateStop(c)&&(t&&t(),r.current=!1)},onDragEnd:c=>{po.info("onDragEnd",c.type),r.current&&t&&(t(),r.current=!1)}}),n=()=>{e&&e(),r.current=!0},i=()=>{r.current&&t&&(t(),r.current=!1)},a=()=>{r.current&&t&&(t(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const oh=()=>{const[e,t]=g.useState(!1),s=O.getInstance();return g.useEffect(()=>{const r=Y(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{r()}},[s,e]),[e]};function nh(e=!1,t="2-digit"){return g.useMemo(()=>{const s=e?12:24;return Array.from({length:s},(r,o)=>{const n=e&&o===0?12:o%s;return{id:o,label:t==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[t,e])}function Po(e,t="2-digit",s=0,r=0){return g.useMemo(()=>Array.from({length:e},(o,n)=>{const i=String(n+s);return{id:n+r,label:t==="2-digit"?i.padStart(2,"0"):i}}),[e,s,r,t])}function ih(e="en-US"){return g.useMemo(()=>["AM","PM"].map(t=>{const s=new Intl.DateTimeFormat(e,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(t==="AM"?0:12))[2].value;return{id:s,label:s}}),[e])}function ah({formatOptions:{hour12:e=!0,hour:t="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=nh(e,t),i=Po(60,s),a=Po(60,r),c=ih(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function ch(e,t){return je.format(e,t)}function lh({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=g.useState(t),i=g.useCallback(w=>{n(M=>{const _=new Date(M);return _.setHours(Number(w)),_})},[]),a=g.useCallback(w=>{n(M=>{const _=new Date(M);return _.setMinutes(Number(w)),_})},[]),c=g.useCallback(w=>{n(M=>{const _=new Date(M);return _.setSeconds(Number(w)),_})},[]),u=g.useCallback(w=>{const M=new Date(w);n(M)},[]),d=ch(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:b}=ah({formatOptions:e,locale:s});return{amPmOptions:b,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:c,setTime:u,time:new Date(o)}}const FE=e=>{const{regionModel:t}=sh(),s=g.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return lh({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function NE(e){return t=>{const[s]=oh();return s?T.jsx(pd,{message:"Wait a moment while your project reloads..."}):T.jsx(e,{...t})}}const Wi=m.createLogger({name:"studio-properties-service",group:"Services"}),UE="/api/kos/studio/properties",uh=async e=>{if(Wi.debug("sending GET for studio-properties"),!e)throw Wi.error("connectionId is undefined"),new Error("connectionId is undefined");return await Ne.get(UE,{},{destinationAddress:e,timeout:500})},jE=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:uh},Symbol.toStringTag,{value:"Module"}));var BE=Object.getOwnPropertyDescriptor,KE=(e,t,s,r)=>{for(var o=r>1?void 0:r?BE(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const dh="studio-properties-model",HE="/kos/studio/properties",Qi={"kos.studio.tool.legacy":1};let ko=class{constructor(e,t,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=e,this.logger=s.logger,this.data=Te(),this.connectionId=t.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var e;(e=this.unsubscribe)==null||e.call(this)}async initializePropertiesSession(){this.unsubscribe=wt.getInstance().subscribeTopic({topic:HE,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[e,t]=await uh(this.connectionId);if(e){this.logger.error(`Error loading studio-properties: ${e}`),this.data.setValues(Qi);return}if(t){const s=Object.keys(t).reduce((r,o)=>(r[o]=t[o]??o,r),{});this.data.setValues(s??Qi),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(e){return this.data[e]}createObservableProperty(e){return dn(()=>this.get(e))}};ko=KE([A(dh)],ko);const zE=new me({class:ko,type:dh});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>E.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>E.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>Fo.observer});exports.AuthState=Wc;exports.BrowserKosRouter=sl;exports.BrowserRouter=Tn;exports.CanvasDispatcher=Ct;exports.CanvasDispatcherServices=qb;exports.CanvasRenderer=Bn;exports.CanvasStreamer=jw;exports.CanvasStreamerBase=Od;exports.ChildModels=Be;exports.CompanionParentModel=bt;exports.ConfigBean=fs;exports.ContainerAwareSetup=tn;exports.CoreExtensionManager=Vv;exports.CoreModels=qn;exports.CreateModelTranslationsContext=Ed;exports.CreateModelTranslationsProvider=bw;exports.DateDisplayFormat=Wd;exports.DateHelpers=Dh;exports.DependencyLifecycle=H;exports.DependencyModels=k;exports.Device=Mr;exports.DeviceServices=mv;exports.DomIntersectionStrategy=rh;exports.EVENT_KOS_MODEL_READY=Bo;exports.EVENT_TROUBLE_ADDED=fg;exports.EVENT_TROUBLE_REMOVED=pg;exports.EXTENSION_CANVAS_RENDERER=te;exports.EXTENSION_FEATURE_FLAG_RESOLVER=Ga;exports.EXTENSION_TROUBLE_DATA_MAPPER=lr;exports.EXTENSION_TROUBLE_MAPPER=Rs;exports.ErrorBoundaryWithFallback=gd;exports.EventBus=bh;exports.EventBusFunctional=wh;exports.EventBusState=Mh;exports.ExtensionManager=S;exports.FUTURE_CONTAINER_MODEL_TYPE=Dl;exports.FUTURE_MODEL_TYPE=wl;exports.FUTURE_NOT_ASSIGNED=fn;exports.FeatureFlagService=Ya;exports.FetchError=pe;exports.FutureContainerFactory=He;exports.FutureContainerModel=Al;exports.FutureContainerSetup=Xo;exports.FutureEndState=Ke;exports.FutureFactory=Lt;exports.FutureHandler=Rr;exports.FutureManager=Je;exports.FutureModel=Ol;exports.FutureService=os;exports.HEADER_CACHE_CONTROL=sa;exports.HEADER_CONTENT_TYPE=ta;exports.HEADER_DESTINATION_ADDR=Le;exports.HEADER_FOS_REQUEST_ID=ra;exports.HEADER_METHOD=Or;exports.HEADER_ORDERED=Uo;exports.HEADER_REQUEST_ID=Is;exports.HEADER_REQUEST_TYPE=Ie;exports.HEADER_RESPONSE_ID=Sr;exports.HEADER_SOURCE_ADDR=ea;exports.HEADER_TOPIC=Ji;exports.HEADER_URL=At;exports.HEADER_WORK_TRACKER=jo;exports.HttpRouteHandlers=xe;exports.KOS_MODEL_ID=Zs;exports.KeyValue=On;exports.KeyValueServices=cm;exports.Kos=ie;exports.KosConfigPropertySpec=rt;exports.KosContainerIndex=sn;exports.KosContextBean=el;exports.KosContextManager=G;exports.KosCore=O;exports.KosCoreModelPropertyMapper=be;exports.KosDataContainer=un;exports.KosDependencyTypes=rf;exports.KosExpressionEvaluator=Hl;exports.KosExtensionUtils=Ph;exports.KosFeatureFlags=qa;exports.KosFetchMethods=Ac;exports.KosGlobalConfig=Qo;exports.KosHttpRouteManager=nn;exports.KosLog=m;exports.KosLogManager=Gl;exports.KosLogManagerServices=my;exports.KosMockEvents=ia;exports.KosModel=Vc;exports.KosModelCollectionProvider=fw;exports.KosModelContainer=Se;exports.KosModelContext=qr;exports.KosModelEvents=P;exports.KosModelFactory=as;exports.KosModelLoader=vd;exports.KosModelLoaderDisplay=wd;exports.KosModelManager=qc;exports.KosModelProvider=md;exports.KosModelRegistrationFactory=me;exports.KosModelRegistry=xo;exports.KosModelState=v;exports.KosModelSymbol=Zo;exports.KosModelVisitor=Bp;exports.KosObservableData=ac;exports.KosRegistration=ig;exports.KosSingletonRegistration=ag;exports.KosTime=ir;exports.KosTimeContext=ei;exports.KosTimeProvider=Ow;exports.KosTimeServices=Ty;exports.KosTimer=id;exports.KosToken=tl;exports.KosTranslationProvider=Rw;exports.KosTranslations=Cu;exports.KosWSTransportStatus=zc;exports.KosWsEvents=Os;exports.LOADER_FEATURE_FLAG=Gh;exports.LOGIN_HOST=oa;exports.LOGIN_URL=gh;exports.LoadingMessage=pd;exports.LogBlock=vs;exports.LogBlockContainer=zr;exports.LogConfig=is;exports.LogStream=ds;exports.LogStreamContainer=As;exports.LogStreamServices=Py;exports.LoggerSetup=en;exports.MODEL_DELETION_DELAY=Yc;exports.MiddlewareChain=Zc;exports.ModelEffects=Ze;exports.MultipleFutureHandler=uf;exports.NestedModelContext=Wr;exports.NetworkInterface=zn;exports.NetworkInterfaceContainer=Ms;exports.NetworkInterfaceServices=Iv;exports.ObservableData=Te;exports.Ota=dr;exports.OutsideAlerter=Ww;exports.PLUGIN_EXTENSION_NAME=kh;exports.PORT=na;exports.PROFILE_LOG_DEBUG=La;exports.PROFILE_LOG_INFO=Fa;exports.PROFILE_RELAX_STORE_VALIDATION=Fh;exports.PROFILE_TOOLS_PREVIEW=ka;exports.ParentModel=ns;exports.PluginExtensionManager=Lh;exports.ProgressBar=lw;exports.ReferenceConfig=Vs;exports.RegionInfo=re;exports.RegionServices=_g;exports.RegistrationManager=x;exports.Registry=zv;exports.STATUS=No;exports.ServiceFactory=oe;exports.SingletonKosModelRegistrationFactory=Me;exports.SoftwareInfo=hr;exports.SoftwareInfoContext=si;exports.SoftwareInfoProvider=Cw;exports.SoftwareInfoServices=mb;exports.StateBean=Es;exports.StateBeanServices=Eb;exports.StateProp=Fn;exports.StatePropServices=xb;exports.StorageDevice=_r;exports.StorageDeviceContainer=Dt;exports.StorageDeviceServices=Dv;exports.StudioProperties=zE;exports.StudioPropertiesServices=jE;exports.SubscriptionHandlers=ee;exports.TIMER_END=Zn;exports.TIMER_EVENT=Wn;exports.TOPIC_TIMER_TICK_EVENT=Qn;exports.TimerManager=ad;exports.TokenContext=Id;exports.TokenProvider=xw;exports.Topics=us;exports.Trans=oE;exports.TransitionMap=Gs;exports.Transitions=rn;exports.Translation=gr;exports.TranslationContainer=ke;exports.TranslationContainerContext=ri;exports.TranslationContext=Bb;exports.TransportFactory=wo;exports.Trouble=ws;exports.TroubleAwareSetup=Jo;exports.TroubleContainer=St;exports.TroubleServices=Jy;exports.Troubles=fe;exports.UsbUpdate=Yn;exports.UsbUpdateContainer=_s;exports.UsbUpdateServices=Nv;exports.WS_EVENT_TYPE=Du;exports.WebSocketEvents=ls;exports.WebSocketTransport=wt;exports.WsEventFactory=Un;exports.acceptOrgInvitation=fd;exports.addDaysToDate=Sa;exports.addFuture=Ml;exports.addMonthsToDate=Oa;exports.api=Sl;exports.applyMixins=_h;exports.arraysEqual=Ih;exports.buildConfigBeanModel=yg;exports.buildFuture=Mn;exports.buildFutureModel=_l;exports.cancelFuture=Tl;exports.checkAppsStarted=dg;exports.convert=bn;exports.convertFileSizeRaw=Th;exports.convertWithUnits=Dg;exports.createBaseMessage=kc;exports.createBroadcastMessageResponse=Uc;exports.createCancellablePromise=rw;exports.createClient=cn;exports.createFosBaseMessage=Pc;exports.createHeaders=Vt;exports.createKosHtpMessageResponse=jc;exports.createKosMessage=Fc;exports.createKosMessageResponse=Bc;exports.createMessageBody=Ve;exports.createModelDependency=Oc;exports.createOptionKey=Xh;exports.createPropKey=st;exports.createReadableStream=Gt;exports.createStudioMessage=Rc;exports.createStudioMessageRequest=Lc;exports.createStudioMessageResponse=Nc;exports.debounce=Ra;exports.del=tc;exports.deleteFuture=El;exports.destroyKosModel=Xe;exports.evaluateScopes=ul;exports.executeChildrenModelLifecycle=Cc;exports.executeDependentModelLifecycle=zt;exports.executeListLifecycle=$c;exports.extractTrailingWildcard=mc;exports.fetchModel=zw;exports.findModel=yf;exports.findModels=uc;exports.formatDate=Da;exports.formatDateSince=Ia;exports.formatDateTime=Aa;exports.formatTime=xa;exports.get=ec;exports.getAllKosCompanionModels=dc;exports.getCalendarMonthArray=Ud;exports.getConfigBean=ll;exports.getDayStrings=jd;exports.getDays=yE;exports.getDaysArray=kd;exports.getDaysInMonth=Wo;exports.getDependenciesByLifecycle=Sc;exports.getFormattedDate=bE;exports.getFormattedMonth=vE;exports.getFormattedMonthsArray=ni;exports.getFormattedYear=ye;exports.getFormattedYearsArray=Nd;exports.getFutures=Yg;exports.getHttpRouteHandlers=sc;exports.getKosCompanionModel=bf;exports.getKosLocalizationDescriptor=_u;exports.getKosMessageLogging=Ba;exports.getKosModel=lc;exports.getKosModelSync=_e;exports.getKosModelType=mf;exports.getKosSessionKey=Jc;exports.getLastDayOfMonth=rs;exports.getLocalizationDescriptor=Rb;exports.getLogLevel=ja;exports.getLogMessageToStudio=Ka;exports.getMessageBody=vo;exports.getMonthsArray=Ld;exports.getObservableCompanions=vf;exports.getQueryParams=ge;exports.getStartedApps=hg;exports.getTranslations=Tu;exports.getYearsArray=Fd;exports.hasDecimals=al;exports.hasHttpRouteHandlers=Js;exports.hasKosProfile=go;exports.hasTrailingWildcard=yc;exports.hslStringToHex=Qa;exports.hslToHex=Wa;exports.httpDelete=nf;exports.initKosProvider=ww;exports.isBoolean=gn;exports.isKosCompanionTypeFactory=Gc;exports.isKosDataModel=cs;exports.isKosLoggingEnabled=jh;exports.isKosModel=Ee;exports.isKosModelContainer=on;exports.isKosModelReady=er;exports.isLeapYear=qo;exports.isLocalRefId=sg;exports.isNumber=Pr;exports.isPrintable=jf;exports.isTroubleAware=Kb;exports.isValidDate=ss;exports.kosAction=X;exports.kosAutoEffect=Y;exports.kosChild=Oe;exports.kosCompanion=ef;exports.kosComputed=dn;exports.kosConfigBean=kr;exports.kosConfigProperty=jg;exports.kosContainerAware=Ja;exports.kosContext=tf;exports.kosDependency=Rt;exports.kosEffect=nl;exports.kosFuture=Xn;exports.kosFutureAware=sf;exports.kosLogger=af;exports.kosLoggerAware=oc;exports.kosModel=A;exports.kosModelEffect=nc;exports.kosObservable=hn;exports.kosParentAware=xr;exports.kosReference=cf;exports.kosStateBean=Zv;exports.kosStateProp=Xv;exports.kosSubscribe=Af;exports.kosTopicHandler=U;exports.kosTroubleAware=lf;exports.kosWhen=Mo;exports.login=ud;exports.mapConfigBeanModelToDto=pl;exports.mapDataToModel=mo;exports.mapDtoToConfigBeanModel=hl;exports.mapDtoToFutureModel=En;exports.mapDtoToFutureOptions=wn;exports.mapUpdateDtoToConfigBeanModel=fl;exports.modelEventTopicFactory=bc;exports.modelFactory=Pt;exports.modelTypeEventTopicFactory=vc;exports.modifyConfigBean=cl;exports.modifyFuture=qg;exports.pairedClientHeartbeat=Yp;exports.pipe=Xc;exports.post=$s;exports.preloadKosModel=Mf;exports.processId=Ch;exports.processMiddleware=zp;exports.put=of;exports.registerCompanionModel=Ef;exports.registerCoreModels=sd;exports.registerExtensionPoint=Ss;exports.registerHttpRoutes=Jf;exports.registerKosModel=fc;exports.registerLegacyModel=hc;exports.resetKosModel=gf;exports.resetPassword=hd;exports.resolveBaseUrl=Qc;exports.resolveChild=Dc;exports.resolveContainerDeltas=Oh;exports.resolveItemListDeltas=$h;exports.resolveKosCompanion=yo;exports.resolveKosContext=ng;exports.resolveKosProfiles=Ua;exports.resolveListDeltas=Sh;exports.resolveServiceUrl=ae;exports.resolveVariable=Za;exports.retryWithExponentialBackoff=Wp;exports.sendAsyncIntent=lg;exports.sendBroadcastMessage=ip;exports.sendIntent=cg;exports.sendKosHttpMessageResponse=Hc;exports.sendKosMessage=rp;exports.sendKosMessageResponse=Kc;exports.sendRequest=rg;exports.sendStudioMessage=np;exports.sendStudioMessageRequest=op;exports.startPasswordReset=dd;exports.stringComponentInsert=xd;exports.studioAcceptOrgInvitation=sw;exports.studioLogin=Jv;exports.studioResetPassword=tw;exports.studioStartPasswordReset=ew;exports.subscribeStore=Gv;exports.syncPublish=og;exports.transitionToActive=Mc;exports.transitionToInit=Ic;exports.transitionToLoad=_c;exports.transitionToReady=Tc;exports.transitionToUnload=Uf;exports.troubleByTypeReducer=ic;exports.troubleDataFactory=fu;exports.unloadKosModel=pf;exports.updateCompanionModelRegistration=Gp;exports.updateModelRegistration=Vp;exports.updateRegion=nd;exports.updateTimeZone=Ao;exports.useAmPmValues=ih;exports.useCalendarDayArray=qd;exports.useConfigBean=pE;exports.useConfigProperty=Pd;exports.useContextModel=dw;exports.useContextModelHierarchy=bd;exports.useDateArrays=Bd;exports.useDateProps=EE;exports.useDateRelativeConfig=ME;exports.useDateRelativeData=Zd;exports.useDayNames=Gd;exports.useDayOptions=Vd;exports.useDays=ai;exports.useDevice=Sd;exports.useFormattedDate=Yd;exports.useFormattedTime=ch;exports.useFunctionWarmup=TE;exports.useHourValues=nh;exports.useKosCore=Td;exports.useKosDateFormats=IE;exports.useKosModel=Z;exports.useKosRegions=sh;exports.useKosTime=Jn;exports.useKosTimeContext=Sw;exports.useKosTimeFormats=AE;exports.useKosTimeZones=$E;exports.useKosTranslation=cE;exports.useKosTranslationContext=Pw;exports.useLocalComputed=RE;exports.useModelFromHierarchy=gw;exports.useMonths=Hd;exports.useMonthsOptions=zd;exports.useMutationObserver=kE;exports.useNetworkInterfaceContainer=$d;exports.useOta=Cd;exports.usePressGesture=LE;exports.useProjectReload=oh;exports.useRegionTimeProps=FE;exports.useRegionalTimeDate=Qd;exports.useSoftwareInfo=ti;exports.useSoftwareInfoContext=Dw;exports.useStateProperty=Qw;exports.useStorageDeviceContainer=Dd;exports.useSuspenseData=Ro;exports.useTimeOptions=ah;exports.useTimeProps=lh;exports.useTimeValues=Po;exports.useTimer=Xw;exports.useTranslationContainer=Ad;exports.useTroubleContainerModel=oi;exports.useTroubleModel=uE;exports.useTroublePresence=dE;exports.useUsbUpdateContainer=Rd;exports.useYears=ii;exports.useYearsOptions=Kd;exports.uuid=tt;exports.variableToHex=Yh;exports.waitForAppToStart=ug;exports.waitForAppsToStart=ol;exports.waitForRequest=ln;exports.whenReady=ue;exports.withDevice=Hw;exports.withKosTime=Vw;exports.withNetworkInterfaceContainer=Gw;exports.withOta=Yw;exports.withProjectReloading=NE;exports.withSoftwareInfo=$w;exports.withStorageDeviceContainer=Zw;exports.withTranslationContainer=lE;exports.withTroubleContainer=hE;exports.withUsbUpdateContainer=fE;exports.wrapPromise=Go;
|
|
197
|
+
`,Dd=()=>{const e=Tr.type;return Z({modelId:e,modelType:Tr.type,options:{}})};function Yw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Dd();return T.jsx(o,{...r,children:T.jsx(e,{...t,device:s})})}}function qw(e,t,s){const r=new Promise(o=>{I.getInstance().whenReady().then(()=>{const{model:n}=I.getInstance().modelManager.createModelInstance(e,t??e,s);return n.whenReady().then(()=>{o(n.modelData)})})});return Yo(r)}function Ww(e){return t=>{const{model:s,status:r,KosModelLoader:o}=ti();return T.jsx(o,{...r,children:T.jsx(e,{...t,kosTime:s})})}}const xd=()=>{const e=Ts.type;return Z({modelId:e,modelType:Ts.type,options:{}})};function Qw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=xd();return T.jsx(o,{...r,children:T.jsx(e,{...t,networkInterfaceContainer:s})})}}const Ad=()=>{const e=hr.type;return Z({modelId:e,modelType:hr.type,options:{}})};function Zw(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Ad();return T.jsx(o,{...r,children:T.jsx(e,{...t,oTA:s})})}}function Xw(e,t){g.useEffect(()=>{function s(o){e.current&&!e.current.contains(o.target)&&t()}function r(o){o.key==="Escape"&&t()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[e,t])}function Jw(e){const t=g.useRef(null),s=e.onAlert;return Xw(t,s),T.jsx("div",{ref:t,style:{width:"100%"},children:e.children})}const eE=e=>{var u;const{stateProp:t}=e,[s,r]=g.useState((u=e.stateProp)==null?void 0:u.value),[o,n]=g.useState(!1),[i,a]=g.useState(void 0);return g.useEffect(()=>{async function d(h){try{h&&(await ue(h),n(!0))}catch(f){a(f.message)}}d(t)},[t]),g.useEffect(()=>{const d=Y(()=>{t&&o&&r(t.value)});return()=>{d()}},[o,t]),[s,{ready:o,error:i}]},Rd=()=>{const[e,t]=g.useState(!1),[s,r]=g.useState([]),o=Dt.type,n=Z({modelId:o,modelType:Dt.type,options:{}});return g.useEffect(()=>{const i=Y(()=>{var a,c;t(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:e,devices:s}};function tE(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Rd();return T.jsx(o,{...r,children:T.jsx(e,{...t,storageDeviceContainer:s})})}}const po=m.createLogger({name:"use-timer"}),sE=({timerName:e,onTimerExpired:t,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=ud.getTimer(e);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${e} does not exist.`);return}const u=$(Zn,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===e&&(f===Jn?t({name:h,action:f,remainingTime:p,timer:n}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:p,timer:n}))});return o&&n.start(),()=>{u.unsubscribe()}},[o,t,r,e,n]),g.useEffect(()=>{if(!n||!s)return;const u=`${Xn}/${e}`,d=$(u,h=>{const{name:f,remainingTime:p}=h==null?void 0:h.body;f===e&&s({name:f,remainingTime:p,timer:n})});return()=>{d.unsubscribe()}},[s,e,n]);const i=g.useCallback(()=>{n?n.start():po.warn(`Timer with name ${e} does not exist.`)},[n,e]),a=g.useCallback(()=>{n?n.reset():po.warn(`Timer with name ${e} does not exist.`)},[n,e]),c=g.useCallback(()=>{n?n.pause():po.warn(`Timer with name ${e} does not exist.`)},[n,e]);return{timer:n,start:i,reset:a,pause:c}},rE=e=>{const t=/[\\^$.*+?()[\]{}|]/g;return RegExp(t.source).test(e)?e.replace(t,"\\$&"):e},oE=e=>e instanceof RegExp,nE=e=>typeof e=="string",iE=(e,t,s)=>{if(e===""||t==="")return e;let r=t;oE(r)||(r=new RegExp("("+rE(r)+")","gi"));const o=e.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},Pd=(e,t,s)=>{let r=e;return Array.isArray(r)||(r=[r]),r.flatMap(o=>nE(o)?iE(o,t,s):o)};function aE(e,t){let s=e;return Object.entries(t).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=Pd(s,n,(i,a)=>o.type==="br"?T.jsx("br",{}):g.cloneElement(o,{key:`${r}-${a}`},i))}),s}const cE=e=>{const{i18nKey:t,t:s,defaults:r,components:o,values:n={},context:i}=e,a=s(t,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=aE(a,o||{});return T.jsx("span",{className:e.className,children:c})},pt=new Map;function lE(e,t){if(pt.has(e)){const s=pt.get(e);if(s.status==="finished")return s.result;throw s.promise}else{const s=t().then(o=>{pt.set(e,{status:"finished",result:o})},o=>{throw pt.set(e,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw pt.set(e,r),s}}function Po(e,t){return lE(e,t)}const uE=async()=>{const e=await hc(ke.type);return await ue(e.model),e.model},dE=async(e,t,s)=>{const r=e.resolveNamespace(t);await ue(r);for(const o of s){const n=e.resolveNamespace(o);await ue(n),pt.set(o,{status:"finished",result:n})}return r},hE=(e,t)=>{const s=[e].flat(),[r,...o]=s,n=Po(ke.type,uE),i=s.join("__"),a=Po(i,()=>dE(n,r,o)),c=g.useMemo(()=>({exists:d=>{const h=t!=null&&t.keyPrefix?`${t.keyPrefix}.${d}`:d;return a?a.exists(h):!1}}),[t==null?void 0:t.keyPrefix,a]);return{t:g.useCallback((d,h)=>{const f=t!=null&&t.keyPrefix?`${t.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(m.debug(`Translation model ${e} not ready for key: ${f}`),f)},[t==null?void 0:t.keyPrefix,e,a]),i18n:c}},kd=()=>{const e=ke.type;return Z({modelId:e,modelType:ke.type,options:{}})};function fE(e){return t=>{const{model:s,status:r,KosModelLoader:o}=kd();return T.jsx(o,{...r,children:T.jsx(e,{...t,translationContainer:s})})}}const pE=e=>Z({modelId:e,modelType:Es.type}),ii=()=>Z({modelId:St.type,modelType:St.type,options:{}}),gE=({troubleType:e,condition:t})=>{const{model:s}=ii(),[r,o]=g.useState(!1),[n,i]=g.useState([]),a=g.useCallback(()=>{var c,u;return n.length>0&&((c=n[0])!=null&&c.resolvable)?(u=n[0])==null?void 0:u.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>Y(()=>{const u=(e?s==null?void 0:s.troubles.getIndexByKey("byType",e):s==null?void 0:s.troubles.data)||[],d=t?u.filter(t):u;o(d.length>0),i(d)}),[t,s,e]),[r,a,n.length>0?n[0]:void 0,n]};function mE(e){return t=>{const{model:s,status:r,KosModelLoader:o}=ii();return T.jsx(o,{...r,children:T.jsx(e,{...t,troubleContainer:s})})}}const Ld=()=>{const e=Os.type,t=Z({modelId:e,modelType:Os.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=g.useState(!1),[o,n]=g.useState(!1),[i,a]=g.useState([]);return g.useEffect(()=>{const c=Y(()=>{var u,d,h;r(((u=t.model)==null?void 0:u.isUsbInserted)??!1),n(((d=t.model)==null?void 0:d.hasAvailableUpdates)??!1),a(((h=t.model)==null?void 0:h.data)??[])});return()=>{c()}},[t.model]),{...t,inserted:s,updateAvailable:o,updates:i}};function yE(e){return t=>{const{model:s,status:r,KosModelLoader:o}=Ld();return T.jsx(o,{...r,children:T.jsx(e,{...t,usbUpdateContainer:s})})}}const bE=({path:e,propKey:t})=>{const{status:s}=Z({modelType:ps.type,modelId:e,options:{path:e}}),[r,o]=g.useState(!1),[n,i]=g.useState(),[a,c]=g.useState(""),[u,d]=g.useState(),h=f=>{n&&t&&n.updateProperty(t,f)};return g.useEffect(()=>{var f;s.model&&i(s.model),s.model&&t&&((f=s.model)!=null&&f.props.has(t)?c(s.model.props[t]):d(`property ${t} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,t]),g.useEffect(()=>{t&&E.autorun(()=>{const f=n==null?void 0:n.props[t];c(f||"")})},[n,t]),{config:n,ready:r,value:a,error:u,updateValue:h}},vE=(e,t)=>{switch(t.type){case"UPDATE":return t.payload;default:return e}},Fd=({configProperty:e,optionsTransformer:t})=>{const[s,r]=g.useState(!1),[o,n]=g.useState(""),[i,a]=g.useReducer(vE,{value:String(e==null?void 0:e.value),displayValue:e==null?void 0:e.displayValue,significantValue:e==null?void 0:e.significantValue,unit:e==null?void 0:e.unit,options:e==null?void 0:e.options,mappedOptions:[],updateProperty:e==null?void 0:e.updateProperty,displayOptions:e==null?void 0:e.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&&(e==null||e.updateProperty(d))},[e]);return g.useEffect(()=>{async function u(d){try{d&&(await ue(d),r(!0))}catch(h){n(h.message)}}u(e)},[e]),g.useEffect(()=>{const u=Y(()=>{if(e&&s){let d=[];t&&(d=t(e.options)),a({type:"UPDATE",payload:{value:String(e.value),displayValue:e.displayValue,significantValue:e.significantValue,unit:e.unit,options:e.options,mappedOptions:d,updateProperty:e.updateProperty,displayOptions:e==null?void 0:e.displayOptions}})}});return()=>{u()}},[e,t,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:t?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function wE(e,t){const s=t??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return e===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[e]??0}function EE(e,t){return new Date(e,t,0).getDate()}function Nd(e,t){const s=wE(t,e),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function Ud(){return[...Array(12).keys()].map(t=>new Date(0,t).getMonth())}function jd(e=[2018,2028]){const t=[];for(let s=e[0];s<=e[1];s++)t.push(s);return t}function Bd(e,t=[2018,2028]){const s=jd(t);return e==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function ai(e="numeric",t="en-US"){const s=new Intl.DateTimeFormat(t,{month:e,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function ME({locale:e="en-US",year:t,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(t,i,r),c=new Intl.DateTimeFormat(e,{month:o.month}).format(a),u=new Intl.DateTimeFormat(e,{year:o.year}).format(a),d=new Intl.DateTimeFormat(e,{day:o.day}).format(a);return n?n=="MMDDYY"?`${c} ${d} ${u}`:n==="DDMMYY"?`${d} ${c} ${u}`:n==="YYMMDD"?`${u} ${c} ${d}`:`${u} ${d} ${c}`:new Intl.DateTimeFormat(e,o).format(a)}function ye(e){return e.toString().length===2?new Date(Date.parse(`01 Jan 20${e}`)).getFullYear():e}function TE(e){return typeof e=="string"?new Date(Date.parse(`01 ${e.substring(0,3)} 2023`)).getMonth()+1:e}function Kd(e,t,s){const r=ye(t),o=new Date(r,e,1).getDay(),n=new Date(r,e+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function ss(e,t,s){const r=t-1,o=new Date(e,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function rs(e,t){return new Date(e,t,0).getDate()}function Hd(e="en-US",t="short"){const s=new Intl.DateTimeFormat(e,{weekday:t}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function zd({locale:e="en-US",year:t=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:o=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=ci(n,r),u=Gd(n,r,e),d=Vd(i,e),h=Yd(i,e),f=li(t,s),p=qd(t,s,e,o),b=Zd(s,t,p),w=Wd(e,a);return{daysArray:f,monthsArray:d,yearsArray:c,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:b,dayNamesArray:w}}function ci(e="long",t=[2018,2028]){return g.useMemo(()=>Bd(e,t),[e,t])}function Gd(e="long",t=[2018,2028],s="en-US"){const r=ci(e,t);return g.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function Vd(e,t="en-US"){return g.useMemo(()=>ai(e,t),[e,t])}function Yd(e,t="en-US"){const s=g.useMemo(()=>Ud(),[]),r=g.useMemo(()=>ai(e,t),[e,t]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function li(e,t){const s=ye(e);return g.useMemo(()=>Nd(s,t),[t,s])}const _E=(e,t,s,r=[])=>{const o=new Date(e,t,s).getDay();return r.length>0&&r.includes(o)};function qd(e,t,s="en-US",r=[]){const o=li(e,t);return g.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:_E(e,t,i,r)})),[r,s,t,o,e])}function Wd(e="en-US",t="short"){return g.useMemo(()=>Hd(e,t),[e,t])}function Qd({year:e=new Date().getFullYear(),month:t=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=t,n=new Date(e,o,s);return{formattedDate:je.format(n,r)}}function Zd(e,t,s){return g.useMemo(()=>Kd(e,t,s),[e,t,s])}var Xd=(e=>(e.MMDDYY="MMDDYY",e.DDMMYY="DDMMYY",e.YYMMDD="YYMMDD",e.YYDDMM="YYDDMM",e))(Xd||{});function OE({locale:e="en-US",date:{year:t=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:o="long",monthFormat:n="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:u=[]}={}}){const[d,h]=g.useState(t),[f,p]=g.useState(c),[b,w]=g.useState(s),[M,_]=g.useState(r);g.useEffect(()=>{h(t)},[t]),g.useEffect(()=>{w(s)},[s]),g.useEffect(()=>{_(r)},[r]);const{yearsArray:F,yearsOptionsArray:Q,monthsArray:D,monthsOptionsArray:O,daysArray:W,daysOptionsArray:B,calendarDayArray:J,dayNamesArray:Ue}=zd({locale:e,year:d,yearRange:f,month:b,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:$e}=Qd({year:d,month:b,day:M,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:w,setDay:_,nextMonth:()=>{const se=b<11?ye(d):ye(d+1),ce=b<11?b+1:0;if(!ss(se,ce,M)){const Ve=rs(se,ce);_(Ve)}ce===0&&h(se),w(ce)},previousMonth:()=>{const se=ye(b===0?d-1:d),ce=b===0?11:b-1;if(!ss(se,ce,M)){const Ve=rs(se,ce);_(Ve)}ce===11&&h(se),w(ce)},nextYear:()=>{const se=d<f[1]?d+1:f[0],ce=ye(se);if(ss(ce,b,M))h(se);else{const Ve=rs(ye(d+1),b);_(Ve),h(se)}},previousYear:()=>{const se=d>f[0]?d-1:f[0],ce=ye(se);if(ss(ce,b,M))h(se);else{const Ve=rs(ye(d-1),b);_(Ve),h(se)}}},dateState:{year:d,yearRange:f,month:b,day:M,yearsArray:F,yearsOptionsArray:Q,monthsArray:D,monthsOptionsArray:O,daysArray:W,daysOptionsArray:B,calendarDayNames:Ue,calendarDayArray:J,formattedDate:$e}}}function Jd({date:e=new Date,dateFormat:t,timeFormat:s,options:r={}}){const[o,n]=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 e=="string"?je.parseISO(e):e;return g.useEffect(()=>{c?a(""):t?a(je.format(h,t)):d&&a(je.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[c,e,t,h,u,d]),g.useEffect(()=>{s?n(je.format(h,s)):d&&n(je.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[e,s,h,u,d]),{formattedDate:i,formattedTime:o}}const eh=({secondsFromMidnight:e=0})=>{const[t,s]=g.useState(0),[r,o]=g.useState(0),[n,i]=g.useState(0),[a,c]=g.useState(new Date),{formattedTime:u}=Jd({date:a,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const d=Number(e),h=Math.floor(d/3600),f=Math.floor(d%3600/60),p=d%60;s(h),o(f),i(p);const b=new Date;b.setHours(0,0,0,0);const w=new Date(b.getTime()+d*1e3);c(new Date(w))},[e]),{hours:t,minutes:r,seconds:n,formattedTime:u,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},IE=({configProperty:e})=>{const{value:t}=Fd({configProperty:e}),s=parseInt(t||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=eh({secondsFromMidnight:s}),c=g.useRef();return g.useEffect(()=>{const u=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{e&&e.updateProperty(u.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[e,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function SE(e,t={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=t;g.useEffect(()=>{const o=()=>{try{e({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[e,s,r])}const $E=e=>T.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),CE=(e=$E)=>{const[t,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=Y(()=>{s((n==null?void 0:n.dateFormatOptions.map(e))||[])});return()=>{c()}},[n,i,e]),g.useEffect(()=>{const c=Y(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&o({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{c()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const a=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&&(n==null||n.setSelectedDateFormat(u))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(c=>c.id))??[],regionModel:n,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:t}}},DE=e=>T.jsx("option",{title:e,value:e,children:e},e),th="kos:service:region:settings",sh="timeZone",xE=`${th}-${sh}`,AE=(e=DE)=>{const[t,s]=g.useState([]),[r,o]=g.useState(""),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=rt.factory(xE)({path:th,attribute:sh});g.useEffect(()=>{const u=Y(()=>{s((n==null?void 0:n.timeZones.map(e))||[]),n!=null&&n.timeZones.length&&Ro(n==null?void 0:n.timeZones[0])});return()=>{u()}},[n,i,e]),g.useEffect(()=>{const u=Y(()=>{o(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&&Ro(d)},[]);return{options:t,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:t}}},rh="kos:service:region",oh="regionId",RE=`${rh}-${oh}`,PE=e=>T.jsx("option",{title:e,value:e,children:e},e),nh=(e=PE)=>{const[t,s]=g.useState([]),[r,o]=g.useState("factory"),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=rt.factory(RE)({path:rh,attribute:oh});g.useEffect(()=>{const u=Y(()=>{s((n==null?void 0:n.availableRegions.map(e))||[])});return()=>{u()}},[n,i,e]),g.useEffect(()=>{const u=Y(()=>{o(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&&cd(d)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:t}}},kE=e=>T.jsx("option",{title:e.id,value:e.format,children:e.format},e.id),LE=(e=kE)=>{const[t,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const c=Y(()=>{s((n==null?void 0:n.timeFormatOptions.map(e))||[])});return()=>{c()}},[n,i,e]),g.useEffect(()=>{const c=Y(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&o({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{c()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const a=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&&(n==null||n.setSelectedTimeFormat(u))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(c=>c.id))??[],regionModel:n,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:t}}},FE=(e,t)=>g.useMemo(()=>fn(e),t),NE={config:{attributes:!0,childList:!0,subtree:!0}};function UE(e,t,s=NE){const[r,o]=g.useState(null);g.useEffect(()=>{if(!t||typeof t!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(t);o(n)},[t,s,o]),g.useEffect(()=>{if(!r)return()=>{};if(!e)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(e,n)}catch(i){m.error(i)}return()=>{r&&r.disconnect()}},[r,e,s])}const ih={validateStart:function(e){return!0},validateStop:function(e){const t=e.event.currentTarget.getBoundingClientRect(),[s,r]=e.xy;return s<t.left||s>t.right||r<t.top||r>t.bottom}},go=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function jE({onPressed:e,onRelease:t,intersectionStrategy:s=ih}){const r=g.useRef(!1),o=yh.useGesture({onDragStart:c=>{go.info("onDragStart",c.type),s.validateStart(c)&&(e&&e(),r.current=!0)},onDrag:c=>{go.info("onDrag",c.type),r.current&&s.validateStop(c)&&(t&&t(),r.current=!1)},onDragEnd:c=>{go.info("onDragEnd",c.type),r.current&&t&&(t(),r.current=!1)}}),n=()=>{e&&e(),r.current=!0},i=()=>{r.current&&t&&(t(),r.current=!1)},a=()=>{r.current&&t&&(t(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const ah=()=>{const[e,t]=g.useState(!1),s=I.getInstance();return g.useEffect(()=>{const r=Y(()=>{s&&s.reloading!==e&&t(s.reloading)});return()=>{r()}},[s,e]),[e]};function ch(e=!1,t="2-digit"){return g.useMemo(()=>{const s=e?12:24;return Array.from({length:s},(r,o)=>{const n=e&&o===0?12:o%s;return{id:o,label:t==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[t,e])}function ko(e,t="2-digit",s=0,r=0){return g.useMemo(()=>Array.from({length:e},(o,n)=>{const i=String(n+s);return{id:n+r,label:t==="2-digit"?i.padStart(2,"0"):i}}),[e,s,r,t])}function lh(e="en-US"){return g.useMemo(()=>["AM","PM"].map(t=>{const s=new Intl.DateTimeFormat(e,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(t==="AM"?0:12))[2].value;return{id:s,label:s}}),[e])}function uh({formatOptions:{hour12:e=!0,hour:t="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=ch(e,t),i=ko(60,s),a=ko(60,r),c=lh(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function dh(e,t){return je.format(e,t)}function hh({formatOptions:e,initialDate:t=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=g.useState(t),i=g.useCallback(w=>{n(M=>{const _=new Date(M);return _.setHours(Number(w)),_})},[]),a=g.useCallback(w=>{n(M=>{const _=new Date(M);return _.setMinutes(Number(w)),_})},[]),c=g.useCallback(w=>{n(M=>{const _=new Date(M);return _.setSeconds(Number(w)),_})},[]),u=g.useCallback(w=>{const M=new Date(w);n(M)},[]),d=dh(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:b}=uh({formatOptions:e,locale:s});return{amPmOptions:b,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:c,setTime:u,time:new Date(o)}}const BE=e=>{const{regionModel:t}=nh(),s=g.useMemo(()=>({hour12:t==null?void 0:t.is12HourTimeFormat}),[t==null?void 0:t.is12HourTimeFormat]);return hh({...e,locale:t==null?void 0:t.regionId,format:t==null?void 0:t.selectedTimeFormat,formatOptions:s})};function KE(e){return t=>{const[s]=ah();return s?T.jsx(yd,{message:"Wait a moment while your project reloads..."}):T.jsx(e,{...t})}}const Zi=m.createLogger({name:"studio-properties-service",group:"Services"}),HE="/api/kos/studio/properties",fh=async e=>{if(Zi.debug("sending GET for studio-properties"),!e)throw Zi.error("connectionId is undefined"),new Error("connectionId is undefined");return await Ne.get(HE,{},{destinationAddress:e,timeout:500})},zE=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:fh},Symbol.toStringTag,{value:"Module"}));var GE=Object.getOwnPropertyDescriptor,VE=(e,t,s,r)=>{for(var o=r>1?void 0:r?GE(t,s):t,n=e.length-1,i;n>=0;n--)(i=e[n])&&(o=i(o)||o);return o};const ph="studio-properties-model",YE="/kos/studio/properties",Xi={"kos.studio.tool.legacy":1};let Lo=class{constructor(e,t,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=e,this.logger=s.logger,this.data=Te(),this.connectionId=t.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var e;(e=this.unsubscribe)==null||e.call(this)}async initializePropertiesSession(){this.unsubscribe=wt.getInstance().subscribeTopic({topic:YE,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[e,t]=await fh(this.connectionId);if(e){this.logger.error(`Error loading studio-properties: ${e}`),this.data.setValues(Xi);return}if(t){const s=Object.keys(t).reduce((r,o)=>(r[o]=t[o]??o,r),{});this.data.setValues(s??Xi),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(e){return this.data[e]}createObservableProperty(e){return fn(()=>this.get(e))}};Lo=VE([A(ph)],Lo);const qE=new me({class:Lo,type:ph});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>E.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>E.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>No.observer});exports.AuthState=Xc;exports.BrowserKosRouter=nl;exports.BrowserRouter=On;exports.CanvasDispatcher=Ct;exports.CanvasDispatcherServices=Xb;exports.CanvasRenderer=Hn;exports.CanvasStreamer=zw;exports.CanvasStreamerBase=Cd;exports.ChildModels=Be;exports.CompanionParentModel=bt;exports.ConfigBean=ps;exports.ContainerAwareSetup=rn;exports.CoreExtensionManager=Wv;exports.CoreModels=Qn;exports.CreateModelTranslationsContext=_d;exports.CreateModelTranslationsProvider=Mw;exports.DateDisplayFormat=Xd;exports.DateHelpers=Rh;exports.DependencyLifecycle=H;exports.DependencyModels=k;exports.Device=Tr;exports.DeviceServices=wv;exports.DomIntersectionStrategy=ih;exports.EVENT_KOS_MODEL_READY=Ko;exports.EVENT_TROUBLE_ADDED=yg;exports.EVENT_TROUBLE_REMOVED=bg;exports.EXTENSION_CANVAS_RENDERER=te;exports.EXTENSION_FEATURE_FLAG_RESOLVER=qa;exports.EXTENSION_TROUBLE_DATA_MAPPER=ur;exports.EXTENSION_TROUBLE_MAPPER=Ps;exports.ErrorBoundaryWithFallback=bd;exports.EventBus=Eh;exports.EventBusFunctional=Th;exports.EventBusState=Oh;exports.ExtensionManager=S;exports.FUTURE_CONTAINER_MODEL_TYPE=Rl;exports.FUTURE_MODEL_TYPE=Tl;exports.FUTURE_NOT_ASSIGNED=gn;exports.FeatureFlagService=Wa;exports.FetchError=pe;exports.FutureAliases=as;exports.FutureContainerFactory=He;exports.FutureContainerModel=kl;exports.FutureContainerSetup=Jo;exports.FutureEndState=Ke;exports.FutureFactory=Lt;exports.FutureHandler=Pr;exports.FutureManager=Je;exports.FutureModel=Cl;exports.FutureService=os;exports.HEADER_CACHE_CONTROL=oa;exports.HEADER_CONTENT_TYPE=ra;exports.HEADER_DESTINATION_ADDR=Le;exports.HEADER_FOS_REQUEST_ID=na;exports.HEADER_METHOD=Sr;exports.HEADER_ORDERED=jo;exports.HEADER_REQUEST_ID=Is;exports.HEADER_REQUEST_TYPE=Oe;exports.HEADER_RESPONSE_ID=$r;exports.HEADER_SOURCE_ADDR=sa;exports.HEADER_TOPIC=ta;exports.HEADER_URL=At;exports.HEADER_WORK_TRACKER=Bo;exports.HttpRouteHandlers=xe;exports.KOS_MODEL_ID=Xs;exports.KeyValue=$n;exports.KeyValueServices=hm;exports.Kos=ie;exports.KosConfigPropertySpec=rt;exports.KosContainerIndex=on;exports.KosContextBean=rl;exports.KosContextManager=V;exports.KosCore=I;exports.KosCoreModelPropertyMapper=be;exports.KosDataContainer=hn;exports.KosDependencyTypes=cf;exports.KosExpressionEvaluator=Vl;exports.KosExtensionUtils=Fh;exports.KosFeatureFlags=Qa;exports.KosFetchMethods=kc;exports.KosGlobalConfig=Zo;exports.KosHttpRouteManager=cn;exports.KosLog=m;exports.KosLogManager=Wl;exports.KosLogManagerServices=wy;exports.KosMockEvents=ca;exports.KosModel=qc;exports.KosModelCollectionProvider=yw;exports.KosModelContainer=Se;exports.KosModelContext=Wr;exports.KosModelEvents=P;exports.KosModelFactory=cs;exports.KosModelLoader=Md;exports.KosModelLoaderDisplay=Td;exports.KosModelManager=Zc;exports.KosModelProvider=vd;exports.KosModelRegistrationFactory=me;exports.KosModelRegistry=Ao;exports.KosModelState=v;exports.KosModelSymbol=Xo;exports.KosModelVisitor=Gp;exports.KosObservableData=uc;exports.KosRegistration=ug;exports.KosSingletonRegistration=dg;exports.KosTime=ar;exports.KosTimeContext=si;exports.KosTimeProvider=Dw;exports.KosTimeServices=Sy;exports.KosTimer=ld;exports.KosToken=ol;exports.KosTranslationProvider=Fw;exports.KosTranslations=Au;exports.KosWSTransportStatus=Yc;exports.KosWsEvents=Ss;exports.LOADER_FEATURE_FLAG=Wh;exports.LOGIN_HOST=ia;exports.LOGIN_URL=bh;exports.LoadingMessage=yd;exports.LogBlock=ws;exports.LogBlockContainer=Gr;exports.LogConfig=is;exports.LogStream=hs;exports.LogStreamContainer=Rs;exports.LogStreamServices=Ny;exports.LoggerSetup=sn;exports.MODEL_DELETION_DELAY=Qc;exports.MiddlewareChain=el;exports.ModelEffects=Ze;exports.MultipleFutureContainerSetup=en;exports.MultipleFutureHandler=cc;exports.NestedModelContext=Qr;exports.NetworkInterface=Vn;exports.NetworkInterfaceContainer=Ts;exports.NetworkInterfaceServices=Cv;exports.ObservableData=Te;exports.Ota=hr;exports.OutsideAlerter=Jw;exports.PLUGIN_EXTENSION_NAME=Nh;exports.PORT=aa;exports.PROFILE_LOG_DEBUG=Na;exports.PROFILE_LOG_INFO=Ua;exports.PROFILE_RELAX_STORE_VALIDATION=jh;exports.PROFILE_TOOLS_PREVIEW=Fa;exports.ParentModel=ns;exports.PluginExtensionManager=Uh;exports.ProgressBar=fw;exports.ReferenceConfig=Vs;exports.RegionInfo=re;exports.RegionServices=$g;exports.RegistrationManager=x;exports.Registry=qv;exports.STATUS=Uo;exports.ServiceFactory=oe;exports.SingletonKosModelRegistrationFactory=Me;exports.SoftwareInfo=fr;exports.SoftwareInfoContext=oi;exports.SoftwareInfoProvider=Rw;exports.SoftwareInfoServices=wb;exports.StateBean=Ms;exports.StateBeanServices=Ob;exports.StateProp=Un;exports.StatePropServices=kb;exports.StorageDevice=Or;exports.StorageDeviceContainer=Dt;exports.StorageDeviceServices=Pv;exports.StudioProperties=qE;exports.StudioPropertiesServices=zE;exports.SubscriptionHandlers=ee;exports.TIMER_END=Jn;exports.TIMER_EVENT=Zn;exports.TOPIC_TIMER_TICK_EVENT=Xn;exports.TimerManager=ud;exports.TokenContext=$d;exports.TokenProvider=kw;exports.Topics=ds;exports.Trans=cE;exports.TransitionMap=Ys;exports.Transitions=nn;exports.Translation=mr;exports.TranslationContainer=ke;exports.TranslationContainerContext=ni;exports.TranslationContext=Gb;exports.TransportFactory=Eo;exports.Trouble=Es;exports.TroubleAwareSetup=tn;exports.TroubleContainer=St;exports.TroubleServices=rb;exports.Troubles=fe;exports.UsbUpdate=Wn;exports.UsbUpdateContainer=Os;exports.UsbUpdateServices=Kv;exports.WS_EVENT_TYPE=Ru;exports.WebSocketEvents=us;exports.WebSocketTransport=wt;exports.WsEventFactory=Bn;exports.acceptOrgInvitation=md;exports.addDaysToDate=Ca;exports.addFuture=Ol;exports.addMonthsToDate=$a;exports.api=Dl;exports.applyMixins=Sh;exports.arraysEqual=$h;exports.buildConfigBeanModel=Eg;exports.buildFuture=_n;exports.buildFutureModel=Sl;exports.cancelFuture=Il;exports.checkAppsStarted=gg;exports.convert=wn;exports.convertFileSizeRaw=Ih;exports.convertWithUnits=Pg;exports.createBaseMessage=Nc;exports.createBroadcastMessageResponse=Kc;exports.createCancellablePromise=aw;exports.createClient=un;exports.createFosBaseMessage=Fc;exports.createHeaders=Gt;exports.createKosHtpMessageResponse=Hc;exports.createKosMessage=jc;exports.createKosMessageResponse=zc;exports.createMessageBody=Ge;exports.createModelDependency=Cc;exports.createOptionKey=tf;exports.createPropKey=st;exports.createReadableStream=Vt;exports.createStudioMessage=Lc;exports.createStudioMessageRequest=Uc;exports.createStudioMessageResponse=Bc;exports.debounce=ka;exports.del=rc;exports.deleteFuture=_l;exports.destroyKosModel=Xe;exports.evaluateScopes=fl;exports.executeChildrenModelLifecycle=Ac;exports.executeDependentModelLifecycle=zt;exports.executeListLifecycle=xc;exports.extractTrailingWildcard=vc;exports.fetchModel=qw;exports.findModel=wf;exports.findModels=fc;exports.formatDate=Aa;exports.formatDateSince=Sa;exports.formatDateTime=Pa;exports.formatTime=Ra;exports.get=sc;exports.getAllKosCompanionModels=pc;exports.getCalendarMonthArray=Kd;exports.getConfigBean=hl;exports.getDayStrings=Hd;exports.getDays=EE;exports.getDaysArray=Nd;exports.getDaysInMonth=Qo;exports.getDependenciesByLifecycle=Dc;exports.getFormattedDate=ME;exports.getFormattedMonth=TE;exports.getFormattedMonthsArray=ai;exports.getFormattedYear=ye;exports.getFormattedYearsArray=Bd;exports.getFutures=Zg;exports.getHttpRouteHandlers=oc;exports.getKosCompanionModel=Ef;exports.getKosLocalizationDescriptor=Su;exports.getKosMessageLogging=Ha;exports.getKosModel=hc;exports.getKosModelSync=_e;exports.getKosModelType=vf;exports.getKosSessionKey=sl;exports.getLastDayOfMonth=rs;exports.getLocalizationDescriptor=Fb;exports.getLogLevel=Ka;exports.getLogMessageToStudio=za;exports.getMessageBody=wo;exports.getMonthsArray=Ud;exports.getObservableCompanions=Mf;exports.getQueryParams=ge;exports.getStartedApps=mg;exports.getTranslations=Iu;exports.getYearsArray=jd;exports.hasDecimals=ul;exports.hasHttpRouteHandlers=er;exports.hasKosProfile=mo;exports.hasTrailingWildcard=wc;exports.hslStringToHex=Xa;exports.hslToHex=Za;exports.httpDelete=uf;exports.initKosProvider=_w;exports.isBoolean=yn;exports.isKosCompanionTypeFactory=Wc;exports.isKosDataModel=ls;exports.isKosLoggingEnabled=Hh;exports.isKosModel=Ee;exports.isKosModelContainer=an;exports.isKosModelReady=tr;exports.isLeapYear=Wo;exports.isLocalRefId=ig;exports.isNumber=kr;exports.isPrintable=zf;exports.isTroubleAware=Vb;exports.isValidDate=ss;exports.kosAction=X;exports.kosAutoEffect=Y;exports.kosChild=Ie;exports.kosCompanion=rf;exports.kosComputed=fn;exports.kosConfigBean=Lr;exports.kosConfigProperty=zg;exports.kosContainerAware=tc;exports.kosContext=of;exports.kosDependency=Rt;exports.kosEffect=cl;exports.kosFuture=ei;exports.kosFutureAware=nf;exports.kosLogger=df;exports.kosLoggerAware=ic;exports.kosModel=A;exports.kosModelEffect=ac;exports.kosMultipleFutureAware=af;exports.kosObservable=pn;exports.kosParentAware=Ar;exports.kosReference=hf;exports.kosStateBean=tw;exports.kosStateProp=sw;exports.kosSubscribe=Lf;exports.kosTopicHandler=U;exports.kosTroubleAware=ff;exports.kosWhen=To;exports.login=fd;exports.mapConfigBeanModelToDto=yl;exports.mapDataToModel=yo;exports.mapDtoToConfigBeanModel=gl;exports.mapDtoToFutureModel=Tn;exports.mapDtoToFutureOptions=Mn;exports.mapUpdateDtoToConfigBeanModel=ml;exports.modelEventTopicFactory=Ec;exports.modelFactory=Pt;exports.modelTypeEventTopicFactory=Mc;exports.modifyConfigBean=dl;exports.modifyFuture=Xg;exports.pairedClientHeartbeat=Zp;exports.pipe=tl;exports.post=Cs;exports.preloadKosModel=Of;exports.processId=Ah;exports.processMiddleware=qp;exports.put=lf;exports.registerCompanionModel=_f;exports.registerCoreModels=nd;exports.registerExtensionPoint=$s;exports.registerHttpRoutes=rp;exports.registerKosModel=mc;exports.registerLegacyModel=gc;exports.resetKosModel=bf;exports.resetPassword=gd;exports.resolveBaseUrl=Jc;exports.resolveChild=Rc;exports.resolveContainerDeltas=Ch;exports.resolveItemListDeltas=xh;exports.resolveKosCompanion=bo;exports.resolveKosContext=lg;exports.resolveKosProfiles=Ba;exports.resolveListDeltas=Dh;exports.resolveServiceUrl=ae;exports.resolveVariable=Ja;exports.retryWithExponentialBackoff=Jp;exports.sendAsyncIntent=fg;exports.sendBroadcastMessage=up;exports.sendIntent=hg;exports.sendKosHttpMessageResponse=Vc;exports.sendKosMessage=ap;exports.sendKosMessageResponse=Gc;exports.sendRequest=ag;exports.sendStudioMessage=lp;exports.sendStudioMessageRequest=cp;exports.startPasswordReset=pd;exports.stringComponentInsert=Pd;exports.studioAcceptOrgInvitation=iw;exports.studioLogin=rw;exports.studioResetPassword=nw;exports.studioStartPasswordReset=ow;exports.subscribeStore=Qv;exports.syncPublish=cg;exports.transitionToActive=Oc;exports.transitionToInit=$c;exports.transitionToLoad=Sc;exports.transitionToReady=Ic;exports.transitionToUnload=Hf;exports.troubleByTypeReducer=lc;exports.troubleDataFactory=mu;exports.unloadKosModel=yf;exports.updateCompanionModelRegistration=Qp;exports.updateModelRegistration=Wp;exports.updateRegion=cd;exports.updateTimeZone=Ro;exports.useAmPmValues=lh;exports.useCalendarDayArray=Zd;exports.useConfigBean=bE;exports.useConfigProperty=Fd;exports.useContextModel=gw;exports.useContextModelHierarchy=Ed;exports.useDateArrays=zd;exports.useDateProps=OE;exports.useDateRelativeConfig=IE;exports.useDateRelativeData=eh;exports.useDayNames=Wd;exports.useDayOptions=qd;exports.useDays=li;exports.useDevice=Dd;exports.useFormattedDate=Qd;exports.useFormattedTime=dh;exports.useFunctionWarmup=SE;exports.useHourValues=ch;exports.useKosCore=Id;exports.useKosDateFormats=CE;exports.useKosModel=Z;exports.useKosRegions=nh;exports.useKosTime=ti;exports.useKosTimeContext=xw;exports.useKosTimeFormats=LE;exports.useKosTimeZones=AE;exports.useKosTranslation=hE;exports.useKosTranslationContext=Nw;exports.useLocalComputed=FE;exports.useModelFromHierarchy=vw;exports.useMonths=Vd;exports.useMonthsOptions=Yd;exports.useMutationObserver=UE;exports.useNetworkInterfaceContainer=xd;exports.useOta=Ad;exports.usePressGesture=jE;exports.useProjectReload=ah;exports.useRegionTimeProps=BE;exports.useRegionalTimeDate=Jd;exports.useSoftwareInfo=ri;exports.useSoftwareInfoContext=Pw;exports.useStateProperty=eE;exports.useStorageDeviceContainer=Rd;exports.useSuspenseData=Po;exports.useTimeOptions=uh;exports.useTimeProps=hh;exports.useTimeValues=ko;exports.useTimer=sE;exports.useTranslationContainer=kd;exports.useTroubleContainerModel=ii;exports.useTroubleModel=pE;exports.useTroublePresence=gE;exports.useUsbUpdateContainer=Ld;exports.useYears=ci;exports.useYearsOptions=Gd;exports.uuid=tt;exports.variableToHex=Qh;exports.waitForAppToStart=pg;exports.waitForAppsToStart=al;exports.waitForRequest=dn;exports.whenReady=ue;exports.withDevice=Yw;exports.withKosTime=Ww;exports.withNetworkInterfaceContainer=Qw;exports.withOta=Zw;exports.withProjectReloading=KE;exports.withSoftwareInfo=Aw;exports.withStorageDeviceContainer=tE;exports.withTranslationContainer=fE;exports.withTroubleContainer=mE;exports.withUsbUpdateContainer=yE;exports.wrapPromise=Yo;
|
|
198
198
|
//# sourceMappingURL=index.cjs.map
|