@kosdev-code/kos-ui-sdk 2.0.34 → 2.0.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +40 -40
- package/index.cjs.map +1 -1
- package/index.js +4247 -4016
- package/index.js.map +1 -1
- package/models/models/canvas-dispatcher/canvas-dispatcher-model.d.ts.map +1 -1
- package/models/models/canvas-dispatcher/types/index.d.ts +24 -1
- package/models/models/canvas-dispatcher/utils/renderers/matrix-renderer.d.ts +16 -1
- package/models/models/canvas-dispatcher/utils/renderers/matrix-renderer.d.ts.map +1 -1
- package/models/models/canvas-dispatcher/utils/renderers/renderer-factory.d.ts.map +1 -1
- package/models/models/canvas-dispatcher/utils/renderers/scrolling-image-renderer.d.ts +38 -0
- package/models/models/canvas-dispatcher/utils/renderers/scrolling-image-renderer.d.ts.map +1 -0
- package/models/models/canvas-renderer/canvas-renderer-model.d.ts +4 -1
- package/models/models/canvas-renderer/canvas-renderer-model.d.ts.map +1 -1
- package/package.json +2 -2
package/index.cjs
CHANGED
|
@@ -1,80 +1,80 @@
|
|
|
1
|
-
"use strict";var iu=Object.defineProperty;var au=(t,e,s)=>e in t?iu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var l=(t,e,s)=>(au(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("loglevel"),M=require("mobx"),y=require("robot3"),$e=require("date-fns"),_=require("@emotion/react/jsx-runtime"),oo=require("@emotion/styled"),si=require("react-dom"),Fe=require("@emotion/react"),g=require("react"),no=require("mobx-react-lite"),cu=require("@use-gesture/react"),sr="method",ri="topic",lt="url",es="request-id",rr="response-id",io="status",Ie="dst-addr",oi="src-addr",me="type",ao="ordered",co="tracker",ni="Content-Type",ii="Cache-Control",ai="requestId",ci=process.env.KOS_LOGIN_URL||"http://localhost",li=process.env.KOS_APP_PORT||"8080",lu=`${ci}:${li}`,Ds="{MODEL_ID}";var ts=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(ts||{}),di=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(di||{});const lo="/kos/model/ready/";$.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const k=globalThis.kos.subscriptions,du=()=>Symbol("eventKey");function uo(t){return k[t]&&Object.getOwnPropertySymbols(k[t]).length>0}function O(t,e){const s=du();return k[t]||($.debug(`Initializing subscription for ${t}`),k[t]={}),$.debug(`Subscribing to ${t} with id ${s.toString()}`),k[t][s]=e,{count:k[t]?Object.getOwnPropertySymbols(k[t]).length:0,unsubscribe:()=>($.debug(`Unsubscribing from ${t} with id ${s.toString()}`),k[t]&&k[t][s]&&delete k[t][s],k[t]&&Object.getOwnPropertySymbols(k[t]).length===0&&delete k[t],{count:k[t]?Object.getOwnPropertySymbols(k[t]).length:0})}}function U(t,e,s={}){if(!k[t]||Object.getOwnPropertySymbols(k[t]).length===0)return $.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(k[t]).length;return Object.getOwnPropertySymbols(k[t]).forEach(o=>{if(s.sync){const n=s.sync;$.debug(`Performing sync publish for ${t} with sync id ${n}`),k[t][o]({body:e,headers:s}).then(i=>{$.debug(`Response recieved for ${n}, publishing back to source.`),U(n,i)})}else $.debug(`Performing async publish for ${t}`),k[t][o]({body:e,headers:s})}),{eventType:t,subscribers:r}}function uu(){$.warn("Resetting event bus"),Object.keys(k).forEach(t=>delete k[t])}function ui(t,e){const s=O(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function ho(t,e){return new Promise((s,r)=>{let o=null;const n=ui(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const hu=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:uo,once:ui,publish:U,reset:uu,subscribe:O,waitFor:ho},Symbol.toStringTag,{value:"Module"}));function or(t,e){const s=O(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function nr(t,e){return new Promise((s,r)=>{let o=null;const n=or(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function hi(t,e){const s=t.map(r=>nr(r,e));return Promise.all(s)}function gi(t,e){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};t.forEach(c=>{const d=or(c,u=>{i||(i=!0,a(),s({eventType:c,data:u}))});o.push(d)}),e&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function fi(t,e,s){return O(t,o=>{o&&e(o)&&s(o)}).unsubscribe}function pi(t,e,s){return O(t,o=>{if(o){const n=e(o);s(n)}}).unsubscribe}function mi(t,e,s){let r=null;const o=O(t,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},e)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function yi(t,e,s){let r=0,o=null;const n=O(t,i=>{const a=Date.now(),c=a-r;c>=e?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},e-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function bi(t,e,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=O(t,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},e)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function go(t,e=1){const s=[];return O(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),O(t,r))}}function wi(t,e){const s=t.map(r=>O(r,o=>{o&&e(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function vi(t,e){let s=t;const r=[],o=new Set;return Object.values(e).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=O(n,a=>{const c=e[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function Mi(t,e,s,r){const o=nr(e,r);return U(t,s),o}async function*Ei(t){const e=[],s=[],r=O(t,o=>{o&&(s.length>0?s.shift()(o):e.push(o))});try{for(;;)e.length>0?yield e.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const gu={once:or,waitFor:nr,waitForAll:hi,race:gi,filter:fi,map:pi,debounce:mi,throttle:yi,buffer:bi,replay:go,merge:wi,stateMachine:vi,request:Mi,eventIterator:Ei},fu=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:gu,buffer:bi,debounce:mi,eventIterator:Ei,filter:fi,map:pi,merge:wi,once:or,race:gi,replay:go,request:Mi,stateMachine:vi,throttle:yi,waitFor:nr,waitForAll:hi},Symbol.toStringTag,{value:"Module"}));async function ir(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=e,i=ho(t,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(u=>{setTimeout(()=>u(c),100)})])}function _i(t,e,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=O(t,a=>{a&&(n=!0,e(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||e(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function Ti(t,e){let s;const r=new Set,o=async()=>{try{typeof e=="string"?s=await(await fetch(e)).json():s=await e(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};O(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let n=!1;const i=()=>{n||(n=!0,o())};return{get state(){return s},async getState(){return i(),s===void 0&&await new Promise(a=>{const c=()=>{s!==void 0?a():setTimeout(c,10)};c()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function fo(t,e){if(typeof t=="string")return ir(t,e);const s=t,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=e,i=await r(),a=e.transformState?e.transformState(i):i;if(o&&o(a))return a;const c=s.map(u=>ho(u,n)),d=await Promise.all(c);return d[d.length-1]}function Ii(t,e,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=O(t,async d=>{if(d){if(n){const u=n(d);if(i.has(u))return;i.add(u),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await e(d)}}),c=setInterval(async()=>{try{const d=await r(),u=Array.isArray(d)?d:[d];for(const h of u)if(n){const f=n(h);i.has(f)||(i.add(f),await e(h))}else await e(h)}catch(d){console.error("Failed to fetch missed events:",d)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function Oi(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(u){if(a.state==="connected"&&a.data)return a.data;const h=await ir(e,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:u});return a.state="connected",a.data=h,d(),h},subscribe(u){return c.add(u),u(a),()=>{c.delete(u)}},async reconnect(){a.state="connecting",d();try{const u=await n();a.state="connected",a.data=u,d()}catch{a.state="error",d(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,d=()=>{c.forEach(u=>u(a))};return O(e,u=>{a.state="connected",u!=null&&u.body&&(a.data=u.body),d()}),O(s,()=>{a.state="disconnected",d(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&O(r,()=>{a.state="error",d()}),o&&O(o,u=>{u!=null&&u.body&&a.state==="connected"&&(a.data=u.body,d())}),a.reconnect(),a}const pu={waitForOrGetState:ir,subscribeWithInitialState:_i,createStatefulEventStream:Ti,waitForAllWithState:fo,createResilientEventHandler:Ii,createConnectionStateManager:Oi},mu=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:pu,createConnectionStateManager:Oi,createResilientEventHandler:Ii,createStatefulEventStream:Ti,subscribeWithInitialState:_i,waitForAllWithState:fo,waitForOrGetState:ir},Symbol.toStringTag,{value:"Module"})),yu=(t,e=0)=>{if(!+t)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=e<0?0:e,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(t)/Math.log(s)),i=parseFloat((t/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function po(t){let e="pending",s;const r=t.then(n=>{e="success",s=n},n=>{e="error",s=n});return{read:()=>{switch(e){case"pending":throw r;case"error":throw s;default:return s}}}}function dt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function bu(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,o)})})}function wu(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const mo=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},vu=({container:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r),a=mo(n,t.data).map(s).filter(Boolean);t.removeAll(a);const c=n.map(e).filter(Boolean);t.addAll(c)},Mu=({container:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);mo(n,t.models).forEach(s),n.forEach(e)},Eu=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);mo(n,t).forEach(s),n.forEach(e)},_u=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},Mn=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),En=[{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 Si(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=En.length;s++){const r=En[s];if(Math.abs(e)<r.amount)return Mn.format(Math.round(e),r.name);e/=r.amount}return Mn.format(Math.round(e),"years")}const yo=t=>t%4===0&&t%100!==0||t%400===0,bo=(t,e)=>[31,yo(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],$i=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,bo(s.getFullYear(),s.getMonth()))),s},Di=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},Je="en-US",Ci={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"}},Ri={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"}},Ai=(t,{dateStyle:e="short",locales:s=Je}={dateStyle:"short",locales:Je})=>{const r=e==="short"?Ci.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},Pi=(t,{locales:e=Je,timeStyle:s="short"}={locales:Je,timeStyle:"short"})=>{const r=Ri[s];return new Intl.DateTimeFormat(e,r).format(t)},Li=(t,{dateStyle:e="short",locales:s=Je,timeStyle:r="short"}={dateStyle:"short",locales:Je,timeStyle:"short"})=>{const o={...e&&Ci[e],...r&&Ri[r]};return new Intl.DateTimeFormat(s,o).format(t)},Tu=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Di,addMonthsToDate:$i,formatDate:Ai,formatDateSince:Si,formatDateTime:Li,formatTime:Pi,getDaysInMonth:bo,isLeapYear:yo},Symbol.toStringTag,{value:"Module"}));function xi(t,e,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,o)},s)}}const ne="canvas-renderer",Er=new Map,_n=new Map,_r=new Map,Tr=new Map,ss=(t,e)=>{Fi[t]=e},Fi={indexExtension:{registerIndexExtension:(t,e)=>{const s=Tr.get(t)||{};Object.assign(s,e),Tr.set(t,e)},loadIndexExtensions:t=>Tr.get(t)||{}},loader:{registerLoader:(t,e)=>{_n.set(t,e)},executeLoader:async(t,e)=>{const s=_n.get(t);if(s)return await s(e)}},propertyMapper:{registerPropertyMapper:(t,e)=>{_r.set(t,e)},hasMapper:t=>_r.has(t),executeMapper:(t,e,s)=>{const r=_r.get(t);return r?r(e,s):""}},dataMapper:{registerDataMapper:(t,e)=>{const s=Er.get(t)||[];s.push(e),Er.set(t,s)},executeMapper:async(t,e,s)=>{const r=Er.get(t);if(!r)return{};const o={};for(const n of r){const i=await n(e,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(t,e)=>{if(!S[ne]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}S[ne].register(t,e)}}},S=Fi,Iu=async({context:t,extension:e})=>{const s=await S.loader.executeLoader(e,{});return t==null||t.set(e,s),s},Ou=async({extension:t,contextData:e,data:s})=>await S.dataMapper.executeMapper(t,s,e),Su=async({extension:t,contextData:e,data:s})=>await S.propertyMapper.executeMapper(t,s,e),$u=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Ou,executeLoaderExtension:Iu,executePropertyMapperExtension:Su},Symbol.toStringTag,{value:"Module"})),Du="Extensions";class Cu{constructor(){l(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}const ae=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),ki="studio.tools.preview",Ru="studio.relax.store.validation",Ni="studio.log.debug",Ui="studio.log.info",Au={profiles:[ki]};var ti;const Pu=((ti=globalThis.getKosConfig)==null?void 0:ti.call(globalThis))||JSON.stringify(Au),ji=JSON.parse(Pu);globalThis.kosConfig=ji;const wo=ji,Bi=()=>wo.profiles||[],Nr=t=>Bi().includes(t),Lu=()=>wo.logging||!1,xu=()=>{const t=Nr(Ni),e=Nr(Ui);return t?"DEBUG":e?"INFO":void 0},Ki=()=>{const t=ae(),e=xu(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Hi=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Gi=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",zi="ws-log",Fu=$.methodFactory,Vi=Hi(),ku=Gi();$.methodFactory=function(t,e,s){const r=Fu(t,e,s);return function(o,n){var c;const i=s?String(s):"",a=i?`[${String(i).substring(i.lastIndexOf(":")+1)}] | `:"[root] | ";r(`${a}${o}`,n||""),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==zi||Vi&&ku)&&globalThis.kosLog(`UI: ${a}${o}`)}};let Yi=Ki();$.setLevel(Yi);window.setKosLogLevel=t=>{Yi=t,$.setLevel(t)};const Cs=$.getLogger(zi);window.enableKosMessageLog=()=>{Cs.setLevel($.levels.INFO)};window.disableKosMessageLog=()=>{Cs.setLevel($.levels.ERROR)};Vi?window.enableKosMessageLog():window.disableKosMessageLog();const Nu=["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(";"),Uu=["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(";"),us=t=>e=>{$.getLevel()<=t&&e()},p={...$,ifDebug:us($.levels.DEBUG),ifInfo:us($.levels.INFO),ifWarn:us($.levels.WARN),ifError:us($.levels.ERROR),getLogger:t=>$.getLogger(`kos::${t}`),getLoggers:()=>$.getLoggers(),createLogger:({name:t,group:e})=>{var n,i,a,c;const s=`${e?`${e}:`:"kos"}::${t}`,r=$.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(d=>d.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(d=>s.startsWith(d.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Cs.info(`%c⬆ ${e}`,Nu)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Cs.info(`%c⬇ ${e}`,Uu)}},qi="featureFlagResolver",hs=new Map;ss(qi,{register:(t,e)=>{var s;hs.has(t)||hs.set(t,[]),(s=hs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=hs.get(t);if(!s)return[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(p.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return Qi.updateFlags(i),Object.keys(i)}});const ju="kos.loader.featureFlag";class Wi{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new Wi;const Qi=window.KosFeatureFlags,Zi=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,o=n=>{const i=(n+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},Ji=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return Zi(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Xi=(t,e)=>getComputedStyle(t).getPropertyValue(e),Bu=(t,e)=>Ji(Xi(t,e)),Ku=(t,e)=>{const s={...t};return s.id&&delete s.id,s},Ur=(t,e,s=Ku)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})},Ir=new Map,ea={addToDeletionQueue:(t,e)=>{const s=Ir.get(t)||[];s.push(e),Ir.set(t,s)},cancelDeletion:t=>{const e=Ir.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},Hu=p.createLogger({name:"kos-dependency-manager"});class Gu{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(e,s){ea.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(e)||r.push(e),this._usedByCache.set(s,r);const o=this._usesCache.get(e)||[];o.includes(s)||o.push(s),this._usesCache.set(e,o)}remove(e,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==e));const o=this._usesCache.get(e)||[];this._usesCache.set(e,o.filter(n=>n!==s))}canDestroy(e){const s=this._usedByCache.get(e);return s!=null&&s.length?(Hu.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var b=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(b||{}),A=(t=>(t.CREATE="create",t.INITIALIZE="init",t.LOAD="load",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.RESET="go_offline",t.UNLOAD="unload",t.FAILED="failed",t.GO_ACTIVE="go_active",t.GO_INACTIVE="go_inactive",t.TIMEOUT="timeout",t))(A||{});const Tn=p.createLogger({name:"kos-model-cache"});class zu{constructor(e=[]){l(this,"_modelsById",M.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?(Tn.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Tn.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const W=Symbol("SubscriptionHandlers"),L=Symbol("DependencyModels"),Pt=Symbol("FutureService"),Lt=Symbol("ChildModels"),xt=Symbol("ParentModel"),Ft=Symbol("LogConfig"),_s=Symbol("ReferenceConfig"),ta=Symbol("KosModelSymbol"),Ne=Symbol("ModelEffects"),Rs=Symbol("CompanionParentModel"),he=(t,e)=>{t[Lt]=t[Lt]||{},t[Lt][e]=!0},Be=t=>`{PROP_${String(t)}}`,Vu=t=>`{PROP_${String(t)}}`,Yu=Be("kosParentId"),ar=t=>e=>{e[xt]=e[xt]||{};const s=(t==null?void 0:t.parentId)||Yu;e[xt]={parentId:s}},Xe=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=Xe({value:r[n],modelId:e,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp(".*({PROP_(.+)})");let n=r!=null&&r.includes(Ds)?r.replace(Ds,e):r;const i=n.match(o);if(i&&s&&(Object.getOwnPropertyNames(s).includes(i[2])||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(i[2]))){const a=s[i[2]];n=a?n.replace(i[1],a):void 0}return n}else return r;return r},qu=p.createLogger({group:"decorators",name:"kos-model"});function Wu(t,e,s){var n;const r=(n=t[xt])==null?void 0:n.parentId;if(!r)return;const o=Xe({value:r,modelData:s,modelId:e});o&&typeof o=="string"&&j.setParentContext(e,o)}function Qu(t){const e=t[Pt];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function Zu(t,e){const s=t[L]||{};Object.entries(s).forEach(([r,o])=>{const n=Xe({value:o.id||o.modelType,modelData:t,modelId:e}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,d])=>(a[c]=Xe({value:d,modelData:t,modelId:e}),a),{});if(typeof n=="string"){if(!o.lazy){const a=I.getInstance().modelManager.createModelInstance(o.modelType,n,i);t[r]=a.data}I.getInstance().modelManager.addDependency(e,n)}})}function Ju(t){try{return M.makeAutoObservable(t)}catch(e){return qu.error("Failed to make observable:",e),t}}const Xu={construct(t,e){var a;const[s,r={}]=e,o=j.createContext(s);Wu(t,s,r);const n=p.createLogger({name:t.prototype.modelTypeId,group:((a=t[Ft])==null?void 0:a.group)??"kos-model"}),i=new t(s,r,{logger:n,kosContext:o});return Qu(i),Zu(i,s),Ju(i)}};function R(t){return e=>{var r,o;const s=e;return s.prototype.modelTypeId=t,s.prototype[ta]=!0,(r=s.prototype)[W]??(r[W]={}),(o=s.prototype)[L]??(o[L]={}),p.ifDebug(()=>{p.debug(`Registering model with id ${t}`)}),new Proxy(s,Xu)}}const eh=({modelType:t})=>e=>{ar()(e),R(t)(e)};function th(t,e,s){const r=s.value;s.value=function(...o){const n=j.getContext(this.id);return o.push(n),r.apply(this,o)}}var N=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(N||{});const sh=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:N},Symbol.toStringTag,{value:"Module"})),Ee=Symbol("HttpRouteHandlers"),In="__httpBrowserRouter";function cr(t){return function(s){return function(r,o,n){r[Ee]=r[Ee]||[];const i={method:t,path:s,handler:o};return r[Ee].push(i),r[L]=r[L]||{},r[L][In]||(r[L][In]={modelType:"browser-router-model",lifecycle:N.INIT}),n}}}const sa=cr("GET"),rs=cr("POST"),rh=cr("PUT"),ra=cr("DELETE"),oh=ra;function As(t){return!!(t!=null&&t[Ee])&&t[Ee].length>0}function oa(t){return(t==null?void 0:t[Ee])||[]}const nh=({group:t}={group:""})=>e=>{e[Ft]=e[Ft]||{},e[Ft]={group:t}};function na(t){return(e,s,r)=>{e[Ne]=e[Ne]||{},e[Ne][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const ih=t=>(e,s)=>{e[_s]=e[_s]||{},e[_s][s]=t},ut=({modelType:t,id:e,options:s,lifecycle:r})=>(o,n)=>{o[L]=o[L]||{},o[L][n]={modelType:t,id:e,options:s,lifecycle:r||N.INIT}},ah=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>o=>{o[W]=o[W]||{},Array.isArray(t)?t.forEach(n=>{o[W][n]={websocket:s,handler:e,condition:r}}):o[W][t]={websocket:s,handler:xi(o,M.action(e),200),condition:r}};function ia(t,e,s){const r={};if(!t.endsWith("/*"))return r;const o=t.slice(0,-2);if(e.startsWith(o)){const n=e.slice(o.length+1),i=s||"path";r[i]=n}return r}function aa(t){return t.endsWith("/*")}function x({topic:t,condition:e=(T,K)=>!0,transform:s=T=>T,websocket:r=!1,fos:o=!1,bridge:n=!1,skipParse:i=!1,lifecycle:a,destinationAddress:c,debounce:d,throttle:u,buffer:h,filter:f,once:m,replay:w,wildcardName:v,flow:E}){return(T,K,fe)=>{T[W]=T[W]||{};let D=fe.value;const z=typeof d=="number"?d:d==null?void 0:d.delay,F=typeof u=="number"?u:u==null?void 0:u.interval;z&&z>0?D=ch(D,d):F&&F>0?D=lh(D,u):h?D=dh(D,h):m&&(D=uh(D));let V=e;if(f){const ve=e;V=(wn,vn,Mr)=>f(Mr)?ve(wn,vn,Mr):!1}const Se={websocket:r,fos:o,bridge:n,handler:D,condition:V,transform:s,lifecycle:a,skipParse:i,destinationAddress:c,wildcardName:v,flow:E};Array.isArray(t)?t.forEach(ve=>{T[W][ve]=Se}):T[W][t]=Se,w&&hh(t,w.bufferSize)}}function ch(t,e){const s=typeof e=="number"?e:e.delay,r=typeof e=="object"?e.discardIntermediate:!1;let o=null,n=[];return function(i){r?(o&&clearTimeout(o),o=setTimeout(()=>{t.call(this,i),o=null},s)):(n.push(i),o&&clearTimeout(o),o=setTimeout(()=>{const a=[...n];n=[],t.call(this,a),o=null},s))}}function lh(t,e){const s=typeof e=="number"?e:e.interval,r=typeof e=="object"?e.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const d=[...i];i=[],t.call(this,d)}};return function(d){const u=Date.now(),h=u-o;r?h>=s?(o=u,t.call(this,d)):n||(n=setTimeout(()=>{o=Date.now(),t.call(this,d),n=null},s-h)):(i.push(d),h>=s?(o=u,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function dh(t,e){const s=[];let r=null;const o=e.maxSize||1e3,n=i=>{s.length>0&&(t.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=o){r&&(clearTimeout(r),r=null),n(this);return}r||(r=setTimeout(()=>{n(this),r=null},e.time))}}function uh(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function hh(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{go(r,e)})}function ca(t,e){return`${lo}${t}${e?`/${e}`:`/${t}`}`}function la(t){return`${lo}${t}`}function Or(t){const e=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of t){const i=M.when(o,()=>{e.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});e.push(i)}})}const da=5e3;class gh extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const ua=(t,e,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{p.error(`Model ${e.modelId} - ${e.modelTypeName} - ${s} timed out after ${t}ms`),a(new gh(`${e.modelId} - ${e.modelTypeName} - ${s}`,e))},t)}),cancel:()=>{r&&clearTimeout(r)}}},ha=t=>t.fsm.transitionTo(A.GO_ACTIVE,b.ACTIVE),ga=t=>t.whenReady(),fa=t=>t.fsm.transitionTo(A.LOAD,b.LOADED),fh=t=>t.fsm.transitionTo(A.UNLOAD,b.UNLOADED),pa=t=>t.fsm.transitionTo(A.INITIALIZE,b.INITIALIZED);var vo=(t=>(t.ACTIVE="active",t.READY="ready",t.LOAD="load",t.UNLOAD="unload",t.INIT="init",t))(vo||{});const Ts={active:ha,ready:ga,load:fa,init:pa},ma=(t,e)=>{const s=e.id||e.modelType,r=Xe({value:s,modelData:t.modelData,modelId:t.modelId});p.debug(`activating dependent model ${e.modelType} with id ${r}`);const o=Object.keys((e==null?void 0:e.options)||{}).reduce((i,a)=>{const c=e.options[a];return i[a]=Xe({value:c,modelData:t.modelData,modelId:t.modelId}),i},{});return{dependentModel:I.getInstance().modelManager.createModelInstance(e.modelType,r,o),dataModelId:r}},ya=(t,e=N.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[L])||{};return Object.keys(s).length===0?(p.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],{dependentModel:a,dataModelId:c}=ma(t,i);t.modelData[n]=a.data,p.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const d=async(f,m,w)=>{var v;await((v=f.whenReady)==null?void 0:v.call(f)),p.debug(`dependent model ${m} with id ${w} - READY`)},{promise:u,cancel:h}=ua(da,t,t.status);return Promise.race([d(a.model,i.modelType,c).then(()=>{h()}).catch(f=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${c}:`,f),h()}),u])}).filter(n=>!!n)},ba=async(t,e,s,r)=>{if(p.debug(`Execute lifecycle with ${e.length} models`),e.length===0){p.debug(`${t.modelId} has no children. Returning`);return}if(!s){p.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return Ts[s]&&a?c=Ts[s](a):(a||p.error("model is undefined. This shouldn't happen"),Ts[s]||p.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(p.error(`No model found ${a.modelId}`),!1):(p.error(`No promise found ${a.modelId}`),!1)),i=(await Promise.allSettled(o.map(a=>{var u;const{promise:c,cancel:d}=ua(da,a.model,a.status);return Promise.race([(u=a.promise)==null?void 0:u.then(()=>{d()}).catch(h=>{p.error(`Model ${a.modelId} - ${a.type} failed to transition to ${s}: ${h.message}`),d()}),c])}))).filter(a=>a.status==="rejected");i.length>0&&p.error(`Model ${t.modelId} had ${i.length} failed child models on ${r}`)},wa=async(t,e,s)=>{await ba(t,t.getChildren().filter(r=>!!r),e,s)},wt=async(t,e)=>{const r=(await Promise.allSettled(ya(t,e))).filter(o=>o.status==="rejected");r.length&&(p.error(`There were ${r.length} failed dependent models on ${e}`),p.error(r))},ph=t=>typeof t.toJSON=="function",kt=t=>t[L]!==void 0,Mo=t=>t.revision!==void 0&&t.index!==void 0,va=t=>{if(t){if(kt(t))return t;if(Mo(t))return t.data;if(t instanceof Map||t instanceof M.ObservableMap||t instanceof Set)return Array.from(t.values()).filter(kt);if(Array.isArray(t))return t.filter(kt)}};function mh(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),yh(t.modelData,t.modelTypeName,t.modelId,t)}function yh(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,d;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[L]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(u=>({type:u.modelTypeName,id:u.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(u=>({id:u.id||u.modelType,type:u.modelType,options:u.options,lifecycle:u.lifecycle}))},children:{count:o.length,data:o.map(u=>({id:u.modelId,type:u.modelTypeName}))},data:((d=t.toJSON)==null?void 0:d.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];kt(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:Mo(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 bh{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==b.FAILED).filter(r=>!!r);return s.forEach(r=>{try{j.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[Lt])||{};return Object.keys(e).map(r=>va(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class wh{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class vh{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[Ne])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},d=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(d)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Mh=p.createLogger({name:"model-active-machine"}),Eh=t=>{const e=y.createMachine(b.INACTIVE,{[b.FAILED]:y.state(y.transition(A.GO_ACTIVE,b.ACTIVATING)),[b.INACTIVE]:y.state(y.transition(A.GO_ACTIVE,b.ACTIVATING)),[b.ACTIVATING]:y.invoke(()=>(t.activeStatus=b.ACTIVATING,t.activate()),y.transition("done",b.ACTIVE,y.action(()=>{t.activeStatus=b.ACTIVE})),y.transition("error",b.FAILED,y.action(()=>{t.activeStatus=b.FAILED}))),[b.ACTIVE]:y.state(y.transition(A.GO_INACTIVE,b.DEACTIVATING)),[b.DEACTIVATING]:y.invoke(()=>(t.activeStatus=b.DEACTIVATING,t.deactivate()),y.transition("done",b.INACTIVE,y.action(()=>{t.activeStatus=b.INACTIVE})),y.transition("error",b.FAILED,y.action(()=>{t.activeStatus=b.FAILED})))});return{service:y.interpret(e,r=>Mh.debug(r.machine.current)),machine:e}},On=p.createLogger({name:"model-online-machine"}),_h=t=>{const e=y.createMachine(b.OFFLINE,{[b.ONLINE]:y.state(y.transition(A.GO_OFFLINE,b.OFFLINE,y.action(async()=>{await t.offline(),t.onlineStatus=b.OFFLINE}))),[b.OFFLINE]:y.state(y.transition(A.GO_ONLINE,b.ONLINE,y.action(async()=>{On.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=b.ONLINE,await t.fsm.transitionTo(A.INITIALIZE,b.INITIALIZED)})))}),s=y.interpret(e,r=>On.debug(r.machine.current));return{machine:e,service:s}},Th=t=>{var r;const e=Eh(t).service,s=_h(t).service;return y.createMachine(b.CREATING,{[b.CREATING]:y.state(y.transition(A.CREATE,b.CREATED)),[b.CREATED]:y.state(y.immediate(b.INITIALIZING)),[b.INITIALIZING]:y.invoke(()=>(q(()=>{t.status=b.INITIALIZING}),t.init()),y.transition("done",b.INITIALIZED,y.action(()=>{t.status=b.INITIALIZED})),y.transition("error",b.FAILED,y.action(()=>{p.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=b.FAILED}))),[b.INITIALIZED]:y.state(y.immediate(b.LOADING)),[b.LOADING]:y.invoke(()=>(q(()=>{t.status=b.LOADING}),t.load()),y.transition("done",b.LOADED,y.action(()=>{t.status=b.LOADED})),y.transition("error",b.FAILED,y.action(()=>{t.status=b.FAILED}))),[b.LOADED]:y.state(y.immediate(b.READYING),y.transition(A.UNLOAD,b.UNLOADING)),[b.RESETTING]:y.invoke(()=>{var o;return q(()=>{t.status=b.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},y.transition("done",b.LOADED,y.action(()=>{t.status=b.LOADED}))),[b.READYING]:y.invoke(()=>(q(()=>{t.status=b.READYING}),t.ready()),y.transition("done",b.READY,y.action(()=>{q(()=>{t.status=b.READY}),s.send(A.GO_ONLINE)})),y.transition("error",b.FAILED,y.action(()=>{t.status=b.FAILED}))),[b.READY]:y.state(y.transition(A.UNLOAD,b.UNLOADED,y.action((r=t.unload)==null?void 0:r.bind(t))),y.transition(A.RESET,b.RESETTING),y.transition(A.GO_ONLINE,b.READY,y.action(()=>{s.send(A.GO_ONLINE)})),y.transition(A.GO_OFFLINE,b.READY,y.action(()=>{s.send(A.GO_OFFLINE)})),y.transition(A.GO_ACTIVE,b.READY,y.action(()=>{e.send(A.GO_ACTIVE)})),y.transition(A.GO_INACTIVE,b.READY,y.action(()=>{e.send(A.GO_INACTIVE)}))),[b.UNLOADED]:y.state(),[b.FAILED]:y.state()})},Ih=p.createLogger({name:"kos-model-lifecycle"}),Oh=t=>({service:y.interpret(Th(t),s=>Ih.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class Sh{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=Oh(e);this.service=r.service,this.service.send(A.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=b.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[b.ACTIVE,b.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const Ma="browser-router-model";class Eo{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!As(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=pe(Ma))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return As(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=oa(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function $h(t,e){if(!As(t))return;const s=pe(Ma);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new Eo(t,e).setRouter(s.model)}class Dh{static create({modelId:e,modelTypeName:s,component:r}){const o=[r??"kos",s,e].filter(Boolean).join(".");return p.createLogger({name:o})}}class Ch{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e){this.queue.push(e)}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class Rh{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=O("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(A.GO_ONLINE,b.ONLINE)}),r=O("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(A.GO_OFFLINE,b.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}class Ah{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=O(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function Sn(t){return new Ah(t)}var Ea=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(Ea||{});const _a=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${sr}:${s}
|
|
1
|
+
"use strict";var lu=Object.defineProperty;var du=(t,e,s)=>e in t?lu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var l=(t,e,s)=>(du(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("loglevel"),M=require("mobx"),y=require("robot3"),$e=require("date-fns"),_=require("@emotion/react/jsx-runtime"),oo=require("@emotion/styled"),ri=require("react-dom"),Fe=require("@emotion/react"),g=require("react"),no=require("mobx-react-lite"),uu=require("@use-gesture/react"),sr="method",oi="topic",lt="url",ts="request-id",rr="response-id",io="status",Ie="dst-addr",ni="src-addr",ye="type",ao="ordered",co="tracker",ii="Content-Type",ai="Cache-Control",ci="requestId",li=process.env.KOS_LOGIN_URL||"http://localhost",di=process.env.KOS_APP_PORT||"8080",hu=`${li}:${di}`,Ds="{MODEL_ID}";var ss=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(ss||{}),ui=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(ui||{});const lo="/kos/model/ready/";D.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const U=globalThis.kos.subscriptions,fu=()=>Symbol("eventKey");function uo(t){return U[t]&&Object.getOwnPropertySymbols(U[t]).length>0}function $(t,e){const s=fu();return U[t]||(D.debug(`Initializing subscription for ${t}`),U[t]={}),D.debug(`Subscribing to ${t} with id ${s.toString()}`),U[t][s]=e,{count:U[t]?Object.getOwnPropertySymbols(U[t]).length:0,unsubscribe:()=>(D.debug(`Unsubscribing from ${t} with id ${s.toString()}`),U[t]&&U[t][s]&&delete U[t][s],U[t]&&Object.getOwnPropertySymbols(U[t]).length===0&&delete U[t],{count:U[t]?Object.getOwnPropertySymbols(U[t]).length:0})}}function B(t,e,s={}){if(!U[t]||Object.getOwnPropertySymbols(U[t]).length===0)return D.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(U[t]).length;return Object.getOwnPropertySymbols(U[t]).forEach(o=>{if(s.sync){const n=s.sync;D.debug(`Performing sync publish for ${t} with sync id ${n}`),U[t][o]({body:e,headers:s}).then(i=>{D.debug(`Response recieved for ${n}, publishing back to source.`),B(n,i)})}else D.debug(`Performing async publish for ${t}`),U[t][o]({body:e,headers:s})}),{eventType:t,subscribers:r}}function gu(){D.warn("Resetting event bus"),Object.keys(U).forEach(t=>delete U[t])}function hi(t,e){const s=$(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function ho(t,e){return new Promise((s,r)=>{let o=null;const n=hi(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const pu=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:uo,once:hi,publish:B,reset:gu,subscribe:$,waitFor:ho},Symbol.toStringTag,{value:"Module"}));function or(t,e){const s=$(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function nr(t,e){return new Promise((s,r)=>{let o=null;const n=or(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function fi(t,e){const s=t.map(r=>nr(r,e));return Promise.all(s)}function gi(t,e){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};t.forEach(c=>{const d=or(c,u=>{i||(i=!0,a(),s({eventType:c,data:u}))});o.push(d)}),e&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function pi(t,e,s){return $(t,o=>{o&&e(o)&&s(o)}).unsubscribe}function mi(t,e,s){return $(t,o=>{if(o){const n=e(o);s(n)}}).unsubscribe}function yi(t,e,s){let r=null;const o=$(t,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},e)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function bi(t,e,s){let r=0,o=null;const n=$(t,i=>{const a=Date.now(),c=a-r;c>=e?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},e-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function wi(t,e,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=$(t,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},e)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function fo(t,e=1){const s=[];return $(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),$(t,r))}}function vi(t,e){const s=t.map(r=>$(r,o=>{o&&e(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function Mi(t,e){let s=t;const r=[],o=new Set;return Object.values(e).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=$(n,a=>{const c=e[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function Ei(t,e,s,r){const o=nr(e,r);return B(t,s),o}async function*_i(t){const e=[],s=[],r=$(t,o=>{o&&(s.length>0?s.shift()(o):e.push(o))});try{for(;;)e.length>0?yield e.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const mu={once:or,waitFor:nr,waitForAll:fi,race:gi,filter:pi,map:mi,debounce:yi,throttle:bi,buffer:wi,replay:fo,merge:vi,stateMachine:Mi,request:Ei,eventIterator:_i},yu=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:mu,buffer:wi,debounce:yi,eventIterator:_i,filter:pi,map:mi,merge:vi,once:or,race:gi,replay:fo,request:Ei,stateMachine:Mi,throttle:bi,waitFor:nr,waitForAll:fi},Symbol.toStringTag,{value:"Module"}));async function ir(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=e,i=ho(t,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(u=>{setTimeout(()=>u(c),100)})])}function Ti(t,e,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=$(t,a=>{a&&(n=!0,e(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||e(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function Ii(t,e){let s;const r=new Set,o=async()=>{try{typeof e=="string"?s=await(await fetch(e)).json():s=await e(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};$(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let n=!1;const i=()=>{n||(n=!0,o())};return{get state(){return s},async getState(){return i(),s===void 0&&await new Promise(a=>{const c=()=>{s!==void 0?a():setTimeout(c,10)};c()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function go(t,e){if(typeof t=="string")return ir(t,e);const s=t,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=e,i=await r(),a=e.transformState?e.transformState(i):i;if(o&&o(a))return a;const c=s.map(u=>ho(u,n)),d=await Promise.all(c);return d[d.length-1]}function Oi(t,e,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=$(t,async d=>{if(d){if(n){const u=n(d);if(i.has(u))return;i.add(u),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await e(d)}}),c=setInterval(async()=>{try{const d=await r(),u=Array.isArray(d)?d:[d];for(const h of u)if(n){const f=n(h);i.has(f)||(i.add(f),await e(h))}else await e(h)}catch(d){console.error("Failed to fetch missed events:",d)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function Si(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(u){if(a.state==="connected"&&a.data)return a.data;const h=await ir(e,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:u});return a.state="connected",a.data=h,d(),h},subscribe(u){return c.add(u),u(a),()=>{c.delete(u)}},async reconnect(){a.state="connecting",d();try{const u=await n();a.state="connected",a.data=u,d()}catch{a.state="error",d(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,d=()=>{c.forEach(u=>u(a))};return $(e,u=>{a.state="connected",u!=null&&u.body&&(a.data=u.body),d()}),$(s,()=>{a.state="disconnected",d(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&$(r,()=>{a.state="error",d()}),o&&$(o,u=>{u!=null&&u.body&&a.state==="connected"&&(a.data=u.body,d())}),a.reconnect(),a}const bu={waitForOrGetState:ir,subscribeWithInitialState:Ti,createStatefulEventStream:Ii,waitForAllWithState:go,createResilientEventHandler:Oi,createConnectionStateManager:Si},wu=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:bu,createConnectionStateManager:Si,createResilientEventHandler:Oi,createStatefulEventStream:Ii,subscribeWithInitialState:Ti,waitForAllWithState:go,waitForOrGetState:ir},Symbol.toStringTag,{value:"Module"})),vu=(t,e=0)=>{if(!+t)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=e<0?0:e,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(t)/Math.log(s)),i=parseFloat((t/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function po(t){let e="pending",s;const r=t.then(n=>{e="success",s=n},n=>{e="error",s=n});return{read:()=>{switch(e){case"pending":throw r;case"error":throw s;default:return s}}}}function dt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function Mu(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,o)})})}function Eu(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const mo=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},_u=({container:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r),a=mo(n,t.data).map(s).filter(Boolean);t.removeAll(a);const c=n.map(e).filter(Boolean);t.addAll(c)},Tu=({container:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);mo(n,t.models).forEach(s),n.forEach(e)},Iu=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);mo(n,t).forEach(s),n.forEach(e)},Ou=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},Mn=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),En=[{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 $i(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=En.length;s++){const r=En[s];if(Math.abs(e)<r.amount)return Mn.format(Math.round(e),r.name);e/=r.amount}return Mn.format(Math.round(e),"years")}const yo=t=>t%4===0&&t%100!==0||t%400===0,bo=(t,e)=>[31,yo(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Di=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,bo(s.getFullYear(),s.getMonth()))),s},Ci=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},Je="en-US",Ri={short:{year:"numeric",month:"2-digit",day:"2-digit"},medium:{year:"numeric",month:"short",day:"2-digit"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}},Pi={short:{hour:"2-digit",minute:"2-digit",hour12:!0},medium:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0},long:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZoneName:"short"},full:{hour:"2-digit",minute:"2-digit",hour12:!0,timeZoneName:"long"}},Ai=(t,{dateStyle:e="short",locales:s=Je}={dateStyle:"short",locales:Je})=>{const r=e==="short"?Ri.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},Li=(t,{locales:e=Je,timeStyle:s="short"}={locales:Je,timeStyle:"short"})=>{const r=Pi[s];return new Intl.DateTimeFormat(e,r).format(t)},xi=(t,{dateStyle:e="short",locales:s=Je,timeStyle:r="short"}={dateStyle:"short",locales:Je,timeStyle:"short"})=>{const o={...e&&Ri[e],...r&&Pi[r]};return new Intl.DateTimeFormat(s,o).format(t)},Su=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Ci,addMonthsToDate:Di,formatDate:Ai,formatDateSince:$i,formatDateTime:xi,formatTime:Li,getDaysInMonth:bo,isLeapYear:yo},Symbol.toStringTag,{value:"Module"}));function Fi(t,e,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,o)},s)}}const ee="canvas-renderer",Er=new Map,_n=new Map,_r=new Map,Tr=new Map,rs=(t,e)=>{ki[t]=e},ki={indexExtension:{registerIndexExtension:(t,e)=>{const s=Tr.get(t)||{};Object.assign(s,e),Tr.set(t,e)},loadIndexExtensions:t=>Tr.get(t)||{}},loader:{registerLoader:(t,e)=>{_n.set(t,e)},executeLoader:async(t,e)=>{const s=_n.get(t);if(s)return await s(e)}},propertyMapper:{registerPropertyMapper:(t,e)=>{_r.set(t,e)},hasMapper:t=>_r.has(t),executeMapper:(t,e,s)=>{const r=_r.get(t);return r?r(e,s):""}},dataMapper:{registerDataMapper:(t,e)=>{const s=Er.get(t)||[];s.push(e),Er.set(t,s)},executeMapper:async(t,e,s)=>{const r=Er.get(t);if(!r)return{};const o={};for(const n of r){const i=await n(e,s);Object.assign(o,i)}return o}},canvas:{registerRenderer:(t,e)=>{if(!S[ee]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}S[ee].register(t,e)}}},S=ki,$u=async({context:t,extension:e})=>{const s=await S.loader.executeLoader(e,{});return t==null||t.set(e,s),s},Du=async({extension:t,contextData:e,data:s})=>await S.dataMapper.executeMapper(t,s,e),Cu=async({extension:t,contextData:e,data:s})=>await S.propertyMapper.executeMapper(t,s,e),Ru=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Du,executeLoaderExtension:$u,executePropertyMapperExtension:Cu},Symbol.toStringTag,{value:"Module"})),Pu="Extensions";class Au{constructor(){l(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}const le=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),Ni="studio.tools.preview",Lu="studio.relax.store.validation",Ui="studio.log.debug",ji="studio.log.info",xu={profiles:[Ni]};var si;const Fu=((si=globalThis.getKosConfig)==null?void 0:si.call(globalThis))||JSON.stringify(xu),Bi=JSON.parse(Fu);globalThis.kosConfig=Bi;const wo=Bi,Ki=()=>wo.profiles||[],Nr=t=>Ki().includes(t),ku=()=>wo.logging||!1,Nu=()=>{const t=Nr(Ui),e=Nr(ji);return t?"DEBUG":e?"INFO":void 0},Hi=()=>{const t=le(),e=Nu(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Gi=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",zi=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Vi="ws-log",Uu=D.methodFactory,Yi=Gi(),ju=zi();D.methodFactory=function(t,e,s){const r=Uu(t,e,s);return function(o,n){var c;const i=s?String(s):"",a=i?`[${String(i).substring(i.lastIndexOf(":")+1)}] | `:"[root] | ";r(`${a}${o}`,n||""),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==Vi||Yi&&ju)&&globalThis.kosLog(`UI: ${a}${o}`)}};let qi=Hi();D.setLevel(qi);window.setKosLogLevel=t=>{qi=t,D.setLevel(t)};const Cs=D.getLogger(Vi);window.enableKosMessageLog=()=>{Cs.setLevel(D.levels.INFO)};window.disableKosMessageLog=()=>{Cs.setLevel(D.levels.ERROR)};Yi?window.enableKosMessageLog():window.disableKosMessageLog();const Bu=["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(";"),Ku=["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(";"),us=t=>e=>{D.getLevel()<=t&&e()},p={...D,ifDebug:us(D.levels.DEBUG),ifInfo:us(D.levels.INFO),ifWarn:us(D.levels.WARN),ifError:us(D.levels.ERROR),getLogger:t=>D.getLogger(`kos::${t}`),getLoggers:()=>D.getLoggers(),createLogger:({name:t,group:e})=>{var n,i,a,c;const s=`${e?`${e}:`:"kos"}::${t}`,r=D.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(d=>d.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(d=>s.startsWith(d.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Cs.info(`%c⬆ ${e}`,Bu)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Cs.info(`%c⬇ ${e}`,Ku)}},Wi="featureFlagResolver",hs=new Map;rs(Wi,{register:(t,e)=>{var s;hs.has(t)||hs.set(t,[]),(s=hs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=hs.get(t);if(!s)return[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(p.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return Zi.updateFlags(i),Object.keys(i)}});const Hu="kos.loader.featureFlag";class Qi{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new Qi;const Zi=window.KosFeatureFlags,Ji=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,o=n=>{const i=(n+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},Xi=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return Ji(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},ea=(t,e)=>getComputedStyle(t).getPropertyValue(e),Gu=(t,e)=>Xi(ea(t,e)),zu=(t,e)=>{const s={...t};return s.id&&delete s.id,s},Ur=(t,e,s=zu)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})},Ir=new Map,ta={addToDeletionQueue:(t,e)=>{const s=Ir.get(t)||[];s.push(e),Ir.set(t,s)},cancelDeletion:t=>{const e=Ir.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},Vu=p.createLogger({name:"kos-dependency-manager"});class Yu{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(e,s){ta.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(e)||r.push(e),this._usedByCache.set(s,r);const o=this._usesCache.get(e)||[];o.includes(s)||o.push(s),this._usesCache.set(e,o)}remove(e,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==e));const o=this._usesCache.get(e)||[];this._usesCache.set(e,o.filter(n=>n!==s))}canDestroy(e){const s=this._usedByCache.get(e);return s!=null&&s.length?(Vu.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}var b=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(b||{}),A=(t=>(t.CREATE="create",t.INITIALIZE="init",t.LOAD="load",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.RESET="go_offline",t.UNLOAD="unload",t.FAILED="failed",t.GO_ACTIVE="go_active",t.GO_INACTIVE="go_inactive",t.TIMEOUT="timeout",t))(A||{});const Tn=p.createLogger({name:"kos-model-cache"});class qu{constructor(e=[]){l(this,"_modelsById",M.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?(Tn.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Tn.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}const Q=Symbol("SubscriptionHandlers"),x=Symbol("DependencyModels"),Lt=Symbol("FutureService"),xt=Symbol("ChildModels"),Ft=Symbol("ParentModel"),kt=Symbol("LogConfig"),_s=Symbol("ReferenceConfig"),sa=Symbol("KosModelSymbol"),Ne=Symbol("ModelEffects"),Rs=Symbol("CompanionParentModel"),ge=(t,e)=>{t[xt]=t[xt]||{},t[xt][e]=!0},Be=t=>`{PROP_${String(t)}}`,Wu=t=>`{PROP_${String(t)}}`,Qu=Be("kosParentId"),ar=t=>e=>{e[Ft]=e[Ft]||{};const s=(t==null?void 0:t.parentId)||Qu;e[Ft]={parentId:s}},Xe=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=Xe({value:r[n],modelId:e,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp(".*({PROP_(.+)})");let n=r!=null&&r.includes(Ds)?r.replace(Ds,e):r;const i=n.match(o);if(i&&s&&(Object.getOwnPropertyNames(s).includes(i[2])||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(i[2]))){const a=s[i[2]];n=a?n.replace(i[1],a):void 0}return n}else return r;return r},Zu=p.createLogger({group:"decorators",name:"kos-model"});function Ju(t,e,s){var n;const r=(n=t[Ft])==null?void 0:n.parentId;if(!r)return;const o=Xe({value:r,modelData:s,modelId:e});o&&typeof o=="string"&&K.setParentContext(e,o)}function Xu(t){const e=t[Lt];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function eh(t,e){const s=t[x]||{};Object.entries(s).forEach(([r,o])=>{const n=Xe({value:o.id||o.modelType,modelData:t,modelId:e}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,d])=>(a[c]=Xe({value:d,modelData:t,modelId:e}),a),{});if(typeof n=="string"){if(!o.lazy){const a=O.getInstance().modelManager.createModelInstance(o.modelType,n,i);t[r]=a.data}O.getInstance().modelManager.addDependency(e,n)}})}function th(t){try{return M.makeAutoObservable(t)}catch(e){return Zu.error("Failed to make observable:",e),t}}const sh={construct(t,e){var a;const[s,r={}]=e,o=K.createContext(s);Ju(t,s,r);const n=p.createLogger({name:t.prototype.modelTypeId,group:((a=t[kt])==null?void 0:a.group)??"kos-model"}),i=new t(s,r,{logger:n,kosContext:o});return Xu(i),eh(i,s),th(i)}};function R(t){return e=>{var r,o;const s=e;return s.prototype.modelTypeId=t,s.prototype[sa]=!0,(r=s.prototype)[Q]??(r[Q]={}),(o=s.prototype)[x]??(o[x]={}),p.ifDebug(()=>{p.debug(`Registering model with id ${t}`)}),new Proxy(s,sh)}}const rh=({modelType:t})=>e=>{ar()(e),R(t)(e)};function oh(t,e,s){const r=s.value;s.value=function(...o){const n=K.getContext(this.id);return o.push(n),r.apply(this,o)}}var j=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(j||{});const nh=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:j},Symbol.toStringTag,{value:"Module"})),Ee=Symbol("HttpRouteHandlers"),In="__httpBrowserRouter";function cr(t){return function(s){return function(r,o,n){r[Ee]=r[Ee]||[];const i={method:t,path:s,handler:o};return r[Ee].push(i),r[x]=r[x]||{},r[x][In]||(r[x][In]={modelType:"browser-router-model",lifecycle:j.INIT}),n}}}const ra=cr("GET"),os=cr("POST"),ih=cr("PUT"),oa=cr("DELETE"),ah=oa;function Ps(t){return!!(t!=null&&t[Ee])&&t[Ee].length>0}function na(t){return(t==null?void 0:t[Ee])||[]}const ch=({group:t}={group:""})=>e=>{e[kt]=e[kt]||{},e[kt]={group:t}};function ia(t){return(e,s,r)=>{e[Ne]=e[Ne]||{},e[Ne][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const lh=t=>(e,s)=>{e[_s]=e[_s]||{},e[_s][s]=t},ut=({modelType:t,id:e,options:s,lifecycle:r})=>(o,n)=>{o[x]=o[x]||{},o[x][n]={modelType:t,id:e,options:s,lifecycle:r||j.INIT}},dh=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>o=>{o[Q]=o[Q]||{},Array.isArray(t)?t.forEach(n=>{o[Q][n]={websocket:s,handler:e,condition:r}}):o[Q][t]={websocket:s,handler:Fi(o,M.action(e),200),condition:r}};function aa(t,e,s){const r={};if(!t.endsWith("/*"))return r;const o=t.slice(0,-2);if(e.startsWith(o)){const n=e.slice(o.length+1),i=s||"path";r[i]=n}return r}function ca(t){return t.endsWith("/*")}function F({topic:t,condition:e=(T,k)=>!0,transform:s=T=>T,websocket:r=!1,fos:o=!1,bridge:n=!1,skipParse:i=!1,lifecycle:a,destinationAddress:c,debounce:d,throttle:u,buffer:h,filter:f,once:m,replay:w,wildcardName:v,flow:E}){return(T,k,se)=>{T[Q]=T[Q]||{};let I=se.value;const V=typeof d=="number"?d:d==null?void 0:d.delay,N=typeof u=="number"?u:u==null?void 0:u.interval;V&&V>0?I=uh(I,d):N&&N>0?I=hh(I,u):h?I=fh(I,h):m&&(I=gh(I));let Y=e;if(f){const ve=e;Y=(wn,vn,Mr)=>f(Mr)?ve(wn,vn,Mr):!1}const Se={websocket:r,fos:o,bridge:n,handler:I,condition:Y,transform:s,lifecycle:a,skipParse:i,destinationAddress:c,wildcardName:v,flow:E};Array.isArray(t)?t.forEach(ve=>{T[Q][ve]=Se}):T[Q][t]=Se,w&&ph(t,w.bufferSize)}}function uh(t,e){const s=typeof e=="number"?e:e.delay,r=typeof e=="object"?e.discardIntermediate:!1;let o=null,n=[];return function(i){r?(o&&clearTimeout(o),o=setTimeout(()=>{t.call(this,i),o=null},s)):(n.push(i),o&&clearTimeout(o),o=setTimeout(()=>{const a=[...n];n=[],t.call(this,a),o=null},s))}}function hh(t,e){const s=typeof e=="number"?e:e.interval,r=typeof e=="object"?e.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const d=[...i];i=[],t.call(this,d)}};return function(d){const u=Date.now(),h=u-o;r?h>=s?(o=u,t.call(this,d)):n||(n=setTimeout(()=>{o=Date.now(),t.call(this,d),n=null},s-h)):(i.push(d),h>=s?(o=u,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function fh(t,e){const s=[];let r=null;const o=e.maxSize||1e3,n=i=>{s.length>0&&(t.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=o){r&&(clearTimeout(r),r=null),n(this);return}r||(r=setTimeout(()=>{n(this),r=null},e.time))}}function gh(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function ph(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{fo(r,e)})}function la(t,e){return`${lo}${t}${e?`/${e}`:`/${t}`}`}function da(t){return`${lo}${t}`}function Or(t){const e=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of t){const i=M.when(o,()=>{e.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});e.push(i)}})}const ua=5e3;class mh extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const ha=(t,e,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{p.error(`Model ${e.modelId} - ${e.modelTypeName} - ${s} timed out after ${t}ms`),a(new mh(`${e.modelId} - ${e.modelTypeName} - ${s}`,e))},t)}),cancel:()=>{r&&clearTimeout(r)}}},fa=t=>t.fsm.transitionTo(A.GO_ACTIVE,b.ACTIVE),ga=t=>t.whenReady(),pa=t=>t.fsm.transitionTo(A.LOAD,b.LOADED),yh=t=>t.fsm.transitionTo(A.UNLOAD,b.UNLOADED),ma=t=>t.fsm.transitionTo(A.INITIALIZE,b.INITIALIZED);var vo=(t=>(t.ACTIVE="active",t.READY="ready",t.LOAD="load",t.UNLOAD="unload",t.INIT="init",t))(vo||{});const Ts={active:fa,ready:ga,load:pa,init:ma},ya=(t,e)=>{const s=e.id||e.modelType,r=Xe({value:s,modelData:t.modelData,modelId:t.modelId});p.debug(`activating dependent model ${e.modelType} with id ${r}`);const o=Object.keys((e==null?void 0:e.options)||{}).reduce((i,a)=>{const c=e.options[a];return i[a]=Xe({value:c,modelData:t.modelData,modelId:t.modelId}),i},{});return{dependentModel:O.getInstance().modelManager.createModelInstance(e.modelType,r,o),dataModelId:r}},ba=(t,e=j.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[x])||{};return Object.keys(s).length===0?(p.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],{dependentModel:a,dataModelId:c}=ya(t,i);t.modelData[n]=a.data,p.debug(`waiting for dependent model ${i.modelType} with id ${c} - waiting for WHENREADY`);const d=async(f,m,w)=>{var v;await((v=f.whenReady)==null?void 0:v.call(f)),p.debug(`dependent model ${m} with id ${w} - READY`)},{promise:u,cancel:h}=ha(ua,t,t.status);return Promise.race([d(a.model,i.modelType,c).then(()=>{h()}).catch(f=>{console.error(`Error waiting for dependent model ${i.modelType} with id ${c}:`,f),h()}),u])}).filter(n=>!!n)},wa=async(t,e,s,r)=>{if(p.debug(`Execute lifecycle with ${e.length} models`),e.length===0){p.debug(`${t.modelId} has no children. Returning`);return}if(!s){p.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return Ts[s]&&a?c=Ts[s](a):(a||p.error("model is undefined. This shouldn't happen"),Ts[s]||p.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(p.error(`No model found ${a.modelId}`),!1):(p.error(`No promise found ${a.modelId}`),!1)),i=(await Promise.allSettled(o.map(a=>{var u;const{promise:c,cancel:d}=ha(ua,a.model,a.status);return Promise.race([(u=a.promise)==null?void 0:u.then(()=>{d()}).catch(h=>{p.error(`Model ${a.modelId} - ${a.type} failed to transition to ${s}: ${h.message}`),d()}),c])}))).filter(a=>a.status==="rejected");i.length>0&&p.error(`Model ${t.modelId} had ${i.length} failed child models on ${r}`)},va=async(t,e,s)=>{await wa(t,t.getChildren().filter(r=>!!r),e,s)},vt=async(t,e)=>{const r=(await Promise.allSettled(ba(t,e))).filter(o=>o.status==="rejected");r.length&&(p.error(`There were ${r.length} failed dependent models on ${e}`),p.error(r))},bh=t=>typeof t.toJSON=="function",Nt=t=>t[x]!==void 0,Mo=t=>t.revision!==void 0&&t.index!==void 0,Ma=t=>{if(t){if(Nt(t))return t;if(Mo(t))return t.data;if(t instanceof Map||t instanceof M.ObservableMap||t instanceof Set)return Array.from(t.values()).filter(Nt);if(Array.isArray(t))return t.filter(Nt)}};function wh(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),vh(t.modelData,t.modelTypeName,t.modelId,t)}function vh(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,d;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[x]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(u=>({type:u.modelTypeName,id:u.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(u=>({id:u.id||u.modelType,type:u.modelType,options:u.options,lifecycle:u.lifecycle}))},children:{count:o.length,data:o.map(u=>({id:u.modelId,type:u.modelTypeName}))},data:((d=t.toJSON)==null?void 0:d.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];Nt(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:Mo(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 Mh{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==b.FAILED).filter(r=>!!r);return s.forEach(r=>{try{K.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[xt])||{};return Object.keys(e).map(r=>Ma(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class Eh{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class _h{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[Ne])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},d=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(d)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Th=p.createLogger({name:"model-active-machine"}),Ih=t=>{const e=y.createMachine(b.INACTIVE,{[b.FAILED]:y.state(y.transition(A.GO_ACTIVE,b.ACTIVATING)),[b.INACTIVE]:y.state(y.transition(A.GO_ACTIVE,b.ACTIVATING)),[b.ACTIVATING]:y.invoke(()=>(t.activeStatus=b.ACTIVATING,t.activate()),y.transition("done",b.ACTIVE,y.action(()=>{t.activeStatus=b.ACTIVE})),y.transition("error",b.FAILED,y.action(()=>{t.activeStatus=b.FAILED}))),[b.ACTIVE]:y.state(y.transition(A.GO_INACTIVE,b.DEACTIVATING)),[b.DEACTIVATING]:y.invoke(()=>(t.activeStatus=b.DEACTIVATING,t.deactivate()),y.transition("done",b.INACTIVE,y.action(()=>{t.activeStatus=b.INACTIVE})),y.transition("error",b.FAILED,y.action(()=>{t.activeStatus=b.FAILED})))});return{service:y.interpret(e,r=>Th.debug(r.machine.current)),machine:e}},On=p.createLogger({name:"model-online-machine"}),Oh=t=>{const e=y.createMachine(b.OFFLINE,{[b.ONLINE]:y.state(y.transition(A.GO_OFFLINE,b.OFFLINE,y.action(async()=>{await t.offline(),t.onlineStatus=b.OFFLINE}))),[b.OFFLINE]:y.state(y.transition(A.GO_ONLINE,b.ONLINE,y.action(async()=>{On.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=b.ONLINE,await t.fsm.transitionTo(A.INITIALIZE,b.INITIALIZED)})))}),s=y.interpret(e,r=>On.debug(r.machine.current));return{machine:e,service:s}},Sh=t=>{var r;const e=Ih(t).service,s=Oh(t).service;return y.createMachine(b.CREATING,{[b.CREATING]:y.state(y.transition(A.CREATE,b.CREATED)),[b.CREATED]:y.state(y.immediate(b.INITIALIZING)),[b.INITIALIZING]:y.invoke(()=>(W(()=>{t.status=b.INITIALIZING}),t.init()),y.transition("done",b.INITIALIZED,y.action(()=>{t.status=b.INITIALIZED})),y.transition("error",b.FAILED,y.action(()=>{p.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=b.FAILED}))),[b.INITIALIZED]:y.state(y.immediate(b.LOADING)),[b.LOADING]:y.invoke(()=>(W(()=>{t.status=b.LOADING}),t.load()),y.transition("done",b.LOADED,y.action(()=>{t.status=b.LOADED})),y.transition("error",b.FAILED,y.action(()=>{t.status=b.FAILED}))),[b.LOADED]:y.state(y.immediate(b.READYING),y.transition(A.UNLOAD,b.UNLOADING)),[b.RESETTING]:y.invoke(()=>{var o;return W(()=>{t.status=b.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},y.transition("done",b.LOADED,y.action(()=>{t.status=b.LOADED}))),[b.READYING]:y.invoke(()=>(W(()=>{t.status=b.READYING}),t.ready()),y.transition("done",b.READY,y.action(()=>{W(()=>{t.status=b.READY}),s.send(A.GO_ONLINE)})),y.transition("error",b.FAILED,y.action(()=>{t.status=b.FAILED}))),[b.READY]:y.state(y.transition(A.UNLOAD,b.UNLOADED,y.action((r=t.unload)==null?void 0:r.bind(t))),y.transition(A.RESET,b.RESETTING),y.transition(A.GO_ONLINE,b.READY,y.action(()=>{s.send(A.GO_ONLINE)})),y.transition(A.GO_OFFLINE,b.READY,y.action(()=>{s.send(A.GO_OFFLINE)})),y.transition(A.GO_ACTIVE,b.READY,y.action(()=>{e.send(A.GO_ACTIVE)})),y.transition(A.GO_INACTIVE,b.READY,y.action(()=>{e.send(A.GO_INACTIVE)}))),[b.UNLOADED]:y.state(),[b.FAILED]:y.state()})},$h=p.createLogger({name:"kos-model-lifecycle"}),Dh=t=>({service:y.interpret(Sh(t),s=>$h.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class Ch{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=Dh(e);this.service=r.service,this.service.send(A.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=b.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[b.ACTIVE,b.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const Ea="browser-router-model";class Eo{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!Ps(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=me(Ea))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return Ps(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=na(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function Rh(t,e){if(!Ps(t))return;const s=me(Ea);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new Eo(t,e).setRouter(s.model)}class Ph{static create({modelId:e,modelTypeName:s,component:r}){const o=[r??"kos",s,e].filter(Boolean).join(".");return p.createLogger({name:o})}}class Ah{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e){this.queue.push(e)}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class Lh{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=$("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(A.GO_ONLINE,b.ONLINE)}),r=$("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(A.GO_OFFLINE,b.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}class xh{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=$(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function Sn(t){return new xh(t)}var _a=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(_a||{});const Ta=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${sr}:${s}
|
|
2
2
|
`;return o+=`topic:${t}
|
|
3
3
|
`,o+=`${lt}:${t}
|
|
4
|
-
`,o+=`${
|
|
4
|
+
`,o+=`${ts}:${e}
|
|
5
5
|
`,r&&(o+=`${Ie}:${r}
|
|
6
|
-
`),o+=`${
|
|
6
|
+
`),o+=`${ye}:kos.studio.request
|
|
7
7
|
`,o+=`
|
|
8
|
-
`,o},
|
|
8
|
+
`,o},Ia=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n})=>{let i=`${oi}:/http${t}
|
|
9
9
|
`;return i+=`${sr}:${s}
|
|
10
10
|
`,i+=`${lt}:${t}
|
|
11
|
-
`,i+=`${
|
|
11
|
+
`,i+=`${ci}:${e}
|
|
12
12
|
`,r&&(i+=`${Ie}:${r}
|
|
13
13
|
`),o&&(i+=`${ao}:true
|
|
14
14
|
`),n&&(i+=`${co}:${n}
|
|
15
|
-
`),i+=`${
|
|
15
|
+
`),i+=`${ye}:fos.http.request
|
|
16
16
|
`,i+=`
|
|
17
|
-
`,i},
|
|
17
|
+
`,i},Oa=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n,bridge:i,headers:a})=>{let c=`${sr}:${s}
|
|
18
18
|
`;return c+=`${lt}:${t}
|
|
19
|
-
`,c+=`${
|
|
19
|
+
`,c+=`${ts}:${e}
|
|
20
20
|
`,r&&(c+=`${Ie}:${r}
|
|
21
21
|
`),o&&(c+=`${ao}:true
|
|
22
22
|
`),n&&(c+=`${co}:${n}
|
|
23
23
|
`),a&&Object.keys(a).forEach(d=>{c+=`${d}:${a[d]}
|
|
24
|
-
`}),c+=`${
|
|
24
|
+
`}),c+=`${ye}:${i?"fos":"kos"}.http.request
|
|
25
25
|
`,c+=`
|
|
26
|
-
`,c},
|
|
26
|
+
`,c},Ae=(t,e)=>{let s=t;return e&&(s+=e),s};function Mt(t){const e={...t};return{append(s,r){e[s]=r},delete(s){delete e[s]},get(s){return e[s]},forEach(s){Object.keys(e).forEach(r=>s(e[r],r,this))},has(s){return Object.hasOwn(e,s)},set(s,r){e[s]=r},keys(){return Object.keys(e)},values(){return Object.values(e)},entries(){return Object.entries(e)}}}function Et(t){let e=!1;return window.ReadableStream?new ReadableStream({start(r){function o(){return Promise.resolve({done:e,value:t}).then(({done:n,value:i})=>{if(n){r.close();return}r.enqueue(i),e=!0,o()})}o()}}):t}const Sa=({path:t,requestId:e,destinationAddress:s})=>{let r=`topic:${t}
|
|
27
27
|
`;return r+=`${lt}:${t}
|
|
28
|
-
`,r+=`${
|
|
28
|
+
`,r+=`${ts}:${e}
|
|
29
29
|
`,r+=`${Ie}:${s}
|
|
30
|
-
`,r+=`${
|
|
30
|
+
`,r+=`${ye}:kos.studio.request
|
|
31
31
|
`,r+=`
|
|
32
|
-
`,r}
|
|
32
|
+
`,r},$a=({requestId:t,destinationAddress:e,requestType:s,headers:r})=>{let o=`${ts}:${t}
|
|
33
33
|
`;return o+=`${Ie}:${e}
|
|
34
|
-
`,o+=`${
|
|
34
|
+
`,o+=`${ye}:${s}
|
|
35
35
|
`,r&&Object.keys(r).forEach(n=>{o+=`${n}:${r[n]}
|
|
36
36
|
`}),o+=`
|
|
37
|
-
`,o},
|
|
37
|
+
`,o},Fh=(t,e)=>{const s=t,r=Ae($a(e),typeof s=="string"?s:JSON.stringify(s)),o=O.getInstance().transport.socket;o?(p.debug("Sending message",r),o.socket.send(r)):p.error("socket transport is not initialized")},Da=({path:t,responseId:e,status:s,destinationAddress:r})=>{let o=`topic:${t}
|
|
38
38
|
`;return o+=`${lt}:${t}
|
|
39
39
|
`,e&&(o+=`${rr}:${e}
|
|
40
40
|
`),o+=`${io}:${s}
|
|
41
41
|
`,o+=`${Ie}:${r}
|
|
42
|
-
`,o+=`${
|
|
42
|
+
`,o+=`${ye}:kos.studio.response
|
|
43
43
|
`,o+=`
|
|
44
|
-
`,o},
|
|
45
|
-
`;return e+=`${
|
|
44
|
+
`,o},kh=(t,e)=>{const s=t,r=Ae(Sa(e),JSON.stringify(s)),o=O.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Nh=(t,e)=>{const s=e.responseId?{status:e.status,data:t}:t,r=Ae(Da(e),JSON.stringify(s)),o=O.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Ca=({topic:t})=>{let e=`topic:${t}
|
|
45
|
+
`;return e+=`${ye}:kos.broker.send
|
|
46
46
|
`,e+=`
|
|
47
|
-
`,e},
|
|
47
|
+
`,e},Ra=({responseId:t,destinationAddress:e,type:s,sourceAddress:r,status:o})=>{let n=`${rr}:${t}
|
|
48
48
|
`;return n+=`${Ie}:${e}
|
|
49
|
-
`,n+=`${
|
|
50
|
-
`,n+=`${
|
|
49
|
+
`,n+=`${ni}:${r}
|
|
50
|
+
`,n+=`${ye}:${s??"kos.message.request"}
|
|
51
51
|
`,n+=`${io}:${o}
|
|
52
|
-
`,n+=`${
|
|
53
|
-
`,n+=`${
|
|
52
|
+
`,n+=`${ii}:application/json
|
|
53
|
+
`,n+=`${ai}:no-cache
|
|
54
54
|
`,n+=`
|
|
55
|
-
`,n},
|
|
55
|
+
`,n},Pa=({topic:t,responseId:e,destinationAddress:s,type:r})=>{let o=`topic:${t}
|
|
56
56
|
`;return e&&(o+=`${rr}:${e}
|
|
57
57
|
`),o+=`${Ie}:${s}
|
|
58
|
-
`,o+=`${
|
|
58
|
+
`,o+=`${ye}:${r??"kos.message.request"}
|
|
59
59
|
`,o+=`
|
|
60
|
-
`,o},
|
|
60
|
+
`,o},Uh=({msg:t,options:e})=>{const s=t,r=Ae(Ca(e),JSON.stringify(s)),o=O.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},Aa=({msg:t,options:e})=>{const s=t,r=Ae(Pa(e),JSON.stringify(s)),o=O.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},La=({msg:t,options:e})=>{const s=t,r=Ae(Ra(e),JSON.stringify(s)),o=O.getInstance().transport.socket;o?o.socket.send(r):p.error("socket transport is not initialized")},jr=(t,e)=>{try{return e?t.body??t:JSON.parse(t.body)}catch{return t.body||t}};class jh extends WebSocket{constructor(e){super(e)}}function $n(t){const e=`
|
|
61
61
|
|
|
62
62
|
`,s=`
|
|
63
|
-
`,r=/:(.*)/s,[o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[d,u]=c.split(r).map(h=>h.trim());return d&&u&&(a[d]=u),a},{}),body:n}}function
|
|
63
|
+
`,r=/:(.*)/s,[o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[d,u]=c.split(r).map(h=>h.trim());return d&&u&&(a[d]=u),a},{}),body:n}}function Bh(t){const e=`
|
|
64
64
|
|
|
65
65
|
`,s=`
|
|
66
|
-
`,r=/:(.*)/s,[,o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[d,u]=c.split(r).map(h=>h.trim());return d&&u&&(a[d]=u),a},{}),body:n}}class _o{constructor({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:n,onConnectionLost:i,Transport:a=
|
|
66
|
+
`,r=/:(.*)/s,[,o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[d,u]=c.split(r).map(h=>h.trim());return d&&u&&(a[d]=u),a},{}),body:n}}class _o{constructor({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:n,onConnectionLost:i,Transport:a=jh}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"socket");l(this,"connectionEstablished");l(this,"alias");l(this,"onConnectionEstablished");l(this,"onConnectionLost");l(this,"offlineMessages",[]);l(this,"oldSend");this.host=e,this.port=s,this.protocol=r,this.onConnectionEstablished=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 d,u;if(c!=null&&c.body){p.wsReceive(c==null?void 0:c.body);const h={data:c.body};(u=(d=this.socket)==null?void 0:d.onmessage)==null||u.call(d,h)}}),M.makeObservable(this,{connectionEstablished:M.observable})}addOfflineMessage(e){this.offlineMessages.push({msg:e})}processMessageEvent(e){const{data:s}=e;return $n(s)}onMessage(e){try{p.debug("webSocketTransport: onMessage received");const{headers:s,body:r}=this.processMessageEvent(e);p.wsReceive(e.data);const o=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(o){let n=r,i=s;if(o==="kos.sniffer.msg"){const{headers:a,body:c}=Bh(e.data);n=c,i={...s,...a}}B(o,n,i)}}catch(s){p.error("onMessage exception",s.message,s.stack)}}onOpen(e){p.info("websocket connection opened"),this.socket=e.currentTarget,M.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
|
|
67
67
|
alias:${this.alias}
|
|
68
68
|
|
|
69
|
-
`),p.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;p.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),M.runInAction(()=>{this.connectionEstablished=!1}),p.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(e){var s,r;if(p.wsSend(e),window.kosLogEvents){const{headers:o,body:n}=$n(String(e));
|
|
69
|
+
`),p.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;p.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),M.runInAction(()=>{this.connectionEstablished=!1}),p.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(e){var s,r;if(p.wsSend(e),window.kosLogEvents){const{headers:o,body:n}=$n(String(e));B(ss.SEND,{headers:o,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:o,requestId:n}=window.kosTopicIntercept(e);if(o){e=`mocked:true
|
|
70
70
|
${e}`;const a={data:`mocked:true
|
|
71
|
-
${o(n)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,e)}else this.oldSend.call(this.socket,e)}}class
|
|
71
|
+
${o(n)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,e)}else this.oldSend.call(this.socket,e)}}class Kh{constructor(e){l(this,"addEventListener");l(this,"dispatchEvent");l(this,"removeEventListener");l(this,"_onclose");l(this,"_onerror");l(this,"_onmessage");l(this,"_onopen");l(this,"messageQueue",[]);l(this,"isSending",!1);D.debug(`called Bridge Transport with addr ${e}`);const s=this;globalThis.kosWindowWebsocketRecv=r=>{if(s.onmessage){const o={data:r};s.onmessage(o)}},D.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),D.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>D.debug("not implemented"),this.dispatchEvent=()=>D.debug("not implemented"),this.removeEventListener=()=>D.debug("not implemented")}close(){D.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const e=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(e),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(e){this.messageQueue.push(e),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(e){globalThis.kosWindowWebsocketSend(e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage=e}get onopen(){return this._onopen}set onopen(e){this._onopen=e}get onclose(){return this._onclose}set onclose(e){this._onclose=e}get onerror(){return this._onerror}set onerror(e){this._onopen=e}}class Hh extends _o{constructor({host:s,port:r,alias:o}){super({host:s,port:r,Transport:Kh,alias:o,protocol:"kos://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class Gh extends _o{constructor({host:s,port:r}){super({host:s,port:r,protocol:"ws://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class zh extends _o{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 Br{static build({host:e,port:s,protocol:r,fos:o,alias:n,onConnectionEstablished:i,onConnectionLost:a}){return p.debug("initializing websocket connection"),p.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),p.warn(`fos: ${o?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!o?(p.warn("Using bridged message transport"),new Hh({host:e,port:s,protocol:r,onConnectionEstablished:i,onConnectionLost:a,alias:n})):o?new Gh({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a}):new zh({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a})}}const Vh=le();Vh.fos&&(window.kosUseFos=!0);const Dn=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=Dn?parseInt(Dn):0;const xe=D.getLogger("web-socket-transport");var xa=(t=>(t.NOT_INITIALIZED="not_initialized",t.INITIALIZED="initialized",t.OFFLINE="OFFLINE",t.ONLINE="ONLINE",t))(xa||{}),Ut=(t=>(t.CONNECTED="websocket.connected",t.DISCONNECTED="websocket.disconnected",t.RELOAD="websocket.reload",t))(Ut||{});class et{constructor({host:e="localhost",port:s=8080,protocol:r="ws://",token:o,initialize:n,alias:i,fos:a}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"_token");l(this,"webSocketSupported",!!globalThis.WebSocket);l(this,"authorized");l(this,"alias");l(this,"socket");l(this,"fosSocket");l(this,"fosPort");l(this,"useFosTransport");this.host=e,this.port=s,this.protocol=r,this._token=o,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!a,this.fosPort=a==null?void 0:a.port,this.socket=void 0,this.fosSocket=void 0;let c=!1;M.makeObservable(this,{authorized:M.observable,socket:M.observable,fosSocket:M.observable,init:M.action,connectionEstablished:M.computed}),M.reaction(()=>this.connectionEstablished,d=>{d&&(xe.warn("Connection Established"),B("websocket.connected","websocket.connected"),c&&B("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 e,s;if(p.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=Br.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=Br.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{xe.error("Connection Lost"),B("websocket.disconnected","websocket.disconnected"),this.init()}}),globalThis.kosWindowWebsocketOpen){const r={currentTarget:this.socket.socket};(s=(e=this.socket.socket)==null?void 0:e.onopen)==null||s.call(e,r)}return this}_sendSubscriptionMessage(e,s,r=!1,o=!1,n){var f,m,w,v;xe.debug(`${s} to topic ${e}`);const i=le(),a=i==null?void 0:i.connId,c=n??a??((f=window==null?void 0:window.kosBridge)==null?void 0:f.call(window,"connId"));xe.debug(`subscribing with connId ${c}`);const d=c?`dst-addr:${c}
|
|
72
72
|
`:"",u=r?`subscribe:${e}`:o?`type:fos.broker
|
|
73
73
|
cmd:${s}
|
|
74
74
|
${d}topics:${e}
|
|
75
75
|
`:`${d}type:kos.broker.${s}
|
|
76
76
|
|
|
77
|
-
["${e}"]`;if(r?(m=this.fosSocket)==null?void 0:m.connectionEstablished:(w=this.socket)==null?void 0:w.connectionEstablished){const E=r?this.fosSocket:this.socket;(v=E==null?void 0:E.socket)==null||v.send(u)}else{xe.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(u)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=O(e,s);return xe.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();xe.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(et,"_instance");class Gh{constructor(e){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=e,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(e){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of e)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(e,s)}async*processSingleEvent(e){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(e))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(e),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([e]):[e],this.updateProcessingStats([e])}}async*processBatchedEvents(e,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const d=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(d.length===0)return;this.config.backpressure&&await this.waitForCapacity();const u=this.config.transform?this.config.transform(d):d;return this.stats.batchesProcessed++,this.updateProcessingStats(d),u};try{for await(const d of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(d);this.eventQueue.length>0;){const u=this.dequeueEvent();u&&n.push(u);const f=Date.now()-i;if(n.length>=r||f>=o){const m=await a();m!==void 0&&(yield m);break}}else{n.push(d);const h=Date.now()-i;if(n.length>=r||h>=o){const f=await a();f!==void 0&&(yield f)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(e){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(e,s);return this.config.filter.historySize&&(this.filterHistory.push(e),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const e=Date.now(),s=Math.floor(e/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const e=Date.now(),o=(Math.floor(e/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-e;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=e;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-e;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(e){if(this.eventQueue.push(e),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const e=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,e}updateProcessingStats(e){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+e.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?e.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(e){return this.activePromises.add(e),e.finally(()=>this.activePromises.delete(e)),e}getStats(){return{...this.stats}}}class zh{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(e){var o;const s=((o=this.modelData)==null?void 0:o[W])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.flow)this.subscribeWithFlowControl(i,c,a);else{const d=this.createHandler(c,i);this.subscribe(i,c,d,a===N.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,o){const n=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=et.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=O(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(e,r,s);if(this.model.isReady()){const d=jr(r,s.skipParse),u=s.transform(d);if(a&&s.condition(u,this.modelData,r))return this.callHandlerWithWildcard(s,u,c,r)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`);const d=()=>{const u=jr(r,s.skipParse),h=s.transform(u);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)};this.offlineQueue.enqueue(d)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!aa(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return ia(e,o,r.wildcardName)}callHandlerWithWildcard(e,s,r,o){if(r&&Object.keys(r).length>0){const n={...o,wildcardCapture:r};return e.handler.call(this.modelData,s,n,this.modelData)}else return e.handler.call(this.modelData,s,o,this.modelData)}resolvePropKey(e){const s=/.*({PROP_(.+)})/;let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",this.modelId):e;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}async subscribeWithFlowControl(e,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const o=new Gh(e.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===N.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(e,s,r,o){const n=new AbortController;try{let i;if(e.websocket){const a=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;et.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Sn(s)}else i=Sn(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const o=e.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}}function Ge(t,e){const s=`[Model:${e}]`;return{debug:(...r)=>t.debug(s,...r),info:(...r)=>t.info(s,...r),warn:(...r)=>t.warn(s,...r),error:(...r)=>t.error(s,...r)}}function Vh(t){return!!(t!=null&&t[Ne])&&Object.keys(t[Ne]).length>0}function Yh(t){return!!(t!=null&&t[W])&&Object.keys(t[W]).length>0}function qh(t){return!!(t!=null&&t[Ee])&&t[Ee].length>0}class Wh{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=Dh.create({modelId:s,modelTypeName:r}),i=new Sh(e,Ge(n,"fsm")),a=new Ch(Ge(n,"offline-queue")),c=new wh(e),d=new bh(e),u={fsm:i,offlineQueue:a,companionManager:c,childResolver:d};if(Vh(o)&&(u.effectManager=new vh(r,s,o,Ge(n,"effect"))),Yh(o)){const h=Ge(n,"subscription");u.subscriptionManager=new zh(e,o,s,a,h),u.onlineLifecycleManager=new Rh(e,Ge(n,"online"))}return qh(o)&&(u.httpRouteManager=new Eo(o,Ge(n,"http-routes"))),u}}const P=$.getLogger("kos-model"),Qh="kos.extension.model.loader";class xa{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=b.CREATED,this._activeStatus=b.INACTIVE,this._onlineStatus=b.OFFLINE;const o=Wh.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),mh(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===b.ACTIVE}isOnline(){return this._onlineStatus===b.ONLINE}isReady(){return this._status===b.READY}async deactivate(){var e,s,r;P.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=j.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),P.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw P.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r;P.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await wt(this,N.ACTIVATE);try{const o=j.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.activate)==null?void 0:s.call(e,o)),P.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(r=this.subscriptionManager)==null||r.registerAll(N.ACTIVATE),P.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw P.debug(`Model ${this.modelId} failed to activate`),o}}async whenLoaded(){await Or([{condition:()=>this.status===b.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{P.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await Or([{condition:()=>this.status===b.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{P.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Or([{condition:()=>this.status===b.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===b.READY,onMatch:()=>{P.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r;if(this.fsm.current===b.READY){P.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{P.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await wt(this,N.READY),await wa(this,vo.READY,N.READY);const o=j.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.ready)==null?void 0:s.call(e,o)),this.offlineQueue.flush(),(r=this.subscriptionManager)==null||r.registerAll(N.READY),P.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};U(ca(this.modelTypeName,this.modelId),n),U(la(this.modelTypeName),n)}catch(o){throw P.error(o),Error(o)}}async load(){var o,n,i,a,c;const e=this[Rs];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===b.LOADED||this.fsm.current===b.LOADING){P.debug(`Model ${s} with id ${r} already loaded or loading`);return}P.debug(`Loading model ${s} with id ${r}`),await wt(this,N.LOAD);try{const d=j.getContext(r),u=`${Qh}.${s}`,h=await S.loader.executeLoader(u,{});h&&(P.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(u,h)),await((n=(o=this.modelData)==null?void 0:o.load)==null?void 0:n.call(o,d)),q(()=>{this.loaded=!0}),P.debug(`Model ${s} with id ${r} successfully loaded`),(i=this.subscriptionManager)==null||i.registerAll(N.LOAD),(a=this.httpRouteManager)==null||a.registerAll(),(c=this.effectManager)==null||c.setup()}catch(d){throw P.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,o,n,i;P.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const a=this.getChildren().map(d=>{var u;return(u=d.unload)==null?void 0:u.call(d)}).filter(d=>!!d);await Promise.allSettled(a);const c=j.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,c)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),P.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 P.debug(`Model ${this.modelId} failed to unload`),a}}async init(){var n,i,a;const e=this[Rs];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=j.getContext(s);P.debug(`Initializing model ${r} with id ${s}`),await wt(this,N.INIT);try{await((i=(n=this.modelData)==null?void 0:n.init)==null?void 0:i.call(n,o)),this.initialized=!0,P.debug(`Model ${r} with id ${s} initialized`),(a=this.onlineLifecycleManager)==null||a.register(),this.registerSubscribers(N.INIT)}catch(c){throw P.error(`Model ${s} failed to initialize`,c),c}}async registerSubscribers(e){var s;P.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}async online(){var s,r;P.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=j.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e))}async offline(){var s,r,o;P.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=j.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,e))}accept(e){e.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(e){this.companionManager.add(e)}clearCompanionModels(){this.companionManager.clear()}}const Fa=t=>typeof t=="function",Cn=p.createLogger({name:"kos-model-instantiator"});class Zh{constructor(e,s){this.registry=e,this.cache=s}createModelInstance(e,s,r={}){const o=this.registry.models[e];if(!o)throw new Error(`No model registered for type ${e}`);const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Cn.debug(`Creating model instance: ${e} [${n}]`);const a=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),c=new xa({modelTypeName:e,id:n,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(n);if(!i)throw Cn.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}_createCompanionModels(e,s){var n;const r=e.modelTypeName,o=((n=this.registry.companionModels)==null?void 0:n[r])||[];for(const{type:i}of o){const a=Fa(i)?i(e.modelData,s):i;if(!a)continue;const c=`${a}-${e.modelId}`,d=this.createModelInstance(a,c,{data:s,companionParent:e.modelData,kosParentId:e.modelId});d!=null&&d.model&&(d.model[Rs]=e,e.addCompanionModel(d.model))}}}let Jh=class{constructor(e){this._registry=e}get registry(){return this._registry}getModelTypeRegistry(e){const s=this.registry.models[e];if(!s)throw new Error(`No registration for model type ${e}`);return s}registerModel(e){const s=e.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...e.registration})}registerCompanionModel(e,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[e]??(o[e]=[]),this.registry.companionModels[e].some(n=>n.type===s)||this.registry.companionModels[e].push({type:s})}getModelSubscriptions(e){var s;return((s=this.getModelTypeRegistry(e))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(e){var r;const s=(r=this.getModelTypeRegistry(e))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${e}`);return s}getModelFactory(e){return ht(e)}};const ka=10,Rn=p.createLogger({name:"kos-model-manager"});class Na{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Gu,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=e=>{const s=this.getModelById(e);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=e=>{var r,o;const s=this.getModelById(e);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=e=>{var r;const s=this.getModelById(e);if(s)return((r=s.modelData)==null?void 0:r.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(e,s){const r=this.getInstance(s);return r._registry=new Jh(e),r.cache=new zu(e.preloadModels),r.instantiator=new Zh(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Rn.debug("Creating new instance of KosModelManager"),new this),(r=globalThis.kos)==null?void 0:r.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(e=>(Rn.debug(`preloading ${e}`),typeof e=="string"?this.createModelInstance(e).model:this.createModelInstance(e.modelType,e.modelId,e.options).model))}get models(){return this.cache.models}getModelById(e){return this.cache.getModelById(e)}addModel(e){return this.cache.addModel(e)}removeModel(e){this.cache.removeModel(e.modelId)}hasModel(e){return this.cache.hasModel(e)}getModelsByType(e,s){return Array.from(this.models).filter(r=>r.modelTypeName===e).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(e){return this._registry.getModelSubscriptions(e)}getDataModelBuilder(e){return this._registry.getDataModelBuilder(e)}getModelFactory(e){return ht(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(A.RESET,b.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),ea.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),ka)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var Is=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.RELOADING="reloading",t))(Is||{}),We=(t=>(t.CREATE="create",t.INITIALIZE="init",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.UNLOAD="unload",t.RELOAD="reload",t))(We||{});const Xh=t=>{const e=y.createMachine("offline",{online:y.state(y.transition("go_offline","offline",y.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:y.state(y.transition("go_online","online",y.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=y.interpret(e,n=>$.debug(n.machine.current)),r=y.createMachine({creating:y.state(y.transition("create","created")),created:y.state(y.immediate("initializing")),initializing:y.invoke(()=>t.init(),y.transition("done","initialized")),initialized:y.state(y.immediate("loading")),loading:y.invoke(()=>t.load(),y.transition("done","loaded")),loaded:y.state(y.immediate("readying"),y.transition("unload","unloading")),readying:y.invoke(()=>t.ready(),y.transition("done","ready",y.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:y.invoke(()=>t.reload(),y.transition("done","loading")),ready:y.state(y.transition("reload","reloading"),y.transition("unload","unloaded",y.action(t.unload.bind(t))),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=>$.debug(n.machine.current)),online:s}},se=async t=>{if(t.id){const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},Ue=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(t)},eg=async t=>{if(await I.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(A.UNLOAD,b.UNLOADED)},Ua=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(t),p.debug(`reload model initiated for model ${t.id}, model ready: ${Ps(t)} - ${Date.now()} `),await se(t),p.debug(`reload model complete for model ${t.id}, model ready: ${Ps(t)} - ${Date.now()} `)},tg=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},ja=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},pe=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Ba=(t,e)=>{if(!t)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},sg=(t,e)=>Ba(t,e)[0],rg=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},Ka=t=>{if(!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},og=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},Kr=(t,e)=>{const s=I.getInstance().modelManager.getModelById(t);if(!s){p.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},ce=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,Ps=t=>{const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},ng=p.createLogger({name:"kos-model-factory"}),Ut={byModelType:t=>I.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=Ut.byModelType(e);if(!r)throw ng.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},Z={Factory:{create:t=>e=>(s,r)=>(r&&j.setParentContext(e,r),Ut.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&j.setParentContext(t,s),Ut.getModelInstance(t,t,e))},Model:{instance:t=>e=>Ut.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const An=window.KosRegistry.coreModels,Sr=window.KosRegistry.preloadModels,$r=window.KosRegistry.companionModels,gs=window.KosRegistry.models,C={model:{registerLegacyModel:t=>(e,s)=>(An.set(e,s),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(Sr.includes(e)||Sr.push(e),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=Dr(e)?e.registration():e;return gs.set(r.type,r),Dr(e)&&e.relatedModels.forEach(o=>gs.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],Dr(e)&&e.relatedModels.forEach(o=>I.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&C.model.preloadModel(t)(r.type),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},get:t=>gs.get(t),getAll:()=>Array.from(gs.entries()),getPreloadModels:()=>Sr,getLegacyModels:()=>Array.from(An.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=$r.get(e)||[];return r.push(s),$r.set(e,r),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from($r.entries())}},Ha=C.model.registerLegacyModel,Ga=C.model.register,ig=C.companion.register,ag=C.model.preloadModel,za=t=>typeof t.updateModel=="function",Dr=t=>t.registration!==void 0&&typeof t.registration=="function";class Va{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=ce(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){C.model.register({})(this.registration()),this.registerRelatedModels()}}class ge extends Va{constructor(e){super({...e,singleton:!1,factory:Z.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=pe(e);if(!r)throw new Error("Model not found with id "+e);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(za(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 ye extends Va{constructor(e){super({...e,singleton:!0,factory:Z.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=pe(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=e(r);if(this.guard(o)){if(za(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})},options:r=>({build:()=>{const o=e(r);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const H=p.createLogger({name:"kos-core"}),cg=()=>{const t=ae(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},lg=()=>{const t=window.location.protocol,e=ae(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},dg=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=ae(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},ug=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=ae(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},hg=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?p.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):p.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},Pn=t=>typeof t.reload=="function",gg=t=>typeof t.unload=="function";var Ya=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(Ya||{});class I{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=Is.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),O("token",a=>{a&&(this.transport.token=a.body)}),O(Nt.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(We.GO_ONLINE)}),O(Nt.DISCONNECTED,async()=>{this.fsmService.service.send(We.GO_OFFLINE)}),O("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),O("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),O(Nt.RELOAD,()=>{this.fsmService.service.send(We.RELOAD)}),O("/studio/project/reload",()=>{this.fsmService.service.send(We.RELOAD)});const s=et.getInstance(),r=dg(),o=ug(),n=lg();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=cg()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Xh(this),this.fsmService.service.send(We.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var o,n,i,a;const e=Date.now();if(this._reloading){H.info("reload already in progress");return}this._reloading=!0,H.warn("reloading KOS Core"),H.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Pn(c.modelData)&&(H.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),H.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Pn(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{H.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){H.debug("KOS Core going online"),await this._transport.whenReady(),H.debug("KOS Transport Ready. Calling online() for models"),U("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){H.debug("KOS Core going offline"),U("/kosCore/offline","/kosCore/offline")}async unload(){var o;H.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,H.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)gg(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===Is.READY)}async ready(){H.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(e.map(o=>{const{promise:n,cancel:i}=hg(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw H.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);H.debug("leaving kos-core ready() ")}get isReady(){return this.status===Is.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){H.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,H.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){H.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,H.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(d=>{var h,f;const u=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[d];u&&(Array.isArray(u)?u.forEach(m=>{S.dataMapper.registerDataMapper(d,m)}):S.dataMapper.registerDataMapper(d,u))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(d=>{var h,f;const u=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[d];u&&S.propertyMapper.registerPropertyMapper(d,u)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(d=>{var h,f;const u=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[d];u&&S.loader.registerLoader(d,u)}),C.model.getAll().forEach(([,d])=>{e.models={...e.models,...d.registration}}),e.models={...e.models,...C.model.getLegacyModels()},C.companion.getAll().forEach(([d,u])=>{e.companionModels={...e.companionModels},e.companionModels[d]=e.companionModels[d]||[];for(const h of u)e.companionModels[d].push({type:h})}),C.model.getPreloadModels().forEach(d=>{e.preloadModels.includes(d)||e.preloadModels.push(d)});const n=Na.create(e,s);return o.modelManager=n,o}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function Hr(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function fg(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function pg(t){return await t.arrayBuffer()}function mg(t,e){return new Blob([t],{type:e||"application/octet-stream"})}async function yg(t){const e={},s=[],r=[];t.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:Hr(i)})}else e[o]=n.toString();return{fields:e,files:s}}function bg(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function wg(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:Hr(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await pg(t);return{data:Hr(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await yg(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const fs=p.createLogger({name:"kos-fetch"}),vg=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Mg=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),Eg=t=>t!=null&&t.studio?_a:t!=null&&t.fos?Ta:Ia,_g=async(t,e)=>{const s=I.getInstance().transport;await s.whenReady();const r=dt(),o=new URL(t),n=`${o.pathname}${o.search}`;fs.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||vg,a=Eg(e),c=await wg(e==null?void 0:e.body),d={};c.contentType&&(d["content-type"]=c.contentType),c.encoding&&(d["content-encoding"]=c.encoding);const u=Pe(a({path:n,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...d}}),c.data);return new Promise(h=>{let f=null,m=null;if(e!=null&&e.signal){if(e.signal.aborted){h({headers:vt({}),status:0,ok:!1,json:async()=>null,body:Mt(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}});return}e.signal.addEventListener("abort",()=>{m&&clearTimeout(m),f&&f(),h({headers:vt({}),status:0,ok:!1,json:async()=>null,body:Mt(""),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.")}})})}m=setTimeout(()=>{fs.error(`Timeout occurred - url: ${t}`),f&&f(),h({headers:vt({}),status:404,ok:!1,json:async()=>null,body:Mt(""),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 w=O(r,E=>{m&&clearTimeout(m);const T=(E==null?void 0:E.headers)||{},K=T["content-type"]||"text/plain",fe=T["content-encoding"],we=(E==null?void 0:E.body)||"";let D=we;if(fe==="base64"&&we)try{D=fg(we)}catch(F){fs.error("Failed to decode base64 response",F)}const z={headers:vt(T),status:T.status&&parseInt(T.status)||200,ok:T.status==="200",json:async()=>{try{if(typeof D=="string")return D.length?JSON.parse(D):null;{const V=new TextDecoder().decode(D);return V.length?JSON.parse(V):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof D=="string"?D:new TextDecoder().decode(D),arrayBuffer:async()=>D instanceof ArrayBuffer?D:new TextEncoder().encode(D).buffer,blob:async()=>D instanceof ArrayBuffer?mg(D,K):new Blob([D],{type:K}),formData:async()=>{const F=new FormData;if(K==="multipart/form-data"&&typeof D=="string")try{const V=JSON.parse(D);V.fields&&Object.entries(V.fields).forEach(([Se,ve])=>{F.append(Se,ve)}),V.files&&fs.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return F},body:e!=null&&e.stream?bg(async F=>{if(D instanceof ArrayBuffer)F.enqueue(new Uint8Array(D));else{const V=new TextEncoder;F.enqueue(V.encode(D))}F.close()}):Mt(typeof D=="string"?D:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};w.unsubscribe(),Mg().then(()=>h(z))});f=w.unsubscribe;const v=e!=null&&e.fos?s.fosSocket:s.socket;if(!v)throw Error(`No web socket transport available: ${e}`);v==null||v.send(u)})};exports.BASE_URL="kos:";exports.kosFetch=_g;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const Tg=p.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Ig{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){Tg.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}const qa=()=>({isMock:!1,URL:exports.BASE_URL}),Og=p.createLogger({name:"kos-service-request"}),Sg="errUnknown";async function ps(t,e,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(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${h}=${r.query[h]}`).join("&"):"",a=`${qa().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;Og.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const d=await exports.kosFetch(a,c);return d.status<200||d.status>=400?[`${d.statusText||Sg}`,null]:[null,(await d.json()).data]}function To(){return{get:(t,e,s)=>ps(t,"get",s,e),post:(t,e,s,r)=>ps(t,"post",r,e,s),put:(t,e,s,r)=>ps(t,"put",r,e,s),delete:(t,e,s,r)=>ps(t,"delete",r,e,s)}}class Wa{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const $g=async(t,e)=>{const s=new Wa;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},ht=t=>({type:t,build:(e,s)=>I.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=I.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),Dg=t=>{I.getInstance().modelManager.registerModel(t)},Cg=(t,e)=>{I.getInstance().modelManager.registerCompanionModel(t,e)},Qa=Symbol("KosObservableData");class Za{constructor(){l(this,"map");l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var o;return this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=M.observable.map(new Map)}setValue(e,s){this.map.set(e,s)}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}Za.prototype[Qa]=!0;function Rg(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const De=t=>{const e=Rg(Za,t);return new e(t)},Ln="/kos/ui/internal/heartbeat/",Ag=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${Ln}${t}`,callback:()=>{a=performance.now()}}),d=r??3e3,u=window.setInterval(()=>{let v=performance.now()-a;v=v/1e3,v>d/1e3&&i.abort()},d),h=o??2e3,f=window.setInterval(()=>{Aa({msg:{},options:{topic:`${Ln}${t}`,destinationAddress:e}})},h),m=()=>{window.clearInterval(f),window.clearInterval(u),c()},w=()=>{m(),s&&s(),i.signal.removeEventListener("abort",w)};return i.signal.addEventListener("abort",w),{cleanUpHeartbeat:m}},Ja=(...t)=>e=>t.reduce((s,r)=>r(s),e),Pg={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Lg(t,e){let s=1;const r={...Pg,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(p.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(d=>setTimeout(d,a)),s++;else throw c}throw new Error("All attempts failed")}const xg=p.createLogger({name:"kos-service-request"}),X=t=>({isMock:!1,URL:exports.BASE_URL}),Fg=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:d,destinationAddress:u})=>{const h={method:"DELETE"};t&&(h.destinationAddress=t),o&&(h.tracker=o),gt(h,{ordered:i,studio:a,fos:c,bridge:d,destinationAddress:u});const f=await s(n||`${e}/${r}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},gt=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i})=>(i&&(t.timeout=i),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),kg=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,destinationAddress:d})=>{const u={method:"GET"};t&&(u.destinationAddress=t),gt(u,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=await s(r||e,u);if(!f.ok){let w;try{w=await f.json()}catch{}throw new ie(`There was a problem retrieving the model; returned status ${f.status}`,w)}return await f.json()},Ng=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:d,destinationAddress:u})=>{const h={method:"GET"};t&&(h.destinationAddress=t),c&&(h.tracker=c),gt(h,{timeout:d,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const f=r||e;xg.debug(`resolvedUrl: ${f}`);const m=await s(f,h);if(!m.ok){let v;try{v=await m.json()}catch{}throw new ie(`There was a problem retrieving the model; returned status ${m.status}`,v)}return await m.json()},Ug=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:d,destinationAddress:u})=>{const h={method:"GET"};t&&(h.destinationAddress=t),gt(h,{timeout:d,ordered:n,studio:i,fos:a,bridge:c,destinationAddress:u});const f=r||`${e}/${o}`,m=await s(f,h);if(!m.ok){let v;try{v=await m.json()}catch{}throw new ie(`There was a problem retrieving the model; returned status ${m.status}`,v)}return await m.json()};class ie extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const xn=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:d,timeout:u,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(f.destinationAddress=t),i&&(f.tracker=i),gt(f,{timeout:u,ordered:n,studio:a,fos:c,bridge:d,destinationAddress:h});const m=await s(o||e,f);if(!m.ok){let v;try{v=await m.json()}catch{}throw new ie(`There was a problem sending the POST data; returned status ${m.status}`,v)}return await m.json()},Fn=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:d,bridge:u,timeout:h,destinationAddress:f})=>{const m={method:t};o&&(m.body=JSON.stringify(o)),e&&(m.destinationAddress=e),gt(m,{timeout:h,ordered:a,studio:c,fos:d,bridge:u,destinationAddress:f});const w=await r(i||`${s}/${n}`,m);if(!w.ok){let E;try{E=await w.json()}catch{}throw new ie(`There was a problem modifying the model; returned status ${w.status}`,E)}return await w.json()},J={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:kg(t,s||e,c),getModelById:Ug(t,r||e,c),getOne:Ng(t,r||e,c),addModel:xn(t,n||e,c),deleteModel:Fg(t,o||e,c),modifyModel:Fn("POST",t,i||e,c),putModel:Fn("PUT",t,i||e,c),postModel:xn(t,n||e,c)}}},jg=dt(),Xa=()=>`kos-${jg}`,Bg=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(Xa()),Io=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=O(t,i=>{$.debug(`recieved response for refId ${t}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),Kg=async(t,e,s)=>{const r=Io(s),o=await Promise.allSettled([t(e),r]);if(o[0].status==="fulfilled"){if(o[1].status==="rejected")throw Error(o[1].reason);if(o[0].value){if(o[1].value.error)throw Error(o[1].value.error);return o[0].value.data=o[1].value,o[0].value}}else throw Error(o[0].reason)},Hg=async({topic:t,msg:e,requestId:s})=>{const r=s??dt(),o=Io(r);U(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},re=new Map;class ec{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){q(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=pe(this._parent))==null?void 0:e.model}get companionModels(){const e=pe(this._id);return e!=null&&e.model?Ka(e.model):[]}get(e){var s,r;if(this._context.has(e))return this._context.get(e);if(this.companionModels.length>0){const o=this.companionModels.find(n=>{var i;return!n.id||!re.has(n.id)?!1:(i=re.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=re.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=re.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const j={createContext:(t,e)=>{const s=re.get(t)??new ec(t);if(e){if(!re.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return re.set(t,s),s},getContext:t=>re.get(t),deleteContext:t=>{re.delete(t)},setParentContext:(t,e)=>{var s;if(!re.has(e))throw new Error(`Parent context ${e} does not exist`);(s=re.get(t))==null||s.setParent(e)},rootContext:()=>re.get("root")};j.createContext("root");const Gg=t=>j.getContext(t.id);function zg(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class Oo{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=De(),this.generateIndex(),M.autorun(()=>{this._container.revision&&this.generateIndex()}),M.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(e,s,r=this._map,o=this.data){const n=r.get(e)||new Set;n.add(s),r.set(e,n),o[e]=Array.from(n)}resolveIndex(e,s){this.data.keys.filter(o=>!Object.keys(s).includes(o)).forEach(o=>{delete this.data[o],this._map.delete(o)}),Object.keys(s).forEach(o=>{const n=s[o],i=this.data[o]||[];if(zg(n,i))p.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=e.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){M.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,e,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,e,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function Vg(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>M.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const yt=p.createLogger({name:"kos-container-model"});class be{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?S.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const o=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=M.observable.map(o),this.idx=De(),this._parentId=e==null?void 0:e.parentId,M.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Oo({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(e,s){this._data.set(e.id||"",e),e.id&&this._parentId&&j.setParentContext(e.id,this._parentId),s||this.increment();const r=this._disposerMap.get(e.id);r&&(r(),this._disposerMap.delete(e.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([u,h])=>[h,u])),a=u=>{var f,m;n.includes(u.name)&&((f=this.index.get(i.get(u.name)))==null||f.refresh());const h=o.filter(([,w])=>typeof w=="function");for(const[w]of h)(m=this.index.get(w))==null||m.refresh()},c=Vg(e,a,n.filter(u=>typeof u=="string")),d=M.observe(e,a);this._disposerMap.set(e.id||"",()=>[d,...c].forEach(u=>u()))}removeModel(e,s){this._data.delete(e),s||this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(yt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(yt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return yt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(e=>{const s=e.id;Ue(e).then(()=>{yt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>yt.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const Cr=p.createLogger({name:"kos-data-container"});class So{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=De(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Oo({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}get revision(){return this._revision}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s))})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=M.isObservable(e)?e:M.observable.object(e),o=this._disposerMap.get(e.id);o&&(o(),this._disposerMap.delete(e.id)),this._data.set(r.id||"",r),s||this.increment();const n=M.observe(r,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(r.id||"",n)}removeModel(e){this._data.delete(e),this.increment();const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}updateModel(e){const s=M.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Cr.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(Cr.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Cr.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class Yg{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return Z.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return ce(this.type)}}class qg{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return Z.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return ce(this.type)}}class tc{constructor(){l(this,"_token");M.makeAutoObservable(this),O("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class sc{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:o})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===e&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===e&&o.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(e.path),i={...e,params:n,query:o};for(const c of this.routes){const d=this.matchRoute(c.path,r);if(c.method===e.method&&d){i.params=d;let u=0;const h=async()=>{if(u<c.middlewares.length){const f=c.middlewares[u++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),o=this.parseQueryParams(r);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:o,params:i}}return{path:s,query:o,params:{}}}matchRoute(e,s){const r=e.split("/").filter(Boolean),o=s.split("/").filter(Boolean);if(r.length!==o.length)return null;const n={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))n[r[i].slice(1)]=decodeURIComponent(o[i]);else if(r[i]!==o[i])return null;return n}parseQueryParams(e){return e?e.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const rc=p.createLogger({name:"intent-service"}),Wg=t=>{uo(`/kos/intent/${t.type}`)?U(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):rc.info(`No subscribers for intent ${t.type}. Intent not sent.`)},Qg=async t=>new Promise(e=>{const{type:s,options:r}=t;if(uo(`/kos/intent/${t.type}`)){const o=dt(),{unsubscribe:n}=O(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);U(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else rc.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Me=p.createLogger({name:"app-startup-service"});async function oc(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return Me.warn("No app IDs provided to waitForAppsToStart"),!0;Me.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await fo(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>ep),[d,u]=await c.get("/api/kos/apps/started");return d?(Me.error("Error fetching started apps:",d),[]):u}catch(c){Me.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(d=>{const u=c.find(h=>h.appId===d);return!(!u||!u.started||o&&!u.postStarted)}),timeout:s}),a=t.filter(c=>{const d=i.find(u=>u.appId===c);return!!(!d||!d.started||o&&!d.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(Me.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return Me.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Me.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function Zg(t,e={}){return oc([t],e)}async function Jg(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];t.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){Me.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function Xg(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return Me.error("Failed to fetch started apps:",t),[]}}const Gr=M.when,$o=M.computed,q=M.runInAction,B=M.autorun,nc=M.reaction,Do=M.observable,Co="Not Assigned",ef="kos.trouble.added",tf="kos.trouble.removed";var de=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(de||{}),jt=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(jt||{});const ic=p.createLogger({name:"config-bean-service",group:"Services"}),Ro=exports.BASE_URL,ac=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:sf,getOne:rf}=J.build({destinationAddress:"",basePath:`${Ro}/kos/config/`}),cc=async(t,e,s="/api/kos/config")=>(ic.debug(`sending modify request for ConfigBean: ${t}`),sf({model:e,urlOverride:`${Ro}${s}/${t}`})),lc=async(t,e="/api/kos/config")=>(ic.debug(`sending get request for ConfigBean: ${t}`),await rf({urlOverride:`${Ro}${e}/details/${t}/15`})),Ao=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",lr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function dc(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function uc(t,e="",s={}){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e?`${e}.${r}`:r;typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])?uc(t[r],o,s):s[o]=t[r]}return s}const hc=(t,e)=>{const s=t.details[0].bean||dc(t.details[0].scopes),r=uc(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},gc=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&Ao(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&lr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},fc=t=>Object.fromEntries(t.props.entries),of=t=>e=>s=>t.build(e,s);var nf=Object.defineProperty,af=Object.getOwnPropertyDescriptor,pc=(t,e,s,r)=>{for(var o=r>1?void 0:r?af(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&nf(e,s,o),o};function cf(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Po="config-bean-model",ms=p.getLogger(Po),lf=Be("path");let Ls=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=cc,getConfigBean:r=lc}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=De(),this.prevProps=De()}get values(){return this.props.values}async ready(){ms.debug(`readying config bean ${this.path}`),ms.debug(`complete readying config bean ${this.path}`)}async load(){ms.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;hc(e,this),ms.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;q(()=>{s&&(this._schema=s)})}}get schemaKeys(){var t;return Object.keys(((t=this._schema)==null?void 0:t.schema)||{})}getSchemaForProperty(t){var s,r;if(this.schemaKeys.includes(t))return(s=this._schema)==null?void 0:s.schema[t];const e=cf(this.schemaKeys,t);if(e)return(r=this._schema)==null?void 0:r.schema[e]}async updateProperty(t,e){this.props[t]=e,await this.updateConfigBean()}async updateConfigBean(){const t=fc(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){gc(t,this)}};pc([x({topic:`/kos/config/${lf}`,websocket:!0})],Ls.prototype,"handleConfigBeanUpdated",1);Ls=pc([R(Po)],Ls);const Ht=new ge({class:Ls,type:Po}),dr=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[L]=r[L]||{},r[L][o]={modelType:Ht.type,id:`${Ht.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:N.INIT,lazy:e}},{URL:mc}=X(),{getOne:df,getAll:uf}=J.build({basePath:`${mc}/api/kos/regions/info`}),yc=async()=>await df({}),bc=async()=>await uf({urlOverride:`${mc}/api/kos/regions`}),hf=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:yc,getRegions:bc},Symbol.toStringTag,{value:"Module"}));var te=(t=>(t[t.family=0]="family",t[t.scale=1]="scale",t[t.offset=2]="offset",t[t.decimals=3]="decimals",t[t.alias=4]="alias",t[t.system=5]="system",t))(te||{});const wc={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 gf(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{...wc});return{...t,...r}}function ff(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...wc}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function pf(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),o[n.measure]=i,o},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}var mf=Object.defineProperty,yf=Object.getOwnPropertyDescriptor,Lo=(t,e,s,r)=>{for(var o=r>1?void 0:r?yf(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&mf(e,s,o),o};const Os="region-info-model",bt=p.createLogger({name:"region-info-model"});let Gt=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[te.system]}getUnitMeasure(t){const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[te.family]}getDefaultUnitDecimalPlaces(t,e,s){if(!t||!e)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[t];if(!o)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[e.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(o).join(", ")}`);const i=n[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${t} and unit system: ${e}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[te.decimals]}getDefaultUnitForMeasure(t,e){if(!t||!e)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[t];if(!s)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[e.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(t,e,s){if(e[te.family]!==s[te.family])throw new Error(`Cannot convert between units of different families: ${e[te.family]} and ${s[te.family]}`);const r=e[te.offset],o=e[te.scale],n=s[te.scale],i=s[te.offset],a=s[te.decimals];return((t-r)/(o/n)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,o)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];if(!i&&s.measure&&s.system){const d=this.measureMap[s.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=d[s.system])==null?void 0:a.default,i||bt.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const d=this.measureMap[e.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=d[e.system])==null?void 0:c.default,n||bt.info("Could not find default unit for measure",e.measure)}return!n||!i?(bt.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){bt.debug("initializing region info")}async load(){bt.debug("loading region info");const t=await bc();t&&(this.regions=t.data.map(s=>s.id),this.timeZoneMap=t.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=t.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const e=await yc();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(gf,{}),this.measureMap=e.data.unitSystems.reduce(ff,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(pf,{}),this.timeFormats=e.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=e.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var t,e;await((e=(t=this.regionSource).ready)==null?void 0:e.call(t))}};Lo([dr({path:"kos:service:region:settings"})],Gt.prototype,"regionSource",2);Lo([dr({path:"kos:service:region"})],Gt.prototype,"region",2);Gt=Lo([R(Os)],Gt);const Q={registration:{[Os]:{class:Gt,singleton:!0}},type:Os,factory:Z.Singleton.create(Os)},xs=({source:t,defaultSystem:e="si",defaultMeasure:s})=>{let r={system:e,measure:s};return typeof t=="string"?r={...r,unit:t}:r={...r,...t},r},xo=(t,e,s)=>{const{model:r}=pe(Q.type);if(!r)throw new Error("RegionInfo model not found");if(!Ps(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=xs({source:e}),i=xs({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function kn(t,e,s){const r=e.toLowerCase().replace(/_/g,"-").replace(/s$/,""),o=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const n=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(o,{style:"unit",unit:r,unitDisplay:n,minimumFractionDigits:a,maximumFractionDigits:i}).format(t)}catch{return e}}const bf=(t,e,s,r)=>{const o=xo(t,e,s),n=xs({source:e}),{model:i}=pe(Q.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},d=xs({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),u=i.getDefaultUnitForMeasure(a,d.system),h=i.getDefaultUnitDecimalPlaces(a,d.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:u||n.unit||"",display:kn(o,u||n.unit||"",{...f,mode:"long"}),shortDisplay:kn(o,u||n.unit||"",{...f,mode:"short"})}};function Nn({start:t,end:e,count:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(t>=e)throw new Error("Start should be less than end.");const o=(e-t)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(t+i*o);n.push(a.toFixed(r))}return n}function Un({start:t,end:e,interval:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(t>=e)throw new Error("Start should be less than end.");const o=[];let n=t;for(;n<=e;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==e.toString()&&o.push(e.toString()),o}const ze=(t,e)=>s=>!t||!e?s:lr(s)?xo(Number(s),t,e):s,wf=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Nn(t.options).map(ze(s,r));if(t.options.type==="rangeInterval")return Un(t.options).map(ze(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(ze(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Nn(t.options.unitSystems[e]).map(ze(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Un(t.options.unitSystems[e]).map(ze(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(ze(s,r))}}return[]},vf=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var Mf=Object.defineProperty,Ef=Object.getOwnPropertyDescriptor,Fo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ef(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Mf(e,s,o),o};function _f(t){return(t==null?void 0:t.type)==="enum"}function Tf(t){switch(t){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return t}}function If(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return $e.format(r,e)}const Ss="config-bean-prop-model",Ve=p.createLogger({name:"config-bean-prop-model"}),Of=Be("path"),Sf=Be("serviceBasePath");let zt=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return ac(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(t,e,s)}getDefaultUnitForMeasure(t,e){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(t,e)}get schemaType(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.type?t.type:"String"}get schemaFormat(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.format?Tf(t.format):""}get options(){var i;const t=this.regionInfo.defaultUnitSystem,e=this.getConverter(),s=((i=e==null?void 0:e.to)==null?void 0:i.system)??t,r=this.bean.getSchemaForProperty(this.attribute),o=_f(r)?r.values:wf(r,s,e==null?void 0:e.from,e==null?void 0:e.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,o=(t==null?void 0:t.system)||e,n=t==null?void 0:t.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),o=this.convertUnit(e.to,t,s);return{backend:r,display:o}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let d=String(t);return d=c.formatToParts(Number(t))[0].value,Number(d)}}catch(c){Ve.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,o)}return e||""}async activate(){Ve.debug(`activating config bean ${this.id}`)}get displayValue(){const t=this.value;if(typeof t=="boolean")return String(t);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return If(t,s)}if(!isNaN(t))try{const e=this.getConverter(),s=this.getFormatterOptions(e);if(s){let r=String(t);return r=s.format(Number(t)),r}}catch(e){Ve.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var o;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??e;return vf(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,o;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=t==null?void 0:t.to)==null?void 0:o.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var n,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,d=this.formatter||c;if(d){let u=typeof d=="function"?d(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):d;s&&(u={unit:this.getDefaultUnit(t),...u},u.style==="unit"&&(u.maximumFractionDigits=u.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...u})}catch(h){Ve.error(`error creating formatter ${u}. Returning the raw value`,h)}}else Ve.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,d,u,h,f,m;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const w=(r=this.converter)==null?void 0:r.measure,v=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,T=w||v||E||e,K=((d=(c=this.converter)==null?void 0:c.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(T,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),fe=((m=(f=this.converter)==null?void 0:f.to)==null?void 0:m.system)??this.regionInfo.getUnitSystem(K),we=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:we,...this.converter.from},to:{...this.converter.to,unit:K,system:fe},measure:T}}if(s&&e){const w=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),v=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(w);return{measure:e,to:{unit:v===E?s:w}}}}async updateProperty(t){Ve.debug(`updating property ${this.attribute} with value ${t}`);let e=t;if(this.getConverter()&&!isNaN(e)){const{backend:o,display:n}=this.getConverterUnits();e=this.regionInfo.convert(Number(e),n,o)}const r=Array.isArray(e)?JSON.stringify(e):String(e);await this.bean.updateProperty(this.attribute,r)}};Fo([ut({modelType:Q.type})],zt.prototype,"regionInfo",2);Fo([dr({path:Of,serviceBasePath:Sf})],zt.prototype,"bean",2);zt=Fo([R(Ss)],zt);const Ke={registration:{[Ss]:{class:zt,singleton:!1}},type:Ss,factory:Z.Factory.create(Ss)};function $f(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(d,u)=>{d[L]=d[L]||{},d[L][u]={modelType:Ke.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:N.INIT,lazy:n}}}class Df{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=Do.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=B(()=>{var o,n;(e.endState||e.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,e))});this.disposers.set(s||e.id,r)}removeFuture(e){var s;this.futures.delete(e||this.context),(s=this.disposers.get(e||this.context))==null||s(),this.disposers.delete(e||this.context)}getFuture(e){return this.futures.get(e||this.context)}get futureMap(){return this.futures}}class ur{constructor(e){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=B(()=>{var r,o;(e.endState||e.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw p.error(e),e}}}const vc="future-model",ft=ht(vc),hr=p.createLogger({name:"future-service",group:"Services"}),{isMock:Cf,URL:os}=X();var Ce=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(Ce||{});const{getAll:Rf,modifyModel:Af,addModel:Pf,deleteModel:Lf,postModel:xf}=J.build({destinationAddress:"",basePath:`${os}/api/future`,mock:Cf}),Ff=async()=>await Rf({}),Mc=async(t,e="/api/kos/future")=>(hr.info(`sending delete request for Future: ${t}`),await Lf({id:t,urlOverride:`${os}${e}/${t}`})),Ec=async(t,e="/api/kos/future")=>(hr.info("sending add request for Future"),await Pf({model:t,urlOverride:`${os}${e}`})),kf=async(t,e,s="/api/kos/future")=>(hr.info(`sending modify request for Future: ${t}`),Af({model:e,id:t,urlOverride:`${os}${s}/${t}`})),_c=async(t,e="/api/kos/future")=>(hr.info(`sending cancel request for Future: ${t}`),xf({urlOverride:`${os}${e}/${t}/cancel`,ordered:!0,model:{}})),ko=t=>({id:String(t.id),progress:t.progress,remainingTimeMs:t.remainingTimeMs,endState:t.endState,reason:t.reason,clientData:t.clientData,reasonData:t.reasonData,note:t.note,tracker:t.tracker}),No=(t,e)=>{p.debug(`future dto ${t.id} end state ${t.endState}`),p.debug(`future model ${e.id} end state ${e.endState}`),e.endState?p.debug(`future model ${e.id} is already complete`):(p.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=ko(t);q(()=>{Object.keys(s).forEach(r=>{r==="id"?(e.futureId=s.id,s.tracker||(e.id=s.id)):r==="tracker"?e.id=s.tracker:e[r]=s[r]})})}))},Tc=t=>e=>s=>t.build(String(e),s),Uo=t=>e=>Ja(ko,Tc(t)(e.tracker||e.id))(e);var Nf=Object.defineProperty,Uf=Object.getOwnPropertyDescriptor,Ic=(t,e,s,r)=>{for(var o=r>1?void 0:r?Uf(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Nf(e,s,o),o};const Rr=p.getLogger(ft.type);let Fs=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=_c,Gr(()=>this.status===Ce.Success||this.status===Ce.Fail,()=>{Rr.info(`Future ${this.id} has completed with status ${this.status}`),Ue(this)})}async load(){Rr.debug(`loading Future ${this.id}`)}unload(){Rr.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Gr(()=>this.futureId!==Co),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[d,u]of Object.entries(e))if(Math.abs(t)>=u){s=d,r=Math.round(t/u);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),No(t,this)}};Ic([x({topic:`kos.future/${Ds}`})],Fs.prototype,"handleFutureUpdated",1);Fs=Ic([R(ft.type)],Fs);const Oc=Fs,Sc=To();var jf=Object.defineProperty,Bf=Object.getOwnPropertyDescriptor,$c=(t,e,s,r)=>{for(var o=r>1?void 0:r?Bf(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&jf(e,s,o),o};const Dc="browser-router-model",Kf="kos.http.request",Hf="kos.http.response";let ks=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new sc}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],o=e.headers.url,n=e.headers.method,i=e.headers["request-id"],a={id:i,method:n,path:o,body:t};let c=200;const d={send:u=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(u),Pa({msg:u,options:{responseId:i,destinationAddress:s,type:Hf,sourceAddress:r,status:c}})},status:function(u){return c=u,this}};if(a.path==="/openapi.json"){d.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,d)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};$c([x({topic:Kf})],ks.prototype,"handleRequest",1);ks=$c([R(Dc)],ks);const jo=new ye({class:ks,type:Dc}),Cc="future-container-model",Re=ht(Cc),Rc=t=>Uo(ft)(t),Gf=t=>{const e=Rc(t);return Re.build(Re.type,{}).addFutureModel(e),e},zf=t=>Re.build(Re.type,{}).getFuture(String(t)),je={buildFutureModel:Rc,initiateFuture:Gf,getFuture:zf};var Vf=Object.defineProperty,Yf=Object.getOwnPropertyDescriptor,Bo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Yf(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Vf(e,s,o),o};const ys=p.getLogger(Re.type);let Vt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=Mc,addFuture:o=Ec}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new be,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){ys.error("error deleting a Future"),ys.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Uo(ft)(s);return this.addFutureModel(r),r}}catch(e){throw ys.error("error creating a Future"),ys.error(e),e}}handleFutureUpdated(t,e){const s=je.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),U(r,e.body,e.headers)}};Bo([he],Vt.prototype,"_futures",2);Bo([x({topic:"kos.future"})],Vt.prototype,"handleFutureUpdated",1);Vt=Bo([R(Re.type)],Vt);const Ac=Vt,{URL:ns}=X(),{getOne:qf,postModel:Wf,deleteModel:Pc}=J.build({basePath:`${ns}/api/keyVal`}),zr=p.createLogger({name:"key-value-service",group:"Services"}),Lc=async(t,e)=>{await Pc({urlOverride:`${ns}/api/keyVal/${t}/${e}`,id:e})},xc=async(t,e,s)=>{const r=await Wf({urlOverride:`${ns}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw zr.error("Failed to update studio-state data",r),new Error(`Failed to update studio-state data for namespace ${t}`);return r.data},Fc=async(t="studio")=>{zr.debug("sending GET for studio-state");const e=await qf({urlOverride:`${ns}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw zr.error("Failed to retrieve studio-state data",e),new Error(`Failed to retrieve studio-state data for namespace ${t}`);return e.data},Qf=async t=>{await Pc({urlOverride:`${ns}/api/keyVal/${t}}`,id:""})},Zf=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Lc,deleteKeyValueNamespace:Qf,getKeyValue:Fc,updateKeyValue:xc},Symbol.toStringTag,{value:"Module"}));var Jf=Object.defineProperty,Xf=Object.getOwnPropertyDescriptor,Ko=(t,e,s,r)=>{for(var o=r>1?void 0:r?Xf(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Jf(e,s,o),o};const kc="key-value-model";let Yt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=De(),this.namespace=e.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(t,e){this.logger.debug(`updating studio-state ${t} with value ${e}`),e!==void 0?(await xc(this.namespace,t,e),this.data[t]=e):(await Lc(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await Fc(this.namespace);this.data.setValues(t)}handleStateUpdate(t){t.namespace===this.namespace&&(this.data[t.key]=t.value)}handleStateDelete(t){t.namespace===this.namespace&&(this.data[t.key]=void 0)}};Ko([x({topic:"/keyVal/set"})],Yt.prototype,"handleStateUpdate",1);Ko([x({topic:"/keyVal/remove"})],Yt.prototype,"handleStateDelete",1);Yt=Ko([R(kc)],Yt);const Ho=new ge({class:Yt,type:kc}),Oe=To(),ep=Object.freeze(Object.defineProperty({__proto__:null,default:Oe},Symbol.toStringTag,{value:"Module"})),tp=p.createLogger({name:"kos-log-manager-service",group:"Services"}),sp="/api/kos/logs/overrides",Nc=async()=>(tp.debug("sending GET for kos-log-manager"),await Oe.get(sp)),rp=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:Nc},Symbol.toStringTag,{value:"Module"}));var op=Object.defineProperty,np=Object.getOwnPropertyDescriptor,gr=(t,e,s,r)=>{for(var o=r>1?void 0:r?np(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&op(e,s,o),o};const Uc="kos-log-manager-model",ip="/kos/logs/override/add/*",ap="/kos/logs/override/remove/*",cp=t=>{if(typeof t=="string")return t;if(typeof t=="number")switch(t){case 0:return"trace";case 1:return"debug";case 2:return"info";case 3:return"warn";case 4:return"error";default:return"info"}return"info"};let tt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new So}updateModel(t){}resolveLoggers(){const t=p.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:cp(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=p.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=p.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await Nc();if(t){this.logger.error("Failed to load log overrides",t);return}const s=(e==null?void 0:e.filter(r=>{var o;return((o=r.type)==null?void 0:o.toUpperCase())==="UI"}).map(r=>({name:r.name??"",type:r.type??"",level:r.level??"info",id:r.name||""})))??[];this._overrides.addAll(s),s.forEach(r=>{this.setLogLevels(r)})}};gr([sa("/api/kos/ui/loggers")],tt.prototype,"getAllLoggers",1);gr([x({topic:ip,websocket:!0,wildcardName:"nodeType"})],tt.prototype,"handleOverrideAdded",1);gr([x({topic:ap,websocket:!0,wildcardName:"nodeType"})],tt.prototype,"handleOverrideRemoved",1);tt=gr([R(Uc)],tt);const jc=new ye({class:tt,type:Uc}),{URL:is}=X(),{postModel:Go,getOne:lp}=J.build({basePath:`${is}/api/kos-time`});p.createLogger({name:"kos-time-service",group:"Services"});const Bc=async t=>{const e=await Go({model:t,urlOverride:`${is}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Kc=async t=>{const e=await Go({model:t,urlOverride:`${is}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Hc=async t=>{const e=await Go({model:{},urlOverride:`${is}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},Gc=async()=>{const t=await lp({urlOverride:`${is}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},dp=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Gc,setDate:Kc,setTime:Bc,setTimezone:Hc},Symbol.toStringTag,{value:"Module"}));var up=Object.defineProperty,hp=Object.getOwnPropertyDescriptor,fr=(t,e,s,r)=>{for(var o=r>1?void 0:r?hp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&up(e,s,o),o};const Et="kos-time-model",gp="/kos/time/time",fp="/kos/time/day",pp="/kos/time/timezone";let st=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await Bc(t)}async updateSystemDate(t){await Kc(t)}async updateSystemTimezone(t){await Hc(t)}handleTimeChange(){U(jt.TIME_CHANGE,{})}handleDayChange(){U(jt.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),U(jt.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await Gc();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};fr([x({topic:gp,websocket:!0})],st.prototype,"handleTimeChange",1);fr([x({topic:fp,websocket:!0})],st.prototype,"handleDayChange",1);fr([x({topic:pp,websocket:!0})],st.prototype,"handleTimeZoneChange",1);st=fr([R(Et)],st);const Ns={registration:{[Et]:{class:st,singleton:!0}},type:Et,predicate:ce(Et),factory:Z.Singleton.create(Et)};var mp=Object.defineProperty,yp=Object.getOwnPropertyDescriptor,zc=(t,e,s,r)=>{for(var o=r>1?void 0:r?yp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&mp(e,s,o),o};const Vc="log-block-container-model";let Us=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new be({parentId:t,sortKey:"blockNum"})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};zc([he],Us.prototype,"_models",2);Us=zc([R(Vc)],Us);const bp=p.createLogger({name:"log-stream-container-service",group:"Services"}),Yc=()=>{var r;const t=ae(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return p.error(`getKosConnectionId: ${s}`),s},pt=Yc(),wp="/api/kos/logs/node/{nodeId}/streams",qc=async()=>(bp.debug("sending GET for log-stream-container"),await Oe.get(wp,{path:{nodeId:"primary"}},{destinationAddress:pt})),Wc=async(t,e="primary")=>{await Oe.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:pt})},Qc=async t=>{await Oe.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:pt})},vp=async()=>{await Oe.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:pt})},Zc=async t=>await Oe.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:pt}),Jc=async(t,e)=>await Oe.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:pt}),Mp=Object.freeze(Object.defineProperty({__proto__:null,createOverride:vp,getKosConnectionId:Yc,getLogStreamBlock:Jc,getLogStreamBlocks:Zc,getLogStreams:qc,subscribeToLogStream:Wc,unsubscribeFromLogStream:Qc},Symbol.toStringTag,{value:"Module"}));var Ep=Object.defineProperty,_p=Object.getOwnPropertyDescriptor,Tp=(t,e,s,r)=>{for(var o=r>1?void 0:r?_p(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ep(e,s,o),o};const Xc="log-block-model";let Vr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await Jc(this.stream,this.blockNum);if(t){this.logger.error(`Failed to get log block ${this.blockNum}`);return}e&&this.addLines(e.lines,!0)}updateModel(t){this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount}addLines(t,e){const s=e?[]:this.lines;this.lines=[...s,...t],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};Vr=Tp([R(Xc)],Vr);const qt=new ge({class:Vr,type:Xc}),pr=new ge({class:Us,type:Vc});pr.addRelatedModel(qt);var Ip=Object.defineProperty,Op=Object.getOwnPropertyDescriptor,el=(t,e,s,r)=>{for(var o=r>1?void 0:r?Op(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ip(e,s,o),o};const tl="log-stream-model";let js=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"_blocks");l(this,"name");l(this,"currentBlockId");l(this,"isResetting");l(this,"generatorInstance");l(this,"shouldStop",!1);this.id=t,this.logger=s.logger,this.currentBlockId="",this.name=e.name,this.nodeId=e.nodeId,this.isResetting=!0,this._blocks=pr.instance(`${t}-blocks`).options({}).build()}get firstLineNum(){const t=this.populated[0];return t?t.startLineNum:0}get currentBlock(){const t=this.currentBlockId;return this._blocks.getModel(t)}get populated(){return this._blocks.data.filter(t=>t.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((t,e)=>t+e.lineCount,0)}accept(t){t.visit(this)}updateBlock(t){var r;let e=this._blocks.models.getModel(`${t.stream}-block-${t.blockNum}`);const s={nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)};e||(e=qt.instance(`${t.stream}-block-${t.blockNum}`).options(s).build(),this._blocks.addModel(e)),e&&e.updateModel(s),(!this.currentBlock||t.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}addBlock(t){var s;const e=qt.instance(`${t.stream}-block-${t.blockNum}`).options({nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)}).build();this._blocks.addModel(e),(!this.currentBlock||t.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}removeBlock(t){this._blocks.models.removeModel(`${this.name}-block-${t}`)}async subscribe(){await Wc(this.name)}async unsubscribe(){await Qc(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const e of this._blocks.models.data)e.lines=[];const t=this._blocks.data[this._blocks.data.length-1];t&&await t.syncLines(),this.isResetting=!1}async init(){this.logger.debug(`initializing log-stream ${this.id}`)}async load(){this.logger.debug(`loading log-stream ${this.id}`);const[t,e]=await Zc(this.name);if(t){this.logger.error(`Error loading log stream: ${t}`);return}if(e)for(const r of e)this.addBlock(r);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const r=this._blocks.data[this._blocks.data.length-2];r&&await r.syncLines()}}start(){return this.shouldStop=!1,this.generatorInstance=this.streamLogs(),this.generatorInstance}stop(){var t;this.shouldStop=!0,(t=this.generatorInstance)==null||t.next(),console.log("Requested generator stop.")}async*streamLogs(){const t=[];let e=null,s=0,r=this.currentBlockId;const o=nc(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(r!==(n==null?void 0:n.blockId))r=n==null?void 0:n.blockId,s=0,t.push(...i.lines);else{const a=i.lines.slice(s);t.push(...a),s+=a.length}e&&(e(),e=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(t.length===0&&await new Promise(n=>e=n);t.length>0;)yield t.shift()}finally{o()}}};el([he],js.prototype,"_blocks",2);js=el([R(tl)],js);const Bt=new ge({class:js,type:tl});var Sp=Object.defineProperty,$p=Object.getOwnPropertyDescriptor,He=(t,e,s,r)=>{for(var o=r>1?void 0:r?$p(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Sp(e,s,o),o};const sl="log-stream-container-model",Dp="/kos/logs/subscription/addBlock/*",Cp="/kos/logs/subscription/updateBlock/*",Rp="/kos/logs/subscription/removeBlock/*",Ap="/kos/logs/subscription/lines/*",rl="/kos/logs/streams/add/*";let _e=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new be({parentId:t}),this.selectedStream=void 0}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}updateModel(t){}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}updateSelectedStream(t){this.selectedStream=t}handleStreamAdded(t){this.logger.debug(`Received topic: ${rl}`);const e=t.stream,s=Bt.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.addBlock(t)}handleRemoveBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.removeBlock(t.blockNum)}handleUpdateBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.updateBlock(t)}handleLogLine(t,e){var o;this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&((o=r.currentBlock)==null||o.addLines(t.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(t){const e=Bt.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(e),await e.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[t,e]=await qc();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=Bt.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};He([he],_e.prototype,"_models",2);He([x({topic:[rl],websocket:!0})],_e.prototype,"handleStreamAdded",1);He([x({topic:[Dp],websocket:!0})],_e.prototype,"handleAddBlock",1);He([x({topic:[Rp],websocket:!0})],_e.prototype,"handleRemoveBlock",1);He([x({topic:[Cp],websocket:!0})],_e.prototype,"handleUpdateBlock",1);He([x({topic:[Ap],websocket:!0})],_e.prototype,"handleLogLine",1);_e=He([R(sl)],_e);const as=new ye({class:_e,type:sl});as.addRelatedModel(Bt);as.addRelatedModel(pr);as.addRelatedModel(qt);const Pp=t=>t.rank!==void 0,Lp=t=>t.visibleRole!==void 0,xp=t=>t.color!==void 0,Fp=t=>{const e=t.info;return Pp(e)?e.rank:0},kp=t=>{const e=t.info;return xp(e)?e.color:"orange"},Np=t=>{const e=t.info;return Lp(e)?e.visibleRole:"TECHNICIAN"},{URL:zo}=X(),{getAll:Up,postModel:ol}=J.build({basePath:`${zo}/api/kos/troubles`}),nl=async()=>await Up({}),il=async(t,e)=>{try{const s=await ol({model:{},urlOverride:`${zo}/api/kos/troubles/resolve/${t}`,tracker:e});return s!=null&&s.data&&je.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:Ce.Fail,tracker:e,reason:"Failed to resolve trouble"};return je.initiateFuture(r),r}},jp=async(t,e)=>{try{const s=await ol({model:t,urlOverride:`${zo}/api/kos/troubles/resolve/`,tracker:e});return s!=null&&s.data&&je.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:Ce.Fail,tracker:e,reason:"Failed to resolve troubles"};return je.initiateFuture(r),r}},Bp=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:jp,getTroubles:nl,resolveTrouble:il},Symbol.toStringTag,{value:"Module"})),Bs="troubleDataMapper",bs=new Map;ss(Bs,{register:(t,e)=>{var s;bs.has(t)||bs.set(t,[]),(s=bs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=bs.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:p.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const cs="troubleMapper",ws=new Map;ss(cs,{register:(t,e)=>{var s;ws.has(t)||ws.set(t,[]),(s=ws.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=ws.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(p.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});S[cs].register("nozzle",async t=>[t.data.nozzlePath]);S[cs].register("path",async t=>[t.data.path]);const Kp=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>S[cs].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},al=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>S[Bs].execute(i,t)),r=S[Bs].execute(t.type,t);s.push(r);const n=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...t.data,...n}};class Hp{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class Gp{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class Ye{static getHandler(e){switch(e){case"ResolvableTrouble":return new Hp;case"BlockPumpTrouble":return new Gp;default:return}}}var zp=Object.defineProperty,Vp=Object.getOwnPropertyDescriptor,cl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Vp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&zp(e,s,o),o};const _t="trouble-model";function vs(t){return typeof t.shouldDefer=="boolean"}let Ks=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:d,createTime:u,role:h,color:f,...m},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,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=w.logger,this.type=c,this._troubleId=o,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=f,this.tags=s,this.info=r,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,m),this.futureHandler=new ur(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=Ye.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Ye.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=Ye.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Ye.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=Ye.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=Ye.getHandler(this.type))==null?void 0:t.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await al(this)}get deferredCompanion(){const t=Kr(this.id,e=>vs(e));if(t&&vs(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Kr(this.id,e=>vs(e));return t&&vs(t.modelData)?t.modelData.shouldDefer:!1}clearDefer(){var t;(t=this.deferredCompanion)==null||t.clearDefer()}defer(){var t;(t=this.deferredCompanion)==null||t.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(t){var e;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(e=this.deferredCompanion)==null||e.defer();return}return await il(this._troubleId,t)}};cl([ln()],Ks.prototype,"resolve",1);Ks=cl([R(_t)],Ks);const Wt={registration:{[_t]:{class:Ks,singleton:!1}},type:_t,predicate:ce(_t),factory:Z.Factory.create(_t)};var Yp=Object.defineProperty,qp=Object.getOwnPropertyDescriptor,mr=(t,e,s,r)=>{for(var o=r>1?void 0:r?qp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Yp(e,s,o),o};const jn=p.createLogger({name:"trouble-container-model"});function Bn(t){return S.propertyMapper.hasMapper(de.TroubleRank)?S.propertyMapper.executeMapper(de.TroubleRank,t):Fp(t)}function Kn(t){return(S.propertyMapper.hasMapper(de.TroubleColor)?S.propertyMapper.executeMapper(de.TroubleColor,t):kp(t)).toLowerCase()}function Hn(t){return(S.propertyMapper.hasMapper(de.TroubleRole)?S.propertyMapper.executeMapper(de.TroubleRole,t):Np(t)).toLowerCase()}const Wp="trouble-container-model";class oe{}l(oe,"INDEX_TROUBLES_BY_IFACE","byIface"),l(oe,"INDEX_TROUBLES_BY_TYPE","byType"),l(oe,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(oe,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(oe,"SORT_KEY_RANK","rank"),l(oe,"TROUBLES_DEFERRED","true");let rt=class{constructor(t){l(this,"id");l(this,"troubles");this.id=t,this.troubles=new be({indexMap:{[oe.INDEX_TROUBLES_BY_IFACE]:Kp,[oe.INDEX_TROUBLES_BY_TYPE]:"type",[oe.INDEX_TROUBLES_BY_GROUP]:"group",[oe.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:oe.SORT_KEY_RANK,parentId:t})}async load(){jn.debug("loading trouble container");const t=await nl();try{t==null||t.data.forEach(e=>{const s={...e,rank:Bn(e),color:Kn(e),role:Hn(e),id:String(e.id)},r=Wt.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw jn.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&Ue(s)}handleTroubleAdded(t){const e={...t,rank:Bn(t),color:Kn(t),role:Hn(t),id:String(t.id)};if(e.role==="NONE")return;const s=Wt.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};mr([he],rt.prototype,"troubles",2);mr([x({topic:"/kos/trouble/remove",websocket:!0,lifecycle:N.INIT})],rt.prototype,"handleTroubleRemoved",1);mr([x({topic:"/kos/trouble/add",websocket:!0})],rt.prototype,"handleTroubleAdded",1);rt=mr([R(Wp)],rt);const Ms="trouble-container-model",ot={registration:{[Ms]:{class:rt,singleton:!0}},type:Ms,predicate:ce(Ms),factory:Z.Singleton.create(Ms)},{URL:ll}=X(),{getAll:Qp}=J.build({basePath:`${ll}/api/kos/ota`}),Gn=p.createLogger({name:"ota-service",group:"Services"}),Zp=async()=>{Gn.debug("sending GET request to /api/kos/ota/artifacts");const t=await Qp({urlOverride:`${ll}/api/kos/ota/artifacts`});return Gn.debug("getArtifacts - response:",t),t==null?void 0:t.data};var Jp=Object.defineProperty,Xp=Object.getOwnPropertyDescriptor,yr=(t,e,s,r)=>{for(var o=r>1?void 0:r?Xp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Jp(e,s,o),o};const dl="ota-model",em=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Ar=t=>{const e=t.artifactInfo,s=em(t.requests),r=(e==null?void 0:e.identifier)||(s==null?void 0:s.kabId);if(!r)return;let o;switch(t.status){case"INSTALLED":o="ready";break;case"INVALID":o="error";break;case"MISSING":o=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":o="pending"}const n=e===void 0;return{id:r,manifest:n,label:e==null?void 0:e.version,name:e==null?void 0:e.name,status:o,error:o==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:o==="error"?s==null?void 0:s.errorCount:0,progress:o==="downloading"&&s&&!n?s.currentSize/(e==null?void 0:e.size)*100:void 0,size:e==null?void 0:e.size}};let nt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new So);l(this,"troubleContainer");this.id=t,this.logger=s.logger}get downloadInProgressTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:e[0]}get updatePendingTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:e[0]}get pausedDueToErrorsTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:e[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var t;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(t=this.updatePendingTrouble)==null||t.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const t=await Zp();t&&t.forEach(e=>{const s=Ar(e);s&&this.data.addModel(s)})}catch(t){this.logger.error(`loading ota ${this.id} - error:`,t)}}async handleAllArtifacts(t){this.logger.debug("handleAllArtifacts:",t),await this.data.clear();try{t.forEach(e=>{const s=Ar(e);s&&this.data.addModel(s)})}catch(e){this.logger.error(`handleAllArtifacts ${this.id} - error:`,e)}}handleChangedArtifacts(t){this.logger.debug("handleChangedArtifacts:",t);try{t.forEach(e=>{const s=Ar(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};yr([ut({modelType:ot.type})],nt.prototype,"troubleContainer",2);yr([x({topic:"/kos/ota/artifacts/all",websocket:!0})],nt.prototype,"handleAllArtifacts",1);yr([x({topic:"/kos/ota/artifacts/changed",websocket:!0})],nt.prototype,"handleChangedArtifacts",1);nt=yr([R(dl)],nt);const Hs=new ye({class:nt,type:dl});function tm(t){let e;const s=async(...r)=>{e&&e.abort(),e=new AbortController;const o=e;try{return await t(...r,o.signal)}finally{e===o&&(e=void 0)}};return s.cancel=()=>{e&&(e.abort(),e=void 0)},s.getController=()=>e,s.isActive=()=>!!e,s}const Pr=p.createLogger({name:"software-info-service",group:"Services"}),Vo=async t=>{Pr.debug("sending GET for software-info");const[e,s]=await Sc.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Pr.debug("Request was aborted"),new ie("Request was aborted")):(Pr.error("Failed to fetch software-info",e),new ie("Failed to fetch software-info"));return s},sm=tm(Vo),rm=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Vo,getSoftwareInfosWithCancel:sm},Symbol.toStringTag,{value:"Module"}));var om=Object.defineProperty,nm=Object.getOwnPropertyDescriptor,im=(t,e,s,r)=>{for(var o=r>1?void 0:r?nm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&om(e,s,o),o};const Tt="software-info-model";let Yr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=t,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(t,e){return t.reduce((s,r)=>(s[r[e]]=[...s[r[e]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const t=await Vo(),e=(t==null?void 0:t.nodes)||{};q(()=>{const r=Object.keys(e).map(o=>e[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(t){t instanceof ie&&this.logger.error("Failed to fetch software-info",t)}}};Yr=im([R(Tt)],Yr);const Gs={registration:{[Tt]:{class:Yr,singleton:!1}},type:Tt,predicate:ce(Tt),factory:Z.Factory.create(Tt)},{URL:ul}=X(),{getOne:am}=J.build({basePath:`${ul}/api/kos/state`}),cm=p.createLogger({name:"state-bean-service",group:"Services"}),hl=async({path:t})=>(cm.debug("sending GET for state-bean"),await am({urlOverride:`${ul}/api/kos/state/${t}`})),lm=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:hl},Symbol.toStringTag,{value:"Module"}));var dm=Object.defineProperty,um=Object.getOwnPropertyDescriptor,gl=(t,e,s,r)=>{for(var o=r>1?void 0:r?um(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&dm(e,s,o),o};const It="state-bean-model",hm=Be("path");let zs=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=t,this.logger=s.logger,this.props=Do.map(new Map),Ur(e,this)}updateModel(t){Ur(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&Ao(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&lr(r)&&(r=Number(r)),this.props.set(e,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(t){Object.entries(t).forEach(([e,s])=>{this.props.set(e,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const t=await hl({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};gl([x({topic:`/kos/state/${hm}`,websocket:!0})],zs.prototype,"handleConfigBeanUpdated",1);zs=gl([R(It)],zs);const Qt={registration:{[It]:{class:zs,singleton:!1}},type:It,predicate:ce(It),factory:Z.Factory.create(It)};var gm=Object.defineProperty,fm=Object.getOwnPropertyDescriptor,fl=(t,e,s,r)=>{for(var o=r>1?void 0:r?fm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&gm(e,s,o),o};const Ot="state-prop-model",zn=Be("path");let Vs=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=t,this.logger=s.logger,this.path=e.path,this.attribute=e.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var t;return((t=this.value)==null?void 0:t.toString())??""}};fl([ut({modelType:Qt.type,id:`state-bean-${zn}`,options:{path:zn}})],Vs.prototype,"stateBean",2);Vs=fl([R(Ot)],Vs);const Yo={registration:{[Ot]:{class:Vs,singleton:!1}},type:Ot,predicate:ce(Ot),factory:Z.Factory.create(Ot)},{URL:pm}=X(),{getAll:mm}=J.build({basePath:`${pm}/api/state-prop`}),ym=p.createLogger({name:"state-prop-service",group:"Services"}),bm=async()=>(ym.debug("sending GET for state-prop"),await mm({})),wm=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:bm},Symbol.toStringTag,{value:"Module"})),{URL:qo}=X(),{getOne:pl}=J.build({basePath:`${qo}/api/translation`}),Kt=p.createLogger({name:"translation-service",group:"Services"}),vm=()=>{const t=window.location.origin,e=ae();return(e==null?void 0:e.host)||t},ml=async(t,e)=>{Kt.debug("sending GET for translation");const s=e??vm();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Kt.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Kt.error("Error fetching translations",r),r}},Mm=async()=>{Kt.debug("getting localization descriptor");const t=await pl({urlOverride:`${qo}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get tool localization descriptor ${t==null?void 0:t.status}`);return t.data},yl=t=>async()=>{Kt.debug("getting kos localization descriptor");const e=await pl({urlOverride:`${qo}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get tool localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},bl="langResolver";var Em=Object.defineProperty,_m=Object.getOwnPropertyDescriptor,Tm=(t,e,s,r)=>{for(var o=r>1?void 0:r?_m(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Em(e,s,o),o};const St="translation-model";function Im(t){const e=typeof t=="string",s=e?!1:!!(t!=null&&t.data)&&typeof(t==null?void 0:t.data)!="string",r=e?t:t==null?void 0:t.defaultValue,o=e||t==null?void 0:t.context,n=e?void 0:s?t==null?void 0:t.data:t;return{isBasicOptions:e,defaultValue:r,context:o,data:n}}function wl(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null){const n=wl(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function vl(t,e){const s={...t};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(typeof e[r]=="object"&&e[r]!==null&&typeof t[r]=="object"&&t[r]!==null?s[r]=vl(t[r],e[r]):s[r]=e[r]);return s}const qr=(t,e)=>{const s=/__(.*?)__/g,r=t.replace(s,(o,n)=>Object.prototype.hasOwnProperty.call(e||{},n.trim())?e==null?void 0:e[n.trim()]:o);return r===t?r:s.test(r)?qr(r,e):r},Es=(t,e,s)=>{const r=/{{(.*?)}}/g,n=qr(t,e).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return qr(n,e)},Vn=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let Wr=class{constructor(t,e,s){l(this,"id");l(this,"namespace");l(this,"descriptor");l(this,"defaultLocale");l(this,"currentLocale");l(this,"bundleResolver");l(this,"data");l(this,"logger");l(this,"resolver");l(this,"disposer");l(this,"context");l(this,"rootUrl");this.id=t,this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.currentLocale||"en",this.namespace=e.namespace,this.descriptor=e.descriptor,this.rootUrl=e.rootUrl,this.data={},this.resolver=e.resolver||s.kosContext.get(bl),this.bundleResolver=e.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(t){const e=this.descriptor[t];if(!t||!e)return[this.defaultLocale];if(!this.defaultLocale&&!e.fallbacks)return[t];let s=e.fallbacks||[this.defaultLocale];return s.includes(t)||(s=[t,...s]),s}async loadTranslations(){const t=this.getTranslationLocales(this.currentLocale).reverse(),e=t.map(r=>{if(this.bundleResolver){const o=j.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return ml(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);q(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=vl(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=wl(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=Vn(this.namespace,t);if(e!==this.namespace){const r=this.context.getModel(e);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(t,e){if(!t)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=Im(e),{namespace:n,key:i}=Vn(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Es(d,this.data,o)):Es(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Es(d,this.data,o)):Es(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=M.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};Wr=Tm([ar(),R(St)],Wr);const Ys={registration:{[St]:{class:Wr,singleton:!1}},type:St,predicate:ce(St),factory:Z.Factory.create(St)};var Om=Object.defineProperty,Sm=Object.getOwnPropertyDescriptor,Ml=(t,e,s,r)=>{for(var o=r>1?void 0:r?Sm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Om(e,s,o),o};const $t="translation-container-model",$m=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function Dm(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error(`namespace ${t} not found in descriptor`);const r=s.basePath,o=s.locales[e].file;return $m([r,o])}let qs=class{constructor(t,e,s){l(this,"id");l(this,"lang");l(this,"rootUrl");l(this,"descriptor");l(this,"_defaultNamespace");l(this,"resolver");l(this,"logger");l(this,"descriptorUrl");l(this,"namespaces",[]);l(this,"_models");this.id=t,this.lang=e.lang||"en",this.descriptor=e.descriptor,this._defaultNamespace=e.defaultNamespace,this.descriptorUrl=e.descriptorUrl,this.rootUrl=e.rootUrl,this.resolver=e.resolver||Dm.bind(this),s.kosContext.set(bl,this.resolver),this.logger=s.logger,this._models=new be({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel(`translation-${this._defaultNamespace}`):void 0}getModel(t){return this.logger.debug(`getting model ${t}`),this._models.getModel(`translation-${t}`)}get models(){return this._models}get data(){return this._models.data}async reload(){this._models.clear(),await Ua(this);for(const t of this.namespaces){const e=this.resolveNamespace(t);await se(e)}}resolveNamespace(t){var s;if((s=this.descriptor.namespaces)==null?void 0:s[t]){const r=Object.keys(this.descriptor.namespaces[t].locales)[0],o=this.descriptor.namespaces[t].locales[r].defaultLocale,n=Ys.factory(`translation-${t}`)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[t].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(t)||q(()=>{this.namespaces.push(t)}),n}else{this.logger.warn(`namespace ${t} not found in descriptor`);const r=Ys.factory(`translation-${t}`)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing translation-container container ${this.id}`)}async load(){this.logger.debug(`loading translation-container container ${this.id}`)}};Ml([he],qs.prototype,"_models",2);qs=Ml([R($t)],qs);const Te={registration:{[$t]:{class:qs,singleton:!0}},type:$t,predicate:ce($t),factory:Z.Singleton.create($t)},Cm={set(t,e){const s=j.getContext(Te.type);s&&s.set(t,e)},get(t){const e=j.getContext(Te.type);return e==null?void 0:e.get(t)}},El={async init(t){const e=Te.factory(t);return await se(e),{translations:e}}};function Rm(t){return t.troubles!==void 0&&t.troubles instanceof Array&&t.troublesByType!==void 0&&typeof t.troublesByType=="object"}const Am=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},_l="kos-ws-event",Wo=ht(_l);var Pm=Object.defineProperty,Lm=Object.getOwnPropertyDescriptor,Qo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Lm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Pm(e,s,o),o};const xm=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){p.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const d=this._topicMap.get(i)||0;a=`${a}-${d+1}`,this._topicMap.set(i,d+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:xm({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),p.debug(`logged ${this.events.size} events`)}}};Qo([x({topic:[ts.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Qo([x({topic:[ts.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Qo([R(Wo.type)],exports.WsEventModel);const Yn=ae(),Fm=Yn.debug==="true"||Yn.debug===!0,km="/api/system/canvas",Tl=async(t,e)=>{const s=e||km,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Fm?"false":"true"},body:t})},Nm=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Tl},Symbol.toStringTag,{value:"Module"})),Um=(t,e,s)=>t>>5<<5|e>>5<<2|s>>6;function jm(t,e,s){if(e==="base64"){const r=s?t.filter((o,n)=>n%4!==3):Array.from(t);return btoa(String.fromCharCode(...r))}else{const r=[];for(let o=0;o<t.length;o+=4)r.push(Um(t[o],t[o+1],t[o+2]));return String.fromCharCode(...r)}}var Bm=Object.defineProperty,Km=Object.getOwnPropertyDescriptor,Il=(t,e,s,r)=>{for(var o=r>1?void 0:r?Km(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Bm(e,s,o),o};const Ol="canvas-renderer-model";function Lr(t){return typeof t.onDone=="function"}let Ws=class{constructor(t,e,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);l(this,"isStreaming",!1);l(this,"renderLoopId",null);l(this,"sendIntervalId",null);l(this,"timeoutId",null);l(this,"apiPath");l(this,"endpointName");l(this,"width",50);l(this,"height",30);l(this,"fps",10);l(this,"durationMs",null);l(this,"_onFrame",null);this.id=t,this.logger=s.logger,this.width=e.width??50,this.height=e.height??30,this.fps=e.fps??10,this.durationMs=e.durationMs??null,this.apiPath=e.apiPath??"/api/system/canvas",this.endpointName=e.endpoint}set onFrame(t){this._onFrame=t}set renderer(t){var e,s;this._renderer&&(this.stopStreaming(),(s=(e=this._renderer).dispose)==null||s.call(e)),this._renderer=t,this.isStreaming&&this.startStreaming()}sendDataFrame(t,e){Tl(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{this.stopStreaming()});return}}handleFrame(t){var s;const e=jm(t,"base64",!0);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(){var t,e;this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(e=(t=this._renderer)==null?void 0:t.pause)==null||e.call(t)}isOneShotDone(){var t,e;return Lr(this._renderer)&&((e=(t=this._renderer).isOneShot)==null?void 0:e.call(t))===!0&&this._renderer.isOneShotDone}startStreaming(){var t,e,s,r;{if(!this._renderer)return;if(!this.apiPath){this.logger.error(`No endpoint configured for canvas renderer ${this.id}`);return}this.isStreaming=!0,this._renderer.reset(),(e=(t=this._renderer).play)==null||e.call(t);const o=Lr(this._renderer);Lr(this._renderer)&&this._renderer.onDone(()=>{var a;this.logger.debug(`Renderer completed for ${this.id}`),U("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(a=this._renderer)==null?void 0:a.constructor.name,timestamp:Date.now()}),this.stopStreaming()}),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()});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,d;const a=(d=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:d.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(t,e)=>{this.stopStreaming(),e.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(t,e)=>{this.startStreaming(),e.send({status:"OK"})})}};Il([ut({modelType:jo.type})],Ws.prototype,"router",2);Ws=Il([R(Ol)],Ws);const Zo=new ge({class:Ws,type:Ol});class Sl{constructor({src:e}){l(this,"video");l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);l(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=e,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(e,s){this.canvas.width=e,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,e,s)}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}onDone(e){this.doneCallback=e}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}}class Hm{constructor(){l(this,"canvas");l(this,"gl");l(this,"lastWidth",0);l(this,"lastHeight",0);l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl");if(!e)throw new Error("WebGL not supported");this.gl=e}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(e*s*4);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const o=new Uint8ClampedArray(r.length);for(let n=0;n<s;n++){const i=n*e*4,a=(s-1-n)*e*4;o.set(r.subarray(i,i+e*4),a)}return o}}class Gm extends Hm{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
|
|
77
|
+
["${e}"]`;if(r?(m=this.fosSocket)==null?void 0:m.connectionEstablished:(w=this.socket)==null?void 0:w.connectionEstablished){const E=r?this.fosSocket:this.socket;(v=E==null?void 0:E.socket)==null||v.send(u)}else{xe.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(u)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=$(e,s);return xe.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();xe.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(et,"_instance");class Yh{constructor(e){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=e,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(e){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of e)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(e,s)}async*processSingleEvent(e){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(e))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(e),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([e]):[e],this.updateProcessingStats([e])}}async*processBatchedEvents(e,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const d=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(d.length===0)return;this.config.backpressure&&await this.waitForCapacity();const u=this.config.transform?this.config.transform(d):d;return this.stats.batchesProcessed++,this.updateProcessingStats(d),u};try{for await(const d of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(d);this.eventQueue.length>0;){const u=this.dequeueEvent();u&&n.push(u);const f=Date.now()-i;if(n.length>=r||f>=o){const m=await a();m!==void 0&&(yield m);break}}else{n.push(d);const h=Date.now()-i;if(n.length>=r||h>=o){const f=await a();f!==void 0&&(yield f)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(e){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(e,s);return this.config.filter.historySize&&(this.filterHistory.push(e),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const e=Date.now(),s=Math.floor(e/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const e=Date.now(),o=(Math.floor(e/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-e;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=e;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-e;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(e){if(this.eventQueue.push(e),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const e=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,e}updateProcessingStats(e){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+e.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?e.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(e){return this.activePromises.add(e),e.finally(()=>this.activePromises.delete(e)),e}getStats(){return{...this.stats}}}class qh{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(e){var o;const s=((o=this.modelData)==null?void 0:o[Q])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.flow)this.subscribeWithFlowControl(i,c,a);else{const d=this.createHandler(c,i);this.subscribe(i,c,d,a===j.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,o){const n=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=et.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=$(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(e,r,s);if(this.model.isReady()){const d=jr(r,s.skipParse),u=s.transform(d);if(a&&s.condition(u,this.modelData,r))return this.callHandlerWithWildcard(s,u,c,r)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`);const d=()=>{const u=jr(r,s.skipParse),h=s.transform(u);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)};this.offlineQueue.enqueue(d)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!ca(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return aa(e,o,r.wildcardName)}callHandlerWithWildcard(e,s,r,o){if(r&&Object.keys(r).length>0){const n={...o,wildcardCapture:r};return e.handler.call(this.modelData,s,n,this.modelData)}else return e.handler.call(this.modelData,s,o,this.modelData)}resolvePropKey(e){const s=/.*({PROP_(.+)})/;let r=e.includes("{MODEL_ID}")?e.replace("{MODEL_ID}",this.modelId):e;const o=r.match(s);return o&&o[2]in this.modelData&&(r=r.replace(o[1],this.modelData[o[2]])),r}async subscribeWithFlowControl(e,s,r){this.log.debug(`Setting up flow control for topic: ${s}`);const o=new Yh(e.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===j.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(e,s,r,o){const n=new AbortController;try{let i;if(e.websocket){const a=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;et.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Sn(s)}else i=Sn(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const o=e.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}}function Ge(t,e){const s=`[Model:${e}]`;return{debug:(...r)=>t.debug(s,...r),info:(...r)=>t.info(s,...r),warn:(...r)=>t.warn(s,...r),error:(...r)=>t.error(s,...r)}}function Wh(t){return!!(t!=null&&t[Ne])&&Object.keys(t[Ne]).length>0}function Qh(t){return!!(t!=null&&t[Q])&&Object.keys(t[Q]).length>0}function Zh(t){return!!(t!=null&&t[Ee])&&t[Ee].length>0}class Jh{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=Ph.create({modelId:s,modelTypeName:r}),i=new Ch(e,Ge(n,"fsm")),a=new Ah(Ge(n,"offline-queue")),c=new Eh(e),d=new Mh(e),u={fsm:i,offlineQueue:a,companionManager:c,childResolver:d};if(Wh(o)&&(u.effectManager=new _h(r,s,o,Ge(n,"effect"))),Qh(o)){const h=Ge(n,"subscription");u.subscriptionManager=new qh(e,o,s,a,h),u.onlineLifecycleManager=new Lh(e,Ge(n,"online"))}return Zh(o)&&(u.httpRouteManager=new Eo(o,Ge(n,"http-routes"))),u}}const L=D.getLogger("kos-model"),Xh="kos.extension.model.loader";class Fa{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=b.CREATED,this._activeStatus=b.INACTIVE,this._onlineStatus=b.OFFLINE;const o=Jh.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),wh(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===b.ACTIVE}isOnline(){return this._onlineStatus===b.ONLINE}isReady(){return this._status===b.READY}async deactivate(){var e,s,r;L.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=K.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,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 e,s,r;L.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await vt(this,j.ACTIVATE);try{const o=K.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.activate)==null?void 0:s.call(e,o)),L.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(r=this.subscriptionManager)==null||r.registerAll(j.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 Or([{condition:()=>this.status===b.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 Or([{condition:()=>this.status===b.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 Or([{condition:()=>this.status===b.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===b.READY,onMatch:()=>{L.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r;if(this.fsm.current===b.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 vt(this,j.READY),await va(this,vo.READY,j.READY);const o=K.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.ready)==null?void 0:s.call(e,o)),this.offlineQueue.flush(),(r=this.subscriptionManager)==null||r.registerAll(j.READY),L.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};B(la(this.modelTypeName,this.modelId),n),B(da(this.modelTypeName),n)}catch(o){throw L.error(o),Error(o)}}async load(){var o,n,i,a,c;const e=this[Rs];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===b.LOADED||this.fsm.current===b.LOADING){L.debug(`Model ${s} with id ${r} already loaded or loading`);return}L.debug(`Loading model ${s} with id ${r}`),await vt(this,j.LOAD);try{const d=K.getContext(r),u=`${Xh}.${s}`,h=await S.loader.executeLoader(u,{});h&&(L.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(u,h)),await((n=(o=this.modelData)==null?void 0:o.load)==null?void 0:n.call(o,d)),W(()=>{this.loaded=!0}),L.debug(`Model ${s} with id ${r} successfully loaded`),(i=this.subscriptionManager)==null||i.registerAll(j.LOAD),(a=this.httpRouteManager)==null||a.registerAll(),(c=this.effectManager)==null||c.setup()}catch(d){throw L.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,o,n,i;L.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const a=this.getChildren().map(d=>{var u;return(u=d.unload)==null?void 0:u.call(d)}).filter(d=>!!d);await Promise.allSettled(a);const c=K.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,c)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),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 e=this[Rs];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=K.getContext(s);L.debug(`Initializing model ${r} with id ${s}`),await vt(this,j.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(j.INIT)}catch(c){throw L.error(`Model ${s} failed to initialize`,c),c}}async registerSubscribers(e){var s;L.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}async online(){var s,r;L.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=K.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e))}async offline(){var s,r,o;L.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=K.getContext(this.modelId);await((o=(r=this.modelData)==null?void 0:r.offline)==null?void 0:o.call(r,e))}accept(e){e.visit(this)}getChildren(){return this.childResolver.resolve()}addCompanionModel(e){this.companionManager.add(e)}clearCompanionModels(){this.companionManager.clear()}}const ka=t=>typeof t=="function",Cn=p.createLogger({name:"kos-model-instantiator"});class ef{constructor(e,s){this.registry=e,this.cache=s}createModelInstance(e,s,r={}){const o=this.registry.models[e];if(!o)throw new Error(`No model registered for type ${e}`);const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Cn.debug(`Creating model instance: ${e} [${n}]`);const a=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),c=new Fa({modelTypeName:e,id:n,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(n);if(!i)throw Cn.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}_createCompanionModels(e,s){var n;const r=e.modelTypeName,o=((n=this.registry.companionModels)==null?void 0:n[r])||[];for(const{type:i}of o){const a=ka(i)?i(e.modelData,s):i;if(!a)continue;const c=`${a}-${e.modelId}`,d=this.createModelInstance(a,c,{data:s,companionParent:e.modelData,kosParentId:e.modelId});d!=null&&d.model&&(d.model[Rs]=e,e.addCompanionModel(d.model))}}}let tf=class{constructor(e){this._registry=e}get registry(){return this._registry}getModelTypeRegistry(e){const s=this.registry.models[e];if(!s)throw new Error(`No registration for model type ${e}`);return s}registerModel(e){const s=e.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...e.registration})}registerCompanionModel(e,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[e]??(o[e]=[]),this.registry.companionModels[e].some(n=>n.type===s)||this.registry.companionModels[e].push({type:s})}getModelSubscriptions(e){var s;return((s=this.getModelTypeRegistry(e))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(e){var r;const s=(r=this.getModelTypeRegistry(e))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${e}`);return s}getModelFactory(e){return ht(e)}};const Na=10,Rn=p.createLogger({name:"kos-model-manager"});class Ua{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Yu,globalThis.kos.modelManager=this,globalThis.kos.resolveKosModel=e=>{const s=this.getModelById(e);if(s)return s.modelData||{}},globalThis.kos.kosModelJson=e=>{var r,o;const s=this.getModelById(e);if(s)return((o=(r=s.modelData).toJSON)==null?void 0:o.call(r))||{}},globalThis.kos.kosModelDebug=e=>{var r;const s=this.getModelById(e);if(s)return((r=s.modelData)==null?void 0:r.debugState)||{}},globalThis.kos.kmd=globalThis.kos.kosModelDebug,globalThis.kos.kmj=globalThis.kos.kosModelJson}static create(e,s){const r=this.getInstance(s);return r._registry=new tf(e),r.cache=new qu(e.preloadModels),r.instantiator=new ef(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Rn.debug("Creating new instance of KosModelManager"),new this),(r=globalThis.kos)==null?void 0:r.modelManager}get registry(){return this._registry.registry}get preloadedModels(){return this.cache.preload(e=>(Rn.debug(`preloading ${e}`),typeof e=="string"?this.createModelInstance(e).model:this.createModelInstance(e.modelType,e.modelId,e.options).model))}get models(){return this.cache.models}getModelById(e){return this.cache.getModelById(e)}addModel(e){return this.cache.addModel(e)}removeModel(e){this.cache.removeModel(e.modelId)}hasModel(e){return this.cache.hasModel(e)}getModelsByType(e,s){return Array.from(this.models).filter(r=>r.modelTypeName===e).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(e){return this._registry.getModelSubscriptions(e)}getDataModelBuilder(e){return this._registry.getDataModelBuilder(e)}getModelFactory(e){return ht(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(A.RESET,b.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),ta.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),Na)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var Is=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.RELOADING="reloading",t))(Is||{}),We=(t=>(t.CREATE="create",t.INITIALIZE="init",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.UNLOAD="unload",t.RELOAD="reload",t))(We||{});const sf=t=>{const e=y.createMachine("offline",{online:y.state(y.transition("go_offline","offline",y.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:y.state(y.transition("go_online","online",y.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=y.interpret(e,n=>D.debug(n.machine.current)),r=y.createMachine({creating:y.state(y.transition("create","created")),created:y.state(y.immediate("initializing")),initializing:y.invoke(()=>t.init(),y.transition("done","initialized")),initialized:y.state(y.immediate("loading")),loading:y.invoke(()=>t.load(),y.transition("done","loaded")),loaded:y.state(y.immediate("readying"),y.transition("unload","unloading")),readying:y.invoke(()=>t.ready(),y.transition("done","ready",y.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:y.invoke(()=>t.reload(),y.transition("done","loading")),ready:y.state(y.transition("reload","reloading"),y.transition("unload","unloaded",y.action(t.unload.bind(t))),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=>D.debug(n.machine.current)),online:s}},ne=async t=>{if(t.id){const e=O.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},Ue=async t=>{await O.getInstance().whenReady(),await O.getInstance().modelManager.initiateDestroyModel(t)},rf=async t=>{if(await O.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(A.UNLOAD,b.UNLOADED)},ja=async t=>{await O.getInstance().whenReady(),await O.getInstance().modelManager.reloadModel(t),p.debug(`reload model initiated for model ${t.id}, model ready: ${As(t)} - ${Date.now()} `),await ne(t),p.debug(`reload model complete for model ${t.id}, model ready: ${As(t)} - ${Date.now()} `)},of=async t=>{if(await O.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},Ba=async t=>{if(await O.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},me=t=>{if(!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Ka=(t,e)=>{if(!t)throw new Error("Model type is required");return O.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},nf=(t,e)=>Ka(t,e)[0],af=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=O.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},Ha=t=>{if(!t.id)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},cf=t=>{if(!t)throw new Error("Model ID is required");const e=O.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},Kr=(t,e)=>{const s=O.getInstance().modelManager.getModelById(t);if(!s){p.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},de=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,As=t=>{const e=O.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},lf=p.createLogger({name:"kos-model-factory"}),jt={byModelType:t=>O.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=jt.byModelType(e);if(!r)throw lf.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},J={Factory:{create:t=>e=>(s,r)=>(r&&K.setParentContext(e,r),jt.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&K.setParentContext(t,s),jt.getModelInstance(t,t,e))},Model:{instance:t=>e=>jt.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Pn=window.KosRegistry.coreModels,Sr=window.KosRegistry.preloadModels,$r=window.KosRegistry.companionModels,fs=window.KosRegistry.models,C={model:{registerLegacyModel:t=>(e,s)=>(Pn.set(e,s),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(Sr.includes(e)||Sr.push(e),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=Dr(e)?e.registration():e;return fs.set(r.type,r),Dr(e)&&e.relatedModels.forEach(o=>fs.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],Dr(e)&&e.relatedModels.forEach(o=>O.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&C.model.preloadModel(t)(r.type),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},get:t=>fs.get(t),getAll:()=>Array.from(fs.entries()),getPreloadModels:()=>Sr,getLegacyModels:()=>Array.from(Pn.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=$r.get(e)||[];return r.push(s),$r.set(e,r),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from($r.entries())}},Ga=C.model.registerLegacyModel,za=C.model.register,df=C.companion.register,uf=C.model.preloadModel,Va=t=>typeof t.updateModel=="function",Dr=t=>t.registration!==void 0&&typeof t.registration=="function";class Ya{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=de(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){C.model.register({})(this.registration()),this.registerRelatedModels()}}class pe extends Ya{constructor(e){super({...e,singleton:!1,factory:J.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=me(e);if(!r)throw new Error("Model not found with id "+e);if(this.guard(r))return r;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(Va(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 be extends Ya{constructor(e){super({...e,singleton:!0,factory:J.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=me(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=e(r);if(this.guard(o)){if(Va(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})},options:r=>({build:()=>{const o=e(r);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const G=p.createLogger({name:"kos-core"}),hf=()=>{const t=le(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},ff=()=>{const t=window.location.protocol,e=le(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},gf=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=le(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},pf=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=le(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},mf=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?p.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):p.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},An=t=>typeof t.reload=="function",yf=t=>typeof t.unload=="function";var qa=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(qa||{});class O{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=Is.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),$("token",a=>{a&&(this.transport.token=a.body)}),$(Ut.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(We.GO_ONLINE)}),$(Ut.DISCONNECTED,async()=>{this.fsmService.service.send(We.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}),$(Ut.RELOAD,()=>{this.fsmService.service.send(We.RELOAD)}),$("/studio/project/reload",()=>{this.fsmService.service.send(We.RELOAD)});const s=et.getInstance(),r=gf(),o=pf(),n=ff();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=hf()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=sf(this),this.fsmService.service.send(We.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var o,n,i,a;const e=Date.now();if(this._reloading){G.info("reload already in progress");return}this._reloading=!0,G.warn("reloading KOS Core"),G.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)An(c.modelData)&&(G.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),G.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&An(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{G.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){G.debug("KOS Core going online"),await this._transport.whenReady(),G.debug("KOS Transport Ready. Calling online() for models"),B("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){G.debug("KOS Core going offline"),B("/kosCore/offline","/kosCore/offline")}async unload(){var o;G.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,G.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)yf(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===Is.READY)}async ready(){G.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(e.map(o=>{const{promise:n,cancel:i}=mf(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw G.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);G.debug("leaving kos-core ready() ")}get isReady(){return this.status===Is.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){G.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,G.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){G.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,G.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(d=>{var h,f;const u=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[d];u&&(Array.isArray(u)?u.forEach(m=>{S.dataMapper.registerDataMapper(d,m)}):S.dataMapper.registerDataMapper(d,u))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(d=>{var h,f;const u=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[d];u&&S.propertyMapper.registerPropertyMapper(d,u)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(d=>{var h,f;const u=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[d];u&&S.loader.registerLoader(d,u)}),C.model.getAll().forEach(([,d])=>{e.models={...e.models,...d.registration}}),e.models={...e.models,...C.model.getLegacyModels()},C.companion.getAll().forEach(([d,u])=>{e.companionModels={...e.companionModels},e.companionModels[d]=e.companionModels[d]||[];for(const h of u)e.companionModels[d].push({type:h})}),C.model.getPreloadModels().forEach(d=>{e.preloadModels.includes(d)||e.preloadModels.push(d)});const n=Ua.create(e,s);return o.modelManager=n,o}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(O,"_instance");function Hr(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function bf(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function wf(t){return await t.arrayBuffer()}function vf(t,e){return new Blob([t],{type:e||"application/octet-stream"})}async function Mf(t){const e={},s=[],r=[];t.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:Hr(i)})}else e[o]=n.toString();return{fields:e,files:s}}function Ef(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function _f(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:Hr(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await wf(t);return{data:Hr(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await Mf(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const gs=p.createLogger({name:"kos-fetch"}),Tf=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,If=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),Of=t=>t!=null&&t.studio?Ta:t!=null&&t.fos?Ia:Oa,Sf=async(t,e)=>{const s=O.getInstance().transport;await s.whenReady();const r=dt(),o=new URL(t),n=`${o.pathname}${o.search}`;gs.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||Tf,a=Of(e),c=await _f(e==null?void 0:e.body),d={};c.contentType&&(d["content-type"]=c.contentType),c.encoding&&(d["content-encoding"]=c.encoding);const u=Ae(a({path:n,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...d}}),c.data);return new Promise(h=>{let f=null,m=null;if(e!=null&&e.signal){if(e.signal.aborted){h({headers:Mt({}),status:0,ok:!1,json:async()=>null,body:Et(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}});return}e.signal.addEventListener("abort",()=>{m&&clearTimeout(m),f&&f(),h({headers:Mt({}),status:0,ok:!1,json:async()=>null,body:Et(""),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.")}})})}m=setTimeout(()=>{gs.error(`Timeout occurred - url: ${t}`),f&&f(),h({headers:Mt({}),status:404,ok:!1,json:async()=>null,body:Et(""),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 w=$(r,E=>{m&&clearTimeout(m);const T=(E==null?void 0:E.headers)||{},k=T["content-type"]||"text/plain",se=T["content-encoding"],P=(E==null?void 0:E.body)||"";let I=P;if(se==="base64"&&P)try{I=bf(P)}catch(N){gs.error("Failed to decode base64 response",N)}const V={headers:Mt(T),status:T.status&&parseInt(T.status)||200,ok:T.status==="200",json:async()=>{try{if(typeof I=="string")return I.length?JSON.parse(I):null;{const Y=new TextDecoder().decode(I);return Y.length?JSON.parse(Y):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?vf(I,k):new Blob([I],{type:k}),formData:async()=>{const N=new FormData;if(k==="multipart/form-data"&&typeof I=="string")try{const Y=JSON.parse(I);Y.fields&&Object.entries(Y.fields).forEach(([Se,ve])=>{N.append(Se,ve)}),Y.files&&gs.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return N},body:e!=null&&e.stream?Ef(async N=>{if(I instanceof ArrayBuffer)N.enqueue(new Uint8Array(I));else{const Y=new TextEncoder;N.enqueue(Y.encode(I))}N.close()}):Et(typeof I=="string"?I:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};w.unsubscribe(),If().then(()=>h(V))});f=w.unsubscribe;const v=e!=null&&e.fos?s.fosSocket:s.socket;if(!v)throw Error(`No web socket transport available: ${e}`);v==null||v.send(u)})};exports.BASE_URL="kos:";exports.kosFetch=Sf;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const $f=p.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Df{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=O.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){$f.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}const Wa=()=>({isMock:!1,URL:exports.BASE_URL}),Cf=p.createLogger({name:"kos-service-request"}),Rf="errUnknown";async function ps(t,e,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(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${h}=${r.query[h]}`).join("&"):"",a=`${Wa().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;Cf.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const d=await exports.kosFetch(a,c);return d.status<200||d.status>=400?[`${d.statusText||Rf}`,null]:[null,(await d.json()).data]}function To(){return{get:(t,e,s)=>ps(t,"get",s,e),post:(t,e,s,r)=>ps(t,"post",r,e,s),put:(t,e,s,r)=>ps(t,"put",r,e,s),delete:(t,e,s,r)=>ps(t,"delete",r,e,s)}}class Qa{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const Pf=async(t,e)=>{const s=new Qa;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},ht=t=>({type:t,build:(e,s)=>O.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=O.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),Af=t=>{O.getInstance().modelManager.registerModel(t)},Lf=(t,e)=>{O.getInstance().modelManager.registerCompanionModel(t,e)},Za=Symbol("KosObservableData");class Ja{constructor(){l(this,"map");l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var o;return this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=M.observable.map(new Map)}setValue(e,s){this.map.set(e,s)}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}Ja.prototype[Za]=!0;function xf(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const De=t=>{const e=xf(Ja,t);return new e(t)},Ln="/kos/ui/internal/heartbeat/",Ff=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=O.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${Ln}${t}`,callback:()=>{a=performance.now()}}),d=r??3e3,u=window.setInterval(()=>{let v=performance.now()-a;v=v/1e3,v>d/1e3&&i.abort()},d),h=o??2e3,f=window.setInterval(()=>{Aa({msg:{},options:{topic:`${Ln}${t}`,destinationAddress:e}})},h),m=()=>{window.clearInterval(f),window.clearInterval(u),c()},w=()=>{m(),s&&s(),i.signal.removeEventListener("abort",w)};return i.signal.addEventListener("abort",w),{cleanUpHeartbeat:m}},Xa=(...t)=>e=>t.reduce((s,r)=>r(s),e),kf={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Nf(t,e){let s=1;const r={...kf,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(p.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(d=>setTimeout(d,a)),s++;else throw c}throw new Error("All attempts failed")}const Uf=p.createLogger({name:"kos-service-request"}),te=t=>({isMock:!1,URL:exports.BASE_URL}),jf=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:d,destinationAddress:u})=>{const h={method:"DELETE"};t&&(h.destinationAddress=t),o&&(h.tracker=o),ft(h,{ordered:i,studio:a,fos:c,bridge:d,destinationAddress:u});const f=await s(n||`${e}/${r}`,h);if(!f.ok)throw Error(`There was a problem deleting the model; returned status ${f.status}`);return await f.json()},ft=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i})=>(i&&(t.timeout=i),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),Bf=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,destinationAddress:d})=>{const u={method:"GET"};t&&(u.destinationAddress=t),ft(u,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=await s(r||e,u);if(!f.ok){let w;try{w=await f.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${f.status}`,w)}return await f.json()},Kf=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:d,destinationAddress:u})=>{const h={method:"GET"};t&&(h.destinationAddress=t),c&&(h.tracker=c),ft(h,{timeout:d,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const f=r||e;Uf.debug(`resolvedUrl: ${f}`);const m=await s(f,h);if(!m.ok){let v;try{v=await m.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${m.status}`,v)}return await m.json()},Hf=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:d,destinationAddress:u})=>{const h={method:"GET"};t&&(h.destinationAddress=t),ft(h,{timeout:d,ordered:n,studio:i,fos:a,bridge:c,destinationAddress:u});const f=r||`${e}/${o}`,m=await s(f,h);if(!m.ok){let v;try{v=await m.json()}catch{}throw new ce(`There was a problem retrieving the model; returned status ${m.status}`,v)}return await m.json()};class ce extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const xn=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:d,timeout:u,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(f.destinationAddress=t),i&&(f.tracker=i),ft(f,{timeout:u,ordered:n,studio:a,fos:c,bridge:d,destinationAddress:h});const m=await s(o||e,f);if(!m.ok){let v;try{v=await m.json()}catch{}throw new ce(`There was a problem sending the POST data; returned status ${m.status}`,v)}return await m.json()},Fn=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:d,bridge:u,timeout:h,destinationAddress:f})=>{const m={method:t};o&&(m.body=JSON.stringify(o)),e&&(m.destinationAddress=e),ft(m,{timeout:h,ordered:a,studio:c,fos:d,bridge:u,destinationAddress:f});const w=await r(i||`${s}/${n}`,m);if(!w.ok){let E;try{E=await w.json()}catch{}throw new ce(`There was a problem modifying the model; returned status ${w.status}`,E)}return await w.json()},X={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:Bf(t,s||e,c),getModelById:Hf(t,r||e,c),getOne:Kf(t,r||e,c),addModel:xn(t,n||e,c),deleteModel:jf(t,o||e,c),modifyModel:Fn("POST",t,i||e,c),putModel:Fn("PUT",t,i||e,c),postModel:xn(t,n||e,c)}}},Gf=dt(),ec=()=>`kos-${Gf}`,zf=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(ec()),Io=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=$(t,i=>{D.debug(`recieved response for refId ${t}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),Vf=async(t,e,s)=>{const r=Io(s),o=await Promise.allSettled([t(e),r]);if(o[0].status==="fulfilled"){if(o[1].status==="rejected")throw Error(o[1].reason);if(o[0].value){if(o[1].value.error)throw Error(o[1].value.error);return o[0].value.data=o[1].value,o[0].value}}else throw Error(o[0].reason)},Yf=async({topic:t,msg:e,requestId:s})=>{const r=s??dt(),o=Io(r);B(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},ie=new Map;class tc{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){W(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=me(this._parent))==null?void 0:e.model}get companionModels(){const e=me(this._id);return e!=null&&e.model?Ha(e.model):[]}get(e){var s,r;if(this._context.has(e))return this._context.get(e);if(this.companionModels.length>0){const o=this.companionModels.find(n=>{var i;return!n.id||!ie.has(n.id)?!1:(i=ie.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=ie.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=ie.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const K={createContext:(t,e)=>{const s=ie.get(t)??new tc(t);if(e){if(!ie.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return ie.set(t,s),s},getContext:t=>ie.get(t),deleteContext:t=>{ie.delete(t)},setParentContext:(t,e)=>{var s;if(!ie.has(e))throw new Error(`Parent context ${e} does not exist`);(s=ie.get(t))==null||s.setParent(e)},rootContext:()=>ie.get("root")};K.createContext("root");const qf=t=>K.getContext(t.id);function Wf(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class Oo{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=De(),this.generateIndex(),M.autorun(()=>{this._container.revision&&this.generateIndex()}),M.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(e,s,r=this._map,o=this.data){const n=r.get(e)||new Set;n.add(s),r.set(e,n),o[e]=Array.from(n)}resolveIndex(e,s){this.data.keys.filter(o=>!Object.keys(s).includes(o)).forEach(o=>{delete this.data[o],this._map.delete(o)}),Object.keys(s).forEach(o=>{const n=s[o],i=this.data[o]||[];if(Wf(n,i))p.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=e.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){M.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,e,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,e,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function Qf(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>M.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const bt=p.createLogger({name:"kos-container-model"});class we{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?S.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const o=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=M.observable.map(o),this.idx=De(),this._parentId=e==null?void 0:e.parentId,M.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Oo({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(e,s){this._data.set(e.id||"",e),e.id&&this._parentId&&K.setParentContext(e.id,this._parentId),s||this.increment();const r=this._disposerMap.get(e.id);r&&(r(),this._disposerMap.delete(e.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([u,h])=>[h,u])),a=u=>{var f,m;n.includes(u.name)&&((f=this.index.get(i.get(u.name)))==null||f.refresh());const h=o.filter(([,w])=>typeof w=="function");for(const[w]of h)(m=this.index.get(w))==null||m.refresh()},c=Qf(e,a,n.filter(u=>typeof u=="string")),d=M.observe(e,a);this._disposerMap.set(e.id||"",()=>[d,...c].forEach(u=>u()))}removeModel(e,s){this._data.delete(e),s||this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(bt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(bt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return bt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(e=>{const s=e.id;Ue(e).then(()=>{bt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>bt.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const Cr=p.createLogger({name:"kos-data-container"});class So{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=De(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Oo({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}get revision(){return this._revision}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s))})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=M.isObservable(e)?e:M.observable.object(e),o=this._disposerMap.get(e.id);o&&(o(),this._disposerMap.delete(e.id)),this._data.set(r.id||"",r),s||this.increment();const n=M.observe(r,i=>{Object.values(this._optionsMap||{}).includes(i.name)&&this.increment()});this._disposerMap.set(r.id||"",n)}removeModel(e){this._data.delete(e),this.increment();const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}updateModel(e){const s=M.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Cr.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[])}getIndexByKey(e,s){if(this.index.has(e)){const r=this.index.get(e);return r.index.has(s)?r.getByKey(s):(Cr.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Cr.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.clear(),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id}))}}}class Zf{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return J.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return de(this.type)}}class Jf{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return J.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return de(this.type)}}class sc{constructor(){l(this,"_token");M.makeAutoObservable(this),$("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class rc{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:o})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===e&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===e&&o.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(e.path),i={...e,params:n,query:o};for(const c of this.routes){const d=this.matchRoute(c.path,r);if(c.method===e.method&&d){i.params=d;let u=0;const h=async()=>{if(u<c.middlewares.length){const f=c.middlewares[u++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),o=this.parseQueryParams(r);for(const n of this.routes){const i=this.matchRoute(n.path,s);if(i)return{path:s,query:o,params:i}}return{path:s,query:o,params:{}}}matchRoute(e,s){const r=e.split("/").filter(Boolean),o=s.split("/").filter(Boolean);if(r.length!==o.length)return null;const n={};for(let i=0;i<r.length;i++)if(r[i].startsWith(":"))n[r[i].slice(1)]=decodeURIComponent(o[i]);else if(r[i]!==o[i])return null;return n}parseQueryParams(e){return e?e.split("&").reduce((s,r)=>{const[o,n]=r.split("=").map(decodeURIComponent);return s[o]=n??"",s},{}):{}}}const oc=p.createLogger({name:"intent-service"}),Xf=t=>{uo(`/kos/intent/${t.type}`)?B(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):oc.info(`No subscribers for intent ${t.type}. Intent not sent.`)},eg=async t=>new Promise(e=>{const{type:s,options:r}=t;if(uo(`/kos/intent/${t.type}`)){const o=dt(),{unsubscribe:n}=$(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);B(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else oc.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Me=p.createLogger({name:"app-startup-service"});async function nc(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return Me.warn("No app IDs provided to waitForAppsToStart"),!0;Me.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await go(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>rp),[d,u]=await c.get("/api/kos/apps/started");return d?(Me.error("Error fetching started apps:",d),[]):u}catch(c){Me.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(d=>{const u=c.find(h=>h.appId===d);return!(!u||!u.started||o&&!u.postStarted)}),timeout:s}),a=t.filter(c=>{const d=i.find(u=>u.appId===c);return!!(!d||!d.started||o&&!d.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(Me.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return Me.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Me.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function tg(t,e={}){return nc([t],e)}async function sg(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];t.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){Me.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function rg(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return Me.error("Failed to fetch started apps:",t),[]}}const Gr=M.when,$o=M.computed,W=M.runInAction,H=M.autorun,ic=M.reaction,Do=M.observable,Co="Not Assigned",og="kos.trouble.added",ng="kos.trouble.removed";var he=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(he||{}),Bt=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Bt||{});const ac=p.createLogger({name:"config-bean-service",group:"Services"}),Ro=exports.BASE_URL,cc=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:ig,getOne:ag}=X.build({destinationAddress:"",basePath:`${Ro}/kos/config/`}),lc=async(t,e,s="/api/kos/config")=>(ac.debug(`sending modify request for ConfigBean: ${t}`),ig({model:e,urlOverride:`${Ro}${s}/${t}`})),dc=async(t,e="/api/kos/config")=>(ac.debug(`sending get request for ConfigBean: ${t}`),await ag({urlOverride:`${Ro}${e}/details/${t}/15`})),Po=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",lr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function uc(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function hc(t,e="",s={}){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e?`${e}.${r}`:r;typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])?hc(t[r],o,s):s[o]=t[r]}return s}const fc=(t,e)=>{const s=t.details[0].bean||uc(t.details[0].scopes),r=hc(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},gc=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&Po(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&lr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},pc=t=>Object.fromEntries(t.props.entries),cg=t=>e=>s=>t.build(e,s);var lg=Object.defineProperty,dg=Object.getOwnPropertyDescriptor,mc=(t,e,s,r)=>{for(var o=r>1?void 0:r?dg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&lg(e,s,o),o};function ug(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Ao="config-bean-model",ms=p.getLogger(Ao),hg=Be("path");let Ls=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=lc,getConfigBean:r=dc}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=De(),this.prevProps=De()}get values(){return this.props.values}async ready(){ms.debug(`readying config bean ${this.path}`),ms.debug(`complete readying config bean ${this.path}`)}async load(){ms.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;fc(e,this),ms.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;W(()=>{s&&(this._schema=s)})}}get schemaKeys(){var t;return Object.keys(((t=this._schema)==null?void 0:t.schema)||{})}getSchemaForProperty(t){var s,r;if(this.schemaKeys.includes(t))return(s=this._schema)==null?void 0:s.schema[t];const e=ug(this.schemaKeys,t);if(e)return(r=this._schema)==null?void 0:r.schema[e]}async updateProperty(t,e){this.props[t]=e,await this.updateConfigBean()}async updateConfigBean(){const t=pc(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){gc(t,this)}};mc([F({topic:`/kos/config/${hg}`,websocket:!0})],Ls.prototype,"handleConfigBeanUpdated",1);Ls=mc([R(Ao)],Ls);const Gt=new pe({class:Ls,type:Ao}),dr=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[x]=r[x]||{},r[x][o]={modelType:Gt.type,id:`${Gt.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:j.INIT,lazy:e}},{URL:yc}=te(),{getOne:fg,getAll:gg}=X.build({basePath:`${yc}/api/kos/regions/info`}),bc=async()=>await fg({}),wc=async()=>await gg({urlOverride:`${yc}/api/kos/regions`}),pg=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:bc,getRegions:wc},Symbol.toStringTag,{value:"Module"}));var oe=(t=>(t[t.family=0]="family",t[t.scale=1]="scale",t[t.offset=2]="offset",t[t.decimals=3]="decimals",t[t.alias=4]="alias",t[t.system=5]="system",t))(oe||{});const vc={s:["time",1,0,0],second:["time",1,0,0],m:["time",1/60,0,0],minute:["time",1/60,0,0],h:["time",1/3600,0,0],hour:["time",1/3600,0,0],day:["time",1/86400,0,0],week:["time",1/604800,0,0],month:["time",1/2628e3,0,0],year:["time",1/31536e3,0,0],default:["time",1/.001,0,0],ms:["time",1/.001,0,0],millisecond:["time",1/.001,0,0],microsecond:["time",1/1e-6,0,0],nanosecond:["time",1/1e-9,0,0],picosecond:["time",1/1e-12,0,0]};function mg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{...vc});return{...t,...r}}function yg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...vc}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function bg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{};return Object.hasOwn(n,"default")&&(i[s]=n.name),o[n.measure]=i,o},{time:{[s]:"millisecond"}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}var wg=Object.defineProperty,vg=Object.getOwnPropertyDescriptor,Lo=(t,e,s,r)=>{for(var o=r>1?void 0:r?vg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&wg(e,s,o),o};const Os="region-info-model",wt=p.createLogger({name:"region-info-model"});let zt=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[oe.system]}getUnitMeasure(t){const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[oe.family]}getDefaultUnitDecimalPlaces(t,e,s){if(!t||!e)throw Error("Measure and unit system are required");const r=s==="drt"?"second":s,o=this.measureMap[t];if(!o)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const n=o[e.toLowerCase()];if(!n)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(o).join(", ")}`);const i=n[r||"default"];if(!i)throw Error(`No unit "${r||"default"}" found for measure: ${t} and unit system: ${e}. Unit should come from list of units: ${Object.keys(n).join(", ")}`);return i[oe.decimals]}getDefaultUnitForMeasure(t,e){if(!t||!e)throw Error("Measure and unit system are required");const s=this.defaultMeasureMap[t];if(!s)throw Error(`No unit systems found for measure: ${t}. Measure should come from list of measures: ${Object.keys(this.measureMap).join(", ")}`);const r=s[e.toLowerCase()];if(!r)throw Error(`No unit system found for measure: ${t} and unit system: ${e}. Unit system should come form list of unit systems: ${Object.keys(s).join(", ")}`);return r}convertByUnit(t,e,s){if(e[oe.family]!==s[oe.family])throw new Error(`Cannot convert between units of different families: ${e[oe.family]} and ${s[oe.family]}`);const r=e[oe.offset],o=e[oe.scale],n=s[oe.scale],i=s[oe.offset],a=s[oe.decimals];return((t-r)/(o/n)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,o)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];if(!i&&s.measure&&s.system){const d=this.measureMap[s.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=d[s.system])==null?void 0:a.default,i||wt.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const d=this.measureMap[e.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=d[e.system])==null?void 0:c.default,n||wt.info("Could not find default unit for measure",e.measure)}return!n||!i?(wt.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){wt.debug("initializing region info")}async load(){wt.debug("loading region info");const t=await wc();t&&(this.regions=t.data.map(s=>s.id),this.timeZoneMap=t.data.reduce((s,r)=>({...s,[r.id]:r.timeZones}),this.timeZoneMap),this.regionMap=t.data.reduce((s,r)=>({...s,[r.id]:r}),{}));const e=await bc();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(mg,{}),this.measureMap=e.data.unitSystems.reduce(yg,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(bg,{}),this.timeFormats=e.data.timeFormats.reduce((s,r)=>({...s,[r.id]:r}),{}),this.dateFormats=e.data.dateFormats.reduce((s,r)=>({...s,[r.id]:r}),{}))}async ready(){var t,e;await((e=(t=this.regionSource).ready)==null?void 0:e.call(t))}};Lo([dr({path:"kos:service:region:settings"})],zt.prototype,"regionSource",2);Lo([dr({path:"kos:service:region"})],zt.prototype,"region",2);zt=Lo([R(Os)],zt);const Z={registration:{[Os]:{class:zt,singleton:!0}},type:Os,factory:J.Singleton.create(Os)},xs=({source:t,defaultSystem:e="si",defaultMeasure:s})=>{let r={system:e,measure:s};return typeof t=="string"?r={...r,unit:t}:r={...r,...t},r},xo=(t,e,s)=>{const{model:r}=me(Z.type);if(!r)throw new Error("RegionInfo model not found");if(!As(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=xs({source:e}),i=xs({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function kn(t,e,s){const r=e.toLowerCase().replace(/_/g,"-").replace(/s$/,""),o=new Intl.NumberFormat().resolvedOptions().locale??"en-US";try{const n=(s==null?void 0:s.mode)||"long",i=(s==null?void 0:s.maxDecimals)??2,a=(s==null?void 0:s.minDecimals)??0;return new Intl.NumberFormat(o,{style:"unit",unit:r,unitDisplay:n,minimumFractionDigits:a,maximumFractionDigits:i}).format(t)}catch{return e}}const Mg=(t,e,s,r)=>{const o=xo(t,e,s),n=xs({source:e}),{model:i}=me(Z.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},d=xs({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),u=i.getDefaultUnitForMeasure(a,d.system),h=i.getDefaultUnitDecimalPlaces(a,d.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:u||n.unit||"",display:kn(o,u||n.unit||"",{...f,mode:"long"}),shortDisplay:kn(o,u||n.unit||"",{...f,mode:"short"})}};function Nn({start:t,end:e,count:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<2)throw new Error("Count should be at least 2 for distribution.");if(t>=e)throw new Error("Start should be less than end.");const o=(e-t)/(s-1),n=[];for(let i=0;i<s;i++){const a=Math.round(t+i*o);n.push(a.toFixed(r))}return n}function Un({start:t,end:e,interval:s,decimals:r=0}){if(typeof t!="number"||typeof e!="number"||typeof s!="number")throw new Error("All input values should be numbers.");if(s<=0)throw new Error("Interval should be a positive number.");if(t>=e)throw new Error("Start should be less than end.");const o=[];let n=t;for(;n<=e;)o.push(n.toFixed(r)),n+=s;return o[o.length-1]!==e.toString()&&o.push(e.toString()),o}const ze=(t,e)=>s=>!t||!e?s:lr(s)?xo(Number(s),t,e):s,Eg=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Nn(t.options).map(ze(s,r));if(t.options.type==="rangeInterval")return Un(t.options).map(ze(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(ze(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Nn(t.options.unitSystems[e]).map(ze(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Un(t.options.unitSystems[e]).map(ze(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(ze(s,r))}}return[]},_g=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var Tg=Object.defineProperty,Ig=Object.getOwnPropertyDescriptor,Fo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ig(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Tg(e,s,o),o};function Og(t){return(t==null?void 0:t.type)==="enum"}function Sg(t){switch(t){case"s":return"second";case"ms":return"millisecond";case"min":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"m":return"month";case"y":return"year";case"ml":return"milliliter";default:return t}}function $g(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return $e.format(r,e)}const Ss="config-bean-prop-model",Ve=p.createLogger({name:"config-bean-prop-model"}),Dg=Be("path"),Cg=Be("serviceBasePath");let Vt=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return cc(this.displayOptions)?this.displayOptions.decimals:this.regionInfo.getDefaultUnitDecimalPlaces(t,e,s)}getDefaultUnitForMeasure(t,e){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return this.regionInfo.getDefaultUnitForMeasure(t,e)}get schemaType(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.type?t.type:"String"}get schemaFormat(){const t=this.bean.getSchemaForProperty(this.attribute);return t!=null&&t.format?Sg(t.format):""}get options(){var i;const t=this.regionInfo.defaultUnitSystem,e=this.getConverter(),s=((i=e==null?void 0:e.to)==null?void 0:i.system)??t,r=this.bean.getSchemaForProperty(this.attribute),o=Og(r)?r.values:Eg(r,s,e==null?void 0:e.from,e==null?void 0:e.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,o=(t==null?void 0:t.system)||e,n=t==null?void 0:t.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),o=this.convertUnit(e.to,t,s);return{backend:r,display:o}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let d=String(t);return d=c.formatToParts(Number(t))[0].value,Number(d)}}catch(c){Ve.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,o)}return e||""}async activate(){Ve.debug(`activating config bean ${this.id}`)}get displayValue(){const t=this.value;if(typeof t=="boolean")return String(t);if(this.schemaFormat==="drt"){const s=this.regionInfo.is12HourTimeFormat?"h:mm:ss a":"HH:mm:ss";return $g(t,s)}if(!isNaN(t))try{const e=this.getConverter(),s=this.getFormatterOptions(e);if(s){let r=String(t);return r=s.format(Number(t)),r}}catch(e){Ve.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var o;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??e;return _g(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,o;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=t==null?void 0:t.to)==null?void 0:o.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var n,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,d=this.formatter||c;if(d){let u=typeof d=="function"?d(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):d;s&&(u={unit:this.getDefaultUnit(t),...u},u.style==="unit"&&(u.maximumFractionDigits=u.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...u})}catch(h){Ve.error(`error creating formatter ${u}. Returning the raw value`,h)}}else Ve.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,d,u,h,f,m;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const w=(r=this.converter)==null?void 0:r.measure,v=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,T=w||v||E||e,k=((d=(c=this.converter)==null?void 0:c.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(T,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),se=((m=(f=this.converter)==null?void 0:f.to)==null?void 0:m.system)??this.regionInfo.getUnitSystem(k),P=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:P,...this.converter.from},to:{...this.converter.to,unit:k,system:se},measure:T}}if(s&&e){const w=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),v=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(w);return{measure:e,to:{unit:v===E?s:w}}}}async updateProperty(t){Ve.debug(`updating property ${this.attribute} with value ${t}`);let e=t;if(this.getConverter()&&!isNaN(e)){const{backend:o,display:n}=this.getConverterUnits();e=this.regionInfo.convert(Number(e),n,o)}const r=Array.isArray(e)?JSON.stringify(e):String(e);await this.bean.updateProperty(this.attribute,r)}};Fo([ut({modelType:Z.type})],Vt.prototype,"regionInfo",2);Fo([dr({path:Dg,serviceBasePath:Cg})],Vt.prototype,"bean",2);Vt=Fo([R(Ss)],Vt);const Ke={registration:{[Ss]:{class:Vt,singleton:!1}},type:Ss,factory:J.Factory.create(Ss)};function Rg(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(d,u)=>{d[x]=d[x]||{},d[x][u]={modelType:Ke.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:j.INIT,lazy:n}}}class Pg{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=Do.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=H(()=>{var o,n;(e.endState||e.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,e))});this.disposers.set(s||e.id,r)}removeFuture(e){var s;this.futures.delete(e||this.context),(s=this.disposers.get(e||this.context))==null||s(),this.disposers.delete(e||this.context)}getFuture(e){return this.futures.get(e||this.context)}get futureMap(){return this.futures}}class ur{constructor(e){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=H(()=>{var r,o;(e.endState||e.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw p.error(e),e}}}const Mc="future-model",gt=ht(Mc),hr=p.createLogger({name:"future-service",group:"Services"}),{isMock:Ag,URL:ns}=te();var Ce=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(Ce||{});const{getAll:Lg,modifyModel:xg,addModel:Fg,deleteModel:kg,postModel:Ng}=X.build({destinationAddress:"",basePath:`${ns}/api/future`,mock:Ag}),Ug=async()=>await Lg({}),Ec=async(t,e="/api/kos/future")=>(hr.info(`sending delete request for Future: ${t}`),await kg({id:t,urlOverride:`${ns}${e}/${t}`})),_c=async(t,e="/api/kos/future")=>(hr.info("sending add request for Future"),await Fg({model:t,urlOverride:`${ns}${e}`})),jg=async(t,e,s="/api/kos/future")=>(hr.info(`sending modify request for Future: ${t}`),xg({model:e,id:t,urlOverride:`${ns}${s}/${t}`})),Tc=async(t,e="/api/kos/future")=>(hr.info(`sending cancel request for Future: ${t}`),Ng({urlOverride:`${ns}${e}/${t}/cancel`,ordered:!0,model:{}})),ko=t=>({id:String(t.id),progress:t.progress,remainingTimeMs:t.remainingTimeMs,endState:t.endState,reason:t.reason,clientData:t.clientData,reasonData:t.reasonData,note:t.note,tracker:t.tracker}),No=(t,e)=>{p.debug(`future dto ${t.id} end state ${t.endState}`),p.debug(`future model ${e.id} end state ${e.endState}`),e.endState?p.debug(`future model ${e.id} is already complete`):(p.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=ko(t);W(()=>{Object.keys(s).forEach(r=>{r==="id"?(e.futureId=s.id,s.tracker||(e.id=s.id)):r==="tracker"?e.id=s.tracker:e[r]=s[r]})})}))},Ic=t=>e=>s=>t.build(String(e),s),Uo=t=>e=>Xa(ko,Ic(t)(e.tracker||e.id))(e);var Bg=Object.defineProperty,Kg=Object.getOwnPropertyDescriptor,Oc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Kg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Bg(e,s,o),o};const Rr=p.getLogger(gt.type);let Fs=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=Tc,Gr(()=>this.status===Ce.Success||this.status===Ce.Fail,()=>{Rr.info(`Future ${this.id} has completed with status ${this.status}`),Ue(this)})}async load(){Rr.debug(`loading Future ${this.id}`)}unload(){Rr.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Gr(()=>this.futureId!==Co),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[d,u]of Object.entries(e))if(Math.abs(t)>=u){s=d,r=Math.round(t/u);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),No(t,this)}};Oc([F({topic:`kos.future/${Ds}`})],Fs.prototype,"handleFutureUpdated",1);Fs=Oc([R(gt.type)],Fs);const Sc=Fs,$c=To();var Hg=Object.defineProperty,Gg=Object.getOwnPropertyDescriptor,Dc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Hg(e,s,o),o};const Cc="browser-router-model",zg="kos.http.request",Vg="kos.http.response";let ks=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new rc}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],o=e.headers.url,n=e.headers.method,i=e.headers["request-id"],a={id:i,method:n,path:o,body:t};let c=200;const d={send:u=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(u),La({msg:u,options:{responseId:i,destinationAddress:s,type:Vg,sourceAddress:r,status:c}})},status:function(u){return c=u,this}};if(a.path==="/openapi.json"){d.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,d)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};Dc([F({topic:zg})],ks.prototype,"handleRequest",1);ks=Dc([R(Cc)],ks);const jo=new be({class:ks,type:Cc}),Rc="future-container-model",Re=ht(Rc),Pc=t=>Uo(gt)(t),Yg=t=>{const e=Pc(t);return Re.build(Re.type,{}).addFutureModel(e),e},qg=t=>Re.build(Re.type,{}).getFuture(String(t)),je={buildFutureModel:Pc,initiateFuture:Yg,getFuture:qg};var Wg=Object.defineProperty,Qg=Object.getOwnPropertyDescriptor,Bo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Qg(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Wg(e,s,o),o};const ys=p.getLogger(Re.type);let Yt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=Ec,addFuture:o=_c}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new we,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){ys.error("error deleting a Future"),ys.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Uo(gt)(s);return this.addFutureModel(r),r}}catch(e){throw ys.error("error creating a Future"),ys.error(e),e}}handleFutureUpdated(t,e){const s=je.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),B(r,e.body,e.headers)}};Bo([ge],Yt.prototype,"_futures",2);Bo([F({topic:"kos.future"})],Yt.prototype,"handleFutureUpdated",1);Yt=Bo([R(Re.type)],Yt);const Ac=Yt,{URL:is}=te(),{getOne:Zg,postModel:Jg,deleteModel:Lc}=X.build({basePath:`${is}/api/keyVal`}),zr=p.createLogger({name:"key-value-service",group:"Services"}),xc=async(t,e)=>{await Lc({urlOverride:`${is}/api/keyVal/${t}/${e}`,id:e})},Fc=async(t,e,s)=>{const r=await Jg({urlOverride:`${is}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw zr.error("Failed to update studio-state data",r),new Error(`Failed to update studio-state data for namespace ${t}`);return r.data},kc=async(t="studio")=>{zr.debug("sending GET for studio-state");const e=await Zg({urlOverride:`${is}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw zr.error("Failed to retrieve studio-state data",e),new Error(`Failed to retrieve studio-state data for namespace ${t}`);return e.data},Xg=async t=>{await Lc({urlOverride:`${is}/api/keyVal/${t}}`,id:""})},ep=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:xc,deleteKeyValueNamespace:Xg,getKeyValue:kc,updateKeyValue:Fc},Symbol.toStringTag,{value:"Module"}));var tp=Object.defineProperty,sp=Object.getOwnPropertyDescriptor,Ko=(t,e,s,r)=>{for(var o=r>1?void 0:r?sp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&tp(e,s,o),o};const Nc="key-value-model";let qt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=De(),this.namespace=e.namespace||"studio"}async init(){this.logger.debug(`initializing studio-state ${this.id}`)}async updateState(t,e){this.logger.debug(`updating studio-state ${t} with value ${e}`),e!==void 0?(await Fc(this.namespace,t,e),this.data[t]=e):(await xc(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await kc(this.namespace);this.data.setValues(t)}handleStateUpdate(t){t.namespace===this.namespace&&(this.data[t.key]=t.value)}handleStateDelete(t){t.namespace===this.namespace&&(this.data[t.key]=void 0)}};Ko([F({topic:"/keyVal/set"})],qt.prototype,"handleStateUpdate",1);Ko([F({topic:"/keyVal/remove"})],qt.prototype,"handleStateDelete",1);qt=Ko([R(Nc)],qt);const Ho=new pe({class:qt,type:Nc}),Oe=To(),rp=Object.freeze(Object.defineProperty({__proto__:null,default:Oe},Symbol.toStringTag,{value:"Module"})),op=p.createLogger({name:"kos-log-manager-service",group:"Services"}),np="/api/kos/logs/overrides",Uc=async()=>(op.debug("sending GET for kos-log-manager"),await Oe.get(np)),ip=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:Uc},Symbol.toStringTag,{value:"Module"}));var ap=Object.defineProperty,cp=Object.getOwnPropertyDescriptor,fr=(t,e,s,r)=>{for(var o=r>1?void 0:r?cp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ap(e,s,o),o};const jc="kos-log-manager-model",lp="/kos/logs/override/add/*",dp="/kos/logs/override/remove/*",up=t=>{if(typeof t=="string")return t;if(typeof t=="number")switch(t){case 0:return"trace";case 1:return"debug";case 2:return"info";case 3:return"warn";case 4:return"error";default:return"info"}return"info"};let tt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new So}updateModel(t){}resolveLoggers(){const t=p.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:up(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=p.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=p.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await Uc();if(t){this.logger.error("Failed to load log overrides",t);return}const s=(e==null?void 0:e.filter(r=>{var o;return((o=r.type)==null?void 0:o.toUpperCase())==="UI"}).map(r=>({name:r.name??"",type:r.type??"",level:r.level??"info",id:r.name||""})))??[];this._overrides.addAll(s),s.forEach(r=>{this.setLogLevels(r)})}};fr([ra("/api/kos/ui/loggers")],tt.prototype,"getAllLoggers",1);fr([F({topic:lp,websocket:!0,wildcardName:"nodeType"})],tt.prototype,"handleOverrideAdded",1);fr([F({topic:dp,websocket:!0,wildcardName:"nodeType"})],tt.prototype,"handleOverrideRemoved",1);tt=fr([R(jc)],tt);const Bc=new be({class:tt,type:jc}),{URL:as}=te(),{postModel:Go,getOne:hp}=X.build({basePath:`${as}/api/kos-time`});p.createLogger({name:"kos-time-service",group:"Services"});const Kc=async t=>{const e=await Go({model:t,urlOverride:`${as}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Hc=async t=>{const e=await Go({model:t,urlOverride:`${as}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Gc=async t=>{const e=await Go({model:{},urlOverride:`${as}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},zc=async()=>{const t=await hp({urlOverride:`${as}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},fp=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:zc,setDate:Hc,setTime:Kc,setTimezone:Gc},Symbol.toStringTag,{value:"Module"}));var gp=Object.defineProperty,pp=Object.getOwnPropertyDescriptor,gr=(t,e,s,r)=>{for(var o=r>1?void 0:r?pp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&gp(e,s,o),o};const _t="kos-time-model",mp="/kos/time/time",yp="/kos/time/day",bp="/kos/time/timezone";let st=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await Kc(t)}async updateSystemDate(t){await Hc(t)}async updateSystemTimezone(t){await Gc(t)}handleTimeChange(){B(Bt.TIME_CHANGE,{})}handleDayChange(){B(Bt.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),B(Bt.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await zc();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};gr([F({topic:mp,websocket:!0})],st.prototype,"handleTimeChange",1);gr([F({topic:yp,websocket:!0})],st.prototype,"handleDayChange",1);gr([F({topic:bp,websocket:!0})],st.prototype,"handleTimeZoneChange",1);st=gr([R(_t)],st);const Ns={registration:{[_t]:{class:st,singleton:!0}},type:_t,predicate:de(_t),factory:J.Singleton.create(_t)};var wp=Object.defineProperty,vp=Object.getOwnPropertyDescriptor,Vc=(t,e,s,r)=>{for(var o=r>1?void 0:r?vp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&wp(e,s,o),o};const Yc="log-block-container-model";let Us=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new we({parentId:t,sortKey:"blockNum"})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};Vc([ge],Us.prototype,"_models",2);Us=Vc([R(Yc)],Us);const Mp=p.createLogger({name:"log-stream-container-service",group:"Services"}),qc=()=>{var r;const t=le(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return p.error(`getKosConnectionId: ${s}`),s},pt=qc(),Ep="/api/kos/logs/node/{nodeId}/streams",Wc=async()=>(Mp.debug("sending GET for log-stream-container"),await Oe.get(Ep,{path:{nodeId:"primary"}},{destinationAddress:pt})),Qc=async(t,e="primary")=>{await Oe.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:pt})},Zc=async t=>{await Oe.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:pt})},_p=async()=>{await Oe.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:pt})},Jc=async t=>await Oe.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:pt}),Xc=async(t,e)=>await Oe.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:pt}),Tp=Object.freeze(Object.defineProperty({__proto__:null,createOverride:_p,getKosConnectionId:qc,getLogStreamBlock:Xc,getLogStreamBlocks:Jc,getLogStreams:Wc,subscribeToLogStream:Qc,unsubscribeFromLogStream:Zc},Symbol.toStringTag,{value:"Module"}));var Ip=Object.defineProperty,Op=Object.getOwnPropertyDescriptor,Sp=(t,e,s,r)=>{for(var o=r>1?void 0:r?Op(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ip(e,s,o),o};const el="log-block-model";let Vr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await Xc(this.stream,this.blockNum);if(t){this.logger.error(`Failed to get log block ${this.blockNum}`);return}e&&this.addLines(e.lines,!0)}updateModel(t){this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount}addLines(t,e){const s=e?[]:this.lines;this.lines=[...s,...t],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};Vr=Sp([R(el)],Vr);const Wt=new pe({class:Vr,type:el}),pr=new pe({class:Us,type:Yc});pr.addRelatedModel(Wt);var $p=Object.defineProperty,Dp=Object.getOwnPropertyDescriptor,tl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Dp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&$p(e,s,o),o};const sl="log-stream-model";let js=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"_blocks");l(this,"name");l(this,"currentBlockId");l(this,"isResetting");l(this,"generatorInstance");l(this,"shouldStop",!1);this.id=t,this.logger=s.logger,this.currentBlockId="",this.name=e.name,this.nodeId=e.nodeId,this.isResetting=!0,this._blocks=pr.instance(`${t}-blocks`).options({}).build()}get firstLineNum(){const t=this.populated[0];return t?t.startLineNum:0}get currentBlock(){const t=this.currentBlockId;return this._blocks.getModel(t)}get populated(){return this._blocks.data.filter(t=>t.lines.length>0)}get blocks(){return this._blocks.data}get totalLineCount(){return this.populated.reduce((t,e)=>t+e.lineCount,0)}accept(t){t.visit(this)}updateBlock(t){var r;let e=this._blocks.models.getModel(`${t.stream}-block-${t.blockNum}`);const s={nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)};e||(e=Wt.instance(`${t.stream}-block-${t.blockNum}`).options(s).build(),this._blocks.addModel(e)),e&&e.updateModel(s),(!this.currentBlock||t.blockNum>=((r=this.currentBlock)==null?void 0:r.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}addBlock(t){var s;const e=Wt.instance(`${t.stream}-block-${t.blockNum}`).options({nodeId:t.nodeId,blockNum:t.blockNum,endLineNum:t.endLineNum,lineCount:t.lineCount,startLineNum:t.startLineNum,stream:this.name,endTime:new Date(t.endTime),startTime:new Date(t.startTime)}).build();this._blocks.addModel(e),(!this.currentBlock||t.blockNum>=((s=this.currentBlock)==null?void 0:s.blockNum))&&(this.currentBlockId=`${t.stream}-block-${t.blockNum}`)}removeBlock(t){this._blocks.models.removeModel(`${this.name}-block-${t}`)}async subscribe(){await Qc(this.name)}async unsubscribe(){await Zc(this.name)}async reset(){if(this.isResetting=!0,this.populated.length>0)return;this.logger.debug(`resetting log-stream ${this.id}`);for(const e of this._blocks.models.data)e.lines=[];const t=this._blocks.data[this._blocks.data.length-1];t&&await t.syncLines(),this.isResetting=!1}async init(){this.logger.debug(`initializing log-stream ${this.id}`)}async load(){this.logger.debug(`loading log-stream ${this.id}`);const[t,e]=await Jc(this.name);if(t){this.logger.error(`Error loading log stream: ${t}`);return}if(e)for(const r of e)this.addBlock(r);const s=this._blocks.data[this._blocks.data.length-1];if(s&&await s.syncLines(),this._blocks.data.length>1){const r=this._blocks.data[this._blocks.data.length-2];r&&await r.syncLines()}}start(){return this.shouldStop=!1,this.generatorInstance=this.streamLogs(),this.generatorInstance}stop(){var t;this.shouldStop=!0,(t=this.generatorInstance)==null||t.next(),console.log("Requested generator stop.")}async*streamLogs(){const t=[];let e=null,s=0,r=this.currentBlockId;const o=ic(()=>{const n=this.currentBlock;return n?{blockId:this.currentBlockId,lineCount:n.lines.length}:null},n=>{const i=this.currentBlock;if(i)if(r!==(n==null?void 0:n.blockId))r=n==null?void 0:n.blockId,s=0,t.push(...i.lines);else{const a=i.lines.slice(s);t.push(...a),s+=a.length}e&&(e(),e=null)},{fireImmediately:!0});try{for(const n of this.populated.filter(i=>i!==this.currentBlock))for(const i of n.lines)yield i;for(;;)for(t.length===0&&await new Promise(n=>e=n);t.length>0;)yield t.shift()}finally{o()}}};tl([ge],js.prototype,"_blocks",2);js=tl([R(sl)],js);const Kt=new pe({class:js,type:sl});var Cp=Object.defineProperty,Rp=Object.getOwnPropertyDescriptor,He=(t,e,s,r)=>{for(var o=r>1?void 0:r?Rp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Cp(e,s,o),o};const rl="log-stream-container-model",Pp="/kos/logs/subscription/addBlock/*",Ap="/kos/logs/subscription/updateBlock/*",Lp="/kos/logs/subscription/removeBlock/*",xp="/kos/logs/subscription/lines/*",ol="/kos/logs/streams/add/*";let _e=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new we({parentId:t}),this.selectedStream=void 0}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}updateModel(t){}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}updateSelectedStream(t){this.selectedStream=t}handleStreamAdded(t){this.logger.debug(`Received topic: ${ol}`);const e=t.stream,s=Kt.instance(e).options({name:e,nodeId:"primary"}).build();this.addModel(s)}handleAddBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.addBlock(t)}handleRemoveBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.removeBlock(t.blockNum)}handleUpdateBlock(t,e){this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&r.updateBlock(t)}handleLogLine(t,e){var o;this.logger.debug(`Received topic: ${e.headers.topic}`);const s=t.stream,r=this.models.getModel(s);r&&((o=r.currentBlock)==null||o.addLines(t.lines))}async init(){this.logger.debug(`initializing log-stream-container container ${this.id}`)}async subscribeToLogStream(t){const e=Kt.instance(t).options({name:t,nodeId:"primary"}).build();this.addModel(e),await e.subscribe()}async load(){this.logger.debug(`loading log-stream-container container ${this.id}`);const[t,e]=await Wc();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=Kt.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};He([ge],_e.prototype,"_models",2);He([F({topic:[ol],websocket:!0})],_e.prototype,"handleStreamAdded",1);He([F({topic:[Pp],websocket:!0})],_e.prototype,"handleAddBlock",1);He([F({topic:[Lp],websocket:!0})],_e.prototype,"handleRemoveBlock",1);He([F({topic:[Ap],websocket:!0})],_e.prototype,"handleUpdateBlock",1);He([F({topic:[xp],websocket:!0})],_e.prototype,"handleLogLine",1);_e=He([R(rl)],_e);const cs=new be({class:_e,type:rl});cs.addRelatedModel(Kt);cs.addRelatedModel(pr);cs.addRelatedModel(Wt);const Fp=t=>t.rank!==void 0,kp=t=>t.visibleRole!==void 0,Np=t=>t.color!==void 0,Up=t=>{const e=t.info;return Fp(e)?e.rank:0},jp=t=>{const e=t.info;return Np(e)?e.color:"orange"},Bp=t=>{const e=t.info;return kp(e)?e.visibleRole:"TECHNICIAN"},{URL:zo}=te(),{getAll:Kp,postModel:nl}=X.build({basePath:`${zo}/api/kos/troubles`}),il=async()=>await Kp({}),al=async(t,e)=>{try{const s=await nl({model:{},urlOverride:`${zo}/api/kos/troubles/resolve/${t}`,tracker:e});return s!=null&&s.data&&je.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:Ce.Fail,tracker:e,reason:"Failed to resolve trouble"};return je.initiateFuture(r),r}},Hp=async(t,e)=>{try{const s=await nl({model:t,urlOverride:`${zo}/api/kos/troubles/resolve/`,tracker:e});return s!=null&&s.data&&je.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:Ce.Fail,tracker:e,reason:"Failed to resolve troubles"};return je.initiateFuture(r),r}},Gp=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Hp,getTroubles:il,resolveTrouble:al},Symbol.toStringTag,{value:"Module"})),Bs="troubleDataMapper",bs=new Map;rs(Bs,{register:(t,e)=>{var s;bs.has(t)||bs.set(t,[]),(s=bs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=bs.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:p.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const ls="troubleMapper",ws=new Map;rs(ls,{register:(t,e)=>{var s;ws.has(t)||ws.set(t,[]),(s=ws.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=ws.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(p.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});S[ls].register("nozzle",async t=>[t.data.nozzlePath]);S[ls].register("path",async t=>[t.data.path]);const zp=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>S[ls].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},cl=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>S[Bs].execute(i,t)),r=S[Bs].execute(t.type,t);s.push(r);const n=(await Promise.allSettled(s)).reduce((i,a)=>(a.status==="fulfilled"&&(i={...i,...a.value}),i),{});return{...t.data,...n}};class Vp{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class Yp{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class Ye{static getHandler(e){switch(e){case"ResolvableTrouble":return new Vp;case"BlockPumpTrouble":return new Yp;default:return}}}var qp=Object.defineProperty,Wp=Object.getOwnPropertyDescriptor,ll=(t,e,s,r)=>{for(var o=r>1?void 0:r?Wp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&qp(e,s,o),o};const Tt="trouble-model";function vs(t){return typeof t.shouldDefer=="boolean"}let Ks=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:d,createTime:u,role:h,color:f,...m},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,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=w.logger,this.type=c,this._troubleId=o,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=f,this.tags=s,this.info=r,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,m),this.futureHandler=new ur(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=Ye.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Ye.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=Ye.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Ye.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=Ye.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=Ye.getHandler(this.type))==null?void 0:t.subtitle)||"Trouble"}get troubleId(){return this._troubleId}get resolvable(){return this._resolvable}get future(){return this.futureHandler.future}async resolveMappedData(){return await cl(this)}get deferredCompanion(){const t=Kr(this.id,e=>vs(e));if(t&&vs(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Kr(this.id,e=>vs(e));return t&&vs(t.modelData)?t.modelData.shouldDefer:!1}clearDefer(){var t;(t=this.deferredCompanion)==null||t.clearDefer()}defer(){var t;(t=this.deferredCompanion)==null||t.defer()}getChildren(){return[...this.futureHandler.allFutures]}async resolve(t){var e;if(!this._resolvable)throw this.logger.error(`attempting to resolve an unresolvable trouble with id ${this._troubleId}`),new Error("Trouble is not resolvable");if(this.shouldDefer){(e=this.deferredCompanion)==null||e.defer();return}return await al(this._troubleId,t)}};ll([ln()],Ks.prototype,"resolve",1);Ks=ll([R(Tt)],Ks);const Qt={registration:{[Tt]:{class:Ks,singleton:!1}},type:Tt,predicate:de(Tt),factory:J.Factory.create(Tt)};var Qp=Object.defineProperty,Zp=Object.getOwnPropertyDescriptor,mr=(t,e,s,r)=>{for(var o=r>1?void 0:r?Zp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Qp(e,s,o),o};const jn=p.createLogger({name:"trouble-container-model"});function Bn(t){return S.propertyMapper.hasMapper(he.TroubleRank)?S.propertyMapper.executeMapper(he.TroubleRank,t):Up(t)}function Kn(t){return(S.propertyMapper.hasMapper(he.TroubleColor)?S.propertyMapper.executeMapper(he.TroubleColor,t):jp(t)).toLowerCase()}function Hn(t){return(S.propertyMapper.hasMapper(he.TroubleRole)?S.propertyMapper.executeMapper(he.TroubleRole,t):Bp(t)).toLowerCase()}const Jp="trouble-container-model";class ae{}l(ae,"INDEX_TROUBLES_BY_IFACE","byIface"),l(ae,"INDEX_TROUBLES_BY_TYPE","byType"),l(ae,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(ae,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(ae,"SORT_KEY_RANK","rank"),l(ae,"TROUBLES_DEFERRED","true");let rt=class{constructor(t){l(this,"id");l(this,"troubles");this.id=t,this.troubles=new we({indexMap:{[ae.INDEX_TROUBLES_BY_IFACE]:zp,[ae.INDEX_TROUBLES_BY_TYPE]:"type",[ae.INDEX_TROUBLES_BY_GROUP]:"group",[ae.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:ae.SORT_KEY_RANK,parentId:t})}async load(){jn.debug("loading trouble container");const t=await il();try{t==null||t.data.forEach(e=>{const s={...e,rank:Bn(e),color:Kn(e),role:Hn(e),id:String(e.id)},r=Qt.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw jn.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&Ue(s)}handleTroubleAdded(t){const e={...t,rank:Bn(t),color:Kn(t),role:Hn(t),id:String(t.id)};if(e.role==="NONE")return;const s=Qt.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};mr([ge],rt.prototype,"troubles",2);mr([F({topic:"/kos/trouble/remove",websocket:!0,lifecycle:j.INIT})],rt.prototype,"handleTroubleRemoved",1);mr([F({topic:"/kos/trouble/add",websocket:!0})],rt.prototype,"handleTroubleAdded",1);rt=mr([R(Jp)],rt);const Ms="trouble-container-model",ot={registration:{[Ms]:{class:rt,singleton:!0}},type:Ms,predicate:de(Ms),factory:J.Singleton.create(Ms)},{URL:dl}=te(),{getAll:Xp}=X.build({basePath:`${dl}/api/kos/ota`}),Gn=p.createLogger({name:"ota-service",group:"Services"}),em=async()=>{Gn.debug("sending GET request to /api/kos/ota/artifacts");const t=await Xp({urlOverride:`${dl}/api/kos/ota/artifacts`});return Gn.debug("getArtifacts - response:",t),t==null?void 0:t.data};var tm=Object.defineProperty,sm=Object.getOwnPropertyDescriptor,yr=(t,e,s,r)=>{for(var o=r>1?void 0:r?sm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&tm(e,s,o),o};const ul="ota-model",rm=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Pr=t=>{const e=t.artifactInfo,s=rm(t.requests),r=(e==null?void 0:e.identifier)||(s==null?void 0:s.kabId);if(!r)return;let o;switch(t.status){case"INSTALLED":o="ready";break;case"INVALID":o="error";break;case"MISSING":o=((s==null?void 0:s.currentSize)||0)>0?"downloading":"idle";break;case"STAGED":o="pending"}const n=e===void 0;return{id:r,manifest:n,label:e==null?void 0:e.version,name:e==null?void 0:e.name,status:o,error:o==="error"?s==null?void 0:s.lastErrorReason:void 0,errorCount:o==="error"?s==null?void 0:s.errorCount:0,progress:o==="downloading"&&s&&!n?s.currentSize/(e==null?void 0:e.size)*100:void 0,size:e==null?void 0:e.size}};let nt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new So);l(this,"troubleContainer");this.id=t,this.logger=s.logger}get downloadInProgressTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:e[0]}get updatePendingTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:e[0]}get pausedDueToErrorsTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:e[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var t;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(t=this.updatePendingTrouble)==null||t.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const t=await em();t&&t.forEach(e=>{const s=Pr(e);s&&this.data.addModel(s)})}catch(t){this.logger.error(`loading ota ${this.id} - error:`,t)}}async handleAllArtifacts(t){this.logger.debug("handleAllArtifacts:",t),await this.data.clear();try{t.forEach(e=>{const s=Pr(e);s&&this.data.addModel(s)})}catch(e){this.logger.error(`handleAllArtifacts ${this.id} - error:`,e)}}handleChangedArtifacts(t){this.logger.debug("handleChangedArtifacts:",t);try{t.forEach(e=>{const s=Pr(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};yr([ut({modelType:ot.type})],nt.prototype,"troubleContainer",2);yr([F({topic:"/kos/ota/artifacts/all",websocket:!0})],nt.prototype,"handleAllArtifacts",1);yr([F({topic:"/kos/ota/artifacts/changed",websocket:!0})],nt.prototype,"handleChangedArtifacts",1);nt=yr([R(ul)],nt);const Hs=new be({class:nt,type:ul});function om(t){let e;const s=async(...r)=>{e&&e.abort(),e=new AbortController;const o=e;try{return await t(...r,o.signal)}finally{e===o&&(e=void 0)}};return s.cancel=()=>{e&&(e.abort(),e=void 0)},s.getController=()=>e,s.isActive=()=>!!e,s}const Ar=p.createLogger({name:"software-info-service",group:"Services"}),Vo=async t=>{Ar.debug("sending GET for software-info");const[e,s]=await $c.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Ar.debug("Request was aborted"),new ce("Request was aborted")):(Ar.error("Failed to fetch software-info",e),new ce("Failed to fetch software-info"));return s},nm=om(Vo),im=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Vo,getSoftwareInfosWithCancel:nm},Symbol.toStringTag,{value:"Module"}));var am=Object.defineProperty,cm=Object.getOwnPropertyDescriptor,lm=(t,e,s,r)=>{for(var o=r>1?void 0:r?cm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&am(e,s,o),o};const It="software-info-model";let Yr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=t,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(t,e){return t.reduce((s,r)=>(s[r[e]]=[...s[r[e]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const t=await Vo(),e=(t==null?void 0:t.nodes)||{};W(()=>{const r=Object.keys(e).map(o=>e[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(t){t instanceof ce&&this.logger.error("Failed to fetch software-info",t)}}};Yr=lm([R(It)],Yr);const Gs={registration:{[It]:{class:Yr,singleton:!1}},type:It,predicate:de(It),factory:J.Factory.create(It)},{URL:hl}=te(),{getOne:dm}=X.build({basePath:`${hl}/api/kos/state`}),um=p.createLogger({name:"state-bean-service",group:"Services"}),fl=async({path:t})=>(um.debug("sending GET for state-bean"),await dm({urlOverride:`${hl}/api/kos/state/${t}`})),hm=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:fl},Symbol.toStringTag,{value:"Module"}));var fm=Object.defineProperty,gm=Object.getOwnPropertyDescriptor,gl=(t,e,s,r)=>{for(var o=r>1?void 0:r?gm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&fm(e,s,o),o};const Ot="state-bean-model",pm=Be("path");let zs=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=t,this.logger=s.logger,this.props=Do.map(new Map),Ur(e,this)}updateModel(t){Ur(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&Po(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&lr(r)&&(r=Number(r)),this.props.set(e,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(t){Object.entries(t).forEach(([e,s])=>{this.props.set(e,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const t=await fl({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};gl([F({topic:`/kos/state/${pm}`,websocket:!0})],zs.prototype,"handleConfigBeanUpdated",1);zs=gl([R(Ot)],zs);const Zt={registration:{[Ot]:{class:zs,singleton:!1}},type:Ot,predicate:de(Ot),factory:J.Factory.create(Ot)};var mm=Object.defineProperty,ym=Object.getOwnPropertyDescriptor,pl=(t,e,s,r)=>{for(var o=r>1?void 0:r?ym(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&mm(e,s,o),o};const St="state-prop-model",zn=Be("path");let Vs=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=t,this.logger=s.logger,this.path=e.path,this.attribute=e.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var t;return((t=this.value)==null?void 0:t.toString())??""}};pl([ut({modelType:Zt.type,id:`state-bean-${zn}`,options:{path:zn}})],Vs.prototype,"stateBean",2);Vs=pl([R(St)],Vs);const Yo={registration:{[St]:{class:Vs,singleton:!1}},type:St,predicate:de(St),factory:J.Factory.create(St)},{URL:bm}=te(),{getAll:wm}=X.build({basePath:`${bm}/api/state-prop`}),vm=p.createLogger({name:"state-prop-service",group:"Services"}),Mm=async()=>(vm.debug("sending GET for state-prop"),await wm({})),Em=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Mm},Symbol.toStringTag,{value:"Module"})),{URL:qo}=te(),{getOne:ml}=X.build({basePath:`${qo}/api/translation`}),Ht=p.createLogger({name:"translation-service",group:"Services"}),_m=()=>{const t=window.location.origin,e=le();return(e==null?void 0:e.host)||t},yl=async(t,e)=>{Ht.debug("sending GET for translation");const s=e??_m();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Ht.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Ht.error("Error fetching translations",r),r}},Tm=async()=>{Ht.debug("getting localization descriptor");const t=await ml({urlOverride:`${qo}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get tool localization descriptor ${t==null?void 0:t.status}`);return t.data},bl=t=>async()=>{Ht.debug("getting kos localization descriptor");const e=await ml({urlOverride:`${qo}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get tool localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},wl="langResolver";var Im=Object.defineProperty,Om=Object.getOwnPropertyDescriptor,Sm=(t,e,s,r)=>{for(var o=r>1?void 0:r?Om(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Im(e,s,o),o};const $t="translation-model";function $m(t){const e=typeof t=="string",s=e?!1:!!(t!=null&&t.data)&&typeof(t==null?void 0:t.data)!="string",r=e?t:t==null?void 0:t.defaultValue,o=e||t==null?void 0:t.context,n=e?void 0:s?t==null?void 0:t.data:t;return{isBasicOptions:e,defaultValue:r,context:o,data:n}}function vl(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null){const n=vl(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function Ml(t,e){const s={...t};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(typeof e[r]=="object"&&e[r]!==null&&typeof t[r]=="object"&&t[r]!==null?s[r]=Ml(t[r],e[r]):s[r]=e[r]);return s}const qr=(t,e)=>{const s=/__(.*?)__/g,r=t.replace(s,(o,n)=>Object.prototype.hasOwnProperty.call(e||{},n.trim())?e==null?void 0:e[n.trim()]:o);return r===t?r:s.test(r)?qr(r,e):r},Es=(t,e,s)=>{const r=/{{(.*?)}}/g,n=qr(t,e).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return qr(n,e)},Vn=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let Wr=class{constructor(t,e,s){l(this,"id");l(this,"namespace");l(this,"descriptor");l(this,"defaultLocale");l(this,"currentLocale");l(this,"bundleResolver");l(this,"data");l(this,"logger");l(this,"resolver");l(this,"disposer");l(this,"context");l(this,"rootUrl");this.id=t,this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.currentLocale||"en",this.namespace=e.namespace,this.descriptor=e.descriptor,this.rootUrl=e.rootUrl,this.data={},this.resolver=e.resolver||s.kosContext.get(wl),this.bundleResolver=e.bundleResolver,this.logger=s.logger,this.context=s.kosContext.parentModel}getTranslationLocales(t){const e=this.descriptor[t];if(!t||!e)return[this.defaultLocale];if(!this.defaultLocale&&!e.fallbacks)return[t];let s=e.fallbacks||[this.defaultLocale];return s.includes(t)||(s=[t,...s]),s}async loadTranslations(){const t=this.getTranslationLocales(this.currentLocale).reverse(),e=t.map(r=>{if(this.bundleResolver){const o=K.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return yl(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);W(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=Ml(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=vl(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=Vn(this.namespace,t);if(e!==this.namespace){const r=this.context.getModel(e);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(t,e){if(!t)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=$m(e),{namespace:n,key:i}=Vn(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Es(d,this.data,o)):Es(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Es(d,this.data,o)):Es(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=M.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};Wr=Sm([ar(),R($t)],Wr);const Ys={registration:{[$t]:{class:Wr,singleton:!1}},type:$t,predicate:de($t),factory:J.Factory.create($t)};var Dm=Object.defineProperty,Cm=Object.getOwnPropertyDescriptor,El=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Dm(e,s,o),o};const Dt="translation-container-model",Rm=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function Pm(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error(`namespace ${t} not found in descriptor`);const r=s.basePath,o=s.locales[e].file;return Rm([r,o])}let qs=class{constructor(t,e,s){l(this,"id");l(this,"lang");l(this,"rootUrl");l(this,"descriptor");l(this,"_defaultNamespace");l(this,"resolver");l(this,"logger");l(this,"descriptorUrl");l(this,"namespaces",[]);l(this,"_models");this.id=t,this.lang=e.lang||"en",this.descriptor=e.descriptor,this._defaultNamespace=e.defaultNamespace,this.descriptorUrl=e.descriptorUrl,this.rootUrl=e.rootUrl,this.resolver=e.resolver||Pm.bind(this),s.kosContext.set(wl,this.resolver),this.logger=s.logger,this._models=new we({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel(`translation-${this._defaultNamespace}`):void 0}getModel(t){return this.logger.debug(`getting model ${t}`),this._models.getModel(`translation-${t}`)}get models(){return this._models}get data(){return this._models.data}async reload(){this._models.clear(),await ja(this);for(const t of this.namespaces){const e=this.resolveNamespace(t);await ne(e)}}resolveNamespace(t){var s;if((s=this.descriptor.namespaces)==null?void 0:s[t]){const r=Object.keys(this.descriptor.namespaces[t].locales)[0],o=this.descriptor.namespaces[t].locales[r].defaultLocale,n=Ys.factory(`translation-${t}`)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[t].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(t)||W(()=>{this.namespaces.push(t)}),n}else{this.logger.warn(`namespace ${t} not found in descriptor`);const r=Ys.factory(`translation-${t}`)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:this.lang,descriptor:{},resolver:this.resolver});return this.addModel(r),r}}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing translation-container container ${this.id}`)}async load(){this.logger.debug(`loading translation-container container ${this.id}`)}};El([ge],qs.prototype,"_models",2);qs=El([R(Dt)],qs);const Te={registration:{[Dt]:{class:qs,singleton:!0}},type:Dt,predicate:de(Dt),factory:J.Singleton.create(Dt)},Am={set(t,e){const s=K.getContext(Te.type);s&&s.set(t,e)},get(t){const e=K.getContext(Te.type);return e==null?void 0:e.get(t)}},_l={async init(t){const e=Te.factory(t);return await ne(e),{translations:e}}};function Lm(t){return t.troubles!==void 0&&t.troubles instanceof Array&&t.troublesByType!==void 0&&typeof t.troublesByType=="object"}const xm=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},Tl="kos-ws-event",Wo=ht(Tl);var Fm=Object.defineProperty,km=Object.getOwnPropertyDescriptor,Qo=(t,e,s,r)=>{for(var o=r>1?void 0:r?km(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Fm(e,s,o),o};const Nm=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){p.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const d=this._topicMap.get(i)||0;a=`${a}-${d+1}`,this._topicMap.set(i,d+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:Nm({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),p.debug(`logged ${this.events.size} events`)}}};Qo([F({topic:[ss.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Qo([F({topic:[ss.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Qo([R(Wo.type)],exports.WsEventModel);const Yn=le(),Um=Yn.debug==="true"||Yn.debug===!0,jm="/api/system/canvas",Il=async(t,e)=>{const s=e||jm,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Um?"false":"true"},body:t})},Bm=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Il},Symbol.toStringTag,{value:"Module"})),Km=(t,e,s)=>t>>5<<5|e>>5<<2|s>>6;function qn(t,e,s){if(e==="base64"){const r=s?t.filter((o,n)=>n%4!==3):Array.from(t);return btoa(String.fromCharCode(...r))}else{const r=[];for(let o=0;o<t.length;o+=4)r.push(Km(t[o],t[o+1],t[o+2]));return String.fromCharCode(...r)}}var Hm=Object.defineProperty,Gm=Object.getOwnPropertyDescriptor,Ol=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Hm(e,s,o),o};const Sl="canvas-renderer-model";function Lr(t){return typeof t.onDone=="function"}let Ws=class{constructor(t,e,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);l(this,"_clearOnComplete");l(this,"isStreaming",!1);l(this,"renderLoopId",null);l(this,"sendIntervalId",null);l(this,"timeoutId",null);l(this,"apiPath");l(this,"endpointName");l(this,"width",50);l(this,"height",30);l(this,"fps",10);l(this,"durationMs",null);l(this,"_onFrame",null);this.id=t,this.logger=s.logger,this.width=e.width??50,this.height=e.height??30,this.fps=e.fps??10,this.durationMs=e.durationMs??null,this.apiPath=e.apiPath??"/api/system/canvas",this.endpointName=e.endpoint}set onFrame(t){this._onFrame=t}set renderer(t){var e,s;this._renderer&&(this.stopStreaming(),(s=(e=this._renderer).dispose)==null||s.call(e)),this._renderer=t,this.isStreaming&&this.startStreaming()}setClearOnComplete(t){this._clearOnComplete=t}sendDataFrame(t,e){Il(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=qn(t,"base64",!0);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=qn(o,"base64",!0);this.logger.debug(`Sending clear frame: ${t}x${e}, apiPath: ${this.apiPath}`),this.sendDataFrame(n,this.apiPath),(s=this._onFrame)==null||s.call(this,n)}}isOneShotDone(){var t,e;return Lr(this._renderer)&&((e=(t=this._renderer).isOneShot)==null?void 0:e.call(t))===!0&&this._renderer.isOneShotDone}startStreaming(){var t,e,s,r;{if(!this._renderer)return;if(!this.apiPath){this.logger.error(`No endpoint configured for canvas renderer ${this.id}`);return}this.isStreaming=!0,this._renderer.reset(),(e=(t=this._renderer).play)==null||e.call(t);const o=Lr(this._renderer);Lr(this._renderer)&&this._renderer.onDone(()=>{var c,d,u;this.logger.debug(`Renderer completed for ${this.id}`),B("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((u=(d=this._renderer)==null?void 0:d.isOneShot)==null?void 0:u.call(d))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,d;const a=(d=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:d.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(t,e)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),e.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(t,e)=>{this.startStreaming(),e.send({status:"OK"})})}};Ol([ut({modelType:jo.type})],Ws.prototype,"router",2);Ws=Ol([R(Sl)],Ws);const Zo=new pe({class:Ws,type:Sl});class $l{constructor({src:e}){l(this,"video");l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);l(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=e,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(e,s){this.canvas.width=e,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,e,s)}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}onDone(e){this.doneCallback=e}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}}class zm{constructor(){l(this,"canvas");l(this,"gl");l(this,"lastWidth",0);l(this,"lastHeight",0);l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl");if(!e)throw new Error("WebGL not supported");this.gl=e}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(e*s*4);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const o=new Uint8ClampedArray(r.length);for(let n=0;n<s;n++){const i=n*e*4,a=(s-1-n)*e*4;o.set(r.subarray(i,i+e*4),a)}return o}}class Vm extends zm{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
|
|
78
78
|
attribute vec2 a_position;
|
|
79
79
|
void main() {
|
|
80
80
|
gl_Position = vec4(a_position, 0, 1);
|
|
@@ -108,7 +108,7 @@ ${d}topics:${e}
|
|
|
108
108
|
vec3 rgb = hslToRgb(hue, 1.0, 0.5);
|
|
109
109
|
gl_FragColor = vec4(rgb, 1.0);
|
|
110
110
|
}
|
|
111
|
-
`,i=this.compileShader(r.VERTEX_SHADER,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class ls{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("2d");if(!e)throw new Error("2D canvas not supported");this.ctx=e}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}}function Jo(t){class e extends t{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(o){this.doneCallback=o}signalDoneIfNeeded(){var o;this.oneShotDone||((o=this.doneCallback)==null||o.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return e}const zm=Jo(ls);class Vm extends zm{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();l(this,"offset",0);l(this,"speed");l(this,"colors");l(this,"direction");l(this,"loop");this.colors=s,this.direction=r,this.speed=o,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,r){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const o=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(o,0,n,0),a=1/(this.colors.length-1);this.colors.forEach((c,d)=>{i.addColorStop(d*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const Ym=Jo(ls);class qm extends Ym{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 Wm extends Sl{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()}}class Qm extends ls{constructor({speed:s=1,fallChance:r=.7}={}){super();l(this,"columns",[]);l(this,"fallChance");l(this,"speed");this.speed=s,this.fallChance=r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const c=this.columns[a];let d=0,u=0,h=0;i===c?(u=255,h=255):i<c&&i>c-5&&(u=100+Math.floor(30*(5-(c-i))),h=255);const f=(i*s+a)*4;n[f]=d,n[f+1]=u,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(o,0,0)}}class Zm{constructor(e){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=e.patterns,this.loopConfig=e.loop??!1,this.transitionDuration=e.transitionDuration??0,this.patternOverrides=e.patternOverrides??{},this.patternStore=e.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var n,i,a,c;const e=this.patterns[this.currentPatternIndex],s=this.patternStore.get(e);if(!s){console.warn(`Pattern "${e}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[e]??{},o={...s.data,...r};try{this.currentRenderer=Qr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(c=(a=this.currentRenderer).play)==null||c.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(d){console.error(`Failed to create renderer for pattern "${e}":`,d),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const Jm=Jo(ls);class Xm extends Jm{constructor({r:s,g:r,b:o}={r:0,g:0,b:0}){super();l(this,"color");this.color=`rgb(${s},${r},${o})`}setColor(s,r,o){this.color=`rgb(${s},${r},${o})`,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 ey extends ls{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,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?h+(f-h)*6*m:m<.5?f:m<.6666666666666666?h+(f-h)*(.6666666666666666-m)*6:h),d=o<.5?o*(1+r):o+r-o*r,u=2*o-d;n=c(u,d,s+1/3),i=c(u,d,s),a=c(u,d,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let c=0;c<s;c++){const d=(c+this.offset)%s/s,u=this.minHue/360+d*((this.maxHue-this.minHue)/360),[h,f,m]=this.hslToRgb(u,1,.5);n[i++]=h,n[i++]=f,n[i++]=m,n[i++]=255}this.ctx.putImageData(o,0,0)}}const qn=new Map;ss(ne,{register(t,e){qn.set(t,e)},execute(t,e){const s=qn.get(t);return s?new s(e):null}});S.canvas.registerRenderer("video",Wm);S.canvas.registerRenderer("video-basic",Sl);S[ne].register("image",qm);S[ne].register("color",Xm);S[ne].register("matrix",Qm);S[ne].register("sweep",ey);S[ne].register("gradient",Vm);S[ne].register("drop",Gm);S[ne].register("sequence",Zm);const Qr=({mode:t,data:e})=>{const s=S[ne].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var ty=Object.defineProperty,sy=Object.getOwnPropertyDescriptor,mt=(t,e,s,r)=>{for(var o=r>1?void 0:r?sy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ty(e,s,o),o};const $l="canvas-dispatcher-model";function ry(t){if(t=t.replace(/^#/,""),t.length===3&&(t=t.split("").map(s=>s+s).join("")),t.length!==6)return null;const e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:e&255}}let Ae=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new be}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=Zo.instance(t).options({apiPath:e.apiPath,width:e.width,height:e.height,fps:e.fps,durationMs:e.durationMs??null,endpoint:t}).build();return this._endpointRenderers.addModel(s),s}addContent(t,e){this._content.has(t)&&this.logger.warn(`Content "${t}" already exists. Overwriting.`),this._content.set(t,e)}addPattern(t,e){this._patterns.has(t)&&this.logger.warn(`Pattern "${t}" already exists. Overwriting.`),this._patterns.set(t,e)}async handlePatternsPost(t,e){var o,n;const s=t.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=e.status)==null||o.call(e,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(n=e.status)==null||n.call(e,200).send({status:"OK"})}async handlePatternApplication(t,e){var c,d,u;const s=t.params.pattern,r=t.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(c=e.status)==null||c.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=e.status)==null||d.call(e,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type;this.data=n.data;const a=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=Qr({mode:i,data:a}),o.startStreaming(),(u=e.status)==null||u.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var d,u,h;const s=t.params.color,r=ry(s);if(!r){(d=e.status)==null||d.call(e,400).send({error:"Invalid color format"});return}const o=t.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=Qr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleEndpointCreation(t,e){var r,o;const s=t.body;if(!s.apiPath||!s.id){(r=e.status)==null||r.call(e,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=e.status)==null||o.call(e,200).send({status:"OK"})}async load(t){var s;const e=t==null?void 0:t.get(it.loader);e&&((s=e.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};mt([he],Ae.prototype,"_endpointRenderers",2);mt([rs("/api/ui/canvas/patterns")],Ae.prototype,"handlePatternsPost",1);mt([rs("/api/ui/canvas/pattern/:endpoint/:pattern")],Ae.prototype,"handlePatternApplication",1);mt([rs("/api/ui/canvas/color/:endpoint/:color")],Ae.prototype,"handleColorApplication",1);mt([rs("/api/ui/canvas/endpoint")],Ae.prototype,"handleEndpointCreation",1);Ae=mt([R($l)],Ae);const it=new ye({class:Ae,type:$l}),{URL:Xo}=X(),{getOne:Dl}=J.build({basePath:`${Xo}/api/device`}),Qs=p.createLogger({name:"device-service",group:"Services"}),Cl=async()=>{Qs.debug("sending GET for device serial number");try{const t=await Dl({urlOverride:`${Xo}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof ie)return Qs.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Rl=async()=>{Qs.debug("sending GET for device details");try{const t=await Dl({urlOverride:`${Xo}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof ie)return Qs.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},oy=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Rl,getSerialNumber:Cl},Symbol.toStringTag,{value:"Module"}));var ny=Object.defineProperty,iy=Object.getOwnPropertyDescriptor,Al=(t,e,s,r)=>{for(var o=r>1?void 0:r?iy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ny(e,s,o),o};const Pl="device-model",ay="/kos/criticalData/changed",cy="/kos/criticalData/available";let Zs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=t,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[t]=this.nodeId.split("-");return t}get nodeName(){const[,t]=this.nodeId.split("-");return t}updateModel(t){this._serialNumber=t.serialNumber??"unassigned",this._name=t.name??"unassigned",this._nodeId=t.nodeId??"unassigned"}async loadDeviceData(){const[t,e]=await Rl();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}if(e){const{name:s,nodeId:r}=e;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[t,e]=await Cl();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}this.updateModel({serialNumber:e,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};Al([x({topic:[ay,cy],websocket:!0})],Zs.prototype,"handleCriticalDataChanged",1);Zs=Al([R(Pl)],Zs);const Js=new ye({class:Zs,type:Pl});var ly=Object.defineProperty,dy=Object.getOwnPropertyDescriptor,uy=(t,e,s,r)=>{for(var o=r>1?void 0:r?dy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ly(e,s,o),o};const Ll="network-interface-model";let Zr=class{constructor(t,e,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=t,this.logger=s.logger,this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}updateModel(t){this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};Zr=uy([R(Ll)],Zr);const en=new ge({class:Zr,type:Ll}),{URL:hy}=X(),{getAll:gy}=J.build({basePath:`${hy}/api/kos/network/interfaces`}),Wn=p.createLogger({name:"network-interface-service",group:"Services"}),xl=async()=>{Wn.debug("sending GET for copy-logs");try{const t=await gy({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof ie)return Wn.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},fy=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:xl},Symbol.toStringTag,{value:"Module"}));var py=Object.defineProperty,my=Object.getOwnPropertyDescriptor,Fl=(t,e,s,r)=>{for(var o=r>1?void 0:r?my(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&py(e,s,o),o};const kl="network-interface-container-model";let Xs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new be({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await xl();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=en.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Fl([he],Xs.prototype,"_models",2);Xs=Fl([R(kl)],Xs);const Zt=new ye({class:Xs,type:kl});Zt.addRelatedModel(en);const{URL:yy}=X(),{getAll:by}=J.build({basePath:`${yy}/api/kos/storage/devices`}),Qn=p.createLogger({name:"storage-device-service",group:"Services"}),Nl=async()=>{Qn.debug("sending GET for storage-device");const t=await by({});return!(t!=null&&t.data)||t.status!==200?(Qn.error("Failed to retrieve storage-device data",t),[]):t.data},wy=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Nl},Symbol.toStringTag,{value:"Module"}));var vy=Object.defineProperty,My=Object.getOwnPropertyDescriptor,Ey=(t,e,s,r)=>{for(var o=r>1?void 0:r?My(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&vy(e,s,o),o};const Ul="storage-device-model";let Jr=class{constructor(t,e,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=t,this.logger=s.logger,this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}updateModel(t){this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};Jr=Ey([ar(),R(Ul)],Jr);const er=new ge({class:Jr,type:Ul});var _y=Object.defineProperty,Ty=Object.getOwnPropertyDescriptor,tn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ty(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&_y(e,s,o),o};const jl="storage-device-container-model",Iy="/kos/storage";let Jt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new be({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=er.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Nl()).forEach(e=>{const s={...e,kosParentId:this.id},r=er.instance(e.id).options(s).build();this.addModel(r)})}};tn([he],Jt.prototype,"_models",2);tn([x({topic:Iy,websocket:!0})],Jt.prototype,"handleStorageAvailability",1);Jt=tn([R(jl)],Jt);const at=new ye({class:Jt,type:jl});at.addRelatedModel(er);const{URL:sn}=X(),{getAll:Oy,postModel:Sy}=J.build({basePath:`${sn}/api/kos/update/available`}),Zn=p.createLogger({name:"usb-update-service",group:"Services"}),Bl=async()=>{Zn.debug("sending GET for usb-update");const t=await Oy({urlOverride:`${sn}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(Zn.error("Failed to retrieve usb-update data",t),[]):t.data},Kl=async(t,e,s)=>{const r=await Sy({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${sn}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},$y=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Bl,installUpdate:Kl},Symbol.toStringTag,{value:"Module"}));var Dy=Object.defineProperty,Cy=Object.getOwnPropertyDescriptor,Hl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Dy(e,s,o),o};const Gl="usb-update-model";let tr=class{constructor(t,e,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=t,this.logger=s.logger,this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes,this.futureHandler=new ur(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),Kl(this.manifestId,this.deviceId,t)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};Hl([ln()],tr.prototype,"install",1);tr=Hl([R(Gl)],tr);const rn=new ge({class:tr,type:Gl});var Ry=Object.defineProperty,Ay=Object.getOwnPropertyDescriptor,br=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ay(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ry(e,s,o),o};const zl="usb-update-container-model";let ct=class{constructor(t,e,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new be({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await Bl();q(()=>{const e=t.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!e.includes(s.id)).forEach(s=>this.removeModel(s.id)),t.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=rn.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(o)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var t;(t=this.disposer)==null||t.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};br([ut({modelType:at.type})],ct.prototype,"storageService",2);br([he],ct.prototype,"_models",2);br([na({dependencies:t=>[t.isUsbInserted]})],ct.prototype,"usbInsertedEffect",1);ct=br([R(zl)],ct);const Xt=new ye({class:ct,type:zl});Xt.addRelatedModel(rn);const Py=()=>({...{[ft.type]:{class:Oc},[Re.type]:{class:Ac,singleton:!0},...Q.registration,...Ke.registration,...ot.registration,...Ys.registration,...Te.registration,[Wo.type]:{class:exports.WsEventModel,singleton:!0},...Qt.registration,...Yo.registration,...Ns.registration}}),on=Py(),Ly={models:on,preloadModels:[]},Jn=!0,Vl=t=>()=>{const e=on;return Ga(Xr)(Wt).model(ot).model(at).model(Xt).model(Js).model(Hs).model(Ht).model(Gs).model(Ho).model(Zt).model(it).model(Zo).model(jo,Jn).model(as).model(jc,Jn),Object.keys(e).forEach(s=>{const r=e[s];Ha(Xr)(s,r)}),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t)}},ue={};ue.core={models:Vl(ue)};ue.preload=C.model.preloadModel(ue);ue.model=C.model.register(ue);ue.companion=C.companion.register(ue);ue.legacy=C.model.registerLegacyModel(ue);const Xr=ue;class xy{registerTroubleRankMapper(e){return S.propertyMapper.registerPropertyMapper(de.TroubleRank,e),this}registerTroubleRoleMapper(e){return S.propertyMapper.registerPropertyMapper(de.TroubleRole,e),this}registerTroubleColorMapper(e){return S.propertyMapper.registerPropertyMapper(de.TroubleColor,e),this}registerModelLoader(e,s){S.loader.registerLoader(e,s)}registerCanvasPatternLoader(e){S.loader.registerLoader(it.loader,e)}}class ds{constructor(e){l(this,"futureHandler");this.futureHandler=new ur(e)}get future(){return this.futureHandler.future}get progress(){var e;return((e=this.future)==null?void 0:e.progress)||0}get status(){var e;return((e=this.future)==null?void 0:e.status)||"IDLE"}get isRunning(){return this.future?!this.future.endState:!1}get isCancelled(){var e;return((e=this.future)==null?void 0:e.status)==="CANCELLED"||!1}async cancelFuture(){this.future&&await this.future.cancelFuture()}}function Fy(t){const e=new ds(t);t.futureHandler=e.futureHandler,Object.defineProperty(t,"_futureMixin",{value:e,enumerable:!1,configurable:!1,writable:!1})}function Yl(t){const e=new ds(t),s=t;s.futureHandler=e.futureHandler,Object.defineProperty(t,"_futureMixin",{value:e,enumerable:!1,configurable:!1,writable:!1}),Object.defineProperty(t,"future",{get(){return e.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){return e.progress},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){return e.status},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return e.isRunning},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){return e.isCancelled},enumerable:!0,configurable:!0}),s.cancelFuture=async()=>e.cancelFuture()}function ky(){return function(t){const e=t;function s(...r){const o=e.apply(this,r)||this;return Yl(o),o}return s.prototype=e.prototype,Object.setPrototypeOf(s,e),Object.getOwnPropertyNames(e).forEach(r=>{if(r!=="prototype"&&r!=="length"&&r!=="name"){const o=Object.getOwnPropertyDescriptor(e,r);o&&Object.defineProperty(s,r,o)}}),s}}function Ny(t){return new ds(t)}function Uy(t){let e;const s=()=>(e||(e=new ds(t())),e);return{get futureHandler(){return s().futureHandler},get future(){return s().future},get progress(){return s().progress},get status(){return s().status},get isRunning(){return s().isRunning},get isCancelled(){return s().isCancelled},async cancelFuture(){return s().cancelFuture()}}}function jy(t){return t&&typeof t=="object"&&"futureHandler"in t&&"future"in t&&"_futureMixin"in t&&typeof t.cancelFuture=="function"}function By(t){const e=["future","progress","status","isRunning","isCancelled","futureHandler"],s={};for(const r of e){const o=Object.getOwnPropertyDescriptor(t,r);s[r]={exists:r in t,descriptor:o?{enumerable:o.enumerable,configurable:o.configurable,hasGetter:typeof o.get=="function",hasSetter:typeof o.set=="function"}:null,isObservable:t&&typeof t=="object"&&Object.getOwnPropertySymbols(t).some(n=>n.toString().includes("mobx")&&n.toString().includes(r))}}return s}class ql{constructor(e,s){l(this,"parent");l(this,"companion");this.companion=e,this.parent=s}getParent(){return this.parent}setupProxy(e={}){const{excludeProperties:s=[],includeLifecycle:r=!1}=e,o=r?[]:["init","load","unload","ready","dispose","destroy","onInit","onLoad","onUnload","onReady","onDispose","onDestroy"],n=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace"],i=c=>c==="constructor"||c.startsWith("_")||c.startsWith("__")||o.includes(c)||n.includes(c)||s.includes(c)||c in this.companion,a=this.getAllParentProperties(i);for(const c of a)this.createProxyProperty(c)}getAllParentProperties(e){const s=new Set;Object.getOwnPropertyNames(this.parent).filter(o=>!e(o)).forEach(o=>s.add(o));let r=Object.getPrototypeOf(this.parent);for(;r&&r!==Object.prototype;)Object.getOwnPropertyNames(r).filter(o=>!e(o)).forEach(o=>s.add(o)),r=Object.getPrototypeOf(r);return Array.from(s)}createProxyProperty(e){try{const s=this.parent[e];typeof s=="function"?this.companion[e]=(...r)=>s.apply(this.parent,r):Object.defineProperty(this.companion,e,{get:()=>this.parent[e],set:r=>{this.parent[e]=r},enumerable:!0,configurable:!0})}catch(s){console.debug(`Skipping companion proxy for property ${e}:`,s)}}}function Ky(t,e,s={}){const r=new ql(t,e);return t.getParent=()=>r.getParent(),Object.defineProperty(t,"_companionMixin",{value:r,enumerable:!1,configurable:!1,writable:!1}),r.setupProxy(s),r}function Wl(t){return t&&typeof t=="object"&&"_companionMixin"in t&&typeof t.getParent=="function"}function Ql(t){return Wl(t)?t._companionMixin:null}function Hy(t){const e=Ql(t);if(!e)return{error:"No companion mixin found"};const s=e.getParent(),r=Object.getOwnPropertyNames(t),o=Object.getOwnPropertyNames(s),n=r.filter(i=>o.includes(i)&&i!=="constructor"&&!i.startsWith("_"));return{parentType:s.constructor.name,companionType:t.constructor.name,proxiedProps:n,proxiedCount:n.length}}const Gy=async(t,e)=>{const s=Ho.instance(t).options({}).build(),r=e?`${e}-`:"";return await se(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:()=>{Ue(s)}}},Zl="kos:service:region",Jl="regionId",zy=`${Zl}-${Jl}`,Xl=async t=>{const e=Ke.factory(zy)({path:Zl,attribute:Jl});await se(e),e.updateProperty(t)},nn="/kos-timer-event",an="/kos-timer-event/tick",cn="defaultTimerEnd",Dt=p.createLogger({name:"timer-manager"}),Vy=t=>t.updateProperty!==void 0;class ed{constructor(e,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=e;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,Vy(s)&&B(()=>{p.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:cn}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){Dt.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&&(Dt.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(e){this.timeout=e,this.restart()}addTimeoutAction(e){const s=e.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=e.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=e.action:this.timeoutActions.get(s).push(e)}removeTimeoutAction(e){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==e);o.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,o)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(e){this.timeoutActions.has(e)&&this.timeoutActions.get(e).forEach(s=>{var r;Dt.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(Dt.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){U(`${an}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){U(nn,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const Ct=new Map,qe=(t,e)=>{const s=Ct.get(t);if(!s){Dt.error(`Timer ${t} not found`);return}e(s)},td={createRelativeTimer(t,e,s){const r=new Date,o=Math.round((e.getTime()-r.getTime())/1e3);return this.createTimer(t,o,s)},createTimer(t,e=60,s){if(Ct.has(t))return Ct.get(t);const r=new ed(t,e,s);return Ct.set(t,r),r},getTimer(t){return Ct.get(t)},clearTimer(t){qe(t,e=>e.pause())},restartTimer(t){qe(t,e=>e.restart())},resetTimer(t){qe(t,e=>e.reset())},addTimeoutAction(t,e){qe(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){qe(t,s=>s.removeTimeoutAction(e))},startTimer(t){qe(t,e=>e.start())}},sd="kos:service:region:settings",rd="timeZone",Yy=`${sd}-${rd}`,eo=async t=>{const e=Ke.factory(Yy)({path:sd,attribute:rd});await se(e),e.updateProperty(t)},qy=t=>!t||!t.data;function ln(t={}){const{alias:e,namespace:s,abortController:r=!1}=t;return(o,n,i)=>{o[Pt]=o[Pt]||{};const a=i.value,c=async function(...d){const u=dt();p.debug(`Calling future service ${n} with tracker ${u}`);let h,f;r&&(h=new AbortController);const m=je.initiateFuture({tracker:u,id:Co});s&&(m.namespace=s),p.debug(`waiting for future ${m.id} to be ready`),await se(m),p.debug(`future ${m.id} is ready`),q(()=>{p.debug(`Adding future ${m.id} to futureHandler`),this.futureHandler.addFuture(m,e)}),r&&h&&(f=B(()=>{(m.status==="CANCELLED"||m.endState===Ce.Canceled)&&(p.debug(`Future ${m.id} cancelled, aborting request`),h==null||h.abort())}),h.signal.addEventListener("abort",async()=>{if(m.status!=="CANCELLED"&&m.endState!==Ce.Canceled&&!m.endState){p.debug(`AbortController aborted, cancelling future ${m.id}`);try{await m.cancelFuture()}catch(v){p.error(`Failed to cancel future ${m.id}:`,v)}}},{once:!0}));const w=()=>{f&&(f(),f=void 0)};try{const v=[...d];if(r&&h){const K=v[v.length-1];K&&typeof K=="object"&&"aborted"in K?v[v.length-1]=h.signal:v.push(h.signal)}v.push(u);const E=await a.apply(this,v);p.debug(`received future response for ${u}`,E);const T=qy(E)?E:E==null?void 0:E.data;return T?(T.progress=1,p.debug("mapping future response to future model"),m.endState?p.debug(`future ${m.id} has already completed. Not updating the model`):No(T,m)):this.futureHandler.removeFuture(e),w(),T}catch(v){if(w(),r&&(h!=null&&h.signal.aborted)){const E=new Error("Operation cancelled");throw p.debug(`Operation ${n} was cancelled`),E}throw p.error(v),v}};o[Pt][n]={handler:c}}}const Wy=({path:t})=>(e,s)=>{e[L]=e[L]||{},e[L][s]={modelType:Qt.type,id:`${Qt.type}-${t}`,options:{path:t},lifecycle:N.INIT}};function Qy(t){const{path:e,attribute:s}=t;return(r,o)=>{r[L]=r[L]||{},r[L][o]={modelType:Yo.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:N.INIT}}}const Ze=p.createLogger({name:"services",group:"Services"}),Zy=async(t,e)=>od(t,e,`${exports.BASE_URL}/api/server/login`),od=async(t,e,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:t,password:e})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},Jy=async t=>nd(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),nd=async(t,e=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${e}?email=${t}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},Xy=async(t,e)=>id(t,e,`${exports.BASE_URL}/api/server/resetPassword`),id=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{Ze.debug(`resetting password with token ${t} and password ${e.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e})});if(Ze.debug(`password reset returned status ${r.status}`),!r.ok){Ze.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()},eb=async(t,e,s)=>ad(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),ad=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Ze.debug(`accepting invite with token ${t} and password ${e.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e,name:s})});if(Ze.debug(`invitation accept returned status ${o.status}`),!o.ok){Ze.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 tb(t,e,s,r){const o=t instanceof Promise?{promise:t,abortController:e,cancelFuture:s,future:r}:t,{promise:n,abortController:i,cancelFuture:a,future:c}=o,d=n;let u=0,h="PENDING",f=!0;const m=new Set;let w;return c&&typeof c=="object"&&(w=M.autorun(()=>{const v=c.progress||0,E=c.status||"PENDING",T=!c.endState;(v!==u||E!==h||T!==f)&&(u=v,h=E,f=T,m.forEach(K=>{try{K(u,h)}catch(fe){console.warn("Progress callback error:",fe)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",m.forEach(v=>{try{v(u,h)}catch(E){console.warn("Progress callback error:",E)}})),w&&w(),m.clear()}),d.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",m.forEach(v=>{try{v(u,h)}catch(E){console.warn("Progress callback error:",E)}}),w&&w()},d.getController=()=>i,d.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(d,"progress",{get:()=>u,enumerable:!0}),Object.defineProperty(d,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(d,"isRunning",{get:()=>f,enumerable:!0}),d.onProgressUpdate=v=>(m.add(v),v(u,h),()=>m.delete(v)),d}const sb=Fe.keyframes`
|
|
111
|
+
`,i=this.compileShader(r.VERTEX_SHADER,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class mt{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("2d");if(!e)throw new Error("2D canvas not supported");this.ctx=e}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}}function Jo(t){class e extends t{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(o){this.doneCallback=o}signalDoneIfNeeded(){var o;this.oneShotDone||((o=this.doneCallback)==null||o.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return e}const Ym=Jo(mt);class qm extends Ym{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();l(this,"offset",0);l(this,"speed");l(this,"colors");l(this,"direction");l(this,"loop");this.colors=s,this.direction=r,this.speed=o,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,r){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const o=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(o,0,n,0),a=1/(this.colors.length-1);this.colors.forEach((c,d)=>{i.addColorStop(d*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const Wm=Jo(mt);class Dl extends Wm{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 Qm extends $l{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()}}class Zm extends mt{constructor({speed:s=1,fallChance:r=.7,baseColor:o}={}){super();l(this,"columns",[]);l(this,"fallChance");l(this,"speed");l(this,"baseColor");l(this,"trailColors");this.speed=s,this.fallChance=r,this.baseColor=o||{r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let o=0;o<=5;o++){const n=1-o/5*.6;r.push({r:Math.floor(this.baseColor.r*n),g:Math.floor(this.baseColor.g*n),b:Math.floor(this.baseColor.b*n)})}return r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const c=this.columns[a];let d=0,u=0,h=0;if(i===c)d=this.baseColor.r,u=this.baseColor.g,h=this.baseColor.b;else if(i<c&&i>c-this.trailColors.length){const m=c-i;if(m<this.trailColors.length){const w=this.trailColors[m];d=w.r,u=w.g,h=w.b}}const f=(i*s+a)*4;n[f]=d,n[f+1]=u,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(o,0,0)}}class Cl extends mt{constructor(s){super();l(this,"img");l(this,"loaded",!1);l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");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);this.img=new Image,this.img.src=s.src,this.img.crossOrigin="anonymous",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,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}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.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.ctx.drawImage(this.img,0,0,s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),d=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const u=n*d;switch(o){case"left":this.position+=u;break;case"right":this.position+=u;break;case"up":this.position+=u;break;case"down":this.position+=u;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(o,i)}drawScrollingImage(s,r,o,n){var h,f,m,w,v,E,T,k,se;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):(m=this.scrollConfig)!=null&&m.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((w=this.scrollConfig)==null?void 0:w.width)||s,c=((v=this.scrollConfig)==null?void 0:v.height)||r);let d,u;switch(o==="left"||o==="right"?(d=0,((E=this.scrollConfig)==null?void 0:E.offsetY)==="center"||((T=this.scrollConfig)==null?void 0:T.offsetY)===void 0?u=(r-c)/2:u=this.scrollConfig.offsetY):(((k=this.scrollConfig)==null?void 0:k.offsetX)==="center"||((se=this.scrollConfig)==null?void 0:se.offsetX)===void 0?d=(s-a)/2:d=this.scrollConfig.offsetX,u=0),o){case"left":{const P=s-this.position;if(P<s&&P>-a&&this.ctx.drawImage(this.img,P,u,a,c),this.loopConfig&&this.position>n){const I=P+a+n;I<s&&this.ctx.drawImage(this.img,I,u,a,c)}break}case"right":{const P=-a+this.position;if(P>-a&&P<s&&this.ctx.drawImage(this.img,P,u,a,c),this.loopConfig&&P-n-a>-a){const I=P-a-n;I<s&&this.ctx.drawImage(this.img,I,u,a,c)}break}case"up":{const P=r-this.position;if(P>-c&&P<r&&this.ctx.drawImage(this.img,d,P,a,c),this.loopConfig&&P+c+n<r){const I=P+c+n;I>-c&&this.ctx.drawImage(this.img,d,I,a,c)}break}case"down":{const P=-c+this.position;if(P>-c&&P<r&&this.ctx.drawImage(this.img,d,P,a,c),this.loopConfig&&P-n-c>-c){const I=P-c-n;I<r&&this.ctx.drawImage(this.img,d,I,a,c)}break}}}checkScrollCompletion(s,r){var d,u,h,f,m;if(!this.isPlaying)return;const o=this.img.width/this.img.height;let n,i;switch(((d=this.scrollConfig)==null?void 0:d.maintainAspectRatio)!==!1?(u=this.scrollConfig)!=null&&u.height?(i=this.scrollConfig.height,n=i*o):(h=this.scrollConfig)!=null&&h.width?(n=this.scrollConfig.width,i=n/o):s==="left"||s==="right"?(i=this.canvas.height,n=i*o):(n=this.canvas.width,i=n/o):(n=((f=this.scrollConfig)==null?void 0:f.width)||this.canvas.width,i=((m=this.scrollConfig)==null?void 0:m.height)||this.canvas.height),s){case"left":case"right":this.canvas.width+n,this.loopConfig;break;case"up":case"down":this.canvas.height+i,this.loopConfig;break}let a=!1;const c=1;switch(s){case"left":a=this.canvas.width-this.position<-n-c;break;case"right":a=-n+this.position>this.canvas.width+c;break;case"up":a=this.canvas.height-this.position<-i-c;break;case"down":a=-i+this.position>this.canvas.height+c;break}a&&(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.position=0):this.loopConfig===!0&&(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.img.removeAttribute("src"),this.completionCallback=null}}class Jm{constructor(e){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=e.patterns,this.loopConfig=e.loop??!1,this.transitionDuration=e.transitionDuration??0,this.patternOverrides=e.patternOverrides??{},this.patternStore=e.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var n,i,a,c;const e=this.patterns[this.currentPatternIndex],s=this.patternStore.get(e);if(!s){console.warn(`Pattern "${e}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[e]??{},o={...s.data,...r};try{this.currentRenderer=Qr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(c=(a=this.currentRenderer).play)==null||c.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(d){console.error(`Failed to create renderer for pattern "${e}":`,d),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const Xm=Jo(mt);class ey extends Xm{constructor({r:s,g:r,b:o}={r:0,g:0,b:0}){super();l(this,"color");this.color=`rgb(${s},${r},${o})`}setColor(s,r,o){this.color=`rgb(${s},${r},${o})`,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 ty extends mt{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,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?h+(f-h)*6*m:m<.5?f:m<.6666666666666666?h+(f-h)*(.6666666666666666-m)*6:h),d=o<.5?o*(1+r):o+r-o*r,u=2*o-d;n=c(u,d,s+1/3),i=c(u,d,s),a=c(u,d,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let c=0;c<s;c++){const d=(c+this.offset)%s/s,u=this.minHue/360+d*((this.maxHue-this.minHue)/360),[h,f,m]=this.hslToRgb(u,1,.5);n[i++]=h,n[i++]=f,n[i++]=m,n[i++]=255}this.ctx.putImageData(o,0,0)}}const Wn=new Map;rs(ee,{register(t,e){Wn.set(t,e)},execute(t,e){const s=Wn.get(t);return s?new s(e):null}});S.canvas.registerRenderer("video",Qm);S.canvas.registerRenderer("video-basic",$l);S[ee].register("image-static",Dl);S[ee].register("image-scrolling",Cl);const sy=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new Cl(t):new Dl(t)}};S[ee].register("image",sy);S[ee].register("color",ey);S[ee].register("matrix",Zm);S[ee].register("sweep",ty);S[ee].register("gradient",qm);S[ee].register("drop",Vm);S[ee].register("sequence",Jm);const Qr=({mode:t,data:e})=>{const s=S[ee].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var ry=Object.defineProperty,oy=Object.getOwnPropertyDescriptor,yt=(t,e,s,r)=>{for(var o=r>1?void 0:r?oy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ry(e,s,o),o};const Rl="canvas-dispatcher-model";function ny(t){if(t=t.replace(/^#/,""),t.length===3&&(t=t.split("").map(s=>s+s).join("")),t.length!==6)return null;const e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:e&255}}let Pe=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new we}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=Zo.instance(t).options({apiPath:e.apiPath,width:e.width,height:e.height,fps:e.fps,durationMs:e.durationMs??null,endpoint:t}).build();return this._endpointRenderers.addModel(s),s}addContent(t,e){this._content.has(t)&&this.logger.warn(`Content "${t}" already exists. Overwriting.`),this._content.set(t,e)}addPattern(t,e){this._patterns.has(t)&&this.logger.warn(`Pattern "${t}" already exists. Overwriting.`),this._patterns.set(t,e)}async handlePatternsPost(t,e){var o,n;const s=t.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=e.status)==null||o.call(e,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(n=e.status)==null||n.call(e,200).send({status:"OK"})}async handlePatternApplication(t,e){var d,u,h;const s=t.params.pattern,r=t.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(d=e.status)==null||d.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(u=e.status)==null||u.call(e,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=t.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=Qr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var d,u,h;const s=t.params.color,r=ny(s);if(!r){(d=e.status)==null||d.call(e,400).send({error:"Invalid color format"});return}const o=t.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=Qr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleEndpointCreation(t,e){var r,o;const s=t.body;if(!s.apiPath||!s.id){(r=e.status)==null||r.call(e,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=e.status)==null||o.call(e,200).send({status:"OK"})}async load(t){var s;const e=t==null?void 0:t.get(it.loader);e&&((s=e.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};yt([ge],Pe.prototype,"_endpointRenderers",2);yt([os("/api/ui/canvas/patterns")],Pe.prototype,"handlePatternsPost",1);yt([os("/api/ui/canvas/pattern/:endpoint/:pattern")],Pe.prototype,"handlePatternApplication",1);yt([os("/api/ui/canvas/color/:endpoint/:color")],Pe.prototype,"handleColorApplication",1);yt([os("/api/ui/canvas/endpoint")],Pe.prototype,"handleEndpointCreation",1);Pe=yt([R(Rl)],Pe);const it=new be({class:Pe,type:Rl}),{URL:Xo}=te(),{getOne:Pl}=X.build({basePath:`${Xo}/api/device`}),Qs=p.createLogger({name:"device-service",group:"Services"}),Al=async()=>{Qs.debug("sending GET for device serial number");try{const t=await Pl({urlOverride:`${Xo}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof ce)return Qs.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Ll=async()=>{Qs.debug("sending GET for device details");try{const t=await Pl({urlOverride:`${Xo}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof ce)return Qs.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},iy=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Ll,getSerialNumber:Al},Symbol.toStringTag,{value:"Module"}));var ay=Object.defineProperty,cy=Object.getOwnPropertyDescriptor,xl=(t,e,s,r)=>{for(var o=r>1?void 0:r?cy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ay(e,s,o),o};const Fl="device-model",ly="/kos/criticalData/changed",dy="/kos/criticalData/available";let Zs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=t,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[t]=this.nodeId.split("-");return t}get nodeName(){const[,t]=this.nodeId.split("-");return t}updateModel(t){this._serialNumber=t.serialNumber??"unassigned",this._name=t.name??"unassigned",this._nodeId=t.nodeId??"unassigned"}async loadDeviceData(){const[t,e]=await Ll();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}if(e){const{name:s,nodeId:r}=e;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[t,e]=await Al();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}this.updateModel({serialNumber:e,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};xl([F({topic:[ly,dy],websocket:!0})],Zs.prototype,"handleCriticalDataChanged",1);Zs=xl([R(Fl)],Zs);const Js=new be({class:Zs,type:Fl});var uy=Object.defineProperty,hy=Object.getOwnPropertyDescriptor,fy=(t,e,s,r)=>{for(var o=r>1?void 0:r?hy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&uy(e,s,o),o};const kl="network-interface-model";let Zr=class{constructor(t,e,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=t,this.logger=s.logger,this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}updateModel(t){this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};Zr=fy([R(kl)],Zr);const en=new pe({class:Zr,type:kl}),{URL:gy}=te(),{getAll:py}=X.build({basePath:`${gy}/api/kos/network/interfaces`}),Qn=p.createLogger({name:"network-interface-service",group:"Services"}),Nl=async()=>{Qn.debug("sending GET for copy-logs");try{const t=await py({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof ce)return Qn.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},my=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Nl},Symbol.toStringTag,{value:"Module"}));var yy=Object.defineProperty,by=Object.getOwnPropertyDescriptor,Ul=(t,e,s,r)=>{for(var o=r>1?void 0:r?by(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&yy(e,s,o),o};const jl="network-interface-container-model";let Xs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new we({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await Nl();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=en.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Ul([ge],Xs.prototype,"_models",2);Xs=Ul([R(jl)],Xs);const Jt=new be({class:Xs,type:jl});Jt.addRelatedModel(en);const{URL:wy}=te(),{getAll:vy}=X.build({basePath:`${wy}/api/kos/storage/devices`}),Zn=p.createLogger({name:"storage-device-service",group:"Services"}),Bl=async()=>{Zn.debug("sending GET for storage-device");const t=await vy({});return!(t!=null&&t.data)||t.status!==200?(Zn.error("Failed to retrieve storage-device data",t),[]):t.data},My=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Bl},Symbol.toStringTag,{value:"Module"}));var Ey=Object.defineProperty,_y=Object.getOwnPropertyDescriptor,Ty=(t,e,s,r)=>{for(var o=r>1?void 0:r?_y(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ey(e,s,o),o};const Kl="storage-device-model";let Jr=class{constructor(t,e,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=t,this.logger=s.logger,this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}updateModel(t){this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};Jr=Ty([ar(),R(Kl)],Jr);const er=new pe({class:Jr,type:Kl});var Iy=Object.defineProperty,Oy=Object.getOwnPropertyDescriptor,tn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Oy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Iy(e,s,o),o};const Hl="storage-device-container-model",Sy="/kos/storage";let Xt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new we({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=er.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Bl()).forEach(e=>{const s={...e,kosParentId:this.id},r=er.instance(e.id).options(s).build();this.addModel(r)})}};tn([ge],Xt.prototype,"_models",2);tn([F({topic:Sy,websocket:!0})],Xt.prototype,"handleStorageAvailability",1);Xt=tn([R(Hl)],Xt);const at=new be({class:Xt,type:Hl});at.addRelatedModel(er);const{URL:sn}=te(),{getAll:$y,postModel:Dy}=X.build({basePath:`${sn}/api/kos/update/available`}),Jn=p.createLogger({name:"usb-update-service",group:"Services"}),Gl=async()=>{Jn.debug("sending GET for usb-update");const t=await $y({urlOverride:`${sn}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(Jn.error("Failed to retrieve usb-update data",t),[]):t.data},zl=async(t,e,s)=>{const r=await Dy({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${sn}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},Cy=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Gl,installUpdate:zl},Symbol.toStringTag,{value:"Module"}));var Ry=Object.defineProperty,Py=Object.getOwnPropertyDescriptor,Vl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Py(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ry(e,s,o),o};const Yl="usb-update-model";let tr=class{constructor(t,e,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=t,this.logger=s.logger,this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes,this.futureHandler=new ur(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),zl(this.manifestId,this.deviceId,t)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};Vl([ln()],tr.prototype,"install",1);tr=Vl([R(Yl)],tr);const rn=new pe({class:tr,type:Yl});var Ay=Object.defineProperty,Ly=Object.getOwnPropertyDescriptor,br=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ly(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ay(e,s,o),o};const ql="usb-update-container-model";let ct=class{constructor(t,e,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new we({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await Gl();W(()=>{const e=t.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!e.includes(s.id)).forEach(s=>this.removeModel(s.id)),t.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=rn.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(o)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var t;(t=this.disposer)==null||t.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};br([ut({modelType:at.type})],ct.prototype,"storageService",2);br([ge],ct.prototype,"_models",2);br([ia({dependencies:t=>[t.isUsbInserted]})],ct.prototype,"usbInsertedEffect",1);ct=br([R(ql)],ct);const es=new be({class:ct,type:ql});es.addRelatedModel(rn);const xy=()=>({...{[gt.type]:{class:Sc},[Re.type]:{class:Ac,singleton:!0},...Z.registration,...Ke.registration,...ot.registration,...Ys.registration,...Te.registration,[Wo.type]:{class:exports.WsEventModel,singleton:!0},...Zt.registration,...Yo.registration,...Ns.registration}}),on=xy(),Fy={models:on,preloadModels:[]},Xn=!0,Wl=t=>()=>{const e=on;return za(Xr)(Qt).model(ot).model(at).model(es).model(Js).model(Hs).model(Gt).model(Gs).model(Ho).model(Jt).model(it).model(Zo).model(jo,Xn).model(cs).model(Bc,Xn),Object.keys(e).forEach(s=>{const r=e[s];Ga(Xr)(s,r)}),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t)}},fe={};fe.core={models:Wl(fe)};fe.preload=C.model.preloadModel(fe);fe.model=C.model.register(fe);fe.companion=C.companion.register(fe);fe.legacy=C.model.registerLegacyModel(fe);const Xr=fe;class ky{registerTroubleRankMapper(e){return S.propertyMapper.registerPropertyMapper(he.TroubleRank,e),this}registerTroubleRoleMapper(e){return S.propertyMapper.registerPropertyMapper(he.TroubleRole,e),this}registerTroubleColorMapper(e){return S.propertyMapper.registerPropertyMapper(he.TroubleColor,e),this}registerModelLoader(e,s){S.loader.registerLoader(e,s)}registerCanvasPatternLoader(e){S.loader.registerLoader(it.loader,e)}}class ds{constructor(e){l(this,"futureHandler");this.futureHandler=new ur(e)}get future(){return this.futureHandler.future}get progress(){var e;return((e=this.future)==null?void 0:e.progress)||0}get status(){var e;return((e=this.future)==null?void 0:e.status)||"IDLE"}get isRunning(){return this.future?!this.future.endState:!1}get isCancelled(){var e;return((e=this.future)==null?void 0:e.status)==="CANCELLED"||!1}async cancelFuture(){this.future&&await this.future.cancelFuture()}}function Ny(t){const e=new ds(t);t.futureHandler=e.futureHandler,Object.defineProperty(t,"_futureMixin",{value:e,enumerable:!1,configurable:!1,writable:!1})}function Ql(t){const e=new ds(t),s=t;s.futureHandler=e.futureHandler,Object.defineProperty(t,"_futureMixin",{value:e,enumerable:!1,configurable:!1,writable:!1}),Object.defineProperty(t,"future",{get(){return e.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){return e.progress},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){return e.status},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return e.isRunning},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){return e.isCancelled},enumerable:!0,configurable:!0}),s.cancelFuture=async()=>e.cancelFuture()}function Uy(){return function(t){const e=t;function s(...r){const o=e.apply(this,r)||this;return Ql(o),o}return s.prototype=e.prototype,Object.setPrototypeOf(s,e),Object.getOwnPropertyNames(e).forEach(r=>{if(r!=="prototype"&&r!=="length"&&r!=="name"){const o=Object.getOwnPropertyDescriptor(e,r);o&&Object.defineProperty(s,r,o)}}),s}}function jy(t){return new ds(t)}function By(t){let e;const s=()=>(e||(e=new ds(t())),e);return{get futureHandler(){return s().futureHandler},get future(){return s().future},get progress(){return s().progress},get status(){return s().status},get isRunning(){return s().isRunning},get isCancelled(){return s().isCancelled},async cancelFuture(){return s().cancelFuture()}}}function Ky(t){return t&&typeof t=="object"&&"futureHandler"in t&&"future"in t&&"_futureMixin"in t&&typeof t.cancelFuture=="function"}function Hy(t){const e=["future","progress","status","isRunning","isCancelled","futureHandler"],s={};for(const r of e){const o=Object.getOwnPropertyDescriptor(t,r);s[r]={exists:r in t,descriptor:o?{enumerable:o.enumerable,configurable:o.configurable,hasGetter:typeof o.get=="function",hasSetter:typeof o.set=="function"}:null,isObservable:t&&typeof t=="object"&&Object.getOwnPropertySymbols(t).some(n=>n.toString().includes("mobx")&&n.toString().includes(r))}}return s}class Zl{constructor(e,s){l(this,"parent");l(this,"companion");this.companion=e,this.parent=s}getParent(){return this.parent}setupProxy(e={}){const{excludeProperties:s=[],includeLifecycle:r=!1}=e,o=r?[]:["init","load","unload","ready","dispose","destroy","onInit","onLoad","onUnload","onReady","onDispose","onDestroy"],n=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace"],i=c=>c==="constructor"||c.startsWith("_")||c.startsWith("__")||o.includes(c)||n.includes(c)||s.includes(c)||c in this.companion,a=this.getAllParentProperties(i);for(const c of a)this.createProxyProperty(c)}getAllParentProperties(e){const s=new Set;Object.getOwnPropertyNames(this.parent).filter(o=>!e(o)).forEach(o=>s.add(o));let r=Object.getPrototypeOf(this.parent);for(;r&&r!==Object.prototype;)Object.getOwnPropertyNames(r).filter(o=>!e(o)).forEach(o=>s.add(o)),r=Object.getPrototypeOf(r);return Array.from(s)}createProxyProperty(e){try{const s=this.parent[e];typeof s=="function"?this.companion[e]=(...r)=>s.apply(this.parent,r):Object.defineProperty(this.companion,e,{get:()=>this.parent[e],set:r=>{this.parent[e]=r},enumerable:!0,configurable:!0})}catch(s){console.debug(`Skipping companion proxy for property ${e}:`,s)}}}function Gy(t,e,s={}){const r=new Zl(t,e);return t.getParent=()=>r.getParent(),Object.defineProperty(t,"_companionMixin",{value:r,enumerable:!1,configurable:!1,writable:!1}),r.setupProxy(s),r}function Jl(t){return t&&typeof t=="object"&&"_companionMixin"in t&&typeof t.getParent=="function"}function Xl(t){return Jl(t)?t._companionMixin:null}function zy(t){const e=Xl(t);if(!e)return{error:"No companion mixin found"};const s=e.getParent(),r=Object.getOwnPropertyNames(t),o=Object.getOwnPropertyNames(s),n=r.filter(i=>o.includes(i)&&i!=="constructor"&&!i.startsWith("_"));return{parentType:s.constructor.name,companionType:t.constructor.name,proxiedProps:n,proxiedCount:n.length}}const Vy=async(t,e)=>{const s=Ho.instance(t).options({}).build(),r=e?`${e}-`:"";return await ne(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:()=>{Ue(s)}}},ed="kos:service:region",td="regionId",Yy=`${ed}-${td}`,sd=async t=>{const e=Ke.factory(Yy)({path:ed,attribute:td});await ne(e),e.updateProperty(t)},nn="/kos-timer-event",an="/kos-timer-event/tick",cn="defaultTimerEnd",Ct=p.createLogger({name:"timer-manager"}),qy=t=>t.updateProperty!==void 0;class rd{constructor(e,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=e;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,qy(s)&&H(()=>{p.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:cn}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){Ct.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&&(Ct.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(e){this.timeout=e,this.restart()}addTimeoutAction(e){const s=e.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=e.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=e.action:this.timeoutActions.get(s).push(e)}removeTimeoutAction(e){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==e);o.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,o)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(e){this.timeoutActions.has(e)&&this.timeoutActions.get(e).forEach(s=>{var r;Ct.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(Ct.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){B(`${an}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){B(nn,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const Rt=new Map,qe=(t,e)=>{const s=Rt.get(t);if(!s){Ct.error(`Timer ${t} not found`);return}e(s)},od={createRelativeTimer(t,e,s){const r=new Date,o=Math.round((e.getTime()-r.getTime())/1e3);return this.createTimer(t,o,s)},createTimer(t,e=60,s){if(Rt.has(t))return Rt.get(t);const r=new rd(t,e,s);return Rt.set(t,r),r},getTimer(t){return Rt.get(t)},clearTimer(t){qe(t,e=>e.pause())},restartTimer(t){qe(t,e=>e.restart())},resetTimer(t){qe(t,e=>e.reset())},addTimeoutAction(t,e){qe(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){qe(t,s=>s.removeTimeoutAction(e))},startTimer(t){qe(t,e=>e.start())}},nd="kos:service:region:settings",id="timeZone",Wy=`${nd}-${id}`,eo=async t=>{const e=Ke.factory(Wy)({path:nd,attribute:id});await ne(e),e.updateProperty(t)},Qy=t=>!t||!t.data;function ln(t={}){const{alias:e,namespace:s,abortController:r=!1}=t;return(o,n,i)=>{o[Lt]=o[Lt]||{};const a=i.value,c=async function(...d){const u=dt();p.debug(`Calling future service ${n} with tracker ${u}`);let h,f;r&&(h=new AbortController);const m=je.initiateFuture({tracker:u,id:Co});s&&(m.namespace=s),p.debug(`waiting for future ${m.id} to be ready`),await ne(m),p.debug(`future ${m.id} is ready`),W(()=>{p.debug(`Adding future ${m.id} to futureHandler`),this.futureHandler.addFuture(m,e)}),r&&h&&(f=H(()=>{(m.status==="CANCELLED"||m.endState===Ce.Canceled)&&(p.debug(`Future ${m.id} cancelled, aborting request`),h==null||h.abort())}),h.signal.addEventListener("abort",async()=>{if(m.status!=="CANCELLED"&&m.endState!==Ce.Canceled&&!m.endState){p.debug(`AbortController aborted, cancelling future ${m.id}`);try{await m.cancelFuture()}catch(v){p.error(`Failed to cancel future ${m.id}:`,v)}}},{once:!0}));const w=()=>{f&&(f(),f=void 0)};try{const v=[...d];if(r&&h){const k=v[v.length-1];k&&typeof k=="object"&&"aborted"in k?v[v.length-1]=h.signal:v.push(h.signal)}v.push(u);const E=await a.apply(this,v);p.debug(`received future response for ${u}`,E);const T=Qy(E)?E:E==null?void 0:E.data;return T?(T.progress=1,p.debug("mapping future response to future model"),m.endState?p.debug(`future ${m.id} has already completed. Not updating the model`):No(T,m)):this.futureHandler.removeFuture(e),w(),T}catch(v){if(w(),r&&(h!=null&&h.signal.aborted)){const E=new Error("Operation cancelled");throw p.debug(`Operation ${n} was cancelled`),E}throw p.error(v),v}};o[Lt][n]={handler:c}}}const Zy=({path:t})=>(e,s)=>{e[x]=e[x]||{},e[x][s]={modelType:Zt.type,id:`${Zt.type}-${t}`,options:{path:t},lifecycle:j.INIT}};function Jy(t){const{path:e,attribute:s}=t;return(r,o)=>{r[x]=r[x]||{},r[x][o]={modelType:Yo.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:j.INIT}}}const Ze=p.createLogger({name:"services",group:"Services"}),Xy=async(t,e)=>ad(t,e,`${exports.BASE_URL}/api/server/login`),ad=async(t,e,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:t,password:e})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},eb=async t=>cd(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),cd=async(t,e=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${e}?email=${t}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},tb=async(t,e)=>ld(t,e,`${exports.BASE_URL}/api/server/resetPassword`),ld=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{Ze.debug(`resetting password with token ${t} and password ${e.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e})});if(Ze.debug(`password reset returned status ${r.status}`),!r.ok){Ze.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()},sb=async(t,e,s)=>dd(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),dd=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Ze.debug(`accepting invite with token ${t} and password ${e.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e,name:s})});if(Ze.debug(`invitation accept returned status ${o.status}`),!o.ok){Ze.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 rb(t,e,s,r){const o=t instanceof Promise?{promise:t,abortController:e,cancelFuture:s,future:r}:t,{promise:n,abortController:i,cancelFuture:a,future:c}=o,d=n;let u=0,h="PENDING",f=!0;const m=new Set;let w;return c&&typeof c=="object"&&(w=M.autorun(()=>{const v=c.progress||0,E=c.status||"PENDING",T=!c.endState;(v!==u||E!==h||T!==f)&&(u=v,h=E,f=T,m.forEach(k=>{try{k(u,h)}catch(se){console.warn("Progress callback error:",se)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",m.forEach(v=>{try{v(u,h)}catch(E){console.warn("Progress callback error:",E)}})),w&&w(),m.clear()}),d.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",m.forEach(v=>{try{v(u,h)}catch(E){console.warn("Progress callback error:",E)}}),w&&w()},d.getController=()=>i,d.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(d,"progress",{get:()=>u,enumerable:!0}),Object.defineProperty(d,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(d,"isRunning",{get:()=>f,enumerable:!0}),d.onProgressUpdate=v=>(m.add(v),v(u,h),()=>m.delete(v)),d}const ob=Fe.keyframes`
|
|
112
112
|
0% {
|
|
113
113
|
left: -90px;
|
|
114
114
|
color: #eee;
|
|
@@ -120,13 +120,13 @@ ${d}topics:${e}
|
|
|
120
120
|
left: 90px;
|
|
121
121
|
color: #eee;
|
|
122
122
|
}
|
|
123
|
-
`,
|
|
123
|
+
`,nb=Fe.css`
|
|
124
124
|
font-size: 100px;
|
|
125
125
|
margin-top: -80px;
|
|
126
126
|
position: relative;
|
|
127
|
-
animation: ${
|
|
127
|
+
animation: ${ob} ease-in-out infinite alternate;
|
|
128
128
|
animation-duration: 1.2s;
|
|
129
|
-
`,
|
|
129
|
+
`,ib=({children:t})=>ri.createPortal(t,document.body);function ud({message:t="Wait a moment while we load your app.",theme:e="light"}){return _.jsx(ib,{children:_.jsxs(ab,{theme:e,children:[t,_.jsx("div",{css:nb,children:"."})]})})}const ab=oo.div`
|
|
130
130
|
padding-inline: 20px;
|
|
131
131
|
width: 100%;
|
|
132
132
|
height: 100vh;
|
|
@@ -140,7 +140,7 @@ ${d}topics:${e}
|
|
|
140
140
|
left: 0;
|
|
141
141
|
color: ${({theme:t})=>t==="light"?"black":"white"};
|
|
142
142
|
z-index: 10000;
|
|
143
|
-
`;class
|
|
143
|
+
`;class hd extends g.Component{constructor(e){super(e),this.state={error:null,errorInfo:null}}componentDidCatch(e,s){this.setState({error:e,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||_.jsxs("div",{children:[_.jsx("h2",{children:"Something went wrong."}),_.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),_.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const cb={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},lb=({value:t=0,title:e,status:s="normal",subtitle:r})=>{const o=Fe.css`
|
|
144
144
|
display: flex;
|
|
145
145
|
flex-direction: column;
|
|
146
146
|
`,n=Fe.css`
|
|
@@ -160,7 +160,7 @@ ${d}topics:${e}
|
|
|
160
160
|
`,a=Fe.css`
|
|
161
161
|
width: ${t}%;
|
|
162
162
|
height: 35px;
|
|
163
|
-
background-color: ${
|
|
163
|
+
background-color: ${cb[s]};
|
|
164
164
|
text-align: center;
|
|
165
165
|
line-height: 32px;
|
|
166
166
|
color: black;
|
|
@@ -178,7 +178,7 @@ ${d}topics:${e}
|
|
|
178
178
|
transform: translateX(100%) scaleX(0.5);
|
|
179
179
|
}
|
|
180
180
|
}
|
|
181
|
-
`;return _.jsxs("div",{css:o,children:[_.jsxs("div",{css:n,children:[_.jsx("div",{css:i,children:e}),_.jsx("div",{css:[a,t<0?c:""]})]}),_.jsx("div",{children:r})]})},
|
|
181
|
+
`;return _.jsxs("div",{css:o,children:[_.jsxs("div",{css:n,children:[_.jsx("div",{css:i,children:e}),_.jsx("div",{css:[a,t<0?c:""]})]}),_.jsx("div",{children:r})]})},db={setModel:()=>!1},wr=g.createContext(db),ub=()=>{const t=g.useContext(wr);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},fd=({children:t})=>{const[e,s]=g.useState(),r=g.useCallback(o=>(s(o),!0),[s]);return _.jsx(wr.Provider,{value:{model:e,setModel:r},children:t})},gd=p.createLogger({name:"kos-model-hierarchy-context"}),hb={models:[],addModel:()=>{gd.debug("Default implementation being used. Do Nothing.")}},vr=g.createContext(hb),fb=({children:t})=>{const[e,s]=g.useState([]),r=g.useCallback(o=>{e.includes(o)||(gd.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[e]);return _.jsx(vr.Provider,{value:{models:e,addModel:r},children:t})},gb=()=>!0,pd=t=>{const e=g.useContext(vr);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||gb;return g.useMemo(()=>e.models.filter(s),[e.models,s])},pb=t=>pd({filter:s=>{const r=me(s.id);return(r==null?void 0:r.type)===t}})[0],mb=p.createLogger({name:"kos-model-loader"}),yb=()=>_.jsx("div",{}),md=({fallback:t,children:e,...s})=>_.jsx(fd,{children:_.jsx(hd,{fallback:t,children:_.jsx(g.Suspense,{children:_.jsx(yd,{...s,children:e})})})}),yd=t=>{const[e,s]=g.useState(),[r,o]=g.useState(!1),{setModel:n}=g.useContext(wr),i=g.useContext(vr);if(g.useEffect(()=>{t.model&&(s(t.model),n(t.model),o(!0),i&&i.addModel(t.model))},[i,t.model,n]),t.error)throw mb.error(t.error),new Error(t.error);const a=t.loading||_.jsx(yb,{});return _.jsx(_.Fragment,{children:e&&r?t.children:a})},$s={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},bd=g.createContext($s),bb=({translations:t=$s,children:e})=>{const s={header:{...$s.header,...t.header},createModal:{...$s.createModal,...t.createModal}};return _.jsx(bd.Provider,{value:s,children:e})};function wb(t,e){const s=O.create(t,!1,e),r=s.whenReady().then(()=>s);return po(r)}const wd=g.createContext(void 0),vb=(t={models:{},preloadModels:[]},e)=>{const s=wb(t,e),r=({children:o})=>{const n=s.read(),[i,a]=g.useState(n.isOnline);return g.useEffect(()=>{const c=H(()=>{a(n.isOnline)});return()=>{c()}},[n]),_.jsx(wd.Provider,{value:{kosCore:n,online:i},children:o})};return{KosCoreContextProvider:no.observer(r)}},vd=()=>{const t=g.useContext(wd);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},Mb=8,Eb=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),ke=new Map;function _b(t,e){if(ke.has(t)){const s=ke.get(t);if(s.status==="finished"){const r=O.getInstance().modelManager.getModelById(t);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=e().then(()=>{ke.set(t,{status:"finished",key:t})},o=>{throw ke.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw ke.set(t,r),s}}function Tb(t,e){return _b(t,e)}async function Ib(t,e){const{modelId:s,factory:r,modelType:o,options:n,activate:i}=e;let a=0;await t.whenReady();let c;if(n){const u=typeof o=="string"?t.modelManager.getModelFactory(o):r;if(!u)throw Error("No Factory Specified. Cannot create a new instance");c=u.build(s,n)}const d=t.modelManager.getModelById(s);if(!d){if(a>Mb)throw Error(`KOS Model ${s} has not been found`);await Eb(a),a=a+1}return await(d==null?void 0:d.whenReady()),d?(c=d.modelData,{kosModel:d,model:c}):{kosModel:void 0,model:void 0}}const z=t=>{const{modelId:e,modelType:s,activate:r,destroyOnUnmount:o}=t,n=vd(),[i,a]=g.useState(!1),[c,d]=g.useState(),{kosModel:u,model:h}=Tb(e||s||"",()=>Ib(n.kosCore,t));return g.useEffect(()=>{async function f(){try{return await n.kosCore.whenReady(),r&&await(u==null?void 0:u.fsm.transitionTo(A.GO_ACTIVE,b.ACTIVE)),a(!0),u}catch(w){d(w.message)}}let m;return n.kosCore&&e&&f().then(w=>{m=H(()=>{const v=(w==null?void 0:w.status)===b.READY;a(v)})}).catch(w=>{console.error(w)}),()=>{if(r){if(h!=null&&h.id){const w=n.kosCore.modelManager.getModelById(h.id);w==null||w.fsm.transitionTo(A.GO_INACTIVE,b.INACTIVE).then(()=>{if(o){const v=h.id;Ue(h).then(()=>{ke.delete(v),m==null||m()})}})}}else o&&h&&Ue(h).then(()=>{ke.delete(e),m==null||m()})}},[r,o,n.kosCore,u,h,e]),{model:h,ready:i,error:c,status:{model:h,ready:i,error:c},KosModelLoader:md}},dn=()=>{const t=Ns.type;return z({modelId:t,modelType:Ns.type,options:{}})},un=g.createContext(void 0),Ob=({children:t})=>{const{model:e,ready:s}=dn(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return _.jsx(un.Provider,{value:r,children:t})},Sb=()=>{const t=g.useContext(un);if(!t)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return t},hn=()=>{const t=Gs.type;return z({modelId:t,modelType:Gs.type,options:{}})};function $b(t){return()=>e=>{const{model:s,status:r,KosModelLoader:o}=hn();return _.jsx(o,{...r,children:_.jsx(t,{...e,softwareInfo:s})})}}const fn=g.createContext(void 0),Db=({children:t})=>{const{model:e,ready:s}=hn(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return _.jsx(fn.Provider,{value:r,children:t})},Cb=()=>{const t=g.useContext(fn);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Md=new sc,Ed=g.createContext(Md);function Rb({children:t}){return _.jsx(Ed.Provider,{value:Md,children:t})}const gn=g.createContext(void 0),Pb=()=>{const t=window.location.origin,e=le();return(e==null?void 0:e.host)||t},Ab=({children:t,appContext:e,locale:s="en",resolver:r,rootUrl:o,descriptorResolver:n})=>{const[i,a]=g.useState(!1),[c,d]=g.useState(),[u,h]=g.useState(),f=o||Pb(),m=g.useMemo(()=>e??"app/system",[e]);g.useEffect(()=>{async function E(){const k=(Array.isArray(m)?m:[m]).map(V=>(n||bl(V))()),I=(await Promise.allSettled(k)).map(V=>{if(V.status==="rejected"){p.warn("Failed to load localization descriptor",V.reason);return}return V.value}).filter(V=>!!V).reverse().reduce((V,N)=>{const Y=N.path;return Object.keys(N.namespaces).forEach(Se=>{const ve=N.namespaces[Se];ve.basePath=Y}),{...V,namespaces:{...V.namespaces,...N.namespaces}}},{});d(I)}E()},[m,n]),g.useEffect(()=>{async function E(){if(c){const T=f,{translations:k}=await _l.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:T});h(k),a(!0)}}E()},[s,c,r,f]);const w=g.useMemo(()=>i?{setLocale:E=>{u&&(u.currentLocale=E)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,u]),v=i?t:null;return _.jsx(gn.Provider,{value:w,children:v})},Lb=()=>{const t=g.useContext(gn);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},xb=()=>{const t=it.type;return z({modelId:t,modelType:it.type,options:{}})};function Fb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=xb();return _.jsx(o,{...r,children:_.jsx(t,{...e,canvasDispatcher:s})})}}const kb=(t,e,s)=>{const r=atob(t),o=new Uint8ClampedArray(e*s*4);for(let n=0,i=0;n<r.length&&i<o.length;n+=3,i+=4)o[i]=r.charCodeAt(n),o[i+1]=r.charCodeAt(n+1),o[i+2]=r.charCodeAt(n+2),o[i+3]=255;return o},Nb=(t,e,s)=>{const r=new Uint8ClampedArray(e*s*4);for(let o=0;o<t.length;o++){const n=t.charCodeAt(o),i=(n>>5&7)*255/7,a=(n>>2&7)*255/7,c=(n&3)*255/3,d=o*4;r[d]=i,r[d+1]=a,r[d+2]=c,r[d+3]=255}return r};function Ub({ctx:t,format:e,dataString:s,width:r,height:o,pixelSize:n}){const i=e==="base64"?kb(s,r,o):Nb(s,r,o),a=new ImageData(i,r,o),c=document.createElement("canvas");c.width=r,c.height=o;const d=c.getContext("2d");d==null||d.putImageData(a,0,0),t.imageSmoothingEnabled=!1,t.clearRect(0,0,r*n,o*n),t.drawImage(c,0,0,r*n,o*n)}const jb=p.createLogger({name:"canvas-streamer"});jb.debug("main-view component loaded");const xr=10,_d=no.observer(({canvasDispatcher:t,height:e=30,width:s=50,defaultFps:r=10,showPreview:o=!1,name:n,apiPath:i="/api/system/canvas"})=>{const a=g.useRef(null),[c,d]=g.useState();g.useEffect(()=>{const h=t.addNamedEndpoint(n,{apiPath:i,fps:r,width:s,height:e,id:n});d(h)},[t]);const u=g.useCallback(h=>{if(a.current&&o){const f=a.current.getContext("2d");f&&Ub({ctx:f,format:"base64",dataString:h,height:e,width:s,pixelSize:xr})}},[s,e,o]);return g.useEffect(()=>{c&&(c.onFrame=u,c.width=s,c.height=e,c.fps=r)},[c,u,s,e,r]),o&&ri.createPortal(_.jsx(Kb,{children:_.jsx(Hb,{children:_.jsx("canvas",{ref:a,width:s*xr,height:e*xr,style:{border:"1px solid black"}})})}),document.body)}),Bb=Fb(_d),Kb=oo.div`
|
|
182
182
|
display: flex;
|
|
183
183
|
flex-direction: column;
|
|
184
184
|
gap: 8px;
|
|
@@ -186,9 +186,9 @@ ${d}topics:${e}
|
|
|
186
186
|
width: 100%;
|
|
187
187
|
justify-content: space-between;
|
|
188
188
|
align-items: center;
|
|
189
|
-
`,
|
|
189
|
+
`,Hb=oo.div`
|
|
190
190
|
display: flex;
|
|
191
191
|
flex-direction: column;
|
|
192
192
|
align-items: center;
|
|
193
|
-
`,Md=()=>{const t=Js.type;return G({modelId:t,modelType:Js.type,options:{}})};function Kb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Md();return _.jsx(o,{...r,children:_.jsx(t,{...e,device:s})})}}function Hb(t,e,s){const r=new Promise(o=>{I.getInstance().whenReady().then(()=>{const{model:n}=I.getInstance().modelManager.createModelInstance(t,e??t,s);return n.whenReady().then(()=>{o(n.modelData)})})});return po(r)}function Gb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=dn();return _.jsx(o,{...r,children:_.jsx(t,{...e,kosTime:s})})}}const Ed=()=>{const t=Zt.type;return G({modelId:t,modelType:Zt.type,options:{}})};function zb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Ed();return _.jsx(o,{...r,children:_.jsx(t,{...e,networkInterfaceContainer:s})})}}const _d=()=>{const t=Hs.type;return G({modelId:t,modelType:Hs.type,options:{}})};function Vb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=_d();return _.jsx(o,{...r,children:_.jsx(t,{...e,oTA:s})})}}function Yb(t,e){g.useEffect(()=>{function s(o){t.current&&!t.current.contains(o.target)&&e()}function r(o){o.key==="Escape"&&e()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[t,e])}function qb(t){const e=g.useRef(null),s=t.onAlert;return Yb(e,s),_.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const Wb=t=>{var d;const{stateProp:e}=t,[s,r]=g.useState((d=t.stateProp)==null?void 0:d.value),[o,n]=g.useState(!1),[i,a]=g.useState(void 0);return g.useEffect(()=>{async function u(h){try{h&&(await se(h),n(!0))}catch(f){a(f.message)}}u(e)},[e]),g.useEffect(()=>{const u=B(()=>{e&&o&&r(e.value)});return()=>{u()}},[o,e]),[s,{ready:o,error:i}]},Td=()=>{const[t,e]=g.useState(!1),[s,r]=g.useState([]),o=at.type,n=G({modelId:o,modelType:at.type,options:{}});return g.useEffect(()=>{const i=B(()=>{var a,c;e(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:t,devices:s}};function Qb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Td();return _.jsx(o,{...r,children:_.jsx(t,{...e,storageDeviceContainer:s})})}}const Fr=p.createLogger({name:"use-timer"}),Zb=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=td.getTimer(t);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const d=O(nn,u=>{const{name:h,action:f,remainingTime:m}=u==null?void 0:u.body;h===t&&(f===cn?e({name:h,action:f,remainingTime:m,timer:n}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:m,timer:n}))});return o&&n.start(),()=>{d.unsubscribe()}},[o,e,r,t,n]),g.useEffect(()=>{if(!n||!s)return;const d=`${an}/${t}`,u=O(d,h=>{const{name:f,remainingTime:m}=h==null?void 0:h.body;f===t&&s({name:f,remainingTime:m,timer:n})});return()=>{u.unsubscribe()}},[s,t,n]);const i=g.useCallback(()=>{n?n.start():Fr.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=g.useCallback(()=>{n?n.reset():Fr.warn(`Timer with name ${t} does not exist.`)},[n,t]),c=g.useCallback(()=>{n?n.pause():Fr.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:c}},Jb=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},Xb=t=>t instanceof RegExp,ew=t=>typeof t=="string",tw=(t,e,s)=>{if(t===""||e==="")return t;let r=e;Xb(r)||(r=new RegExp("("+Jb(r)+")","gi"));const o=t.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},Id=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>ew(o)?tw(o,e,s):o)};function sw(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=Id(s,n,(i,a)=>o.type==="br"?_.jsx("br",{}):g.cloneElement(o,{key:`${r}-${a}`},i))}),s}const rw=t=>{const{i18nKey:e,t:s,defaults:r,components:o,values:n={},context:i}=t,a=s(e,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=sw(a,o||{});return _.jsx("span",{className:t.className,children:c})},Qe=new Map;function ow(t,e){if(Qe.has(t)){const s=Qe.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{Qe.set(t,{status:"finished",result:o})},o=>{throw Qe.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Qe.set(t,r),s}}function to(t,e){return ow(t,e)}const nw=async()=>{const t=await ja(Te.type);return await se(t.model),t.model},iw=async(t,e,s)=>{const r=t.resolveNamespace(e);await se(r);for(const o of s){const n=t.resolveNamespace(o);await se(n),Qe.set(o,{status:"finished",result:n})}return r},aw=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=to(Te.type,nw),i=s.join("__"),a=to(i,()=>iw(n,r,o)),c=g.useMemo(()=>({exists:u=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${u}`:u;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:g.useCallback((u,h)=>{const f=e!=null&&e.keyPrefix?`${e.keyPrefix}.${u}`:u;return a?a.resolveKey(f,h):(p.debug(`Translation model ${t} not ready for key: ${f}`),f)},[e==null?void 0:e.keyPrefix,t,a]),i18n:c}},Od=()=>{const t=Te.type;return G({modelId:t,modelType:Te.type,options:{}})};function cw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Od();return _.jsx(o,{...r,children:_.jsx(t,{...e,translationContainer:s})})}}const lw=t=>G({modelId:t,modelType:Wt.type}),pn=()=>G({modelId:ot.type,modelType:ot.type,options:{}}),dw=({troubleType:t,condition:e})=>{const{model:s}=pn(),[r,o]=g.useState(!1),[n,i]=g.useState([]),a=g.useCallback(()=>{var c,d;return n.length>0&&((c=n[0])!=null&&c.resolvable)?(d=n[0])==null?void 0:d.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>B(()=>{const d=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],u=e?d.filter(e):d;o(u.length>0),i(u)}),[e,s,t]),[r,a,n.length>0?n[0]:void 0,n]};function uw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=pn();return _.jsx(o,{...r,children:_.jsx(t,{...e,troubleContainer:s})})}}const Sd=()=>{const t=Xt.type,e=G({modelId:t,modelType:Xt.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=B(()=>{var d,u,h;r(((d=e.model)==null?void 0:d.isUsbInserted)??!1),n(((u=e.model)==null?void 0:u.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{c()}},[e.model]),{...e,inserted:s,updateAvailable:o,updates:i}};function hw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Sd();return _.jsx(o,{...r,children:_.jsx(t,{...e,usbUpdateContainer:s})})}}const gw=({path:t,propKey:e})=>{const{status:s}=G({modelType:Ht.type,modelId:t,options:{path:t}}),[r,o]=g.useState(!1),[n,i]=g.useState(),[a,c]=g.useState(""),[d,u]=g.useState(),h=f=>{n&&e&&n.updateProperty(e,f)};return g.useEffect(()=>{var f;s.model&&i(s.model),s.model&&e&&((f=s.model)!=null&&f.props.has(e)?c(s.model.props[e]):u(`property ${e} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,e]),g.useEffect(()=>{e&&M.autorun(()=>{const f=n==null?void 0:n.props[e];c(f||"")})},[n,e]),{config:n,ready:r,value:a,error:d,updateValue:h}},fw=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},$d=({configProperty:t,optionsTransformer:e})=>{const[s,r]=g.useState(!1),[o,n]=g.useState(""),[i,a]=g.useReducer(fw,{value:String(t==null?void 0:t.value),displayValue:t==null?void 0:t.displayValue,significantValue:t==null?void 0:t.significantValue,unit:t==null?void 0:t.unit,options:t==null?void 0:t.options,mappedOptions:[],updateProperty:t==null?void 0:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}),c=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&(t==null||t.updateProperty(u))},[t]);return g.useEffect(()=>{async function d(u){try{u&&(await se(u),r(!0))}catch(h){n(h.message)}}d(t)},[t]),g.useEffect(()=>{const d=B(()=>{if(t&&s){let u=[];e&&(u=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:u,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{d()}},[t,e,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function pw(t,e){const s=e??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return t===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[t]??0}function mw(t,e){return new Date(t,e,0).getDate()}function Dd(t,e){const s=pw(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function Cd(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function Rd(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function Ad(t,e=[2018,2028]){const s=Rd(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function mn(t="numeric",e="en-US"){const s=new Intl.DateTimeFormat(e,{month:t,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function yw({locale:t="en-US",year:e,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(e,i,r),c=new Intl.DateTimeFormat(t,{month:o.month}).format(a),d=new Intl.DateTimeFormat(t,{year:o.year}).format(a),u=new Intl.DateTimeFormat(t,{day:o.day}).format(a);return n?n=="MMDDYY"?`${c} ${u} ${d}`:n==="DDMMYY"?`${u} ${c} ${d}`:n==="YYMMDD"?`${d} ${c} ${u}`:`${d} ${u} ${c}`:new Intl.DateTimeFormat(t,o).format(a)}function le(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function bw(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function Pd(t,e,s){const r=le(e),o=new Date(r,t,1).getDay(),n=new Date(r,t+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function Rt(t,e,s){const r=e-1,o=new Date(t,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function At(t,e){return new Date(t,e,0).getDate()}function Ld(t="en-US",e="short"){const s=new Intl.DateTimeFormat(t,{weekday:e}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function xd({locale:t="en-US",year:e=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:o=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=yn(n,r),d=Fd(n,r,t),u=kd(i,t),h=Nd(i,t),f=bn(e,s),m=Ud(e,s,t,o),w=Kd(s,e,m),v=jd(t,a);return{daysArray:f,monthsArray:u,yearsArray:c,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:m,calendarDayArray:w,dayNamesArray:v}}function yn(t="long",e=[2018,2028]){return g.useMemo(()=>Ad(t,e),[t,e])}function Fd(t="long",e=[2018,2028],s="en-US"){const r=yn(t,e);return g.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function kd(t,e="en-US"){return g.useMemo(()=>mn(t,e),[t,e])}function Nd(t,e="en-US"){const s=g.useMemo(()=>Cd(),[]),r=g.useMemo(()=>mn(t,e),[t,e]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function bn(t,e){const s=le(t);return g.useMemo(()=>Dd(s,e),[e,s])}const ww=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function Ud(t,e,s="en-US",r=[]){const o=bn(t,e);return g.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:ww(t,e,i,r)})),[r,s,e,o,t])}function jd(t="en-US",e="short"){return g.useMemo(()=>Ld(t,e),[t,e])}function Bd({year:t=new Date().getFullYear(),month:e=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=e,n=new Date(t,o,s);return{formattedDate:$e.format(n,r)}}function Kd(t,e,s){return g.useMemo(()=>Pd(t,e,s),[t,e,s])}var Hd=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(Hd||{});function vw({locale:t="en-US",date:{year:e=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:o="long",monthFormat:n="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:d=[]}={}}){const[u,h]=g.useState(e),[f,m]=g.useState(c),[w,v]=g.useState(s),[E,T]=g.useState(r);g.useEffect(()=>{h(e)},[e]),g.useEffect(()=>{v(s)},[s]),g.useEffect(()=>{T(r)},[r]);const{yearsArray:K,yearsOptionsArray:fe,monthsArray:we,monthsOptionsArray:D,daysArray:z,daysOptionsArray:F,calendarDayArray:V,dayNamesArray:Se}=xd({locale:t,year:u,yearRange:f,month:w,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:ve}=Bd({year:u,month:w,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:m,setMonth:v,setDay:T,nextMonth:()=>{const Y=w<11?le(u):le(u+1),ee=w<11?w+1:0;if(!Rt(Y,ee,E)){const Le=At(Y,ee);T(Le)}ee===0&&h(Y),v(ee)},previousMonth:()=>{const Y=le(w===0?u-1:u),ee=w===0?11:w-1;if(!Rt(Y,ee,E)){const Le=At(Y,ee);T(Le)}ee===11&&h(Y),v(ee)},nextYear:()=>{const Y=u<f[1]?u+1:f[0],ee=le(Y);if(Rt(ee,w,E))h(Y);else{const Le=At(le(u+1),w);T(Le),h(Y)}},previousYear:()=>{const Y=u>f[0]?u-1:f[0],ee=le(Y);if(Rt(ee,w,E))h(Y);else{const Le=At(le(u-1),w);T(Le),h(Y)}}},dateState:{year:u,yearRange:f,month:w,day:E,yearsArray:K,yearsOptionsArray:fe,monthsArray:we,monthsOptionsArray:D,daysArray:z,daysOptionsArray:F,calendarDayNames:Se,calendarDayArray:V,formattedDate:ve}}}function Gd({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[o,n]=g.useState("Formatting Time..."),[i,a]=g.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:d,ready:u}=G({modelId:Q.type,modelType:Q.type,options:{}}),h=typeof t=="string"?$e.parseISO(t):t;return g.useEffect(()=>{c?a(""):e?a($e.format(h,e)):u&&a($e.format(h,d!=null&&d.selectedDateFormat?d==null?void 0:d.selectedDateFormat:""))},[c,t,e,h,d,u]),g.useEffect(()=>{s?n($e.format(h,s)):u&&n($e.format(h,d!=null&&d.selectedTimeFormat?d==null?void 0:d.selectedTimeFormat:""))},[t,s,h,d,u]),{formattedDate:i,formattedTime:o}}const zd=({secondsFromMidnight:t=0})=>{const[e,s]=g.useState(0),[r,o]=g.useState(0),[n,i]=g.useState(0),[a,c]=g.useState(new Date),{formattedTime:d}=Gd({date:a,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const u=Number(t),h=Math.floor(u/3600),f=Math.floor(u%3600/60),m=u%60;s(h),o(f),i(m);const w=new Date;w.setHours(0,0,0,0);const v=new Date(w.getTime()+u*1e3);c(new Date(v))},[t]),{hours:e,minutes:r,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},Mw=({configProperty:t})=>{const{value:e}=$d({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=zd({secondsFromMidnight:s}),c=g.useRef();return g.useEffect(()=>{const d=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{t&&t.updateProperty(d.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[t,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function Ew(t,e={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=e;g.useEffect(()=>{const o=()=>{try{t({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[t,s,r])}const _w=t=>_.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),Tw=(t=_w)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=G({modelType:Q.type,modelId:Q.type,options:{}});g.useEffect(()=>{const c=B(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),g.useEffect(()=>{const c=B(()=>{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 u;let d="";typeof c=="string"?d=c:(u=c==null?void 0:c.target)!=null&&u.value&&(d=c.target.value),d&&(n==null||n.setSelectedDateFormat(d))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(c=>c.id))??[],regionModel:n,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:e}}},Iw=t=>_.jsx("option",{title:t,value:t,children:t},t),Vd="kos:service:region:settings",Yd="timeZone",Ow=`${Vd}-${Yd}`,Sw=(t=Iw)=>{const[e,s]=g.useState([]),[r,o]=g.useState(""),{model:n,ready:i}=G({modelType:Q.type,modelId:Q.type,options:{}}),a=Ke.factory(Ow)({path:Vd,attribute:Yd});g.useEffect(()=>{const d=B(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&eo(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,t]),g.useEffect(()=>{const d=B(()=>{o(a.value||"")});return()=>{d()}},[a.value]);const c=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&eo(u)},[]);return{options:e,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:e}}},qd="kos:service:region",Wd="regionId",$w=`${qd}-${Wd}`,Dw=t=>_.jsx("option",{title:t,value:t,children:t},t),Qd=(t=Dw)=>{const[e,s]=g.useState([]),[r,o]=g.useState("factory"),{model:n,ready:i}=G({modelType:Q.type,modelId:Q.type,options:{}}),a=Ke.factory($w)({path:qd,attribute:Wd});g.useEffect(()=>{const d=B(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{d()}},[n,i,t]),g.useEffect(()=>{const d=B(()=>{o(a.value||"factory")});return()=>{d()}},[a.value]);const c=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&Xl(u)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:e}}},Cw=t=>_.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),Rw=(t=Cw)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=G({modelType:Q.type,modelId:Q.type,options:{}});g.useEffect(()=>{const c=B(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),g.useEffect(()=>{const c=B(()=>{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 u;let d="";typeof c=="string"?d=c:(u=c==null?void 0:c.target)!=null&&u.value&&(d=c.target.value),d&&(n==null||n.setSelectedTimeFormat(d))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(c=>c.id))??[],regionModel:n,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:e}}},Aw=(t,e)=>g.useMemo(()=>$o(t),e),Pw={config:{attributes:!0,childList:!0,subtree:!0}};function Lw(t,e,s=Pw){const[r,o]=g.useState(null);g.useEffect(()=>{if(!e||typeof e!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(e);o(n)},[e,s,o]),g.useEffect(()=>{if(!r)return()=>{};if(!t)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(t,n)}catch(i){p.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const Zd={validateStart:function(t){return!0},validateStop:function(t){const e=t.event.currentTarget.getBoundingClientRect(),[s,r]=t.xy;return s<e.left||s>e.right||r<e.top||r>e.bottom}},kr=p.createLogger({name:"usePressGesture",group:"kos-hooks"});function xw({onPressed:t,onRelease:e,intersectionStrategy:s=Zd}){const r=g.useRef(!1),o=cu.useGesture({onDragStart:c=>{kr.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{kr.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{kr.info("onDragEnd",c.type),r.current&&e&&(e(),r.current=!1)}}),n=()=>{t&&t(),r.current=!0},i=()=>{r.current&&e&&(e(),r.current=!1)},a=()=>{r.current&&e&&(e(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const Jd=()=>{const[t,e]=g.useState(!1),s=I.getInstance();return g.useEffect(()=>{const r=B(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function Xd(t=!1,e="2-digit"){return g.useMemo(()=>{const s=t?12:24;return Array.from({length:s},(r,o)=>{const n=t&&o===0?12:o%s;return{id:o,label:e==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[e,t])}function so(t,e="2-digit",s=0,r=0){return g.useMemo(()=>Array.from({length:t},(o,n)=>{const i=String(n+s);return{id:n+r,label:e==="2-digit"?i.padStart(2,"0"):i}}),[t,s,r,e])}function eu(t="en-US"){return g.useMemo(()=>["AM","PM"].map(e=>{const s=new Intl.DateTimeFormat(t,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(e==="AM"?0:12))[2].value;return{id:s,label:s}}),[t])}function tu({formatOptions:{hour12:t=!0,hour:e="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=Xd(t,e),i=so(60,s),a=so(60,r),c=eu(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function su(t,e){return $e.format(t,e)}function ru({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=g.useState(e),i=g.useCallback(v=>{n(E=>{const T=new Date(E);return T.setHours(Number(v)),T})},[]),a=g.useCallback(v=>{n(E=>{const T=new Date(E);return T.setMinutes(Number(v)),T})},[]),c=g.useCallback(v=>{n(E=>{const T=new Date(E);return T.setSeconds(Number(v)),T})},[]),d=g.useCallback(v=>{const E=new Date(v);n(E)},[]),u=su(o,r),{hourOptions:h,minuteOptions:f,secondOptions:m,amPmOptions:w}=tu({formatOptions:t,locale:s});return{amPmOptions:w,formattedTime:u,hourOptions:h,minuteOptions:f,secondOptions:m,setHours:i,setMinutes:a,setSeconds:c,setTime:d,time:new Date(o)}}const Fw=t=>{const{regionModel:e}=Qd(),s=g.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return ru({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function kw(t){return e=>{const[s]=Jd();return s?_.jsx(cd,{message:"Wait a moment while your project reloads..."}):_.jsx(t,{...e})}}const Xn=p.createLogger({name:"studio-properties-service",group:"Services"}),Nw="/api/kos/studio/properties",ou=async t=>{if(Xn.debug("sending GET for studio-properties"),!t)throw Xn.error("connectionId is undefined"),new Error("connectionId is undefined");return await Oe.get(Nw,{},{destinationAddress:t,timeout:500})},Uw=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:ou},Symbol.toStringTag,{value:"Module"}));var jw=Object.defineProperty,Bw=Object.getOwnPropertyDescriptor,Kw=(t,e,s,r)=>{for(var o=r>1?void 0:r?Bw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&jw(e,s,o),o};const nu="studio-properties-model",Hw="/kos/studio/properties",ei={"kos.studio.tool.legacy":1};let ro=class{constructor(t,e,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=t,this.logger=s.logger,this.data=De(),this.connectionId=e.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var t;(t=this.unsubscribe)==null||t.call(this)}async initializePropertiesSession(){this.unsubscribe=et.getInstance().subscribeTopic({topic:Hw,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await ou(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(ei);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??ei),p.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return $o(()=>this.get(t))}};ro=Kw([R(nu)],ro);const Gw=new ge({class:ro,type:nu});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>M.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>M.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>no.observer});exports.AuthState=Ya;exports.BrowserKosRouter=sc;exports.BrowserRouter=jo;exports.CanvasDispatcher=it;exports.CanvasDispatcherServices=Nm;exports.CanvasRenderer=Zo;exports.CanvasStreamer=Ub;exports.CanvasStreamerBase=vd;exports.ChildModels=Lt;exports.CompanionDecoratorMixin=ql;exports.CompanionParentModel=Rs;exports.ConfigBean=Ht;exports.CoreExtensionManager=xy;exports.CoreModels=on;exports.CreateModelTranslationsContext=pd;exports.CreateModelTranslationsProvider=mb;exports.DateDisplayFormat=Hd;exports.DateHelpers=Tu;exports.DependencyLifecycle=N;exports.DependencyModels=L;exports.Device=Js;exports.DeviceServices=oy;exports.DomIntersectionStrategy=Zd;exports.EVENT_KOS_MODEL_READY=lo;exports.EVENT_TROUBLE_ADDED=ef;exports.EVENT_TROUBLE_REMOVED=tf;exports.EXTENSION_CANVAS_RENDERER=ne;exports.EXTENSION_FEATURE_FLAG_RESOLVER=qi;exports.EXTENSION_TROUBLE_DATA_MAPPER=Bs;exports.EXTENSION_TROUBLE_MAPPER=cs;exports.ErrorBoundaryWithFallback=ld;exports.EventBus=hu;exports.EventBusFunctional=fu;exports.EventBusState=mu;exports.ExtensionManager=S;exports.FUTURE_CONTAINER_MODEL_TYPE=Cc;exports.FUTURE_MODEL_TYPE=vc;exports.FUTURE_NOT_ASSIGNED=Co;exports.FeatureFlagService=Wi;exports.FetchError=ie;exports.FutureContainerFactory=Re;exports.FutureContainerModel=Ac;exports.FutureEndState=Ce;exports.FutureFactory=ft;exports.FutureHandler=ur;exports.FutureManager=je;exports.FutureModel=Oc;exports.FutureService=Pt;exports.HEADER_CACHE_CONTROL=ii;exports.HEADER_CONTENT_TYPE=ni;exports.HEADER_DESTINATION_ADDR=Ie;exports.HEADER_FOS_REQUEST_ID=ai;exports.HEADER_METHOD=sr;exports.HEADER_ORDERED=ao;exports.HEADER_REQUEST_ID=es;exports.HEADER_REQUEST_TYPE=me;exports.HEADER_RESPONSE_ID=rr;exports.HEADER_SOURCE_ADDR=oi;exports.HEADER_TOPIC=ri;exports.HEADER_URL=lt;exports.HEADER_WORK_TRACKER=co;exports.HttpRouteHandlers=Ee;exports.KOS_MODEL_ID=Ds;exports.KeyValue=Ho;exports.KeyValueServices=Zf;exports.Kos=Z;exports.KosConfigPropertySpec=Ke;exports.KosContainerIndex=Oo;exports.KosContextBean=ec;exports.KosContextManager=j;exports.KosCore=I;exports.KosCoreModelPropertyMapper=de;exports.KosDataContainer=So;exports.KosDependencyTypes=sh;exports.KosExtensionUtils=$u;exports.KosFeatureFlags=Qi;exports.KosFetchMethods=Ea;exports.KosGlobalConfig=wo;exports.KosHttpRouteManager=Eo;exports.KosLog=p;exports.KosLogManager=jc;exports.KosLogManagerServices=rp;exports.KosMockEvents=di;exports.KosModel=xa;exports.KosModelCollectionProvider=ub;exports.KosModelContainer=be;exports.KosModelContext=wr;exports.KosModelEvents=A;exports.KosModelFactory=Ut;exports.KosModelFutureContainerMixin=ds;exports.KosModelLoader=gd;exports.KosModelLoaderDisplay=fd;exports.KosModelManager=Na;exports.KosModelProvider=dd;exports.KosModelRegistrationFactory=ge;exports.KosModelRegistry=Xr;exports.KosModelState=b;exports.KosModelSymbol=ta;exports.KosModelVisitor=Ig;exports.KosObservableData=Qa;exports.KosRegistration=Yg;exports.KosSingletonRegistration=qg;exports.KosTime=Ns;exports.KosTimeContext=un;exports.KosTimeProvider=Tb;exports.KosTimeServices=dp;exports.KosTimer=ed;exports.KosToken=tc;exports.KosTranslationProvider=Rb;exports.KosTranslations=El;exports.KosWSTransportStatus=La;exports.KosWsEvents=ts;exports.LOADER_FEATURE_FLAG=ju;exports.LOGIN_HOST=ci;exports.LOGIN_URL=lu;exports.LoadingMessage=cd;exports.LogBlock=qt;exports.LogBlockContainer=pr;exports.LogConfig=Ft;exports.LogStream=Bt;exports.LogStreamContainer=as;exports.LogStreamServices=Mp;exports.MODEL_DELETION_DELAY=ka;exports.MiddlewareChain=Wa;exports.ModelEffects=Ne;exports.MultipleFutureHandler=Df;exports.NestedModelContext=vr;exports.NetworkInterface=en;exports.NetworkInterfaceContainer=Zt;exports.NetworkInterfaceServices=fy;exports.ObservableData=De;exports.Ota=Hs;exports.OutsideAlerter=qb;exports.PLUGIN_EXTENSION_NAME=Du;exports.PORT=li;exports.PROFILE_LOG_DEBUG=Ni;exports.PROFILE_LOG_INFO=Ui;exports.PROFILE_RELAX_STORE_VALIDATION=Ru;exports.PROFILE_TOOLS_PREVIEW=ki;exports.ParentModel=xt;exports.PluginExtensionManager=Cu;exports.ProgressBar=ab;exports.ReferenceConfig=_s;exports.RegionInfo=Q;exports.RegionServices=hf;exports.RegistrationManager=C;exports.Registry=Ly;exports.STATUS=io;exports.ServiceFactory=J;exports.SingletonKosModelRegistrationFactory=ye;exports.SoftwareInfo=Gs;exports.SoftwareInfoContext=gn;exports.SoftwareInfoProvider=Sb;exports.SoftwareInfoServices=rm;exports.StateBean=Qt;exports.StateBeanServices=lm;exports.StateProp=Yo;exports.StatePropServices=wm;exports.StorageDevice=er;exports.StorageDeviceContainer=at;exports.StorageDeviceServices=wy;exports.StudioProperties=Gw;exports.StudioPropertiesServices=Uw;exports.SubscriptionHandlers=W;exports.TIMER_END=cn;exports.TIMER_EVENT=nn;exports.TOPIC_TIMER_TICK_EVENT=an;exports.TimerManager=td;exports.TokenContext=wd;exports.TokenProvider=Db;exports.Topics=jt;exports.Trans=rw;exports.TransitionMap=Ts;exports.Transitions=vo;exports.Translation=Ys;exports.TranslationContainer=Te;exports.TranslationContainerContext=fn;exports.TranslationContext=Cm;exports.TransportFactory=Br;exports.Trouble=Wt;exports.TroubleContainer=ot;exports.TroubleServices=Bp;exports.Troubles=oe;exports.UsbUpdate=rn;exports.UsbUpdateContainer=Xt;exports.UsbUpdateServices=$y;exports.WS_EVENT_TYPE=_l;exports.WebSocketEvents=Nt;exports.WebSocketTransport=et;exports.WsEventFactory=Wo;exports.acceptOrgInvitation=ad;exports.addDaysToDate=Di;exports.addFuture=Ec;exports.addMonthsToDate=$i;exports.api=Sc;exports.applyMixins=bu;exports.arraysEqual=wu;exports.buildConfigBeanModel=of;exports.buildFuture=Uo;exports.buildFutureModel=Tc;exports.cancelFuture=_c;exports.checkAppsStarted=Jg;exports.convert=xo;exports.convertFileSizeRaw=yu;exports.convertWithUnits=bf;exports.createBaseMessage=Ia;exports.createBroadcastMessageResponse=Da;exports.createCancellablePromise=tb;exports.createClient=To;exports.createFosBaseMessage=Ta;exports.createHeaders=vt;exports.createKosHtpMessageResponse=Ca;exports.createKosMessage=Sa;exports.createKosMessageResponse=Ra;exports.createKosModelFutureManager=Ny;exports.createLazyKosModelFutureManager=Uy;exports.createMessageBody=Pe;exports.createModelDependency=ma;exports.createOptionKey=Vu;exports.createPropKey=Be;exports.createReadableStream=Mt;exports.createStudioMessage=_a;exports.createStudioMessageRequest=Oa;exports.createStudioMessageResponse=$a;exports.debounce=xi;exports.del=ra;exports.deleteFuture=Mc;exports.destroyKosModel=Ue;exports.evaluateScopes=dc;exports.executeChildrenModelLifecycle=wa;exports.executeDependentModelLifecycle=wt;exports.executeListLifecycle=ba;exports.extractTrailingWildcard=ia;exports.fetchModel=Hb;exports.findModel=sg;exports.findModels=Ba;exports.formatDate=Ai;exports.formatDateSince=Si;exports.formatDateTime=Li;exports.formatTime=Pi;exports.get=sa;exports.getAllKosCompanionModels=Ka;exports.getCalendarMonthArray=Pd;exports.getCompanionMixin=Ql;exports.getConfigBean=lc;exports.getDayStrings=Ld;exports.getDays=mw;exports.getDaysArray=Dd;exports.getDaysInMonth=bo;exports.getDependenciesByLifecycle=ya;exports.getFormattedDate=yw;exports.getFormattedMonth=bw;exports.getFormattedMonthsArray=mn;exports.getFormattedYear=le;exports.getFormattedYearsArray=Ad;exports.getFutures=Ff;exports.getHttpRouteHandlers=oa;exports.getKosCompanionModel=rg;exports.getKosLocalizationDescriptor=yl;exports.getKosMessageLogging=Hi;exports.getKosModel=ja;exports.getKosModelSync=pe;exports.getKosModelType=tg;exports.getKosSessionKey=Xa;exports.getLastDayOfMonth=At;exports.getLocalizationDescriptor=Mm;exports.getLogLevel=Ki;exports.getLogMessageToStudio=Gi;exports.getMessageBody=jr;exports.getMonthsArray=Cd;exports.getObservableCompanions=og;exports.getQueryParams=ae;exports.getStartedApps=Xg;exports.getTranslations=ml;exports.getYearsArray=Rd;exports.hasCompanionMixin=Wl;exports.hasDecimals=ac;exports.hasHttpRouteHandlers=As;exports.hasKosModelFutureSupport=jy;exports.hasKosProfile=Nr;exports.hasTrailingWildcard=aa;exports.hslStringToHex=Ji;exports.hslToHex=Zi;exports.httpDelete=oh;exports.initKosProvider=bb;exports.inspectCompanionMixin=Hy;exports.inspectFutureObservability=By;exports.isBoolean=Ao;exports.isKosCompanionTypeFactory=Fa;exports.isKosDataModel=kt;exports.isKosLoggingEnabled=Lu;exports.isKosModel=ce;exports.isKosModelContainer=Mo;exports.isKosModelReady=Ps;exports.isLeapYear=yo;exports.isLocalRefId=Bg;exports.isNumber=lr;exports.isPrintable=ph;exports.isTroubleAware=Rm;exports.isValidDate=Rt;exports.kosAction=q;exports.kosAutoEffect=B;exports.kosChild=he;exports.kosCompanion=eh;exports.kosComputed=$o;exports.kosConfigBean=dr;exports.kosConfigProperty=$f;exports.kosContext=th;exports.kosDependency=ut;exports.kosEffect=nc;exports.kosFuture=ln;exports.kosLogger=nh;exports.kosModel=R;exports.kosModelEffect=na;exports.kosObservable=Do;exports.kosParentAware=ar;exports.kosReference=ih;exports.kosStateBean=Wy;exports.kosStateProp=Qy;exports.kosSubscribe=ah;exports.kosTopicHandler=x;exports.kosWhen=Gr;exports.login=od;exports.mapConfigBeanModelToDto=fc;exports.mapDataToModel=Ur;exports.mapDtoToConfigBeanModel=hc;exports.mapDtoToFutureModel=No;exports.mapDtoToFutureOptions=ko;exports.mapUpdateDtoToConfigBeanModel=gc;exports.modelEventTopicFactory=ca;exports.modelFactory=ht;exports.modelTypeEventTopicFactory=la;exports.modifyConfigBean=cc;exports.modifyFuture=kf;exports.pairedClientHeartbeat=Ag;exports.pipe=Ja;exports.post=rs;exports.preloadKosModel=ag;exports.processId=_u;exports.processMiddleware=$g;exports.put=rh;exports.registerCompanionModel=ig;exports.registerCoreModels=Vl;exports.registerExtensionPoint=ss;exports.registerHttpRoutes=$h;exports.registerKosModel=Ga;exports.registerLegacyModel=Ha;exports.resetKosModel=Ua;exports.resetPassword=id;exports.resolveBaseUrl=qa;exports.resolveChild=va;exports.resolveContainerDeltas=vu;exports.resolveItemListDeltas=Eu;exports.resolveKosCompanion=Kr;exports.resolveKosContext=Gg;exports.resolveKosProfiles=Bi;exports.resolveListDeltas=Mu;exports.resolveServiceUrl=X;exports.resolveVariable=Xi;exports.retryWithExponentialBackoff=Lg;exports.sendAsyncIntent=Qg;exports.sendBroadcastMessage=Fh;exports.sendIntent=Wg;exports.sendKosHttpMessageResponse=Pa;exports.sendKosMessage=Ph;exports.sendKosMessageResponse=Aa;exports.sendRequest=Kg;exports.sendStudioMessage=xh;exports.sendStudioMessageRequest=Lh;exports.setupCompanionDecoratorMixin=Ky;exports.setupCompleteFutureSupport=Yl;exports.setupMinimalFutureSupport=Fy;exports.startPasswordReset=nd;exports.stringComponentInsert=Id;exports.studioAcceptOrgInvitation=eb;exports.studioLogin=Zy;exports.studioResetPassword=Xy;exports.studioStartPasswordReset=Jy;exports.subscribeStore=Gy;exports.syncPublish=Hg;exports.transitionToActive=ha;exports.transitionToInit=pa;exports.transitionToLoad=fa;exports.transitionToReady=ga;exports.transitionToUnload=fh;exports.troubleByTypeReducer=Am;exports.troubleDataFactory=al;exports.unloadKosModel=eg;exports.updateCompanionModelRegistration=Cg;exports.updateModelRegistration=Dg;exports.updateRegion=Xl;exports.updateTimeZone=eo;exports.useAmPmValues=eu;exports.useCalendarDayArray=Kd;exports.useConfigBean=gw;exports.useConfigProperty=$d;exports.useContextModel=lb;exports.useContextModelHierarchy=hd;exports.useDateArrays=xd;exports.useDateProps=vw;exports.useDateRelativeConfig=Mw;exports.useDateRelativeData=zd;exports.useDayNames=jd;exports.useDayOptions=Ud;exports.useDays=bn;exports.useDevice=Md;exports.useFormattedDate=Bd;exports.useFormattedTime=su;exports.useFunctionWarmup=Ew;exports.useHourValues=Xd;exports.useKosCore=yd;exports.useKosDateFormats=Tw;exports.useKosModel=G;exports.useKosRegions=Qd;exports.useKosTime=dn;exports.useKosTimeContext=Ib;exports.useKosTimeFormats=Rw;exports.useKosTimeZones=Sw;exports.useKosTranslation=aw;exports.useKosTranslationContext=Ab;exports.useLocalComputed=Aw;exports.useModelFromHierarchy=gb;exports.useMonths=kd;exports.useMonthsOptions=Nd;exports.useMutationObserver=Lw;exports.useNetworkInterfaceContainer=Ed;exports.useOta=_d;exports.usePressGesture=xw;exports.useProjectReload=Jd;exports.useRegionTimeProps=Fw;exports.useRegionalTimeDate=Gd;exports.useSoftwareInfo=hn;exports.useSoftwareInfoContext=$b;exports.useStateProperty=Wb;exports.useStorageDeviceContainer=Td;exports.useSuspenseData=to;exports.useTimeOptions=tu;exports.useTimeProps=ru;exports.useTimeValues=so;exports.useTimer=Zb;exports.useTranslationContainer=Od;exports.useTroubleContainerModel=pn;exports.useTroubleModel=lw;exports.useTroublePresence=dw;exports.useUsbUpdateContainer=Sd;exports.useYears=yn;exports.useYearsOptions=Fd;exports.uuid=dt;exports.variableToHex=Bu;exports.waitForAppToStart=Zg;exports.waitForAppsToStart=oc;exports.waitForRequest=Io;exports.whenReady=se;exports.withDevice=Kb;exports.withKosModelFutures=ky;exports.withKosTime=Gb;exports.withNetworkInterfaceContainer=zb;exports.withOta=Vb;exports.withProjectReloading=kw;exports.withSoftwareInfo=Ob;exports.withStorageDeviceContainer=Qb;exports.withTranslationContainer=cw;exports.withTroubleContainer=uw;exports.withUsbUpdateContainer=hw;exports.wrapPromise=po;
|
|
193
|
+
`,Td=()=>{const t=Js.type;return z({modelId:t,modelType:Js.type,options:{}})};function Gb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Td();return _.jsx(o,{...r,children:_.jsx(t,{...e,device:s})})}}function zb(t,e,s){const r=new Promise(o=>{O.getInstance().whenReady().then(()=>{const{model:n}=O.getInstance().modelManager.createModelInstance(t,e??t,s);return n.whenReady().then(()=>{o(n.modelData)})})});return po(r)}function Vb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=dn();return _.jsx(o,{...r,children:_.jsx(t,{...e,kosTime:s})})}}const Id=()=>{const t=Jt.type;return z({modelId:t,modelType:Jt.type,options:{}})};function Yb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Id();return _.jsx(o,{...r,children:_.jsx(t,{...e,networkInterfaceContainer:s})})}}const Od=()=>{const t=Hs.type;return z({modelId:t,modelType:Hs.type,options:{}})};function qb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Od();return _.jsx(o,{...r,children:_.jsx(t,{...e,oTA:s})})}}function Wb(t,e){g.useEffect(()=>{function s(o){t.current&&!t.current.contains(o.target)&&e()}function r(o){o.key==="Escape"&&e()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[t,e])}function Qb(t){const e=g.useRef(null),s=t.onAlert;return Wb(e,s),_.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const Zb=t=>{var d;const{stateProp:e}=t,[s,r]=g.useState((d=t.stateProp)==null?void 0:d.value),[o,n]=g.useState(!1),[i,a]=g.useState(void 0);return g.useEffect(()=>{async function u(h){try{h&&(await ne(h),n(!0))}catch(f){a(f.message)}}u(e)},[e]),g.useEffect(()=>{const u=H(()=>{e&&o&&r(e.value)});return()=>{u()}},[o,e]),[s,{ready:o,error:i}]},Sd=()=>{const[t,e]=g.useState(!1),[s,r]=g.useState([]),o=at.type,n=z({modelId:o,modelType:at.type,options:{}});return g.useEffect(()=>{const i=H(()=>{var a,c;e(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:t,devices:s}};function Jb(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Sd();return _.jsx(o,{...r,children:_.jsx(t,{...e,storageDeviceContainer:s})})}}const Fr=p.createLogger({name:"use-timer"}),Xb=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=od.getTimer(t);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const d=$(nn,u=>{const{name:h,action:f,remainingTime:m}=u==null?void 0:u.body;h===t&&(f===cn?e({name:h,action:f,remainingTime:m,timer:n}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:m,timer:n}))});return o&&n.start(),()=>{d.unsubscribe()}},[o,e,r,t,n]),g.useEffect(()=>{if(!n||!s)return;const d=`${an}/${t}`,u=$(d,h=>{const{name:f,remainingTime:m}=h==null?void 0:h.body;f===t&&s({name:f,remainingTime:m,timer:n})});return()=>{u.unsubscribe()}},[s,t,n]);const i=g.useCallback(()=>{n?n.start():Fr.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=g.useCallback(()=>{n?n.reset():Fr.warn(`Timer with name ${t} does not exist.`)},[n,t]),c=g.useCallback(()=>{n?n.pause():Fr.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:c}},ew=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},tw=t=>t instanceof RegExp,sw=t=>typeof t=="string",rw=(t,e,s)=>{if(t===""||e==="")return t;let r=e;tw(r)||(r=new RegExp("("+ew(r)+")","gi"));const o=t.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},$d=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>sw(o)?rw(o,e,s):o)};function ow(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=$d(s,n,(i,a)=>o.type==="br"?_.jsx("br",{}):g.cloneElement(o,{key:`${r}-${a}`},i))}),s}const nw=t=>{const{i18nKey:e,t:s,defaults:r,components:o,values:n={},context:i}=t,a=s(e,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=ow(a,o||{});return _.jsx("span",{className:t.className,children:c})},Qe=new Map;function iw(t,e){if(Qe.has(t)){const s=Qe.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{Qe.set(t,{status:"finished",result:o})},o=>{throw Qe.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Qe.set(t,r),s}}function to(t,e){return iw(t,e)}const aw=async()=>{const t=await Ba(Te.type);return await ne(t.model),t.model},cw=async(t,e,s)=>{const r=t.resolveNamespace(e);await ne(r);for(const o of s){const n=t.resolveNamespace(o);await ne(n),Qe.set(o,{status:"finished",result:n})}return r},lw=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=to(Te.type,aw),i=s.join("__"),a=to(i,()=>cw(n,r,o)),c=g.useMemo(()=>({exists:u=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${u}`:u;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:g.useCallback((u,h)=>{const f=e!=null&&e.keyPrefix?`${e.keyPrefix}.${u}`:u;return a?a.resolveKey(f,h):(p.debug(`Translation model ${t} not ready for key: ${f}`),f)},[e==null?void 0:e.keyPrefix,t,a]),i18n:c}},Dd=()=>{const t=Te.type;return z({modelId:t,modelType:Te.type,options:{}})};function dw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Dd();return _.jsx(o,{...r,children:_.jsx(t,{...e,translationContainer:s})})}}const uw=t=>z({modelId:t,modelType:Qt.type}),pn=()=>z({modelId:ot.type,modelType:ot.type,options:{}}),hw=({troubleType:t,condition:e})=>{const{model:s}=pn(),[r,o]=g.useState(!1),[n,i]=g.useState([]),a=g.useCallback(()=>{var c,d;return n.length>0&&((c=n[0])!=null&&c.resolvable)?(d=n[0])==null?void 0:d.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>H(()=>{const d=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],u=e?d.filter(e):d;o(u.length>0),i(u)}),[e,s,t]),[r,a,n.length>0?n[0]:void 0,n]};function fw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=pn();return _.jsx(o,{...r,children:_.jsx(t,{...e,troubleContainer:s})})}}const Cd=()=>{const t=es.type,e=z({modelId:t,modelType:es.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=H(()=>{var d,u,h;r(((d=e.model)==null?void 0:d.isUsbInserted)??!1),n(((u=e.model)==null?void 0:u.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{c()}},[e.model]),{...e,inserted:s,updateAvailable:o,updates:i}};function gw(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Cd();return _.jsx(o,{...r,children:_.jsx(t,{...e,usbUpdateContainer:s})})}}const pw=({path:t,propKey:e})=>{const{status:s}=z({modelType:Gt.type,modelId:t,options:{path:t}}),[r,o]=g.useState(!1),[n,i]=g.useState(),[a,c]=g.useState(""),[d,u]=g.useState(),h=f=>{n&&e&&n.updateProperty(e,f)};return g.useEffect(()=>{var f;s.model&&i(s.model),s.model&&e&&((f=s.model)!=null&&f.props.has(e)?c(s.model.props[e]):u(`property ${e} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,e]),g.useEffect(()=>{e&&M.autorun(()=>{const f=n==null?void 0:n.props[e];c(f||"")})},[n,e]),{config:n,ready:r,value:a,error:d,updateValue:h}},mw=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},Rd=({configProperty:t,optionsTransformer:e})=>{const[s,r]=g.useState(!1),[o,n]=g.useState(""),[i,a]=g.useReducer(mw,{value:String(t==null?void 0:t.value),displayValue:t==null?void 0:t.displayValue,significantValue:t==null?void 0:t.significantValue,unit:t==null?void 0:t.unit,options:t==null?void 0:t.options,mappedOptions:[],updateProperty:t==null?void 0:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}),c=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&(t==null||t.updateProperty(u))},[t]);return g.useEffect(()=>{async function d(u){try{u&&(await ne(u),r(!0))}catch(h){n(h.message)}}d(t)},[t]),g.useEffect(()=>{const d=H(()=>{if(t&&s){let u=[];e&&(u=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:u,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{d()}},[t,e,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function yw(t,e){const s=e??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return t===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[t]??0}function bw(t,e){return new Date(t,e,0).getDate()}function Pd(t,e){const s=yw(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function Ad(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function Ld(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function xd(t,e=[2018,2028]){const s=Ld(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function mn(t="numeric",e="en-US"){const s=new Intl.DateTimeFormat(e,{month:t,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function ww({locale:t="en-US",year:e,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(e,i,r),c=new Intl.DateTimeFormat(t,{month:o.month}).format(a),d=new Intl.DateTimeFormat(t,{year:o.year}).format(a),u=new Intl.DateTimeFormat(t,{day:o.day}).format(a);return n?n=="MMDDYY"?`${c} ${u} ${d}`:n==="DDMMYY"?`${u} ${c} ${d}`:n==="YYMMDD"?`${d} ${c} ${u}`:`${d} ${u} ${c}`:new Intl.DateTimeFormat(t,o).format(a)}function ue(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function vw(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function Fd(t,e,s){const r=ue(e),o=new Date(r,t,1).getDay(),n=new Date(r,t+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function Pt(t,e,s){const r=e-1,o=new Date(t,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function At(t,e){return new Date(t,e,0).getDate()}function kd(t="en-US",e="short"){const s=new Intl.DateTimeFormat(t,{weekday:e}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function Nd({locale:t="en-US",year:e=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:o=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=yn(n,r),d=Ud(n,r,t),u=jd(i,t),h=Bd(i,t),f=bn(e,s),m=Kd(e,s,t,o),w=zd(s,e,m),v=Hd(t,a);return{daysArray:f,monthsArray:u,yearsArray:c,yearsOptionsArray:d,monthsOptionsArray:h,daysOptionsArray:m,calendarDayArray:w,dayNamesArray:v}}function yn(t="long",e=[2018,2028]){return g.useMemo(()=>xd(t,e),[t,e])}function Ud(t="long",e=[2018,2028],s="en-US"){const r=yn(t,e);return g.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function jd(t,e="en-US"){return g.useMemo(()=>mn(t,e),[t,e])}function Bd(t,e="en-US"){const s=g.useMemo(()=>Ad(),[]),r=g.useMemo(()=>mn(t,e),[t,e]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function bn(t,e){const s=ue(t);return g.useMemo(()=>Pd(s,e),[e,s])}const Mw=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function Kd(t,e,s="en-US",r=[]){const o=bn(t,e);return g.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:Mw(t,e,i,r)})),[r,s,e,o,t])}function Hd(t="en-US",e="short"){return g.useMemo(()=>kd(t,e),[t,e])}function Gd({year:t=new Date().getFullYear(),month:e=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=e,n=new Date(t,o,s);return{formattedDate:$e.format(n,r)}}function zd(t,e,s){return g.useMemo(()=>Fd(t,e,s),[t,e,s])}var Vd=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(Vd||{});function Ew({locale:t="en-US",date:{year:e=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:o="long",monthFormat:n="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:d=[]}={}}){const[u,h]=g.useState(e),[f,m]=g.useState(c),[w,v]=g.useState(s),[E,T]=g.useState(r);g.useEffect(()=>{h(e)},[e]),g.useEffect(()=>{v(s)},[s]),g.useEffect(()=>{T(r)},[r]);const{yearsArray:k,yearsOptionsArray:se,monthsArray:P,monthsOptionsArray:I,daysArray:V,daysOptionsArray:N,calendarDayArray:Y,dayNamesArray:Se}=Nd({locale:t,year:u,yearRange:f,month:w,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:d}),{formattedDate:ve}=Gd({year:u,month:w,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:m,setMonth:v,setDay:T,nextMonth:()=>{const q=w<11?ue(u):ue(u+1),re=w<11?w+1:0;if(!Pt(q,re,E)){const Le=At(q,re);T(Le)}re===0&&h(q),v(re)},previousMonth:()=>{const q=ue(w===0?u-1:u),re=w===0?11:w-1;if(!Pt(q,re,E)){const Le=At(q,re);T(Le)}re===11&&h(q),v(re)},nextYear:()=>{const q=u<f[1]?u+1:f[0],re=ue(q);if(Pt(re,w,E))h(q);else{const Le=At(ue(u+1),w);T(Le),h(q)}},previousYear:()=>{const q=u>f[0]?u-1:f[0],re=ue(q);if(Pt(re,w,E))h(q);else{const Le=At(ue(u-1),w);T(Le),h(q)}}},dateState:{year:u,yearRange:f,month:w,day:E,yearsArray:k,yearsOptionsArray:se,monthsArray:P,monthsOptionsArray:I,daysArray:V,daysOptionsArray:N,calendarDayNames:Se,calendarDayArray:Y,formattedDate:ve}}}function Yd({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[o,n]=g.useState("Formatting Time..."),[i,a]=g.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:d,ready:u}=z({modelId:Z.type,modelType:Z.type,options:{}}),h=typeof t=="string"?$e.parseISO(t):t;return g.useEffect(()=>{c?a(""):e?a($e.format(h,e)):u&&a($e.format(h,d!=null&&d.selectedDateFormat?d==null?void 0:d.selectedDateFormat:""))},[c,t,e,h,d,u]),g.useEffect(()=>{s?n($e.format(h,s)):u&&n($e.format(h,d!=null&&d.selectedTimeFormat?d==null?void 0:d.selectedTimeFormat:""))},[t,s,h,d,u]),{formattedDate:i,formattedTime:o}}const qd=({secondsFromMidnight:t=0})=>{const[e,s]=g.useState(0),[r,o]=g.useState(0),[n,i]=g.useState(0),[a,c]=g.useState(new Date),{formattedTime:d}=Yd({date:a,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const u=Number(t),h=Math.floor(u/3600),f=Math.floor(u%3600/60),m=u%60;s(h),o(f),i(m);const w=new Date;w.setHours(0,0,0,0);const v=new Date(w.getTime()+u*1e3);c(new Date(v))},[t]),{hours:e,minutes:r,seconds:n,formattedTime:d,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},_w=({configProperty:t})=>{const{value:e}=Rd({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=qd({secondsFromMidnight:s}),c=g.useRef();return g.useEffect(()=>{const d=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{t&&t.updateProperty(d.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[t,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function Tw(t,e={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=e;g.useEffect(()=>{const o=()=>{try{t({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[t,s,r])}const Iw=t=>_.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),Ow=(t=Iw)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=z({modelType:Z.type,modelId:Z.type,options:{}});g.useEffect(()=>{const c=H(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),g.useEffect(()=>{const c=H(()=>{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 u;let d="";typeof c=="string"?d=c:(u=c==null?void 0:c.target)!=null&&u.value&&(d=c.target.value),d&&(n==null||n.setSelectedDateFormat(d))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(c=>c.id))??[],regionModel:n,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:e}}},Sw=t=>_.jsx("option",{title:t,value:t,children:t},t),Wd="kos:service:region:settings",Qd="timeZone",$w=`${Wd}-${Qd}`,Dw=(t=Sw)=>{const[e,s]=g.useState([]),[r,o]=g.useState(""),{model:n,ready:i}=z({modelType:Z.type,modelId:Z.type,options:{}}),a=Ke.factory($w)({path:Wd,attribute:Qd});g.useEffect(()=>{const d=H(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&eo(n==null?void 0:n.timeZones[0])});return()=>{d()}},[n,i,t]),g.useEffect(()=>{const d=H(()=>{o(a.value||"")});return()=>{d()}},[a.value]);const c=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&eo(u)},[]);return{options:e,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:e}}},Zd="kos:service:region",Jd="regionId",Cw=`${Zd}-${Jd}`,Rw=t=>_.jsx("option",{title:t,value:t,children:t},t),Xd=(t=Rw)=>{const[e,s]=g.useState([]),[r,o]=g.useState("factory"),{model:n,ready:i}=z({modelType:Z.type,modelId:Z.type,options:{}}),a=Ke.factory(Cw)({path:Zd,attribute:Jd});g.useEffect(()=>{const d=H(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{d()}},[n,i,t]),g.useEffect(()=>{const d=H(()=>{o(a.value||"factory")});return()=>{d()}},[a.value]);const c=g.useCallback(d=>{var h;let u="factory";typeof d=="string"?u=d:(h=d==null?void 0:d.target)!=null&&h.value&&(u=d.target.value),u&&sd(u)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:e}}},Pw=t=>_.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),Aw=(t=Pw)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=z({modelType:Z.type,modelId:Z.type,options:{}});g.useEffect(()=>{const c=H(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),g.useEffect(()=>{const c=H(()=>{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 u;let d="";typeof c=="string"?d=c:(u=c==null?void 0:c.target)!=null&&u.value&&(d=c.target.value),d&&(n==null||n.setSelectedTimeFormat(d))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(c=>c.id))??[],regionModel:n,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:e}}},Lw=(t,e)=>g.useMemo(()=>$o(t),e),xw={config:{attributes:!0,childList:!0,subtree:!0}};function Fw(t,e,s=xw){const[r,o]=g.useState(null);g.useEffect(()=>{if(!e||typeof e!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(e);o(n)},[e,s,o]),g.useEffect(()=>{if(!r)return()=>{};if(!t)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(t,n)}catch(i){p.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const eu={validateStart:function(t){return!0},validateStop:function(t){const e=t.event.currentTarget.getBoundingClientRect(),[s,r]=t.xy;return s<e.left||s>e.right||r<e.top||r>e.bottom}},kr=p.createLogger({name:"usePressGesture",group:"kos-hooks"});function kw({onPressed:t,onRelease:e,intersectionStrategy:s=eu}){const r=g.useRef(!1),o=uu.useGesture({onDragStart:c=>{kr.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{kr.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{kr.info("onDragEnd",c.type),r.current&&e&&(e(),r.current=!1)}}),n=()=>{t&&t(),r.current=!0},i=()=>{r.current&&e&&(e(),r.current=!1)},a=()=>{r.current&&e&&(e(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const tu=()=>{const[t,e]=g.useState(!1),s=O.getInstance();return g.useEffect(()=>{const r=H(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function su(t=!1,e="2-digit"){return g.useMemo(()=>{const s=t?12:24;return Array.from({length:s},(r,o)=>{const n=t&&o===0?12:o%s;return{id:o,label:e==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[e,t])}function so(t,e="2-digit",s=0,r=0){return g.useMemo(()=>Array.from({length:t},(o,n)=>{const i=String(n+s);return{id:n+r,label:e==="2-digit"?i.padStart(2,"0"):i}}),[t,s,r,e])}function ru(t="en-US"){return g.useMemo(()=>["AM","PM"].map(e=>{const s=new Intl.DateTimeFormat(t,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(e==="AM"?0:12))[2].value;return{id:s,label:s}}),[t])}function ou({formatOptions:{hour12:t=!0,hour:e="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=su(t,e),i=so(60,s),a=so(60,r),c=ru(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function nu(t,e){return $e.format(t,e)}function iu({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=g.useState(e),i=g.useCallback(v=>{n(E=>{const T=new Date(E);return T.setHours(Number(v)),T})},[]),a=g.useCallback(v=>{n(E=>{const T=new Date(E);return T.setMinutes(Number(v)),T})},[]),c=g.useCallback(v=>{n(E=>{const T=new Date(E);return T.setSeconds(Number(v)),T})},[]),d=g.useCallback(v=>{const E=new Date(v);n(E)},[]),u=nu(o,r),{hourOptions:h,minuteOptions:f,secondOptions:m,amPmOptions:w}=ou({formatOptions:t,locale:s});return{amPmOptions:w,formattedTime:u,hourOptions:h,minuteOptions:f,secondOptions:m,setHours:i,setMinutes:a,setSeconds:c,setTime:d,time:new Date(o)}}const Nw=t=>{const{regionModel:e}=Xd(),s=g.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return iu({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function Uw(t){return e=>{const[s]=tu();return s?_.jsx(ud,{message:"Wait a moment while your project reloads..."}):_.jsx(t,{...e})}}const ei=p.createLogger({name:"studio-properties-service",group:"Services"}),jw="/api/kos/studio/properties",au=async t=>{if(ei.debug("sending GET for studio-properties"),!t)throw ei.error("connectionId is undefined"),new Error("connectionId is undefined");return await Oe.get(jw,{},{destinationAddress:t,timeout:500})},Bw=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:au},Symbol.toStringTag,{value:"Module"}));var Kw=Object.defineProperty,Hw=Object.getOwnPropertyDescriptor,Gw=(t,e,s,r)=>{for(var o=r>1?void 0:r?Hw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Kw(e,s,o),o};const cu="studio-properties-model",zw="/kos/studio/properties",ti={"kos.studio.tool.legacy":1};let ro=class{constructor(t,e,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=t,this.logger=s.logger,this.data=De(),this.connectionId=e.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var t;(t=this.unsubscribe)==null||t.call(this)}async initializePropertiesSession(){this.unsubscribe=et.getInstance().subscribeTopic({topic:zw,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await au(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(ti);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??ti),p.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return $o(()=>this.get(t))}};ro=Gw([R(cu)],ro);const Vw=new pe({class:ro,type:cu});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>M.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>M.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>no.observer});exports.AuthState=qa;exports.BrowserKosRouter=rc;exports.BrowserRouter=jo;exports.CanvasDispatcher=it;exports.CanvasDispatcherServices=Bm;exports.CanvasRenderer=Zo;exports.CanvasStreamer=Bb;exports.CanvasStreamerBase=_d;exports.ChildModels=xt;exports.CompanionDecoratorMixin=Zl;exports.CompanionParentModel=Rs;exports.ConfigBean=Gt;exports.CoreExtensionManager=ky;exports.CoreModels=on;exports.CreateModelTranslationsContext=bd;exports.CreateModelTranslationsProvider=bb;exports.DateDisplayFormat=Vd;exports.DateHelpers=Su;exports.DependencyLifecycle=j;exports.DependencyModels=x;exports.Device=Js;exports.DeviceServices=iy;exports.DomIntersectionStrategy=eu;exports.EVENT_KOS_MODEL_READY=lo;exports.EVENT_TROUBLE_ADDED=og;exports.EVENT_TROUBLE_REMOVED=ng;exports.EXTENSION_CANVAS_RENDERER=ee;exports.EXTENSION_FEATURE_FLAG_RESOLVER=Wi;exports.EXTENSION_TROUBLE_DATA_MAPPER=Bs;exports.EXTENSION_TROUBLE_MAPPER=ls;exports.ErrorBoundaryWithFallback=hd;exports.EventBus=pu;exports.EventBusFunctional=yu;exports.EventBusState=wu;exports.ExtensionManager=S;exports.FUTURE_CONTAINER_MODEL_TYPE=Rc;exports.FUTURE_MODEL_TYPE=Mc;exports.FUTURE_NOT_ASSIGNED=Co;exports.FeatureFlagService=Qi;exports.FetchError=ce;exports.FutureContainerFactory=Re;exports.FutureContainerModel=Ac;exports.FutureEndState=Ce;exports.FutureFactory=gt;exports.FutureHandler=ur;exports.FutureManager=je;exports.FutureModel=Sc;exports.FutureService=Lt;exports.HEADER_CACHE_CONTROL=ai;exports.HEADER_CONTENT_TYPE=ii;exports.HEADER_DESTINATION_ADDR=Ie;exports.HEADER_FOS_REQUEST_ID=ci;exports.HEADER_METHOD=sr;exports.HEADER_ORDERED=ao;exports.HEADER_REQUEST_ID=ts;exports.HEADER_REQUEST_TYPE=ye;exports.HEADER_RESPONSE_ID=rr;exports.HEADER_SOURCE_ADDR=ni;exports.HEADER_TOPIC=oi;exports.HEADER_URL=lt;exports.HEADER_WORK_TRACKER=co;exports.HttpRouteHandlers=Ee;exports.KOS_MODEL_ID=Ds;exports.KeyValue=Ho;exports.KeyValueServices=ep;exports.Kos=J;exports.KosConfigPropertySpec=Ke;exports.KosContainerIndex=Oo;exports.KosContextBean=tc;exports.KosContextManager=K;exports.KosCore=O;exports.KosCoreModelPropertyMapper=he;exports.KosDataContainer=So;exports.KosDependencyTypes=nh;exports.KosExtensionUtils=Ru;exports.KosFeatureFlags=Zi;exports.KosFetchMethods=_a;exports.KosGlobalConfig=wo;exports.KosHttpRouteManager=Eo;exports.KosLog=p;exports.KosLogManager=Bc;exports.KosLogManagerServices=ip;exports.KosMockEvents=ui;exports.KosModel=Fa;exports.KosModelCollectionProvider=fb;exports.KosModelContainer=we;exports.KosModelContext=wr;exports.KosModelEvents=A;exports.KosModelFactory=jt;exports.KosModelFutureContainerMixin=ds;exports.KosModelLoader=md;exports.KosModelLoaderDisplay=yd;exports.KosModelManager=Ua;exports.KosModelProvider=fd;exports.KosModelRegistrationFactory=pe;exports.KosModelRegistry=Xr;exports.KosModelState=b;exports.KosModelSymbol=sa;exports.KosModelVisitor=Df;exports.KosObservableData=Za;exports.KosRegistration=Zf;exports.KosSingletonRegistration=Jf;exports.KosTime=Ns;exports.KosTimeContext=un;exports.KosTimeProvider=Ob;exports.KosTimeServices=fp;exports.KosTimer=rd;exports.KosToken=sc;exports.KosTranslationProvider=Ab;exports.KosTranslations=_l;exports.KosWSTransportStatus=xa;exports.KosWsEvents=ss;exports.LOADER_FEATURE_FLAG=Hu;exports.LOGIN_HOST=li;exports.LOGIN_URL=hu;exports.LoadingMessage=ud;exports.LogBlock=Wt;exports.LogBlockContainer=pr;exports.LogConfig=kt;exports.LogStream=Kt;exports.LogStreamContainer=cs;exports.LogStreamServices=Tp;exports.MODEL_DELETION_DELAY=Na;exports.MiddlewareChain=Qa;exports.ModelEffects=Ne;exports.MultipleFutureHandler=Pg;exports.NestedModelContext=vr;exports.NetworkInterface=en;exports.NetworkInterfaceContainer=Jt;exports.NetworkInterfaceServices=my;exports.ObservableData=De;exports.Ota=Hs;exports.OutsideAlerter=Qb;exports.PLUGIN_EXTENSION_NAME=Pu;exports.PORT=di;exports.PROFILE_LOG_DEBUG=Ui;exports.PROFILE_LOG_INFO=ji;exports.PROFILE_RELAX_STORE_VALIDATION=Lu;exports.PROFILE_TOOLS_PREVIEW=Ni;exports.ParentModel=Ft;exports.PluginExtensionManager=Au;exports.ProgressBar=lb;exports.ReferenceConfig=_s;exports.RegionInfo=Z;exports.RegionServices=pg;exports.RegistrationManager=C;exports.Registry=Fy;exports.STATUS=io;exports.ServiceFactory=X;exports.SingletonKosModelRegistrationFactory=be;exports.SoftwareInfo=Gs;exports.SoftwareInfoContext=fn;exports.SoftwareInfoProvider=Db;exports.SoftwareInfoServices=im;exports.StateBean=Zt;exports.StateBeanServices=hm;exports.StateProp=Yo;exports.StatePropServices=Em;exports.StorageDevice=er;exports.StorageDeviceContainer=at;exports.StorageDeviceServices=My;exports.StudioProperties=Vw;exports.StudioPropertiesServices=Bw;exports.SubscriptionHandlers=Q;exports.TIMER_END=cn;exports.TIMER_EVENT=nn;exports.TOPIC_TIMER_TICK_EVENT=an;exports.TimerManager=od;exports.TokenContext=Ed;exports.TokenProvider=Rb;exports.Topics=Bt;exports.Trans=nw;exports.TransitionMap=Ts;exports.Transitions=vo;exports.Translation=Ys;exports.TranslationContainer=Te;exports.TranslationContainerContext=gn;exports.TranslationContext=Am;exports.TransportFactory=Br;exports.Trouble=Qt;exports.TroubleContainer=ot;exports.TroubleServices=Gp;exports.Troubles=ae;exports.UsbUpdate=rn;exports.UsbUpdateContainer=es;exports.UsbUpdateServices=Cy;exports.WS_EVENT_TYPE=Tl;exports.WebSocketEvents=Ut;exports.WebSocketTransport=et;exports.WsEventFactory=Wo;exports.acceptOrgInvitation=dd;exports.addDaysToDate=Ci;exports.addFuture=_c;exports.addMonthsToDate=Di;exports.api=$c;exports.applyMixins=Mu;exports.arraysEqual=Eu;exports.buildConfigBeanModel=cg;exports.buildFuture=Uo;exports.buildFutureModel=Ic;exports.cancelFuture=Tc;exports.checkAppsStarted=sg;exports.convert=xo;exports.convertFileSizeRaw=vu;exports.convertWithUnits=Mg;exports.createBaseMessage=Oa;exports.createBroadcastMessageResponse=Ca;exports.createCancellablePromise=rb;exports.createClient=To;exports.createFosBaseMessage=Ia;exports.createHeaders=Mt;exports.createKosHtpMessageResponse=Ra;exports.createKosMessage=$a;exports.createKosMessageResponse=Pa;exports.createKosModelFutureManager=jy;exports.createLazyKosModelFutureManager=By;exports.createMessageBody=Ae;exports.createModelDependency=ya;exports.createOptionKey=Wu;exports.createPropKey=Be;exports.createReadableStream=Et;exports.createStudioMessage=Ta;exports.createStudioMessageRequest=Sa;exports.createStudioMessageResponse=Da;exports.debounce=Fi;exports.del=oa;exports.deleteFuture=Ec;exports.destroyKosModel=Ue;exports.evaluateScopes=uc;exports.executeChildrenModelLifecycle=va;exports.executeDependentModelLifecycle=vt;exports.executeListLifecycle=wa;exports.extractTrailingWildcard=aa;exports.fetchModel=zb;exports.findModel=nf;exports.findModels=Ka;exports.formatDate=Ai;exports.formatDateSince=$i;exports.formatDateTime=xi;exports.formatTime=Li;exports.get=ra;exports.getAllKosCompanionModels=Ha;exports.getCalendarMonthArray=Fd;exports.getCompanionMixin=Xl;exports.getConfigBean=dc;exports.getDayStrings=kd;exports.getDays=bw;exports.getDaysArray=Pd;exports.getDaysInMonth=bo;exports.getDependenciesByLifecycle=ba;exports.getFormattedDate=ww;exports.getFormattedMonth=vw;exports.getFormattedMonthsArray=mn;exports.getFormattedYear=ue;exports.getFormattedYearsArray=xd;exports.getFutures=Ug;exports.getHttpRouteHandlers=na;exports.getKosCompanionModel=af;exports.getKosLocalizationDescriptor=bl;exports.getKosMessageLogging=Gi;exports.getKosModel=Ba;exports.getKosModelSync=me;exports.getKosModelType=of;exports.getKosSessionKey=ec;exports.getLastDayOfMonth=At;exports.getLocalizationDescriptor=Tm;exports.getLogLevel=Hi;exports.getLogMessageToStudio=zi;exports.getMessageBody=jr;exports.getMonthsArray=Ad;exports.getObservableCompanions=cf;exports.getQueryParams=le;exports.getStartedApps=rg;exports.getTranslations=yl;exports.getYearsArray=Ld;exports.hasCompanionMixin=Jl;exports.hasDecimals=cc;exports.hasHttpRouteHandlers=Ps;exports.hasKosModelFutureSupport=Ky;exports.hasKosProfile=Nr;exports.hasTrailingWildcard=ca;exports.hslStringToHex=Xi;exports.hslToHex=Ji;exports.httpDelete=ah;exports.initKosProvider=vb;exports.inspectCompanionMixin=zy;exports.inspectFutureObservability=Hy;exports.isBoolean=Po;exports.isKosCompanionTypeFactory=ka;exports.isKosDataModel=Nt;exports.isKosLoggingEnabled=ku;exports.isKosModel=de;exports.isKosModelContainer=Mo;exports.isKosModelReady=As;exports.isLeapYear=yo;exports.isLocalRefId=zf;exports.isNumber=lr;exports.isPrintable=bh;exports.isTroubleAware=Lm;exports.isValidDate=Pt;exports.kosAction=W;exports.kosAutoEffect=H;exports.kosChild=ge;exports.kosCompanion=rh;exports.kosComputed=$o;exports.kosConfigBean=dr;exports.kosConfigProperty=Rg;exports.kosContext=oh;exports.kosDependency=ut;exports.kosEffect=ic;exports.kosFuture=ln;exports.kosLogger=ch;exports.kosModel=R;exports.kosModelEffect=ia;exports.kosObservable=Do;exports.kosParentAware=ar;exports.kosReference=lh;exports.kosStateBean=Zy;exports.kosStateProp=Jy;exports.kosSubscribe=dh;exports.kosTopicHandler=F;exports.kosWhen=Gr;exports.login=ad;exports.mapConfigBeanModelToDto=pc;exports.mapDataToModel=Ur;exports.mapDtoToConfigBeanModel=fc;exports.mapDtoToFutureModel=No;exports.mapDtoToFutureOptions=ko;exports.mapUpdateDtoToConfigBeanModel=gc;exports.modelEventTopicFactory=la;exports.modelFactory=ht;exports.modelTypeEventTopicFactory=da;exports.modifyConfigBean=lc;exports.modifyFuture=jg;exports.pairedClientHeartbeat=Ff;exports.pipe=Xa;exports.post=os;exports.preloadKosModel=uf;exports.processId=Ou;exports.processMiddleware=Pf;exports.put=ih;exports.registerCompanionModel=df;exports.registerCoreModels=Wl;exports.registerExtensionPoint=rs;exports.registerHttpRoutes=Rh;exports.registerKosModel=za;exports.registerLegacyModel=Ga;exports.resetKosModel=ja;exports.resetPassword=ld;exports.resolveBaseUrl=Wa;exports.resolveChild=Ma;exports.resolveContainerDeltas=_u;exports.resolveItemListDeltas=Iu;exports.resolveKosCompanion=Kr;exports.resolveKosContext=qf;exports.resolveKosProfiles=Ki;exports.resolveListDeltas=Tu;exports.resolveServiceUrl=te;exports.resolveVariable=ea;exports.retryWithExponentialBackoff=Nf;exports.sendAsyncIntent=eg;exports.sendBroadcastMessage=Uh;exports.sendIntent=Xf;exports.sendKosHttpMessageResponse=La;exports.sendKosMessage=Fh;exports.sendKosMessageResponse=Aa;exports.sendRequest=Vf;exports.sendStudioMessage=Nh;exports.sendStudioMessageRequest=kh;exports.setupCompanionDecoratorMixin=Gy;exports.setupCompleteFutureSupport=Ql;exports.setupMinimalFutureSupport=Ny;exports.startPasswordReset=cd;exports.stringComponentInsert=$d;exports.studioAcceptOrgInvitation=sb;exports.studioLogin=Xy;exports.studioResetPassword=tb;exports.studioStartPasswordReset=eb;exports.subscribeStore=Vy;exports.syncPublish=Yf;exports.transitionToActive=fa;exports.transitionToInit=ma;exports.transitionToLoad=pa;exports.transitionToReady=ga;exports.transitionToUnload=yh;exports.troubleByTypeReducer=xm;exports.troubleDataFactory=cl;exports.unloadKosModel=rf;exports.updateCompanionModelRegistration=Lf;exports.updateModelRegistration=Af;exports.updateRegion=sd;exports.updateTimeZone=eo;exports.useAmPmValues=ru;exports.useCalendarDayArray=zd;exports.useConfigBean=pw;exports.useConfigProperty=Rd;exports.useContextModel=ub;exports.useContextModelHierarchy=pd;exports.useDateArrays=Nd;exports.useDateProps=Ew;exports.useDateRelativeConfig=_w;exports.useDateRelativeData=qd;exports.useDayNames=Hd;exports.useDayOptions=Kd;exports.useDays=bn;exports.useDevice=Td;exports.useFormattedDate=Gd;exports.useFormattedTime=nu;exports.useFunctionWarmup=Tw;exports.useHourValues=su;exports.useKosCore=vd;exports.useKosDateFormats=Ow;exports.useKosModel=z;exports.useKosRegions=Xd;exports.useKosTime=dn;exports.useKosTimeContext=Sb;exports.useKosTimeFormats=Aw;exports.useKosTimeZones=Dw;exports.useKosTranslation=lw;exports.useKosTranslationContext=Lb;exports.useLocalComputed=Lw;exports.useModelFromHierarchy=pb;exports.useMonths=jd;exports.useMonthsOptions=Bd;exports.useMutationObserver=Fw;exports.useNetworkInterfaceContainer=Id;exports.useOta=Od;exports.usePressGesture=kw;exports.useProjectReload=tu;exports.useRegionTimeProps=Nw;exports.useRegionalTimeDate=Yd;exports.useSoftwareInfo=hn;exports.useSoftwareInfoContext=Cb;exports.useStateProperty=Zb;exports.useStorageDeviceContainer=Sd;exports.useSuspenseData=to;exports.useTimeOptions=ou;exports.useTimeProps=iu;exports.useTimeValues=so;exports.useTimer=Xb;exports.useTranslationContainer=Dd;exports.useTroubleContainerModel=pn;exports.useTroubleModel=uw;exports.useTroublePresence=hw;exports.useUsbUpdateContainer=Cd;exports.useYears=yn;exports.useYearsOptions=Ud;exports.uuid=dt;exports.variableToHex=Gu;exports.waitForAppToStart=tg;exports.waitForAppsToStart=nc;exports.waitForRequest=Io;exports.whenReady=ne;exports.withDevice=Gb;exports.withKosModelFutures=Uy;exports.withKosTime=Vb;exports.withNetworkInterfaceContainer=Yb;exports.withOta=qb;exports.withProjectReloading=Uw;exports.withSoftwareInfo=$b;exports.withStorageDeviceContainer=Jb;exports.withTranslationContainer=dw;exports.withTroubleContainer=fw;exports.withUsbUpdateContainer=gw;exports.wrapPromise=po;
|
|
194
194
|
//# sourceMappingURL=index.cjs.map
|