@kosdev-code/kos-ui-sdk 2.1.25 → 2.1.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/core/core/decorators/kos-service-request.d.ts +32 -2
- package/core/core/decorators/kos-service-request.d.ts.map +1 -1
- package/index.cjs +54 -54
- package/index.cjs.map +1 -1
- package/index.js +3056 -3018
- package/index.js.map +1 -1
- package/models/utils/index.d.ts +1 -0
- package/models/utils/index.d.ts.map +1 -1
- package/models/utils/openapi-index.d.ts +3 -0
- package/models/utils/openapi-index.d.ts.map +1 -0
- package/models/utils/service.d.ts +20 -2
- package/models/utils/service.d.ts.map +1 -1
- package/models/utils/services/kos/daily/openapi.d.ts +4349 -0
- package/models/utils/services/kos/daily/service.d.ts +120 -0
- package/models/utils/services/kos/daily/service.d.ts.map +1 -0
- package/models/utils/services/vfs/daily/openapi.d.ts +51 -0
- package/models/utils/services/vfs/daily/service.d.ts +120 -0
- package/models/utils/services/vfs/daily/service.d.ts.map +1 -0
- package/models/utils/services-index.d.ts +3 -0
- package/models/utils/services-index.d.ts.map +1 -0
- package/package.json +2 -2
package/index.cjs
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
"use strict";var Ph=Object.defineProperty;var Rh=(t,e,s)=>e in t?Ph(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var c=(t,e,s)=>(Rh(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("loglevel"),M=require("mobx"),b=require("robot3"),je=require("date-fns"),T=require("@emotion/react/jsx-runtime"),Xo=require("@emotion/styled"),ba=require("react-dom"),Ze=require("@emotion/react"),g=require("react"),Jo=require("mobx-react-lite"),kh=require("@use-gesture/react"),jr="method",va="topic",Ft="url",ks="request-id",Br="response-id",en="status",Ne="dst-addr",wa="src-addr",Oe="type",tn="ordered",sn="tracker",Ea="Content-Type",Ma="Cache-Control",Ta="requestId",Sa=process.env.KOS_LOGIN_URL||"http://localhost",Ia=process.env.KOS_APP_PORT||"8080",Lh=`${Sa}:${Ia}`,dr="{MODEL_ID}";var Ls=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(Ls||{}),_a=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(_a||{});const rn="/kos/model/ready/";D.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const z=globalThis.kos.subscriptions,Fh=()=>Symbol("eventKey");function on(t){return z[t]&&Object.getOwnPropertySymbols(z[t]).length>0}function C(t,e){const s=Fh();return z[t]||(D.debug(`Initializing subscription for ${t}`),z[t]={}),D.debug(`Subscribing to ${t} with id ${s.toString()}`),z[t][s]=e,{count:z[t]?Object.getOwnPropertySymbols(z[t]).length:0,unsubscribe:()=>(D.debug(`Unsubscribing from ${t} with id ${s.toString()}`),z[t]&&z[t][s]&&delete z[t][s],z[t]&&Object.getOwnPropertySymbols(z[t]).length===0&&delete z[t],{count:z[t]?Object.getOwnPropertySymbols(z[t]).length:0})}}function V(t,e,s={}){if(!z[t]||Object.getOwnPropertySymbols(z[t]).length===0)return D.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(z[t]).length;return Object.getOwnPropertySymbols(z[t]).forEach(o=>{if(s.sync){const n=s.sync;D.debug(`Performing sync publish for ${t} with sync id ${n}`),z[t][o]({body:e,headers:s}).then(i=>{D.debug(`Response recieved for ${n}, publishing back to source.`),V(n,i)})}else D.debug(`Performing async publish for ${t}`),z[t][o]({body:e,headers:s})}),{eventType:t,subscribers:r}}function Nh(){D.warn("Resetting event bus"),Object.keys(z).forEach(t=>delete z[t])}function Oa(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function nn(t,e){return new Promise((s,r)=>{let o=null;const n=Oa(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const Uh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:on,once:Oa,publish:V,reset:Nh,subscribe:C,waitFor:nn},Symbol.toStringTag,{value:"Module"}));function Hr(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function Kr(t,e){return new Promise((s,r)=>{let o=null;const n=Hr(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function $a(t,e){const s=t.map(r=>Kr(r,e));return Promise.all(s)}function Ca(t,e){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(l=>l()),n&&clearTimeout(n)};t.forEach(l=>{const u=Hr(l,d=>{i||(i=!0,a(),s({eventType:l,data:d}))});o.push(u)}),e&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function Da(t,e,s){return C(t,o=>{o&&e(o)&&s(o)}).unsubscribe}function xa(t,e,s){return C(t,o=>{if(o){const n=e(o);s(n)}}).unsubscribe}function Aa(t,e,s){let r=null;const o=C(t,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},e)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function Pa(t,e,s){let r=0,o=null;const n=C(t,i=>{const a=Date.now(),l=a-r;l>=e?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},e-l))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function Ra(t,e,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=C(t,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},e)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function an(t,e=1){const s=[];return C(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),C(t,r))}}function ka(t,e){const s=t.map(r=>C(r,o=>{o&&e(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function La(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}=C(n,a=>{const l=e[s];l&&l[n]&&(s=l[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function Fa(t,e,s,r){const o=Kr(e,r);return V(t,s),o}async function*Na(t){const e=[],s=[],r=C(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 jh={once:Hr,waitFor:Kr,waitForAll:$a,race:Ca,filter:Da,map:xa,debounce:Aa,throttle:Pa,buffer:Ra,replay:an,merge:ka,stateMachine:La,request:Fa,eventIterator:Na},Bh=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:jh,buffer:Ra,debounce:Aa,eventIterator:Na,filter:Da,map:xa,merge:ka,once:Hr,race:Ca,replay:an,request:Fa,stateMachine:La,throttle:Pa,waitFor:Kr,waitForAll:$a},Symbol.toStringTag,{value:"Module"}));async function qr(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=e,i=nn(t,n),a=await s(),l=r?r(a):a;return o&&o(l)?(i.catch(()=>{}),l):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(l),100)})])}function Ua(t,e,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=C(t,a=>{a&&(n=!0,e(a))});return Promise.resolve(r()).then(a=>{const l=o?o(a):a;n||e(l)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function ja(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}};C(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(l=>l(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 l=()=>{s!==void 0?a():setTimeout(l,10)};l()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function ln(t,e){if(typeof t=="string")return qr(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 l=s.map(d=>nn(d,n)),u=await Promise.all(l);return u[u.length-1]}function Ba(t,e,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=C(t,async u=>{if(u){if(n){const d=n(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await e(u)}}),l=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(n){const f=n(h);i.has(f)||(i.add(f),await e(h))}else await e(h)}catch(u){console.error("Failed to fetch missed events:",u)}},o);return()=>{a.unsubscribe(),clearInterval(l)}}function Ha(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await qr(e,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:d});return a.state="connected",a.data=h,u(),h},subscribe(d){return l.add(d),d(a),()=>{l.delete(d)}},async reconnect(){a.state="connecting",u();try{const d=await n();a.state="connected",a.data=d,u()}catch{a.state="error",u(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},l=new Set,u=()=>{l.forEach(d=>d(a))};return C(e,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),C(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&C(r,()=>{a.state="error",u()}),o&&C(o,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const Hh={waitForOrGetState:qr,subscribeWithInitialState:Ua,createStatefulEventStream:ja,waitForAllWithState:ln,createResilientEventHandler:Ba,createConnectionStateManager:Ha},Kh=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Hh,createConnectionStateManager:Ha,createResilientEventHandler:Ba,createStatefulEventStream:ja,subscribeWithInitialState:Ua,waitForAllWithState:ln,waitForOrGetState:qr},Symbol.toStringTag,{value:"Module"})),qh=(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 cn(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 it(){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 zh(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 Vh(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const un=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},Ka=t=>t,qa=t=>t,Gh=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=Ka,idMapper:o=qa})=>n=>{const i=n.map(o),l=un(i,t.data).map(r).filter(Boolean);t.removeAll(l);const u=i.map(d=>{const h=t.getModel(d.id);return h&&s?s(d,h):e(d)}).filter(Boolean);t.addAll(u)},Yh=({container:t,onAddItem:e,onRemoveItem:s=Ka,idMapper:r=qa})=>o=>{const n=o.map(r);un(n,t.models).forEach(s),n.forEach(e)},Wh=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);un(n,t).forEach(s),n.forEach(e)},Qh=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},Oi=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),$i=[{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 za(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=$i.length;s++){const r=$i[s];if(Math.abs(e)<r.amount)return Oi.format(Math.round(e),r.name);e/=r.amount}return Oi.format(Math.round(e),"years")}const dn=t=>t%4===0&&t%100!==0||t%400===0,hn=(t,e)=>[31,dn(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Va=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,hn(s.getFullYear(),s.getMonth()))),s},Ga=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},St="en-US",Ya={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"}},Wa={short:{hour:"2-digit",minute:"2-digit",hour12:!0},medium:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0},long:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZoneName:"short"},full:{hour:"2-digit",minute:"2-digit",hour12:!0,timeZoneName:"long"}},Qa=(t,{dateStyle:e="short",locales:s=St}={dateStyle:"short",locales:St})=>{const r=e==="short"?Ya.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},Za=(t,{locales:e=St,timeStyle:s="short"}={locales:St,timeStyle:"short"})=>{const r=Wa[s];return new Intl.DateTimeFormat(e,r).format(t)},Xa=(t,{dateStyle:e="short",locales:s=St,timeStyle:r="short"}={dateStyle:"short",locales:St,timeStyle:"short"})=>{const o={...e&&Ya[e],...r&&Wa[r]};return new Intl.DateTimeFormat(s,o).format(t)},Zh=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Ga,addMonthsToDate:Va,formatDate:Qa,formatDateSince:za,formatDateTime:Xa,formatTime:Za,getDaysInMonth:hn,isLeapYear:dn},Symbol.toStringTag,{value:"Module"}));function Ja(t,e,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,o)},s)}}const te="canvas-renderer",ho=new Map,Ci=new Map,fo=new Map,po=new Map,Fs=(t,e)=>{el[t]=e},el={indexExtension:{registerIndexExtension:(t,e)=>{const s=po.get(t)||{};Object.assign(s,e),po.set(t,e)},loadIndexExtensions:t=>po.get(t)||{}},loader:{registerLoader:(t,e)=>{Ci.set(t,e)},executeLoader:async(t,e)=>{const s=Ci.get(t);if(s)return await s(e)}},propertyMapper:{registerPropertyMapper:(t,e)=>{fo.set(t,e)},hasMapper:t=>fo.has(t),executeMapper:(t,e,s)=>{const r=fo.get(t);return r?r(e,s):""}},dataMapper:{registerDataMapper:(t,e)=>{const s=ho.get(t)||[];s.push(e),ho.set(t,s)},executeMapper:async(t,e,s)=>{const r=ho.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(!$[te]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}$[te].register(t,e)}}},$=el,Xh=async({context:t,extension:e})=>{const s=await $.loader.executeLoader(e,{});return t==null||t.set(e,s),s},Jh=async({extension:t,contextData:e,data:s})=>await $.dataMapper.executeMapper(t,s,e),ef=async({extension:t,contextData:e,data:s})=>await $.propertyMapper.executeMapper(t,s,e),tf=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Jh,executeLoaderExtension:Xh,executePropertyMapperExtension:ef},Symbol.toStringTag,{value:"Module"})),sf="Extensions";class rf{constructor(){c(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}const me=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),tl="studio.tools.preview",of="studio.relax.store.validation",sl="studio.log.debug",rl="studio.log.info",nf={profiles:[tl]};var ya;const af=((ya=globalThis.getKosConfig)==null?void 0:ya.call(globalThis))||JSON.stringify(nf),ol=JSON.parse(af);globalThis.kosConfig=ol;const fn=ol,nl=()=>fn.profiles||[],xo=t=>nl().includes(t),lf=()=>fn.logging||!1,cf=()=>{const t=xo(sl),e=xo(rl);return t?"DEBUG":e?"INFO":void 0},il=()=>{const t=me(),e=cf(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},al=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",ll=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",cl="ws-log",uf=D.methodFactory,ul=al(),df=ll();D.methodFactory=function(t,e,s){const r=uf(t,e,s);return function(...o){var l;const n=s?String(s):"",i=n?`[${String(n).substring(n.lastIndexOf(":")+1)}] | `:"[root] | ",a=o.map(u=>typeof u=="object"?JSON.stringify(u):String(u)).join(" ");r(`${i}${a}`),(l=globalThis==null?void 0:globalThis.kosConfig)!=null&&l.logging&&globalThis.kosLog&&(s!==cl||ul&&df)&&globalThis.kosLog(`UI: ${i}${a}`)}};let dl=il();D.setLevel(dl);window.setKosLogLevel=t=>{dl=t,D.setLevel(t)};const hr=D.getLogger(cl);window.enableKosMessageLog=()=>{hr.setLevel(D.levels.INFO)};window.disableKosMessageLog=()=>{hr.setLevel(D.levels.ERROR)};ul?window.enableKosMessageLog():window.disableKosMessageLog();const hf=["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(";"),ff=["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(";"),Vs=t=>e=>{D.getLevel()<=t&&e()},m={...D,ifDebug:Vs(D.levels.DEBUG),ifInfo:Vs(D.levels.INFO),ifWarn:Vs(D.levels.WARN),ifError:Vs(D.levels.ERROR),getLogger:t=>D.getLogger(`kos::${t}`),getLoggers:()=>D.getLoggers(),createLogger:({name:t,group:e})=>{var n,i,a,l;const s=`${e?`${e}:`:"kos"}::${t}`,r=D.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(u=>u.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(l=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:l.level,o&&r.setLevel(o)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");hr.info(`%c⬆ ${e}`,hf)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");hr.info(`%c⬇ ${e}`,ff)}},hl="featureFlagResolver",Gs=new Map;Fs(hl,{register:(t,e)=>{var s;Gs.has(t)||Gs.set(t,[]),(s=Gs.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Gs.get(t);if(!s)return[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,l)=>(a[l]=!0,a),{});return pl.updateFlags(i),Object.keys(i)}});const pf="kos.loader.featureFlag";class fl{constructor(e={}){c(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 fl;const pl=window.KosFeatureFlags,gl=(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)}`},ml=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return gl(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},yl=(t,e)=>getComputedStyle(t).getPropertyValue(e),gf=(t,e)=>ml(yl(t,e)),mf=(t,e)=>{const s={...t};return s.id&&delete s.id,s},Ao=(t,e,s=mf)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})},ee=Symbol("SubscriptionHandlers"),N=Symbol("DependencyModels"),hs=Symbol("FutureService"),He=Symbol("ChildModels"),fs=Symbol("ParentModel"),ps=Symbol("LogConfig"),or=Symbol("ReferenceConfig"),pn=Symbol("KosModelSymbol"),tt=Symbol("ModelEffects"),Ke=Symbol("CompanionParentModel"),gn=Symbol("FutureContainerSetup"),mn=Symbol("MultipleFutureContainerSetup"),gs=Symbol("FutureAliases"),yn=Symbol("TroubleAwareSetup"),bn=Symbol("LoggerSetup"),vn=Symbol("ContainerAwareSetup"),Ns=Symbol("StateMachineSetup"),Et=Symbol("StateEntryHandlers"),ms=Symbol("StateExitHandlers"),yf=Symbol("StateActionHandlers"),Us=Symbol("OptionsRequired"),bf=m.createLogger({group:"decorators",name:"fsm-injection"});function bl(t){const e=t[Ns];if(!e)return;const{config:s,options:r}=e;Mf(t,s,r),Tf(t,r);const o=Ef(t);vf(t,s,r,o),wf(t,s,r)}function vf(t,e,s,r){t.transition=_f(t,e,s,r.entry,r.exit),t.canTransition=Rf(t,e,s),t.isInState=kf(t,s)}function wf(t,e,s){Sf(t),If(t,e,s)}function Ef(t){const e=t.constructor.prototype[Et]||new Map,s=t.constructor.prototype[ms]||new Map;return{entry:e,exit:s}}function Mf(t,e,s){t._fsmConfig=e,t._fsmOptions=s}function Tf(t,e){const{stateProperty:s,trackHistory:r}=e,o=t._fsmConfig;t[s]=o.initial,t._fsmInitialized=!0,t.isTransitioning=!1,r&&(t.stateHistory=[{state:o.initial,timestamp:new Date}])}function Sf(t){Object.defineProperty(t,"isFsmInitialized",{get(){return this._fsmInitialized},enumerable:!0,configurable:!0})}function If(t,e,s){const{stateProperty:r}=s;Object.defineProperty(t,"allowedTransitions",{get(){if(!this._fsmInitialized)return[];const o=this[r],n=this._fsmConfig.states[o];return n!=null&&n.on?Object.keys(n.on):[]},enumerable:!0,configurable:!0})}function _f(t,e,s,r,o){const{stateProperty:n,throwOnInvalid:i}=s;return function(a){if(!this._fsmInitialized){Of(e.initializeAt,i);return}const l=this[n],u=$f(l,a,this._fsmConfig,i);u&&Df(this,l,u,a,n,r,o,s)}}function Of(t,e){const s=`Cannot transition: FSM not initialized. Waiting for ${t} lifecycle phase.`;if(e)throw new Error(s);console.warn(s)}function $f(t,e,s,r){var i;const o=s.states[t],n=(i=o==null?void 0:o.on)==null?void 0:i[e];if(!n){Cf(t,e,r);return}return n}function Cf(t,e,s){const r=`Invalid transition: Event "${e}" not allowed from state "${t}"`;if(s)throw new Error(r);console.warn(r)}function Df(t,e,s,r,o,n,i,a){t.isTransitioning=!0;try{xf(t,e,i),t[o]=s,Pf(t,s,r,a),Af(t,s,n)}finally{t.isTransitioning=!1}}function xf(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function Af(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function Pf(t,e,s,r){r.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date,event:s})}function Rf(t,e,s){const{stateProperty:r}=s;return function(o){var a;if(!this._fsmInitialized)return!1;const n=this[r],i=this._fsmConfig.states[n];return((a=i==null?void 0:i.on)==null?void 0:a[o])!==void 0}}function kf(t,e){const{stateProperty:s}=e;return function(r){return this._fsmInitialized?this[s]===r:!1}}function vl(t,e){const s=t[Ns];if(!s)return;const{config:r,options:o}=s,{stateProperty:n}=o;r.initializeAt===e&&(t._fsmInitialized||(Lf(t,n,r.initial),t._fsmInitialized=!0,Ff(t,r.initial,o),Nf(t,r.initial),bf.debug(`FSM initialized for model ${t.id} at lifecycle ${e} with initial state "${r.initial}"`)))}function Lf(t,e,s){t[e]=s}function Ff(t,e,s){s.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date})}function Nf(t,e){const r=(t.constructor.prototype[Et]||new Map).get(e);r&&typeof t[r]=="function"&&t[r]()}const $e=(t,e)=>{t[He]=t[He]||{},t[He][e]=!0},at=t=>`{PROP_${String(t)}}`,Uf=t=>`{PROP_${String(t)}}`,jf=at("kosParentId"),zr=t=>e=>{e[fs]=e[fs]||{};const s=(t==null?void 0:t.parentId)||jf;e[fs]={parentId:s},e.prototype[Us]=!0};function Bf(t){return e=>{const s=(t==null?void 0:t.mode)||"decorator",r=(t==null?void 0:t.parentProperty)||"companionParent",o=(t==null?void 0:t.excludeProperties)||[],n=t==null?void 0:t.lifecycle;return zr()(e),e.prototype[Ke]={mode:s,parentProperty:r,excludeProperties:o,lifecycle:n},e}}function wl(t){return e=>{const s=t!=null&&t.legacy?"_models":(t==null?void 0:t.containerProperty)||"container",r=(t==null?void 0:t.includeMethods)!==!1,o=(t==null?void 0:t.includeGetters)!==!1,n=(t==null?void 0:t.modelsProperty)||"models",i=(t==null?void 0:t.containerOptions)||{};return e.prototype[vn]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(t==null?void 0:t.legacy)||!1},e}}function Hf(t,e,s){const r=s.value;s.value=function(...o){const n=Y.getContext(this.id);return o.push(n),r.apply(this,o)}}const Vr=Symbol("KosExecutionContext");function wn(t){return t&&typeof t=="object"&&Vr in t}function Kf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[gn]={mode:s,handlerProperty:r},e}}function qf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[mn]={mode:s,handlerProperty:r},e}}var x=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(x||{}),Be=(t=>(t.CREATE="create",t.CONTINUE="continue",t.FAIL="fail",t))(Be||{});const zf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:x,DependencyResolutionPolicy:Be},Symbol.toStringTag,{value:"Module"})),Pe=Symbol("HttpRouteHandlers"),Di="__httpBrowserRouter";function Gr(t){return function(s){return function(r,o,n){r[Pe]=r[Pe]||[];const i={method:t,path:s,handler:o};return r[Pe].push(i),r[N]=r[N]||{},r[N][Di]||(r[N][Di]={modelType:"browser-router-model",lifecycle:x.INIT}),n}}}const El=Gr("GET"),js=Gr("POST"),Vf=Gr("PUT"),Ml=Gr("DELETE"),Gf=Ml;function fr(t){return!!(t!=null&&t[Pe])&&t[Pe].length>0}function Tl(t){return(t==null?void 0:t[Pe])||[]}const Yf=({group:t}={group:""})=>e=>{e[ps]=e[ps]||{},e[ps]={group:t}};class Sl{static create({modelId:e,modelTypeName:s,component:r}){const o=[r??"kos",s,e].filter(Boolean).join(".");return m.createLogger({name:o})}}function Il(t){return e=>{const s=(t==null?void 0:t.loggerProperty)||"logger",r=t==null?void 0:t.loggerContext;e.prototype[bn]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=e.prototype[pn])==null?void 0:i.type};let n;return Object.defineProperty(e.prototype,s,{get(){if(!n){const i=o();n=Sl.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),e}}function _l(t){return(e,s,r)=>{e[tt]=e[tt]||{},e[tt][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Wf=t=>(e,s)=>{e[or]=e[or]||{},e[or][s]=t},go=m.createLogger({name:"resolve-parameters"}),Ee=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=Ee({value:r[n],modelId:e,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp("{PROP_(.+?)}","g");let n=r!=null&&r.includes(dr)?r.replace(dr,e):r;if(s){let i=!1;const a=/^{PROP_.+?}$/.test(n);if(n=n.replace(o,(l,u)=>{if(Object.getOwnPropertyNames(s).includes(u)||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(u)){const h=s[u];return h?(go.debug(`Resolved ${l} to ${h}`),h):(go[a?"debug":"warn"](`Property ${u} is falsy${a?"":" in composite string"}, marking for undefined return`),i=!0,l)}return go[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),l}),i)return}return n}else return r;return r},st=Symbol("ServiceRequestHandlers"),xi=new WeakMap;function Qf(t){return(e,s,r)=>{var a;e[st]=e[st]||{};const o=r.value,n={...t,handlerMethod:s,originalHandler:o},i=`${((a=t.method)==null?void 0:a.toUpperCase())||"GET"}:${String(t.path)}`;if(e[st][i]=n,!t.lifecycle){const l=function(...u){const d=u[u.length-1],h=async f=>{const p=xi.get(l);if(!p)throw new Error("Service request metadata not found for method");try{const{default:y}=await Promise.resolve().then(()=>ec),w=Ee({value:p.path,modelId:this.id,modelData:this}),E={...typeof p.pathParams=="function"?p.pathParams(this):p.pathParams||{},...(f==null?void 0:f.pathParams)||{}},S={...typeof p.queryParams=="function"?p.queryParams(this):p.queryParams||{},...(f==null?void 0:f.queryParams)||{}},L=(f==null?void 0:f.body)||(typeof p.body=="function"?p.body(this):p.body),R={};Object.keys(E).length>0&&(R.path=E),Object.keys(S).length>0&&(R.query=S);const O=(p.method||"get").toLowerCase(),I=y,[K,q]=O==="get"?await I.get(w,R):O==="post"?await I.post(w,R,L):O==="put"?await I.put(w,R,L):O==="delete"?await I.delete(w,R,L):await I.get(w,R);if(K){if(p.errorHandler)switch(p.errorHandler.strategy){case"log":return console.error(`Service request error: ${K}`),p.errorHandler.onError&&p.errorHandler.onError(new Error(K),this),[null,p.errorHandler.defaultValue];case"ignore":return[null,p.errorHandler.defaultValue];case"default":return[null,p.errorHandler.defaultValue];case"throw":default:return[K,null]}return[K,null]}let J=q;return p.transform&&(J=p.transform(q)),[null,J]}catch(y){return[y.message||"Unknown error",null]}};if(wn(d))return d.$request=h,o.apply(this,u);{const f={[Vr]:!0,$request:h};return o.apply(this,[...u,f])}};xi.set(l,n),r.value=l}return r}}var Ol=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(Ol||{}),ue=(t=>(t.IMMEDIATE="immediate",t.SINGLE="single",t.TTL="ttl",t.PERMANENT="permanent",t.MANUAL="manual",t))(ue||{}),et=(t=>(t.ALL="all",t.AFTER_REQUEST="after-request",t.AFTER_RESPONSE="after-response",t.NONE="none",t))(et||{});const Zf=m.createLogger({name:"kos-state-machine"});function Xf(t,e){return s=>(s.prototype[Ns]={config:{...t,initializeAt:t.initializeAt||x.READY},options:{stateProperty:(e==null?void 0:e.stateProperty)||"currentState",trackHistory:(e==null?void 0:e.trackHistory)||!1,throwOnInvalid:(e==null?void 0:e.throwOnInvalid)!==!1}},s)}function Jf(t){return(e,s)=>{e[Et]||(e[Et]=new Map),e[Et].set(t,s)}}function ep(t){return(e,s)=>{e[ms]||(e[ms]=new Map),e[ms].set(t,s)}}function tp(t){return(e,s,r)=>{const o=r.value;return r.value=function(...n){var u,d;if(!this.isFsmInitialized)return o.apply(this,n);const a=this.currentState;if(!t.allowedStates.includes(a)){const h=`Method ${String(s)} cannot be called from state "${a}". Allowed states: ${t.allowedStates.join(", ")}`;if(t.throwOnInvalid!==void 0?t.throwOnInvalid:((d=(u=this[Ns])==null?void 0:u.options)==null?void 0:d.throwOnInvalid)!==!1)throw new Error(h);Zf.warn(h);return}return o.apply(this,n)},r}}function sp(t){return e=>{const s=(t==null?void 0:t.pathProperty)||"path";return e.prototype[yn]={pathProperty:s},e.prototype[N]=e.prototype[N]||{},e.prototype[N].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},e}}const Nt=({modelType:t,id:e,options:s,lifecycle:r,resolutionPolicy:o})=>(n,i)=>{n[N]=n[N]||{},n[N][i]={modelType:t,id:e,options:s,lifecycle:r||x.INIT,resolutionPolicy:o}};class $l{constructor(e,s){c(this,"futures");c(this,"defaultContext");c(this,"context");c(this,"disposers",new Map);c(this,"container");this.futures=xn.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=W(()=>{var o,n;(e.endState||e.progress)&&((n=(o=this.container)==null?void 0:o.onFutureUpdate)==null||n.call(o,e))});this.disposers.set(s||e.id,r)}removeFuture(e){var s;this.futures.delete(e||this.context),(s=this.disposers.get(e||this.context))==null||s(),this.disposers.delete(e||this.context)}getFuture(e){return this.futures.get(e||this.context)}get futureMap(){return this.futures}}class Yr{constructor(e){c(this,"disposer");c(this,"_future");c(this,"container");c(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=W(()=>{var r,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 m.error(e),e}}}const Cl=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},Dl=Symbol("KosObservableData"),Wt=Symbol("revision");var bT;class xl{constructor(){c(this,"map");c(this,bT,1);c(this,"atomMap",new Map);c(this,"proxyHandler",{get:(e,s)=>{var r;return s===Wt||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.map.has(s),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),M.makeObservable(this,{[Wt]:M.observable})}setValue(e,s){const r=this.map.has(e);this.map.set(e,s),r||M.action(()=>{this[Wt]++})()}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return this[Wt],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)}}bT=Wt;xl.prototype[Dl]=!0;function rp(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const Ie=t=>{const e=rp(xl,t);return new e(t)};function op(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class En{constructor({container:e,key:s}){c(this,"_container");c(this,"_map");c(this,"_key");c(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=Ie(),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(op(n,i))m.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 np(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,l)=>{e({name:i,newValue:a,oldValue:l})}))}const Qt=m.createLogger({name:"kos-container-model"});class Ce{constructor(e){c(this,"_data");c(this,"_sortKey");c(this,"_revision");c(this,"_index");c(this,"_optionsMap");c(this,"_disposerMap",new Map);c(this,"_parentId");c(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?$.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const 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=Ie(),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 En({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(e,s){this._data.set(e.id||"",e),e.id&&this._parentId&&Y.setParentContext(e.id,this._parentId),s||this.increment();const r=this._disposerMap.get(e.id);r&&(r(),this._disposerMap.delete(e.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([d,h])=>[h,d])),a=d=>{var f,p;n.includes(d.name)&&((f=this.index.get(i.get(d.name)))==null||f.refresh());const h=o.filter(([,y])=>typeof y=="function");for(const[y]of h)(p=this.index.get(y))==null||p.refresh()},l=np(e,a,n.filter(d=>typeof d=="string")),u=M.observe(e,a);this._disposerMap.set(e.id||"",()=>[u,...l].forEach(d=>d()))}removeModel(e,s){this._data.delete(e),s||this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Qt.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):(Qt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Qt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(e=>{const s=e.id;rt(e).then(()=>{Qt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Qt.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}var v=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(v||{}),F=(t=>(t.CREATE="create",t.INITIALIZE="init",t.LOAD="load",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.RESET="go_offline",t.UNLOAD="unload",t.FAILED="failed",t.GO_ACTIVE="go_active",t.GO_INACTIVE="go_inactive",t.TIMEOUT="timeout",t))(F||{});const de=async t=>{if(t.id){const e=_.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},rt=async t=>{await _.getInstance().whenReady(),await _.getInstance().modelManager.initiateDestroyModel(t)},ip=async t=>{if(await _.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(F.UNLOAD,v.UNLOADED)},ap=async t=>{await _.getInstance().whenReady(),await _.getInstance().modelManager.reloadModel(t),m.debug(`reload model initiated for model ${t.id}, model ready: ${pr(t)} - ${Date.now()} `),await de(t),m.debug(`reload model complete for model ${t.id}, model ready: ${pr(t)} - ${Date.now()} `)},lp=async t=>{if(await _.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},Al=async t=>{if(await _.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},_e=t=>{if(!t)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Pl=(t,e)=>{if(!t)throw new Error("Model type is required");return _.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},cp=(t,e)=>Pl(t,e)[0],up=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=_.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},Rl=t=>{if(!t.id)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},dp=t=>{if(!t)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},Po=(t,e)=>{const s=_.getInstance().modelManager.getModelById(t);if(!s){m.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},Te=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,pr=t=>{const e=_.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},hp=m.createLogger({name:"kos-model-factory"}),ys={byModelType:t=>_.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=ys.byModelType(e);if(!r)throw hp.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},ie={Factory:{create:t=>e=>(s,r)=>(r&&Y.setParentContext(e,r),ys.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&Y.setParentContext(t,s),ys.getModelInstance(t,t,e))},Model:{instance:t=>e=>ys.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Ai=window.KosRegistry.coreModels,mo=window.KosRegistry.preloadModels,yo=window.KosRegistry.companionModels,Ys=window.KosRegistry.models,A={model:{registerLegacyModel:t=>(e,s)=>(Ai.set(e,s),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(mo.includes(e)||mo.push(e),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=bo(e)?e.registration():e;return Ys.set(r.type,r),bo(e)&&e.relatedModels.forEach(o=>Ys.set(o.type,o.registration())),_.getInstance().isReady&&(_.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),_.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],bo(e)&&e.relatedModels.forEach(o=>_.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&A.model.preloadModel(t)(r.type),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},get:t=>Ys.get(t),getAll:()=>Array.from(Ys.entries()),getPreloadModels:()=>mo,getLegacyModels:()=>Array.from(Ai.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=yo.get(e)||[];return r.push(s),yo.set(e,r),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(yo.entries())}},kl=A.model.registerLegacyModel,Ll=A.model.register,fp=A.companion.register,pp=A.model.preloadModel,Mn=t=>typeof t.updateModel=="function",bo=t=>t.registration!==void 0&&typeof t.registration=="function";class Fl{constructor(e){c(this,"singleton");c(this,"type");c(this,"loader");c(this,"class");c(this,"guard");c(this,"factory");c(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=Te(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){A.model.register({})(this.registration()),this.registerRelatedModels()}}class ye extends Fl{constructor(e){super({...e,singleton:!1,factory:ie.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=_e(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(Mn(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 Se extends Fl{constructor(e){super({...e,singleton:!0,factory:ie.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=_e(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=e(r);if(this.guard(o)){if(Mn(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 Ro=m.createLogger({group:"decorators",name:"kos-model"});function gp(t,e,s){var n;const r=(n=t[fs])==null?void 0:n.parentId;if(!r)return;const o=Ee({value:r,modelData:s,modelId:e});o&&typeof o=="string"&&Y.setParentContext(e,o)}function mp(t){const e=t[hs];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function yp(t,e){const s=t[N]||{};Object.entries(s).forEach(([r,o])=>{const n=Ee({value:o.id||o.modelType,modelData:t,modelId:e}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[l,u])=>(a[l]=Ee({value:u,modelData:t,modelId:e}),a),{});if(typeof n=="string"){if(!o.lazy){const a=_.getInstance().modelManager.createModelInstance(o.modelType,n,i);t[r]=a.data}_.getInstance().modelManager.addDependency(e,n)}})}function bp(t){const e=t[gn];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new Yr(t);t[r]=o,s==="full"&&(Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){var n;return((n=o.future)==null?void 0:n.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var n;return((n=o.future)==null?void 0:n.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var n;return((n=o.future)==null?void 0:n.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function vp(t){const e=t[mn];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new $l(t);t[r]=o,Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0});const n=t[gs];n instanceof Map&&n.forEach(i=>{const a=`${i}Future`;Object.defineProperty(t,a,{get(){return o.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(t,`${i}Progress`,{get(){const l=o.futureMap.get(i);return(l==null?void 0:l.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}Status`,{get(){const l=o.futureMap.get(i);return(l==null?void 0:l.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsRunning`,{get(){const l=o.futureMap.get(i);return l?!l.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsCancelled`,{get(){const l=o.futureMap.get(i);return(l==null?void 0:l.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const l=o.futureMap.get(i);l&&await l.cancelFuture()})}),s==="full"&&(Object.defineProperty(t,"progress",{get(){var i;return((i=o.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var i;return((i=o.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var i;return((i=o.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function wp(t){const e=t[yn];if(!e)return;const{pathProperty:s}=e;Object.defineProperty(t,"troubles",{get(){const r=this[s];if(r==null){const o=`@kosTroubleAware: Path property '${s}' is undefined on model ${this.id||"unknown"}. Returning empty troubles array.`;return this.logger&&typeof this.logger.warn=="function"?this.logger.warn(o):console.warn(o),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((o,n)=>n.rank-o.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troublesByType",{get(){return this.troubles.reduce(Cl,{})},enumerable:!0,configurable:!0})}function Ep(t,e){const s=t[vn];if(!s)return;const{containerProperty:r,includeMethods:o,includeGetters:n,modelsProperty:i,containerOptions:a,legacy:l}=s,u={...a,parentId:a.parentId||e},d=new Ce(u);t[r]=d,t[He]||(t[He]={}),t[He][r]=d,o&&(t.getModel=h=>d.getModel(h),t.addModel=h=>{d.addModel(h)},t.removeModel=h=>{d.removeModel(h)}),n&&(Object.defineProperty(t,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(t,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function Mp(t,e){const s=t.constructor.prototype[Ke];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=e[o];if(!i){Ro.warn(`Companion decorator configured but no parent model found at '${o}'`);return}if(t.getCompanionParent=()=>i,r==="composition")return;const a=["init","load","unload","ready","dispose","destroy","activate"],l=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace","getCompanionParent"],u=p=>{const y=i.constructor.prototype[ee]||{};return Object.values(y).some(w=>{const E=w==null?void 0:w.handler;return E===i[p]||E===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||l.includes(p)||n.includes(p)||u(p)||p in t,h=new Set;Object.getOwnPropertyNames(i).filter(p=>!d(p)).forEach(p=>h.add(p));let f=Object.getPrototypeOf(i);for(;f&&f!==Object.prototype;)Object.getOwnPropertyNames(f).filter(p=>!d(p)).forEach(p=>h.add(p)),f=Object.getPrototypeOf(f);for(const p of h)try{const y=i[p];typeof y=="function"?t[p]=(...w)=>y.apply(i,w):Object.defineProperty(t,p,{get:()=>i[p],set:w=>{i[p]=w},enumerable:!0,configurable:!0})}catch(y){Ro.debug(`Skipping companion proxy for property ${p}:`,y)}}function Tp(t){try{return M.makeAutoObservable(t)}catch(e){return Ro.error("Failed to make observable:",e),t}}const Sp={construct(t,e){var l;const[s,r={}]=e,o=Y.createContext(s);gp(t,s,r);const i=!!t.prototype[bn]?null:m.createLogger({name:t.prototype.modelTypeId,group:((l=t[ps])==null?void 0:l.group)??"kos-model"}),a=new t(s,r,{logger:i,kosContext:o});return mp(a),bp(a),vp(a),wp(a),Ep(a,s),Mp(a,r),bl(a),yp(a,s),Tp(a)}};function P(t){return e=>{var n,i;const s=e,r=typeof t=="string"?{modelTypeId:t,autoRegister:!1}:{autoRegister:!1,...t};s.prototype.modelTypeId=r.modelTypeId,s.prototype[pn]=!0,(n=s.prototype)[ee]??(n[ee]={}),(i=s.prototype)[N]??(i[N]={}),r.optionsRequired&&(s.prototype[Us]=!0),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,Sp);if(r.singleton!==void 0){let a;r.singleton?a=new Se({class:o,type:r.modelTypeId}):a=new ye({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}const Ip=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>o=>{o[ee]=o[ee]||{},Array.isArray(t)?t.forEach(n=>{o[ee][n]={websocket:s,handler:e,condition:r}}):o[ee][t]={websocket:s,handler:Ja(o,M.action(e),200),condition:r}};function Nl(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 Ul(t){return t.endsWith("/*")}function B(t){return(e,s,r)=>{const o=_p(t,r);Cp(e,t.topic,o),t.replay&&Dp(t.topic,t.replay.bufferSize)}}function _p(t,e){const{condition:s=(I,K)=>!0,transform:r=I=>I,websocket:o=!1,fos:n=!1,bridge:i=!1,skipParse:a=!1,lifecycle:l,destinationAddress:u,debounce:d,throttle:h,buffer:f,filter:p,once:y,wildcardName:w,flow:E,requiresBaseline:S}=t,L=e.value,R=Op(L,{debounce:d,throttle:h,buffer:f,once:y}),O=$p(p,s);return{websocket:o,fos:n,bridge:i,handler:R,condition:O,transform:r,lifecycle:l,skipParse:a,destinationAddress:u,wildcardName:w,flow:E,requiresBaseline:S}}function Op(t,e){var n,i;let s=t;const r=typeof e.debounce=="number"?e.debounce:(n=e.debounce)==null?void 0:n.delay,o=typeof e.throttle=="number"?e.throttle:(i=e.throttle)==null?void 0:i.interval;return r&&r>0?s=xp(s,e.debounce):o&&o>0?s=kp(s,e.throttle):e.buffer?s=Lp(async function(l){for(const u of l)await s.call(this,u)},e.buffer):e.once&&(s=Fp(s)),s}function $p(t,e){return t?(s,r,o)=>t(o)?e(s,r,o):!1:e}function Cp(t,e,s){t[ee]=t[ee]||{},Array.isArray(e)?e.forEach(r=>{t[ee][r]=s}):t[ee][e]=s}function Dp(t,e){Np(t,e)}function xp(t,e){const s=typeof e=="number"?e:e.delay;return Ap(e)==="discard"?Pp(t,s):Rp(t,s)}function Ap(t){return(typeof t=="object"?t.discardIntermediate:!1)?"discard":"accumulate"}function Pp(t,e){let s=null;return function(r){s&&clearTimeout(s),s=setTimeout(()=>{t.call(this,r),s=null},e)}}function Rp(t,e){let s=null,r=[];return function(o){r.push(o),s&&clearTimeout(s),s=setTimeout(()=>{const n=[...r];r=[],t.call(this,n),s=null},e)}}function kp(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 l=function(){if(i.length>0){const u=[...i];i=[],t.call(this,u)}};return function(u){const d=Date.now(),h=d-o;r?h>=s?(o=d,t.call(this,u)):n||(n=setTimeout(()=>{o=Date.now(),t.call(this,u),n=null},s-h)):(i.push(u),h>=s?(o=d,l.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),l.call(this),n=null,a=!1},s-h)))}}function Lp(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 Fp(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function Np(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{an(r,e)})}const vo=new Map,jl={addToDeletionQueue:(t,e)=>{const s=vo.get(t)||[];s.push(e),vo.set(t,s)},cancelDeletion:t=>{const e=vo.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},Up=m.createLogger({name:"kos-dependency-manager"});class jp{constructor(){c(this,"_usedByCache",new Map);c(this,"_usesCache",new Map)}add(e,s){jl.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?(Up.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}const Pi=m.createLogger({name:"kos-model-cache"});class Bp{constructor(e=[]){c(this,"_modelsById",M.observable.map(new Map));c(this,"_toDelete",new Map);c(this,"_preloaded",[]);c(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).map(e=>e).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?(Pi.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Pi.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}class nr extends Error{constructor(s,r,o){super(s,{cause:o});c(this,"context");c(this,"originalCause");this.name="KosModelError",this.context=r,this.originalCause=o,o!=null&&o.stack&&(this.stack=`${this.stack}
|
|
1
|
+
"use strict";var Lh=Object.defineProperty;var Fh=(t,e,s)=>e in t?Lh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var c=(t,e,s)=>(Fh(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("loglevel"),M=require("mobx"),b=require("robot3"),He=require("date-fns"),T=require("@emotion/react/jsx-runtime"),Jo=require("@emotion/styled"),Ea=require("react-dom"),Je=require("@emotion/react"),g=require("react"),en=require("mobx-react-lite"),Nh=require("@use-gesture/react"),Br="method",Ma="topic",Ut="url",ks="request-id",Hr="response-id",tn="status",Ne="dst-addr",Ta="src-addr",Oe="type",sn="ordered",rn="tracker",Sa="Content-Type",Ia="Cache-Control",_a="requestId",Oa=process.env.KOS_LOGIN_URL||"http://localhost",$a=process.env.KOS_APP_PORT||"8080",Uh=`${Oa}:${$a}`,hr="{MODEL_ID}";var Ls=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(Ls||{}),Ca=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(Ca||{});const on="/kos/model/ready/";D.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const q=globalThis.kos.subscriptions,jh=()=>Symbol("eventKey");function nn(t){return q[t]&&Object.getOwnPropertySymbols(q[t]).length>0}function C(t,e){const s=jh();return q[t]||(D.debug(`Initializing subscription for ${t}`),q[t]={}),D.debug(`Subscribing to ${t} with id ${s.toString()}`),q[t][s]=e,{count:q[t]?Object.getOwnPropertySymbols(q[t]).length:0,unsubscribe:()=>(D.debug(`Unsubscribing from ${t} with id ${s.toString()}`),q[t]&&q[t][s]&&delete q[t][s],q[t]&&Object.getOwnPropertySymbols(q[t]).length===0&&delete q[t],{count:q[t]?Object.getOwnPropertySymbols(q[t]).length:0})}}function V(t,e,s={}){if(!q[t]||Object.getOwnPropertySymbols(q[t]).length===0)return D.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(q[t]).length;return Object.getOwnPropertySymbols(q[t]).forEach(o=>{if(s.sync){const n=s.sync;D.debug(`Performing sync publish for ${t} with sync id ${n}`),q[t][o]({body:e,headers:s}).then(i=>{D.debug(`Response recieved for ${n}, publishing back to source.`),V(n,i)})}else D.debug(`Performing async publish for ${t}`),q[t][o]({body:e,headers:s})}),{eventType:t,subscribers:r}}function Bh(){D.warn("Resetting event bus"),Object.keys(q).forEach(t=>delete q[t])}function Da(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function an(t,e){return new Promise((s,r)=>{let o=null;const n=Da(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const Hh=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:nn,once:Da,publish:V,reset:Bh,subscribe:C,waitFor:an},Symbol.toStringTag,{value:"Module"}));function Kr(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function qr(t,e){return new Promise((s,r)=>{let o=null;const n=Kr(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function xa(t,e){const s=t.map(r=>qr(r,e));return Promise.all(s)}function Aa(t,e){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(l=>l()),n&&clearTimeout(n)};t.forEach(l=>{const u=Kr(l,d=>{i||(i=!0,a(),s({eventType:l,data:d}))});o.push(u)}),e&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function Ra(t,e,s){return C(t,o=>{o&&e(o)&&s(o)}).unsubscribe}function Pa(t,e,s){return C(t,o=>{if(o){const n=e(o);s(n)}}).unsubscribe}function ka(t,e,s){let r=null;const o=C(t,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},e)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function La(t,e,s){let r=0,o=null;const n=C(t,i=>{const a=Date.now(),l=a-r;l>=e?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},e-l))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function Fa(t,e,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=C(t,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},e)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function ln(t,e=1){const s=[];return C(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),C(t,r))}}function Na(t,e){const s=t.map(r=>C(r,o=>{o&&e(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function Ua(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}=C(n,a=>{const l=e[s];l&&l[n]&&(s=l[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function ja(t,e,s,r){const o=qr(e,r);return V(t,s),o}async function*Ba(t){const e=[],s=[],r=C(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 Kh={once:Kr,waitFor:qr,waitForAll:xa,race:Aa,filter:Ra,map:Pa,debounce:ka,throttle:La,buffer:Fa,replay:ln,merge:Na,stateMachine:Ua,request:ja,eventIterator:Ba},qh=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:Kh,buffer:Fa,debounce:ka,eventIterator:Ba,filter:Ra,map:Pa,merge:Na,once:Kr,race:Aa,replay:ln,request:ja,stateMachine:Ua,throttle:La,waitFor:qr,waitForAll:xa},Symbol.toStringTag,{value:"Module"}));async function zr(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=e,i=an(t,n),a=await s(),l=r?r(a):a;return o&&o(l)?(i.catch(()=>{}),l):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(l),100)})])}function Ha(t,e,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=C(t,a=>{a&&(n=!0,e(a))});return Promise.resolve(r()).then(a=>{const l=o?o(a):a;n||e(l)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function Ka(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}};C(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(l=>l(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 l=()=>{s!==void 0?a():setTimeout(l,10)};l()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function cn(t,e){if(typeof t=="string")return zr(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 l=s.map(d=>an(d,n)),u=await Promise.all(l);return u[u.length-1]}function qa(t,e,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=C(t,async u=>{if(u){if(n){const d=n(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await e(u)}}),l=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(n){const f=n(h);i.has(f)||(i.add(f),await e(h))}else await e(h)}catch(u){console.error("Failed to fetch missed events:",u)}},o);return()=>{a.unsubscribe(),clearInterval(l)}}function za(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await zr(e,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:d});return a.state="connected",a.data=h,u(),h},subscribe(d){return l.add(d),d(a),()=>{l.delete(d)}},async reconnect(){a.state="connecting",u();try{const d=await n();a.state="connected",a.data=d,u()}catch{a.state="error",u(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},l=new Set,u=()=>{l.forEach(d=>d(a))};return C(e,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),C(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&C(r,()=>{a.state="error",u()}),o&&C(o,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const zh={waitForOrGetState:zr,subscribeWithInitialState:Ha,createStatefulEventStream:Ka,waitForAllWithState:cn,createResilientEventHandler:qa,createConnectionStateManager:za},Vh=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:zh,createConnectionStateManager:za,createResilientEventHandler:qa,createStatefulEventStream:Ka,subscribeWithInitialState:Ha,waitForAllWithState:cn,waitForOrGetState:zr},Symbol.toStringTag,{value:"Module"})),Gh=(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 un(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 lt(){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 Yh(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 Wh(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const dn=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},Va=t=>t,Ga=t=>t,Qh=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=Va,idMapper:o=Ga})=>n=>{const i=n.map(o),l=dn(i,t.data).map(r).filter(Boolean);t.removeAll(l);const u=i.map(d=>{const h=t.getModel(d.id);return h&&s?s(d,h):e(d)}).filter(Boolean);t.addAll(u)},Zh=({container:t,onAddItem:e,onRemoveItem:s=Va,idMapper:r=Ga})=>o=>{const n=o.map(r);dn(n,t.models).forEach(s),n.forEach(e)},Xh=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=o=>o})=>o=>{const n=o.map(r);dn(n,t).forEach(s),n.forEach(e)},Jh=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},$i=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Ci=[{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 Ya(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=Ci.length;s++){const r=Ci[s];if(Math.abs(e)<r.amount)return $i.format(Math.round(e),r.name);e/=r.amount}return $i.format(Math.round(e),"years")}const hn=t=>t%4===0&&t%100!==0||t%400===0,fn=(t,e)=>[31,hn(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Wa=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,fn(s.getFullYear(),s.getMonth()))),s},Qa=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},_t="en-US",Za={short:{year:"numeric",month:"2-digit",day:"2-digit"},medium:{year:"numeric",month:"short",day:"2-digit"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}},Xa={short:{hour:"2-digit",minute:"2-digit",hour12:!0},medium:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0},long:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZoneName:"short"},full:{hour:"2-digit",minute:"2-digit",hour12:!0,timeZoneName:"long"}},Ja=(t,{dateStyle:e="short",locales:s=_t}={dateStyle:"short",locales:_t})=>{const r=e==="short"?Za.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},el=(t,{locales:e=_t,timeStyle:s="short"}={locales:_t,timeStyle:"short"})=>{const r=Xa[s];return new Intl.DateTimeFormat(e,r).format(t)},tl=(t,{dateStyle:e="short",locales:s=_t,timeStyle:r="short"}={dateStyle:"short",locales:_t,timeStyle:"short"})=>{const o={...e&&Za[e],...r&&Xa[r]};return new Intl.DateTimeFormat(s,o).format(t)},ef=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Qa,addMonthsToDate:Wa,formatDate:Ja,formatDateSince:Ya,formatDateTime:tl,formatTime:el,getDaysInMonth:fn,isLeapYear:hn},Symbol.toStringTag,{value:"Module"}));function sl(t,e,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,o)},s)}}const te="canvas-renderer",fo=new Map,Di=new Map,po=new Map,go=new Map,Fs=(t,e)=>{rl[t]=e},rl={indexExtension:{registerIndexExtension:(t,e)=>{const s=go.get(t)||{};Object.assign(s,e),go.set(t,e)},loadIndexExtensions:t=>go.get(t)||{}},loader:{registerLoader:(t,e)=>{Di.set(t,e)},executeLoader:async(t,e)=>{const s=Di.get(t);if(s)return await s(e)}},propertyMapper:{registerPropertyMapper:(t,e)=>{po.set(t,e)},hasMapper:t=>po.has(t),executeMapper:(t,e,s)=>{const r=po.get(t);return r?r(e,s):""}},dataMapper:{registerDataMapper:(t,e)=>{const s=fo.get(t)||[];s.push(e),fo.set(t,s)},executeMapper:async(t,e,s)=>{const r=fo.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(!$[te]){console.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}$[te].register(t,e)}}},$=rl,tf=async({context:t,extension:e})=>{const s=await $.loader.executeLoader(e,{});return t==null||t.set(e,s),s},sf=async({extension:t,contextData:e,data:s})=>await $.dataMapper.executeMapper(t,s,e),rf=async({extension:t,contextData:e,data:s})=>await $.propertyMapper.executeMapper(t,s,e),of=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:sf,executeLoaderExtension:tf,executePropertyMapperExtension:rf},Symbol.toStringTag,{value:"Module"})),nf="Extensions";class af{constructor(){c(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}const me=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),ol="studio.tools.preview",lf="studio.relax.store.validation",nl="studio.log.debug",il="studio.log.info",cf={profiles:[ol]};var wa;const uf=((wa=globalThis.getKosConfig)==null?void 0:wa.call(globalThis))||JSON.stringify(cf),al=JSON.parse(uf);globalThis.kosConfig=al;const pn=al,ll=()=>pn.profiles||[],Ao=t=>ll().includes(t),df=()=>pn.logging||!1,hf=()=>{const t=Ao(nl),e=Ao(il);return t?"DEBUG":e?"INFO":void 0},cl=()=>{const t=me(),e=hf(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},ul=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",dl=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",hl="ws-log",ff=D.methodFactory,fl=ul(),pf=dl();D.methodFactory=function(t,e,s){const r=ff(t,e,s);return function(...o){var l;const n=s?String(s):"",i=n?`[${String(n).substring(n.lastIndexOf(":")+1)}] | `:"[root] | ",a=o.map(u=>typeof u=="object"?JSON.stringify(u):String(u)).join(" ");r(`${i}${a}`),(l=globalThis==null?void 0:globalThis.kosConfig)!=null&&l.logging&&globalThis.kosLog&&(s!==hl||fl&&pf)&&globalThis.kosLog(`UI: ${i}${a}`)}};let pl=cl();D.setLevel(pl);window.setKosLogLevel=t=>{pl=t,D.setLevel(t)};const fr=D.getLogger(hl);window.enableKosMessageLog=()=>{fr.setLevel(D.levels.INFO)};window.disableKosMessageLog=()=>{fr.setLevel(D.levels.ERROR)};fl?window.enableKosMessageLog():window.disableKosMessageLog();const gf=["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(";"),mf=["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(";"),Gs=t=>e=>{D.getLevel()<=t&&e()},m={...D,ifDebug:Gs(D.levels.DEBUG),ifInfo:Gs(D.levels.INFO),ifWarn:Gs(D.levels.WARN),ifError:Gs(D.levels.ERROR),getLogger:t=>D.getLogger(`kos::${t}`),getLoggers:()=>D.getLoggers(),createLogger:({name:t,group:e})=>{var n,i,a,l;const s=`${e?`${e}:`:"kos"}::${t}`,r=D.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(u=>u.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(l=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:l.level,o&&r.setLevel(o)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");fr.info(`%c⬆ ${e}`,gf)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");fr.info(`%c⬇ ${e}`,mf)}},gl="featureFlagResolver",Ys=new Map;Fs(gl,{register:(t,e)=>{var s;Ys.has(t)||Ys.set(t,[]),(s=Ys.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Ys.get(t);if(!s)return[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,l)=>(a[l]=!0,a),{});return yl.updateFlags(i),Object.keys(i)}});const yf="kos.loader.featureFlag";class ml{constructor(e={}){c(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 ml;const yl=window.KosFeatureFlags,bl=(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)}`},vl=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return bl(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},wl=(t,e)=>getComputedStyle(t).getPropertyValue(e),bf=(t,e)=>vl(wl(t,e)),vf=(t,e)=>{const s={...t};return s.id&&delete s.id,s},Ro=(t,e,s=vf)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})},ee=Symbol("SubscriptionHandlers"),F=Symbol("DependencyModels"),hs=Symbol("FutureService"),qe=Symbol("ChildModels"),fs=Symbol("ParentModel"),ps=Symbol("LogConfig"),nr=Symbol("ReferenceConfig"),gn=Symbol("KosModelSymbol"),rt=Symbol("ModelEffects"),ze=Symbol("CompanionParentModel"),mn=Symbol("FutureContainerSetup"),yn=Symbol("MultipleFutureContainerSetup"),gs=Symbol("FutureAliases"),bn=Symbol("TroubleAwareSetup"),vn=Symbol("LoggerSetup"),wn=Symbol("ContainerAwareSetup"),Ns=Symbol("StateMachineSetup"),Tt=Symbol("StateEntryHandlers"),ms=Symbol("StateExitHandlers"),wf=Symbol("StateActionHandlers"),Us=Symbol("OptionsRequired"),Ef=m.createLogger({group:"decorators",name:"fsm-injection"});function El(t){const e=t[Ns];if(!e)return;const{config:s,options:r}=e;If(t,s,r),_f(t,r);const o=Sf(t);Mf(t,s,r,o),Tf(t,s,r)}function Mf(t,e,s,r){t.transition=Cf(t,e,s,r.entry,r.exit),t.canTransition=Ff(t,e,s),t.isInState=Nf(t,s)}function Tf(t,e,s){Of(t),$f(t,e,s)}function Sf(t){const e=t.constructor.prototype[Tt]||new Map,s=t.constructor.prototype[ms]||new Map;return{entry:e,exit:s}}function If(t,e,s){t._fsmConfig=e,t._fsmOptions=s}function _f(t,e){const{stateProperty:s,trackHistory:r}=e,o=t._fsmConfig;t[s]=o.initial,t._fsmInitialized=!0,t.isTransitioning=!1,r&&(t.stateHistory=[{state:o.initial,timestamp:new Date}])}function Of(t){Object.defineProperty(t,"isFsmInitialized",{get(){return this._fsmInitialized},enumerable:!0,configurable:!0})}function $f(t,e,s){const{stateProperty:r}=s;Object.defineProperty(t,"allowedTransitions",{get(){if(!this._fsmInitialized)return[];const o=this[r],n=this._fsmConfig.states[o];return n!=null&&n.on?Object.keys(n.on):[]},enumerable:!0,configurable:!0})}function Cf(t,e,s,r,o){const{stateProperty:n,throwOnInvalid:i}=s;return function(a){if(!this._fsmInitialized){Df(e.initializeAt,i);return}const l=this[n],u=xf(l,a,this._fsmConfig,i);u&&Rf(this,l,u,a,n,r,o,s)}}function Df(t,e){const s=`Cannot transition: FSM not initialized. Waiting for ${t} lifecycle phase.`;if(e)throw new Error(s);console.warn(s)}function xf(t,e,s,r){var i;const o=s.states[t],n=(i=o==null?void 0:o.on)==null?void 0:i[e];if(!n){Af(t,e,r);return}return n}function Af(t,e,s){const r=`Invalid transition: Event "${e}" not allowed from state "${t}"`;if(s)throw new Error(r);console.warn(r)}function Rf(t,e,s,r,o,n,i,a){t.isTransitioning=!0;try{Pf(t,e,i),t[o]=s,Lf(t,s,r,a),kf(t,s,n)}finally{t.isTransitioning=!1}}function Pf(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function kf(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function Lf(t,e,s,r){r.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date,event:s})}function Ff(t,e,s){const{stateProperty:r}=s;return function(o){var a;if(!this._fsmInitialized)return!1;const n=this[r],i=this._fsmConfig.states[n];return((a=i==null?void 0:i.on)==null?void 0:a[o])!==void 0}}function Nf(t,e){const{stateProperty:s}=e;return function(r){return this._fsmInitialized?this[s]===r:!1}}function Ml(t,e){const s=t[Ns];if(!s)return;const{config:r,options:o}=s,{stateProperty:n}=o;r.initializeAt===e&&(t._fsmInitialized||(Uf(t,n,r.initial),t._fsmInitialized=!0,jf(t,r.initial,o),Bf(t,r.initial),Ef.debug(`FSM initialized for model ${t.id} at lifecycle ${e} with initial state "${r.initial}"`)))}function Uf(t,e,s){t[e]=s}function jf(t,e,s){s.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date})}function Bf(t,e){const r=(t.constructor.prototype[Tt]||new Map).get(e);r&&typeof t[r]=="function"&&t[r]()}const $e=(t,e)=>{t[qe]=t[qe]||{},t[qe][e]=!0},ct=t=>`{PROP_${String(t)}}`,Hf=t=>`{PROP_${String(t)}}`,Kf=ct("kosParentId"),Vr=t=>e=>{e[fs]=e[fs]||{};const s=(t==null?void 0:t.parentId)||Kf;e[fs]={parentId:s},e.prototype[Us]=!0};function qf(t){return e=>{const s=(t==null?void 0:t.mode)||"decorator",r=(t==null?void 0:t.parentProperty)||"companionParent",o=(t==null?void 0:t.excludeProperties)||[],n=t==null?void 0:t.lifecycle;return Vr()(e),e.prototype[ze]={mode:s,parentProperty:r,excludeProperties:o,lifecycle:n},e}}function Tl(t){return e=>{const s=t!=null&&t.legacy?"_models":(t==null?void 0:t.containerProperty)||"container",r=(t==null?void 0:t.includeMethods)!==!1,o=(t==null?void 0:t.includeGetters)!==!1,n=(t==null?void 0:t.modelsProperty)||"models",i=(t==null?void 0:t.containerOptions)||{};return e.prototype[wn]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(t==null?void 0:t.legacy)||!1},e}}function zf(t,e,s){const r=s.value;s.value=function(...o){const n=Y.getContext(this.id);return o.push(n),r.apply(this,o)}}const Gr=Symbol("KosExecutionContext");function En(t){return t&&typeof t=="object"&&Gr in t}function Vf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[mn]={mode:s,handlerProperty:r},e}}function Gf(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[yn]={mode:s,handlerProperty:r},e}}var x=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(x||{}),Ke=(t=>(t.CREATE="create",t.CONTINUE="continue",t.FAIL="fail",t))(Ke||{});const Yf=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:x,DependencyResolutionPolicy:Ke},Symbol.toStringTag,{value:"Module"})),Re=Symbol("HttpRouteHandlers"),xi="__httpBrowserRouter";function Yr(t){return function(s){return function(r,o,n){r[Re]=r[Re]||[];const i={method:t,path:s,handler:o};return r[Re].push(i),r[F]=r[F]||{},r[F][xi]||(r[F][xi]={modelType:"browser-router-model",lifecycle:x.INIT}),n}}}const Sl=Yr("GET"),js=Yr("POST"),Wf=Yr("PUT"),Il=Yr("DELETE"),Qf=Il;function pr(t){return!!(t!=null&&t[Re])&&t[Re].length>0}function _l(t){return(t==null?void 0:t[Re])||[]}const Zf=({group:t}={group:""})=>e=>{e[ps]=e[ps]||{},e[ps]={group:t}};class Ol{static create({modelId:e,modelTypeName:s,component:r}){const o=[r??"kos",s,e].filter(Boolean).join(".");return m.createLogger({name:o})}}function $l(t){return e=>{const s=(t==null?void 0:t.loggerProperty)||"logger",r=t==null?void 0:t.loggerContext;e.prototype[vn]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=e.prototype[gn])==null?void 0:i.type};let n;return Object.defineProperty(e.prototype,s,{get(){if(!n){const i=o();n=Ol.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),e}}function Cl(t){return(e,s,r)=>{e[rt]=e[rt]||{},e[rt][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Xf=t=>(e,s)=>{e[nr]=e[nr]||{},e[nr][s]=t},mo=m.createLogger({name:"resolve-parameters"}),Ee=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=Ee({value:r[n],modelId:e,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp("{PROP_(.+?)}","g");let n=r!=null&&r.includes(hr)?r.replace(hr,e):r;if(s){let i=!1;const a=/^{PROP_.+?}$/.test(n);if(n=n.replace(o,(l,u)=>{if(Object.getOwnPropertyNames(s).includes(u)||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(u)){const h=s[u];return h?(mo.debug(`Resolved ${l} to ${h}`),h):(mo[a?"debug":"warn"](`Property ${u} is falsy${a?"":" in composite string"}, marking for undefined return`),i=!0,l)}return mo[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),l}),i)return}return n}else return r;return r},ot=Symbol("ServiceRequestHandlers"),Ai=new WeakMap;function Mn(t){return(e,s,r)=>{var a;e[ot]=e[ot]||{};const o=r.value,n={...t,handlerMethod:s,originalHandler:o},i=`${((a=t.method)==null?void 0:a.toUpperCase())||"GET"}:${String(t.path)}`;if(e[ot][i]=n,!t.lifecycle){const l=function(...u){const d=u[u.length-1],h=async f=>{const p=Ai.get(l);if(!p)throw new Error("Service request metadata not found for method");try{const{default:y}=await Promise.resolve().then(()=>rc),w=Ee({value:p.path,modelId:this.id,modelData:this}),E={...typeof p.pathParams=="function"?p.pathParams(this):p.pathParams||{},...(f==null?void 0:f.pathParams)||{}},S={...typeof p.queryParams=="function"?p.queryParams(this):p.queryParams||{},...(f==null?void 0:f.queryParams)||{}},k=(f==null?void 0:f.body)||(typeof p.body=="function"?p.body(this):p.body),O={...(typeof p.requestOptions=="function"?p.requestOptions(this,...u):p.requestOptions)||{},...(f==null?void 0:f.requestOptions)||{}},I={};Object.keys(E).length>0&&(I.path=E),Object.keys(S).length>0&&(I.query=S);const z=(p.method||"get").toLowerCase(),j=y,[Z,je]=z==="get"?await j.get(w,I,O):z==="post"?await j.post(w,I,k,O):z==="put"?await j.put(w,I,k,O):z==="delete"?await j.delete(w,I,k,O):await j.get(w,I,O);if(Z){if(p.errorHandler)switch(p.errorHandler.strategy){case"log":return console.error(`Service request error: ${Z}`),p.errorHandler.onError&&p.errorHandler.onError(new Error(Z),this),[null,p.errorHandler.defaultValue];case"ignore":return[null,p.errorHandler.defaultValue];case"default":return[null,p.errorHandler.defaultValue];case"throw":default:return[Z,null]}return[Z,null]}let Be=je;return p.transform&&(Be=p.transform(je)),[null,Be]}catch(y){return[y.message||"Unknown error",null]}};if(En(d))return d.$request=h,o.apply(this,u);{const f={[Gr]:!0,$request:h};return o.apply(this,[...u,f])}};Ai.set(l,n),r.value=l}return r}}var Dl=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(Dl||{}),ue=(t=>(t.IMMEDIATE="immediate",t.SINGLE="single",t.TTL="ttl",t.PERMANENT="permanent",t.MANUAL="manual",t))(ue||{}),st=(t=>(t.ALL="all",t.AFTER_REQUEST="after-request",t.AFTER_RESPONSE="after-response",t.NONE="none",t))(st||{});const Jf=m.createLogger({name:"kos-state-machine"});function ep(t,e){return s=>(s.prototype[Ns]={config:{...t,initializeAt:t.initializeAt||x.READY},options:{stateProperty:(e==null?void 0:e.stateProperty)||"currentState",trackHistory:(e==null?void 0:e.trackHistory)||!1,throwOnInvalid:(e==null?void 0:e.throwOnInvalid)!==!1}},s)}function tp(t){return(e,s)=>{e[Tt]||(e[Tt]=new Map),e[Tt].set(t,s)}}function sp(t){return(e,s)=>{e[ms]||(e[ms]=new Map),e[ms].set(t,s)}}function rp(t){return(e,s,r)=>{const o=r.value;return r.value=function(...n){var u,d;if(!this.isFsmInitialized)return o.apply(this,n);const a=this.currentState;if(!t.allowedStates.includes(a)){const h=`Method ${String(s)} cannot be called from state "${a}". Allowed states: ${t.allowedStates.join(", ")}`;if(t.throwOnInvalid!==void 0?t.throwOnInvalid:((d=(u=this[Ns])==null?void 0:u.options)==null?void 0:d.throwOnInvalid)!==!1)throw new Error(h);Jf.warn(h);return}return o.apply(this,n)},r}}function op(t){return e=>{const s=(t==null?void 0:t.pathProperty)||"path";return e.prototype[bn]={pathProperty:s},e.prototype[F]=e.prototype[F]||{},e.prototype[F].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},e}}const jt=({modelType:t,id:e,options:s,lifecycle:r,resolutionPolicy:o})=>(n,i)=>{n[F]=n[F]||{},n[F][i]={modelType:t,id:e,options:s,lifecycle:r||x.INIT,resolutionPolicy:o}};class xl{constructor(e,s){c(this,"futures");c(this,"defaultContext");c(this,"context");c(this,"disposers",new Map);c(this,"container");this.futures=An.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=W(()=>{var 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 Wr{constructor(e){c(this,"disposer");c(this,"_future");c(this,"container");c(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=W(()=>{var r,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 m.error(e),e}}}const Al=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},Rl=Symbol("KosObservableData"),Wt=Symbol("revision");var ST;class Pl{constructor(){c(this,"map");c(this,ST,1);c(this,"atomMap",new Map);c(this,"proxyHandler",{get:(e,s)=>{var r;return s===Wt||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.map.has(s),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),M.makeObservable(this,{[Wt]:M.observable})}setValue(e,s){const r=this.map.has(e);this.map.set(e,s),r||M.action(()=>{this[Wt]++})()}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return this[Wt],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)}}ST=Wt;Pl.prototype[Rl]=!0;function np(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const Ie=t=>{const e=np(Pl,t);return new e(t)};function ip(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class Tn{constructor({container:e,key:s}){c(this,"_container");c(this,"_map");c(this,"_key");c(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=Ie(),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(ip(n,i))m.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 ap(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,l)=>{e({name:i,newValue:a,oldValue:l})}))}const Qt=m.createLogger({name:"kos-container-model"});class Ce{constructor(e){c(this,"_data");c(this,"_sortKey");c(this,"_revision");c(this,"_index");c(this,"_optionsMap");c(this,"_disposerMap",new Map);c(this,"_parentId");c(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?$.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const 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=Ie(),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 Tn({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}addModel(e,s){this._data.set(e.id||"",e),e.id&&this._parentId&&Y.setParentContext(e.id,this._parentId),s||this.increment();const r=this._disposerMap.get(e.id);r&&(r(),this._disposerMap.delete(e.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([d,h])=>[h,d])),a=d=>{var f,p;n.includes(d.name)&&((f=this.index.get(i.get(d.name)))==null||f.refresh());const h=o.filter(([,y])=>typeof y=="function");for(const[y]of h)(p=this.index.get(y))==null||p.refresh()},l=ap(e,a,n.filter(d=>typeof d=="string")),u=M.observe(e,a);this._disposerMap.set(e.id||"",()=>[u,...l].forEach(d=>d()))}removeModel(e,s){this._data.delete(e),s||this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Qt.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):(Qt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Qt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(e=>{const s=e.id;nt(e).then(()=>{Qt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Qt.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}var v=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(v||{}),L=(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))(L||{});const de=async t=>{if(t.id){const e=_.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},nt=async t=>{await _.getInstance().whenReady(),await _.getInstance().modelManager.initiateDestroyModel(t)},lp=async t=>{if(await _.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(L.UNLOAD,v.UNLOADED)},cp=async t=>{await _.getInstance().whenReady(),await _.getInstance().modelManager.reloadModel(t),m.debug(`reload model initiated for model ${t.id}, model ready: ${gr(t)} - ${Date.now()} `),await de(t),m.debug(`reload model complete for model ${t.id}, model ready: ${gr(t)} - ${Date.now()} `)},up=async t=>{if(await _.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},kl=async t=>{if(await _.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},_e=t=>{if(!t)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Ll=(t,e)=>{if(!t)throw new Error("Model type is required");return _.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},dp=(t,e)=>Ll(t,e)[0],hp=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=_.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},Fl=t=>{if(!t.id)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},fp=t=>{if(!t)throw new Error("Model ID is required");const e=_.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},Po=(t,e)=>{const s=_.getInstance().modelManager.getModelById(t);if(!s){m.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},Te=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,gr=t=>{const e=_.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},pp=m.createLogger({name:"kos-model-factory"}),ys={byModelType:t=>_.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=ys.byModelType(e);if(!r)throw pp.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},ie={Factory:{create:t=>e=>(s,r)=>(r&&Y.setParentContext(e,r),ys.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&Y.setParentContext(t,s),ys.getModelInstance(t,t,e))},Model:{instance:t=>e=>ys.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Ri=window.KosRegistry.coreModels,yo=window.KosRegistry.preloadModels,bo=window.KosRegistry.companionModels,Ws=window.KosRegistry.models,A={model:{registerLegacyModel:t=>(e,s)=>(Ri.set(e,s),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(yo.includes(e)||yo.push(e),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=vo(e)?e.registration():e;return Ws.set(r.type,r),vo(e)&&e.relatedModels.forEach(o=>Ws.set(o.type,o.registration())),_.getInstance().isReady&&(_.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),_.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],vo(e)&&e.relatedModels.forEach(o=>_.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&A.model.preloadModel(t)(r.type),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},get:t=>Ws.get(t),getAll:()=>Array.from(Ws.entries()),getPreloadModels:()=>yo,getLegacyModels:()=>Array.from(Ri.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=bo.get(e)||[];return r.push(s),bo.set(e,r),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(bo.entries())}},Nl=A.model.registerLegacyModel,Ul=A.model.register,gp=A.companion.register,mp=A.model.preloadModel,Sn=t=>typeof t.updateModel=="function",vo=t=>t.registration!==void 0&&typeof t.registration=="function";class jl{constructor(e){c(this,"singleton");c(this,"type");c(this,"loader");c(this,"class");c(this,"guard");c(this,"factory");c(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=Te(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){A.model.register({})(this.registration()),this.registerRelatedModels()}}class ye extends jl{constructor(e){super({...e,singleton:!1,factory:ie.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=_e(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(Sn(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 Se extends jl{constructor(e){super({...e,singleton:!0,factory:ie.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=_e(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=e(r);if(this.guard(o)){if(Sn(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 ko=m.createLogger({group:"decorators",name:"kos-model"});function yp(t,e,s){var n;const r=(n=t[fs])==null?void 0:n.parentId;if(!r)return;const o=Ee({value:r,modelData:s,modelId:e});o&&typeof o=="string"&&Y.setParentContext(e,o)}function bp(t){const e=t[hs];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function vp(t,e){const s=t[F]||{};Object.entries(s).forEach(([r,o])=>{const n=Ee({value:o.id||o.modelType,modelData:t,modelId:e}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[l,u])=>(a[l]=Ee({value:u,modelData:t,modelId:e}),a),{});if(typeof n=="string"){if(!o.lazy){const a=_.getInstance().modelManager.createModelInstance(o.modelType,n,i);t[r]=a.data}_.getInstance().modelManager.addDependency(e,n)}})}function wp(t){const e=t[mn];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new Wr(t);t[r]=o,s==="full"&&(Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){var n;return((n=o.future)==null?void 0:n.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var n;return((n=o.future)==null?void 0:n.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var n;return((n=o.future)==null?void 0:n.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function Ep(t){const e=t[yn];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new xl(t);t[r]=o,Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0});const n=t[gs];n instanceof Map&&n.forEach(i=>{const a=`${i}Future`;Object.defineProperty(t,a,{get(){return o.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(t,`${i}Progress`,{get(){const l=o.futureMap.get(i);return(l==null?void 0:l.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}Status`,{get(){const l=o.futureMap.get(i);return(l==null?void 0:l.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsRunning`,{get(){const l=o.futureMap.get(i);return l?!l.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsCancelled`,{get(){const l=o.futureMap.get(i);return(l==null?void 0:l.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const l=o.futureMap.get(i);l&&await l.cancelFuture()})}),s==="full"&&(Object.defineProperty(t,"progress",{get(){var i;return((i=o.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var i;return((i=o.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var i;return((i=o.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function Mp(t){const e=t[bn];if(!e)return;const{pathProperty:s}=e;Object.defineProperty(t,"troubles",{get(){const r=this[s];if(r==null){const o=`@kosTroubleAware: Path property '${s}' is undefined on model ${this.id||"unknown"}. Returning empty troubles array.`;return this.logger&&typeof this.logger.warn=="function"?this.logger.warn(o):console.warn(o),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((o,n)=>n.rank-o.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troublesByType",{get(){return this.troubles.reduce(Al,{})},enumerable:!0,configurable:!0})}function Tp(t,e){const s=t[wn];if(!s)return;const{containerProperty:r,includeMethods:o,includeGetters:n,modelsProperty:i,containerOptions:a,legacy:l}=s,u={...a,parentId:a.parentId||e},d=new Ce(u);t[r]=d,t[qe]||(t[qe]={}),t[qe][r]=d,o&&(t.getModel=h=>d.getModel(h),t.addModel=h=>{d.addModel(h)},t.removeModel=h=>{d.removeModel(h)}),n&&(Object.defineProperty(t,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(t,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function Sp(t,e){const s=t.constructor.prototype[ze];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=e[o];if(!i){ko.warn(`Companion decorator configured but no parent model found at '${o}'`);return}if(t.getCompanionParent=()=>i,r==="composition")return;const a=["init","load","unload","ready","dispose","destroy","activate"],l=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace","getCompanionParent"],u=p=>{const y=i.constructor.prototype[ee]||{};return Object.values(y).some(w=>{const E=w==null?void 0:w.handler;return E===i[p]||E===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||l.includes(p)||n.includes(p)||u(p)||p in t,h=new Set;Object.getOwnPropertyNames(i).filter(p=>!d(p)).forEach(p=>h.add(p));let f=Object.getPrototypeOf(i);for(;f&&f!==Object.prototype;)Object.getOwnPropertyNames(f).filter(p=>!d(p)).forEach(p=>h.add(p)),f=Object.getPrototypeOf(f);for(const p of h)try{const y=i[p];typeof y=="function"?t[p]=(...w)=>y.apply(i,w):Object.defineProperty(t,p,{get:()=>i[p],set:w=>{i[p]=w},enumerable:!0,configurable:!0})}catch(y){ko.debug(`Skipping companion proxy for property ${p}:`,y)}}function Ip(t){try{return M.makeAutoObservable(t)}catch(e){return ko.error("Failed to make observable:",e),t}}const _p={construct(t,e){var l;const[s,r={}]=e,o=Y.createContext(s);yp(t,s,r);const i=!!t.prototype[vn]?null:m.createLogger({name:t.prototype.modelTypeId,group:((l=t[ps])==null?void 0:l.group)??"kos-model"}),a=new t(s,r,{logger:i,kosContext:o});return bp(a),wp(a),Ep(a),Mp(a),Tp(a,s),Sp(a,r),El(a),vp(a,s),Ip(a)}};function R(t){return e=>{var n,i;const s=e,r=typeof t=="string"?{modelTypeId:t,autoRegister:!1}:{autoRegister:!1,...t};s.prototype.modelTypeId=r.modelTypeId,s.prototype[gn]=!0,(n=s.prototype)[ee]??(n[ee]={}),(i=s.prototype)[F]??(i[F]={}),r.optionsRequired&&(s.prototype[Us]=!0),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,_p);if(r.singleton!==void 0){let a;r.singleton?a=new Se({class:o,type:r.modelTypeId}):a=new ye({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}const Op=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>o=>{o[ee]=o[ee]||{},Array.isArray(t)?t.forEach(n=>{o[ee][n]={websocket:s,handler:e,condition:r}}):o[ee][t]={websocket:s,handler:sl(o,M.action(e),200),condition:r}};function Bl(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 Hl(t){return t.endsWith("/*")}function H(t){return(e,s,r)=>{const o=$p(t,r);xp(e,t.topic,o),t.replay&&Ap(t.topic,t.replay.bufferSize)}}function $p(t,e){const{condition:s=(I,z)=>!0,transform:r=I=>I,websocket:o=!1,fos:n=!1,bridge:i=!1,skipParse:a=!1,lifecycle:l,destinationAddress:u,debounce:d,throttle:h,buffer:f,filter:p,once:y,wildcardName:w,flow:E,requiresBaseline:S}=t,k=e.value,U=Cp(k,{debounce:d,throttle:h,buffer:f,once:y}),O=Dp(p,s);return{websocket:o,fos:n,bridge:i,handler:U,condition:O,transform:r,lifecycle:l,skipParse:a,destinationAddress:u,wildcardName:w,flow:E,requiresBaseline:S}}function Cp(t,e){var n,i;let s=t;const r=typeof e.debounce=="number"?e.debounce:(n=e.debounce)==null?void 0:n.delay,o=typeof e.throttle=="number"?e.throttle:(i=e.throttle)==null?void 0:i.interval;return r&&r>0?s=Rp(s,e.debounce):o&&o>0?s=Fp(s,e.throttle):e.buffer?s=Np(async function(l){for(const u of l)await s.call(this,u)},e.buffer):e.once&&(s=Up(s)),s}function Dp(t,e){return t?(s,r,o)=>t(o)?e(s,r,o):!1:e}function xp(t,e,s){t[ee]=t[ee]||{},Array.isArray(e)?e.forEach(r=>{t[ee][r]=s}):t[ee][e]=s}function Ap(t,e){jp(t,e)}function Rp(t,e){const s=typeof e=="number"?e:e.delay;return Pp(e)==="discard"?kp(t,s):Lp(t,s)}function Pp(t){return(typeof t=="object"?t.discardIntermediate:!1)?"discard":"accumulate"}function kp(t,e){let s=null;return function(r){s&&clearTimeout(s),s=setTimeout(()=>{t.call(this,r),s=null},e)}}function Lp(t,e){let s=null,r=[];return function(o){r.push(o),s&&clearTimeout(s),s=setTimeout(()=>{const n=[...r];r=[],t.call(this,n),s=null},e)}}function Fp(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 l=function(){if(i.length>0){const u=[...i];i=[],t.call(this,u)}};return function(u){const d=Date.now(),h=d-o;r?h>=s?(o=d,t.call(this,u)):n||(n=setTimeout(()=>{o=Date.now(),t.call(this,u),n=null},s-h)):(i.push(u),h>=s?(o=d,l.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),l.call(this),n=null,a=!1},s-h)))}}function Np(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 Up(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function jp(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{ln(r,e)})}const wo=new Map,Kl={addToDeletionQueue:(t,e)=>{const s=wo.get(t)||[];s.push(e),wo.set(t,s)},cancelDeletion:t=>{const e=wo.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},Bp=m.createLogger({name:"kos-dependency-manager"});class Hp{constructor(){c(this,"_usedByCache",new Map);c(this,"_usesCache",new Map)}add(e,s){Kl.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?(Bp.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}const Pi=m.createLogger({name:"kos-model-cache"});class Kp{constructor(e=[]){c(this,"_modelsById",M.observable.map(new Map));c(this,"_toDelete",new Map);c(this,"_preloaded",[]);c(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).map(e=>e).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?(Pi.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Pi.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}class ir extends Error{constructor(s,r,o){super(s,{cause:o});c(this,"context");c(this,"originalCause");this.name="KosModelError",this.context=r,this.originalCause=o,o!=null&&o.stack&&(this.stack=`${this.stack}
|
|
2
2
|
Caused by: ${o.stack}`)}toDetailedString(){const s=[`KosModelError: ${this.message}`,"","Context:",` Model Type: ${this.context.modelType}`,` Model ID: ${this.context.modelId}`];return this.context.parentModel&&s.push(` Parent Model: ${this.context.parentModel.type} [${this.context.parentModel.id}]`),this.context.lifecycle&&s.push(` Lifecycle: ${this.context.lifecycle}`),this.context.operation&&s.push(` Operation: ${this.context.operation}`),this.context.options&&Object.keys(this.context.options).length>0&&s.push(` Options: ${JSON.stringify(this.context.options,null,2)}`),this.originalCause&&s.push("",`Original Error: ${this.originalCause.message}`),s.join(`
|
|
3
|
-
`)}}function
|
|
3
|
+
`)}}function St(t,e){const s=t instanceof Error?t:new Error(String(t));return t instanceof ir?new ir(`${t.message} (enriched with additional context)`,{...t.context,...e},t.originalCause||s):new ir(`Error in ${e.operation||"model operation"}: ${s.message}`,e,s)}function qp(t,e){t.length!==0&&(m.error(`${e} - ${t.length} error(s) occurred:`),t.forEach(({error:s,context:r},o)=>{const n=s instanceof ir?s:St(s,r);m.error(` [${o+1}/${t.length}] ${n.toDetailedString()}`)}))}function ki(t,e){console.error("Model instantiation failed",{modelType:e.modelType,options:e.options,registryId:e.registryId,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,timestamp:new Date().toISOString()})}const ql=t=>typeof t=="function",Qs=m.createLogger({name:"kos-companion-instantiator"});class zp{constructor(e,s,r){this.registry=e,this.cache=s,this.createModel=r}createCompanionModels(e,s,r){const o=this.getCompanionDefinitions(e.modelTypeName);r!==void 0&&Qs.debug(`Creating ${r} lifecycle companions for ${e.modelTypeName} [${e.modelId}]`);for(const n of o){const i=this.resolveCompanionType(n,e,s,r);i&&this.shouldCreateCompanion(i.lifecycle,r)&&this.instantiateCompanion(i.type,e,s,r)}}getCompanionDefinitions(e){var s;return((s=this.registry.companionModels)==null?void 0:s[e])||[]}resolveCompanionType(e,s,r,o){return ql(e.type)?this.resolveFactoryCompanion(e,s,r,o):this.resolveStringCompanion(e)}resolveFactoryCompanion(e,s,r,o){const n=e.type(s.modelData,r);if(!n)return Qs.debug(`Companion factory returned undefined for ${s.modelTypeName} at ${o||"INIT"} phase`),null;const i=this.extractLifecycleFromType(n);return{type:n,lifecycle:i}}resolveStringCompanion(e){return{type:e.type,lifecycle:e.lifecycle}}extractLifecycleFromType(e){const s=this.registry.models[e];if(!(s!=null&&s.class))return;const r=s.class.prototype[ze];return r==null?void 0:r.lifecycle}shouldCreateCompanion(e,s){return s!==void 0?e===s:e===void 0}instantiateCompanion(e,s,r,o){const n=this.generateCompanionId(e,s.modelId);if(this.companionAlreadyExists(n,e,s.modelTypeName))return;const i=this.createCompanionInstance(e,n,s,r);i&&(this.attachCompanionToParent(i,s),Qs.debug(`Created ${o||"INIT"} companion ${e} for ${s.modelTypeName} [${s.modelId}]`))}generateCompanionId(e,s){return`${e}-${s}`}companionAlreadyExists(e,s,r){return this.cache.hasModel(e)?(Qs.debug(`Companion ${s} already exists for ${r}`),!0):!1}createCompanionInstance(e,s,r,o){const n=this.createModel(e,s,{data:o,companionParent:r.modelData,kosParentId:r.modelId});return(n==null?void 0:n.model)||null}attachCompanionToParent(e,s){e[ze]=s,s.addCompanionModel(e)}}function zl(t,e){return`${on}${t}${e?`/${e}`:`/${t}`}`}function Vl(t){return`${on}${t}`}function Eo(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 Gl=5e3,Vp=t=>t.fsm.transitionTo(L.GO_ACTIVE,v.ACTIVE),Gp=t=>t.whenReady(),Yp=t=>t.fsm.transitionTo(L.LOAD,v.LOADED),Wp=t=>t.fsm.transitionTo(L.UNLOAD,v.UNLOADED),Qp=t=>t.fsm.transitionTo(L.INITIALIZE,v.INITIALIZED);var In=(t=>(t.ACTIVE="active",t.READY="ready",t.LOAD="load",t.UNLOAD="unload",t.INIT="init",t))(In||{});const ar={active:Vp,ready:Gp,load:Yp,unload:Wp,init:Qp};class Yl extends Error{constructor(s,r){super(s);c(this,"model");this.model=r}}const Wl=(t,e,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{m.error(`Model ${e.modelId} - ${e.modelTypeName} - ${s} timed out after ${t}ms`),a(new Yl(`${e.modelId} - ${e.modelTypeName} - ${s}`,e))},t)}),cancel:()=>{r&&clearTimeout(r)}}},Zp=t=>typeof t.toJSON=="function",bs=t=>t[F]!==void 0,_n=t=>t.revision!==void 0&&t.index!==void 0,Ql=t=>{if(t){if(bs(t))return t;if(_n(t))return t.data;if(t instanceof Map||t instanceof M.ObservableMap||t instanceof Set)return Array.from(t.values()).filter(bs);if(Array.isArray(t))return t.filter(bs)}},Zl=(t,e)=>{var f;const s=e.id||e.modelType,r=Ee({value:s,modelData:t.modelData,modelId:t.modelId}),o=e.resolutionPolicy||Ke.CREATE;m.debug(`Resolving dependent model ${e.modelType} with id ${r} (policy: ${o})`);const n=Object.keys((e==null?void 0:e.options)||{}).reduce((p,y)=>{const w=e.options[y];return p[y]=Ee({value:w,modelData:t.modelData,modelId:t.modelId}),p},{}),i=_.getInstance().modelManager,a=i.registry.models[e.modelType];if(!a){const p=`No model registered for type ${e.modelType}`;if(m.error(`Failed to resolve dependency for model ${t.modelId}:
|
|
4
4
|
- Dependency Type: ${e.modelType}
|
|
5
5
|
- Dependency ID: ${r}
|
|
6
6
|
- Resolution Policy: ${o}
|
|
7
7
|
- Parent Model: ${t.modelTypeName}
|
|
8
8
|
- Parent Model ID: ${t.modelId}
|
|
9
|
-
- Error: ${p}`),o===
|
|
9
|
+
- Error: ${p}`),o===Ke.CONTINUE)return m.warn(`Model type not registered (policy: CONTINUE) - Model ${t.modelId} will continue without dependency ${e.modelType} [${r}]`),{dependentModel:null,dataModelId:r,success:!1};throw new Error(`Dependency resolution failed - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${p}`)}const l=i.getModelById(r);if(l){if(l.modelTypeName!==e.modelType){const p=`Model type mismatch: expected ${e.modelType}, found ${l.modelTypeName}`;if(m.error(`Failed to resolve dependency for model ${t.modelId}:
|
|
10
10
|
- Dependency Type: ${e.modelType}
|
|
11
11
|
- Dependency ID: ${r}
|
|
12
12
|
- Resolution Policy: ${o}
|
|
13
13
|
- Parent Model: ${t.modelTypeName}
|
|
14
14
|
- Parent Model ID: ${t.modelId}
|
|
15
15
|
- Found Model Type: ${l.modelTypeName}
|
|
16
|
-
- Error: ${p}`),o===
|
|
16
|
+
- Error: ${p}`),o===Ke.CONTINUE)return m.warn(`Model type mismatch (policy: CONTINUE) - Model ${t.modelId} will continue without dependency`),{dependentModel:null,dataModelId:r,success:!1};throw new Error(`Dependency resolution failed - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${p}`)}return m.debug(`Found existing dependent model ${e.modelType} with id ${r}`),{dependentModel:{model:l,data:l.modelData},dataModelId:r,success:!0}}if(m.debug(`Model ${e.modelType} [${r}] does not exist. Applying resolution policy: ${o}`),o===Ke.CONTINUE)return m.warn(`Model ${e.modelType} [${r}] not found (policy: CONTINUE) - Model ${t.modelId} will continue without this dependency`),{dependentModel:null,dataModelId:r,success:!1};const u=Object.keys(n).length>0,d=a.class||a.create;if(((f=d==null?void 0:d.prototype)==null?void 0:f[Us])===!0&&!u){const p=`Model ${e.modelType} requires options but none were provided`;throw m.error(`Failed to resolve dependency for model ${t.modelId}:
|
|
17
17
|
- Dependency Type: ${e.modelType}
|
|
18
18
|
- Dependency ID: ${r}
|
|
19
19
|
- Resolution Policy: ${o}
|
|
@@ -28,86 +28,86 @@ Caused by: ${o.stack}`)}toDetailedString(){const s=[`KosModelError: ${this.messa
|
|
|
28
28
|
- Parent Model: ${t.modelTypeName}
|
|
29
29
|
- Parent Model ID: ${t.modelId}
|
|
30
30
|
- Provided Options: ${JSON.stringify(n,null,2)}
|
|
31
|
-
- Error: ${y}`),o===Be.FAIL?new Error(`Dependency resolution failed (policy: FAIL) - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${y}`):p}},Wl=(t,e=x.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[N])||{};return Object.keys(s).length===0?(m.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],a=Yl(t,i);if(!a.success||!a.dependentModel)return m.debug(`Skipping dependency ${i.modelType} with id ${a.dataModelId} - resolution failed with CONTINUE policy`),t.modelData[n]=void 0,null;const{dependentModel:l,dataModelId:u}=a;t.modelData[n]=l.data,m.debug(`waiting for dependent model ${i.modelType} with id ${u} - waiting for WHENREADY`);const d=async(p,y,w)=>{var E;await((E=p.whenReady)==null?void 0:E.call(p)),m.debug(`dependent model ${y} with id ${w} - READY`)},{promise:h,cancel:f}=Vl(ql,t,t.status);return Promise.race([d(l.model,i.modelType,u).then(()=>{f()}).catch(p=>{const y=Mt(p,{modelType:i.modelType,modelId:u,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:e,operation:"dependency whenReady()"});throw m.error(y.toDetailedString()),f(),y}),h])}).filter(n=>!!n)},Ql=async(t,e,s,r)=>{if(m.debug(`Execute lifecycle with ${e.length} models`),e.length===0){m.debug(`${t.modelId} has no children. Returning`);return}if(!s){m.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let l;return ir[s]&&a?l=ir[s](a):(a||m.error("model is undefined. This shouldn't happen"),ir[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:l,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),n=await Promise.allSettled(o.map(a=>{var d;if(!a.model||!a.status)return Promise.resolve();const{promise:l,cancel:u}=Vl(ql,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{const f=Mt(h,{modelType:a.type||"unknown",modelId:a.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`});throw m.error(f.toDetailedString()),u(),f}),l])})),i=n.filter(a=>a.status==="rejected");if(i.length>0){const a=i.map(l=>{const u=o[n.indexOf(l)];return{error:l.status==="rejected"?l.reason:new Error("Unknown error"),context:{modelType:u.type||"unknown",modelId:u.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`}}});Hp(a,`Model ${t.modelId} had ${i.length} failed child model(s) on ${r}`)}},Zl=async(t,e,s)=>{await Ql(t,t.getChildren().filter(r=>!!r),e,s)},Xt=async(t,e)=>{const r=(await Promise.allSettled(Wl(t,e))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))};function Qp(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,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}}}),Zp(t.modelData,t.modelTypeName,t.modelId,t)}function Zp(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,l,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((l=r.companionManager)==null?void 0:l.all())||[],i=r.modelData[N]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.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];bs(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:Sn(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 Xp{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{Y.setParentContext(r.modelId,this.model.modelId)}catch(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[He])||{};return Object.keys(e).map(r=>Gl(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 Jp{constructor(e){c(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 eg{constructor(e,s,r,o){c(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[tt])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),l=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},u=n?M.reaction(()=>n(this.modelData),l,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(l);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const tg=m.createLogger({name:"model-active-machine"}),sg=t=>{const e=b.createMachine(v.INACTIVE,{[v.FAILED]:b.state(b.transition(F.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:b.state(b.transition(F.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:b.invoke(()=>(t.activeStatus=v.ACTIVATING,t.activate()),b.transition("done",v.ACTIVE,b.action(()=>{t.activeStatus=v.ACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED}))),[v.ACTIVE]:b.state(b.transition(F.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:b.invoke(()=>(t.activeStatus=v.DEACTIVATING,t.deactivate()),b.transition("done",v.INACTIVE,b.action(()=>{t.activeStatus=v.INACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED})))});return{service:b.interpret(e,r=>tg.debug(r.machine.current)),machine:e}},ki=m.createLogger({name:"model-online-machine"}),rg=t=>{const e=b.createMachine(v.OFFLINE,{[v.ONLINE]:b.state(b.transition(F.GO_OFFLINE,v.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:b.state(b.transition(F.GO_ONLINE,v.ONLINE,b.action(async()=>{ki.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=v.ONLINE,await t.fsm.transitionTo(F.INITIALIZE,v.INITIALIZED)})))}),s=b.interpret(e,r=>ki.debug(r.machine.current));return{machine:e,service:s}},og=t=>{var r;const e=sg(t).service,s=rg(t).service;return b.createMachine(v.CREATING,{[v.CREATING]:b.state(b.transition(F.CREATE,v.CREATED)),[v.CREATED]:b.state(b.immediate(v.INITIALIZING)),[v.INITIALIZING]:b.invoke(()=>(X(()=>{t.status=v.INITIALIZING}),t.init()),b.transition("done",v.INITIALIZED,b.action(()=>{t.status=v.INITIALIZED})),b.transition("error",v.FAILED,b.action(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=v.FAILED}))),[v.INITIALIZED]:b.state(b.immediate(v.LOADING)),[v.LOADING]:b.invoke(()=>(X(()=>{t.status=v.LOADING}),t.load()),b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.LOADED]:b.state(b.immediate(v.READYING),b.transition(F.UNLOAD,v.UNLOADING)),[v.RESETTING]:b.invoke(()=>{var o;return X(()=>{t.status=v.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED}))),[v.READYING]:b.invoke(()=>(X(()=>{t.status=v.READYING}),t.ready()),b.transition("done",v.READY,b.action(()=>{X(()=>{t.status=v.READY}),s.send(F.GO_ONLINE)})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.READY]:b.state(b.transition(F.UNLOAD,v.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(F.RESET,v.RESETTING),b.transition(F.GO_ONLINE,v.READY,b.action(()=>{s.send(F.GO_ONLINE)})),b.transition(F.GO_OFFLINE,v.READY,b.action(()=>{s.send(F.GO_OFFLINE)})),b.transition(F.GO_ACTIVE,v.READY,b.action(()=>{e.send(F.GO_ACTIVE)})),b.transition(F.GO_INACTIVE,v.READY,b.action(()=>{e.send(F.GO_INACTIVE)}))),[v.UNLOADED]:b.state(),[v.FAILED]:b.state()})},ng=m.createLogger({name:"kos-model-lifecycle"}),ig=t=>({service:b.interpret(og(t),s=>ng.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class ag{constructor(e,s){c(this,"disposer");c(this,"service");this.model=e,this.log=s;const r=ig(e);this.service=r.service,this.service.send(F.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=v.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const l=this.getTransitionStatusFor(s);return l===s||l===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[v.ACTIVE,v.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const Xl="browser-router-model";class In{constructor(e,s){c(this,"logger");c(this,"model");c(this,"router",null);c(this,"registered",!1);c(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!fr(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=_e(Xl))==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 fr(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=Tl(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(l){this.logger.error(`Error in route handler ${e.method} ${r}:`,l),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:l instanceof Error?l.message:String(l)})}};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 lg(t,e){if(!fr(t))return;const s=_e(Xl);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 In(t,e).setRouter(s.model)}class cg{constructor(e){c(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const o=this.queue.length,n=this.filterEventsByStrategy(e,s,r),i=o-n.length;this.log.warn(`Processing ${n.length}/${o} offline message(s) with strategy: ${e}`);for(const a of n)try{a.handler()}catch(l){this.log.error(`Error while processing offline message for topic ${a.topic}:`,l)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${n.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case et.ALL:return[...this.queue];case et.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=s);case et.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=r);case et.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(n=>n.receivedAt),o={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(o.afterRequest=this.queue.filter(n=>n.receivedAt>=e).length),s!==void 0&&(o.afterResponse=this.queue.filter(n=>n.receivedAt>=s).length),o}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class ug{constructor(e,s){c(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(F.GO_ONLINE,v.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(F.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}const Jl=()=>({isMock:!1,URL:exports.BASE_URL}),dg=m.createLogger({name:"kos-service-request"}),hg="errUnknown";async function Qs(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=`${Jl().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;dg.debug(`fullUrl: ${a}`);const l={method:String(e).toUpperCase(),body:null,...s};o&&(l.body=JSON.stringify(o));const u=await exports.kosFetch(a,l);return u.status<200||u.status>=400?[`${u.statusText||hg}`,null]:[null,(await u.json()).data]}function _n(){return{get:(t,e,s)=>Qs(t,"get",s,e),post:(t,e,s,r)=>Qs(t,"post",r,e,s),put:(t,e,s,r)=>Qs(t,"put",r,e,s),delete:(t,e,s,r)=>Qs(t,"delete",r,e,s)}}const De=_n(),ec=Object.freeze(Object.defineProperty({__proto__:null,default:De},Symbol.toStringTag,{value:"Module"})),Qe=m.createLogger({name:"kos-service-request-manager",group:"Model"});function fg(t,e){return!t.condition||t.condition(e)}function pg(t,e){return Ee({value:t.path,modelId:e.id,modelData:e})}function gg(t,e){if(t.pathParams)return Ee({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function mg(t,e){if(t.queryParams)return Ee({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function yg(t,e){if(t.body)return Ee({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function bg(t){return(t||"get").toLowerCase()}function Li(t,e){return`${e.toUpperCase()}:${t}`}function tc(t){return t==null}function vg(t,e,s,r){r&&tc(t)&&Qe.warn(`Required field '${e}' is missing in response for ${s}`)}function wg(t,e){return tc(t)&&e!==void 0?e:t}class Eg{constructor(e,s){c(this,"model");c(this,"responseStore");c(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[st]||{};Object.values(s).forEach(r=>{const o=r.lifecycle;this.handlers.has(o)||this.handlers.set(o,[]),this.handlers.get(o).push(r)}),Object.keys(s).length>0&&Qe.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(Qe.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return fg(e,this.model)?!0:(Qe.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),[o,n]=await this.performRequest(s),i=this.captureResponseTiming();return{requestContext:s,error:o,response:n,requestedAt:r.requestedAt,receivedAt:i.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=pg(e,this.model),r=gg(e,this.model),o=mg(e,this.model),n=yg(e,this.model),i=bg(e.method);return{resolvedPath:s,method:i,pathParams:r,queryParams:o,body:n}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,o,n){const i=s.cache||{retention:ue.SINGLE},a=Li(r,s.method||"get");this.responseStore.set(a,e,i,o,n),await s.originalHandler.call(this.model,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,o){const n=De;switch(s){case"get":return await n.get(e,r);case"post":return await n.post(e,r,o);case"put":return await n.put(e,r,o);case"delete":return await n.delete(e,r,o);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(o=>{const n=this.getNestedValue(e,o.from),i=o.transform?this.applyTransform(n,o.transform):n;vg(i,o.from,s.path,o.required||!1);const a=wg(i,o.default);r[o.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,o)=>r==null?void 0:r[o],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return Qe.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(o=>{const n=s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o,i=s.idExtractor?s.idExtractor(n):n.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(n):a.instance(i).options(n).build()}):r.map(o=>s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o):(Qe.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s){const r=s.errorHandler||{strategy:"throw"};switch(r.onError&&r.onError(e,this.model),r.strategy){case"throw":throw e;case"log":Qe.error(`Service request failed for ${s.path}:`,e.message);break;case"ignore":break;case"default":if(r.defaultValue!==void 0){const o=Li(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:ue.SINGLE})}break}}}class Mg{constructor(e){c(this,"subscription");c(this,"unsubscribe");c(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(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 Fi(t){return new Mg(t)}const sc=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${jr}:${s}
|
|
31
|
+
- Error: ${y}`),o===Ke.FAIL?new Error(`Dependency resolution failed (policy: FAIL) - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${y}`):p}},Xl=(t,e=x.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[F])||{};return Object.keys(s).length===0?(m.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],a=Zl(t,i);if(!a.success||!a.dependentModel)return m.debug(`Skipping dependency ${i.modelType} with id ${a.dataModelId} - resolution failed with CONTINUE policy`),t.modelData[n]=void 0,null;const{dependentModel:l,dataModelId:u}=a;t.modelData[n]=l.data,m.debug(`waiting for dependent model ${i.modelType} with id ${u} - waiting for WHENREADY`);const d=async(p,y,w)=>{var E;await((E=p.whenReady)==null?void 0:E.call(p)),m.debug(`dependent model ${y} with id ${w} - READY`)},{promise:h,cancel:f}=Wl(Gl,t,t.status);return Promise.race([d(l.model,i.modelType,u).then(()=>{f()}).catch(p=>{const y=St(p,{modelType:i.modelType,modelId:u,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:e,operation:"dependency whenReady()"});throw m.error(y.toDetailedString()),f(),y}),h])}).filter(n=>!!n)},Jl=async(t,e,s,r)=>{if(m.debug(`Execute lifecycle with ${e.length} models`),e.length===0){m.debug(`${t.modelId} has no children. Returning`);return}if(!s){m.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let l;return ar[s]&&a?l=ar[s](a):(a||m.error("model is undefined. This shouldn't happen"),ar[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:l,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),n=await Promise.allSettled(o.map(a=>{var d;if(!a.model||!a.status)return Promise.resolve();const{promise:l,cancel:u}=Wl(Gl,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{const f=St(h,{modelType:a.type||"unknown",modelId:a.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`});throw m.error(f.toDetailedString()),u(),f}),l])})),i=n.filter(a=>a.status==="rejected");if(i.length>0){const a=i.map(l=>{const u=o[n.indexOf(l)];return{error:l.status==="rejected"?l.reason:new Error("Unknown error"),context:{modelType:u.type||"unknown",modelId:u.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`}}});qp(a,`Model ${t.modelId} had ${i.length} failed child model(s) on ${r}`)}},ec=async(t,e,s)=>{await Jl(t,t.getChildren().filter(r=>!!r),e,s)},Xt=async(t,e)=>{const r=(await Promise.allSettled(Xl(t,e))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))};function Xp(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}}}),Jp(t.modelData,t.modelTypeName,t.modelId,t)}function Jp(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,l,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((l=r.companionManager)==null?void 0:l.all())||[],i=r.modelData[F]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.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];bs(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:_n(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 eg{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{Y.setParentContext(r.modelId,this.model.modelId)}catch(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[qe])||{};return Object.keys(e).map(r=>Ql(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 tg{constructor(e){c(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 sg{constructor(e,s,r,o){c(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[rt])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),l=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},u=n?M.reaction(()=>n(this.modelData),l,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(l);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const rg=m.createLogger({name:"model-active-machine"}),og=t=>{const e=b.createMachine(v.INACTIVE,{[v.FAILED]:b.state(b.transition(L.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:b.state(b.transition(L.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:b.invoke(()=>(t.activeStatus=v.ACTIVATING,t.activate()),b.transition("done",v.ACTIVE,b.action(()=>{t.activeStatus=v.ACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED}))),[v.ACTIVE]:b.state(b.transition(L.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:b.invoke(()=>(t.activeStatus=v.DEACTIVATING,t.deactivate()),b.transition("done",v.INACTIVE,b.action(()=>{t.activeStatus=v.INACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED})))});return{service:b.interpret(e,r=>rg.debug(r.machine.current)),machine:e}},Li=m.createLogger({name:"model-online-machine"}),ng=t=>{const e=b.createMachine(v.OFFLINE,{[v.ONLINE]:b.state(b.transition(L.GO_OFFLINE,v.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:b.state(b.transition(L.GO_ONLINE,v.ONLINE,b.action(async()=>{Li.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=v.ONLINE,await t.fsm.transitionTo(L.INITIALIZE,v.INITIALIZED)})))}),s=b.interpret(e,r=>Li.debug(r.machine.current));return{machine:e,service:s}},ig=t=>{var r;const e=og(t).service,s=ng(t).service;return b.createMachine(v.CREATING,{[v.CREATING]:b.state(b.transition(L.CREATE,v.CREATED)),[v.CREATED]:b.state(b.immediate(v.INITIALIZING)),[v.INITIALIZING]:b.invoke(()=>(J(()=>{t.status=v.INITIALIZING}),t.init()),b.transition("done",v.INITIALIZED,b.action(()=>{t.status=v.INITIALIZED})),b.transition("error",v.FAILED,b.action(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=v.FAILED}))),[v.INITIALIZED]:b.state(b.immediate(v.LOADING)),[v.LOADING]:b.invoke(()=>(J(()=>{t.status=v.LOADING}),t.load()),b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.LOADED]:b.state(b.immediate(v.READYING),b.transition(L.UNLOAD,v.UNLOADING)),[v.RESETTING]:b.invoke(()=>{var o;return J(()=>{t.status=v.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED}))),[v.READYING]:b.invoke(()=>(J(()=>{t.status=v.READYING}),t.ready()),b.transition("done",v.READY,b.action(()=>{J(()=>{t.status=v.READY}),s.send(L.GO_ONLINE)})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.READY]:b.state(b.transition(L.UNLOAD,v.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(L.RESET,v.RESETTING),b.transition(L.GO_ONLINE,v.READY,b.action(()=>{s.send(L.GO_ONLINE)})),b.transition(L.GO_OFFLINE,v.READY,b.action(()=>{s.send(L.GO_OFFLINE)})),b.transition(L.GO_ACTIVE,v.READY,b.action(()=>{e.send(L.GO_ACTIVE)})),b.transition(L.GO_INACTIVE,v.READY,b.action(()=>{e.send(L.GO_INACTIVE)}))),[v.UNLOADED]:b.state(),[v.FAILED]:b.state()})},ag=m.createLogger({name:"kos-model-lifecycle"}),lg=t=>({service:b.interpret(ig(t),s=>ag.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class cg{constructor(e,s){c(this,"disposer");c(this,"service");this.model=e,this.log=s;const r=lg(e);this.service=r.service,this.service.send(L.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=v.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const l=this.getTransitionStatusFor(s);return l===s||l===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[v.ACTIVE,v.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const tc="browser-router-model";class On{constructor(e,s){c(this,"logger");c(this,"model");c(this,"router",null);c(this,"registered",!1);c(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!pr(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=_e(tc))==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 pr(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=_l(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(l){this.logger.error(`Error in route handler ${e.method} ${r}:`,l),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:l instanceof Error?l.message:String(l)})}};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 ug(t,e){if(!pr(t))return;const s=_e(tc);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 On(t,e).setRouter(s.model)}class dg{constructor(e){c(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const o=this.queue.length,n=this.filterEventsByStrategy(e,s,r),i=o-n.length;this.log.warn(`Processing ${n.length}/${o} offline message(s) with strategy: ${e}`);for(const a of n)try{a.handler()}catch(l){this.log.error(`Error while processing offline message for topic ${a.topic}:`,l)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${n.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case st.ALL:return[...this.queue];case st.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=s);case st.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=r);case st.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(n=>n.receivedAt),o={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(o.afterRequest=this.queue.filter(n=>n.receivedAt>=e).length),s!==void 0&&(o.afterResponse=this.queue.filter(n=>n.receivedAt>=s).length),o}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class hg{constructor(e,s){c(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(L.GO_ONLINE,v.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(L.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}const sc=()=>({isMock:!1,URL:exports.BASE_URL}),fg=m.createLogger({name:"kos-service-request"}),pg="errUnknown";async function Zs(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=`${sc().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;fg.debug(`fullUrl: ${a}`);const l={method:String(e).toUpperCase(),body:null,...s};o&&(l.body=JSON.stringify(o));const u=await exports.kosFetch(a,l);return u.status<200||u.status>=400?[`${u.statusText||pg}`,null]:[null,(await u.json()).data]}function Bs(){return{get:(t,e,s)=>Zs(t,"get",s,e),post:(t,e,s,r)=>Zs(t,"post",r,e,s),put:(t,e,s,r)=>Zs(t,"put",r,e,s),delete:(t,e,s,r)=>Zs(t,"delete",r,e,s)}}const De=Bs(),rc=Object.freeze(Object.defineProperty({__proto__:null,default:De},Symbol.toStringTag,{value:"Module"})),Xe=m.createLogger({name:"kos-service-request-manager",group:"Model"});function gg(t,e){return!t.condition||t.condition(e)}function mg(t,e){return Ee({value:t.path,modelId:e.id,modelData:e})}function yg(t,e){if(t.pathParams)return Ee({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function bg(t,e){if(t.queryParams)return Ee({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function vg(t,e){if(t.body)return Ee({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function wg(t){return(t||"get").toLowerCase()}function Fi(t,e){return`${e.toUpperCase()}:${t}`}function oc(t){return t==null}function Eg(t,e,s,r){r&&oc(t)&&Xe.warn(`Required field '${e}' is missing in response for ${s}`)}function Mg(t,e){return oc(t)&&e!==void 0?e:t}class Tg{constructor(e,s){c(this,"model");c(this,"responseStore");c(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[ot]||{};Object.values(s).forEach(r=>{const o=r.lifecycle;this.handlers.has(o)||this.handlers.set(o,[]),this.handlers.get(o).push(r)}),Object.keys(s).length>0&&Xe.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(Xe.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return gg(e,this.model)?!0:(Xe.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),[o,n]=await this.performRequest(s),i=this.captureResponseTiming();return{requestContext:s,error:o,response:n,requestedAt:r.requestedAt,receivedAt:i.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=mg(e,this.model),r=yg(e,this.model),o=bg(e,this.model),n=vg(e,this.model),i=wg(e.method);return{resolvedPath:s,method:i,pathParams:r,queryParams:o,body:n}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,o,n){const i=s.cache||{retention:ue.SINGLE},a=Fi(r,s.method||"get");this.responseStore.set(a,e,i,o,n),await s.originalHandler.call(this.model,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,o){const n=De;switch(s){case"get":return await n.get(e,r);case"post":return await n.post(e,r,o);case"put":return await n.put(e,r,o);case"delete":return await n.delete(e,r,o);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(o=>{const n=this.getNestedValue(e,o.from),i=o.transform?this.applyTransform(n,o.transform):n;Eg(i,o.from,s.path,o.required||!1);const a=Mg(i,o.default);r[o.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,o)=>r==null?void 0:r[o],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return Xe.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(o=>{const n=s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o,i=s.idExtractor?s.idExtractor(n):n.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(n):a.instance(i).options(n).build()}):r.map(o=>s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o):(Xe.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s){const r=s.errorHandler||{strategy:"throw"};switch(r.onError&&r.onError(e,this.model),r.strategy){case"throw":throw e;case"log":Xe.error(`Service request failed for ${s.path}:`,e.message);break;case"ignore":break;case"default":if(r.defaultValue!==void 0){const o=Fi(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:ue.SINGLE})}break}}}class Sg{constructor(e){c(this,"subscription");c(this,"unsubscribe");c(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(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 Ni(t){return new Sg(t)}const nc=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${Br}:${s}
|
|
32
32
|
`;return o+=`topic:${t}
|
|
33
|
-
`,o+=`${
|
|
33
|
+
`,o+=`${Ut}:${t}
|
|
34
34
|
`,o+=`${ks}:${e}
|
|
35
35
|
`,r&&(o+=`${Ne}:${r}
|
|
36
36
|
`),o+=`${Oe}:kos.studio.request
|
|
37
37
|
`,o+=`
|
|
38
|
-
`,o},
|
|
39
|
-
`;return i+=`${
|
|
40
|
-
`,i+=`${
|
|
41
|
-
`,i+=`${
|
|
38
|
+
`,o},ic=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n})=>{let i=`${Ma}:/http${t}
|
|
39
|
+
`;return i+=`${Br}:${s}
|
|
40
|
+
`,i+=`${Ut}:${t}
|
|
41
|
+
`,i+=`${_a}:${e}
|
|
42
42
|
`,r&&(i+=`${Ne}:${r}
|
|
43
|
-
`),o&&(i+=`${
|
|
44
|
-
`),n&&(i+=`${
|
|
43
|
+
`),o&&(i+=`${sn}:true
|
|
44
|
+
`),n&&(i+=`${rn}:${n}
|
|
45
45
|
`),i+=`${Oe}:fos.http.request
|
|
46
46
|
`,i+=`
|
|
47
|
-
`,i},
|
|
48
|
-
`;return l+=`${
|
|
47
|
+
`,i},ac=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n,bridge:i,headers:a})=>{let l=`${Br}:${s}
|
|
48
|
+
`;return l+=`${Ut}:${t}
|
|
49
49
|
`,l+=`${ks}:${e}
|
|
50
50
|
`,r&&(l+=`${Ne}:${r}
|
|
51
|
-
`),o&&(l+=`${
|
|
52
|
-
`),n&&(l+=`${
|
|
51
|
+
`),o&&(l+=`${sn}:true
|
|
52
|
+
`),n&&(l+=`${rn}:${n}
|
|
53
53
|
`),a&&Object.keys(a).forEach(u=>{l+=`${u}:${a[u]}
|
|
54
54
|
`}),l+=`${Oe}:${i?"fos":"kos"}.http.request
|
|
55
55
|
`,l+=`
|
|
56
|
-
`,l},
|
|
57
|
-
`;return r+=`${
|
|
56
|
+
`,l},We=(t,e)=>{let s=t;return e&&(s+=e),s};function Jt(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 es(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 lc=({path:t,requestId:e,destinationAddress:s})=>{let r=`topic:${t}
|
|
57
|
+
`;return r+=`${Ut}:${t}
|
|
58
58
|
`,r+=`${ks}:${e}
|
|
59
59
|
`,r+=`${Ne}:${s}
|
|
60
60
|
`,r+=`${Oe}:kos.studio.request
|
|
61
61
|
`,r+=`
|
|
62
|
-
`,r},
|
|
62
|
+
`,r},cc=({requestId:t,destinationAddress:e,requestType:s,headers:r})=>{let o=`${ks}:${t}
|
|
63
63
|
`;return o+=`${Ne}:${e}
|
|
64
64
|
`,o+=`${Oe}:${s}
|
|
65
65
|
`,r&&Object.keys(r).forEach(n=>{o+=`${n}:${r[n]}
|
|
66
66
|
`}),o+=`
|
|
67
|
-
`,o},
|
|
68
|
-
`;return o+=`${
|
|
69
|
-
`,e&&(o+=`${
|
|
70
|
-
`),o+=`${
|
|
67
|
+
`,o},Ig=(t,e)=>{const s=t,r=We(cc(e),typeof s=="string"?s:JSON.stringify(s)),o=_.getInstance().transport.socket;o?(m.debug("Sending message",r),o.socket.send(r)):m.error("socket transport is not initialized")},uc=({path:t,responseId:e,status:s,destinationAddress:r})=>{let o=`topic:${t}
|
|
68
|
+
`;return o+=`${Ut}:${t}
|
|
69
|
+
`,e&&(o+=`${Hr}:${e}
|
|
70
|
+
`),o+=`${tn}:${s}
|
|
71
71
|
`,o+=`${Ne}:${r}
|
|
72
72
|
`,o+=`${Oe}:kos.studio.response
|
|
73
73
|
`,o+=`
|
|
74
|
-
`,o},
|
|
74
|
+
`,o},_g=(t,e)=>{const s=t,r=We(lc(e),JSON.stringify(s)),o=_.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},Og=(t,e)=>{const s=e.responseId?{status:e.status,data:t}:t,r=We(uc(e),JSON.stringify(s)),o=_.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},dc=({topic:t})=>{let e=`topic:${t}
|
|
75
75
|
`;return e+=`${Oe}:kos.broker.send
|
|
76
76
|
`,e+=`
|
|
77
|
-
`,e},
|
|
77
|
+
`,e},hc=({responseId:t,destinationAddress:e,type:s,sourceAddress:r,status:o})=>{let n=`${Hr}:${t}
|
|
78
78
|
`;return n+=`${Ne}:${e}
|
|
79
|
-
`,n+=`${
|
|
79
|
+
`,n+=`${Ta}:${r}
|
|
80
80
|
`,n+=`${Oe}:${s??"kos.message.request"}
|
|
81
|
-
`,n+=`${
|
|
82
|
-
`,n+=`${
|
|
83
|
-
`,n+=`${
|
|
81
|
+
`,n+=`${tn}:${o}
|
|
82
|
+
`,n+=`${Sa}:application/json
|
|
83
|
+
`,n+=`${Ia}:no-cache
|
|
84
84
|
`,n+=`
|
|
85
|
-
`,n},
|
|
86
|
-
`;return e&&(o+=`${
|
|
85
|
+
`,n},fc=({topic:t,responseId:e,destinationAddress:s,type:r})=>{let o=`topic:${t}
|
|
86
|
+
`;return e&&(o+=`${Hr}:${e}
|
|
87
87
|
`),o+=`${Ne}:${s}
|
|
88
88
|
`,o+=`${Oe}:${r??"kos.message.request"}
|
|
89
89
|
`,o+=`
|
|
90
|
-
`,o}
|
|
90
|
+
`,o},$g=({msg:t,options:e})=>{const s=t,r=We(dc(e),JSON.stringify(s)),o=_.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},pc=({msg:t,options:e})=>{const s=t,r=We(fc(e),JSON.stringify(s)),o=_.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},gc=({msg:t,options:e})=>{const s=t,r=We(hc(e),JSON.stringify(s)),o=_.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},Lo=(t,e)=>{try{return e?t.body??t:JSON.parse(t.body)}catch{return t.body||t}};class Cg{constructor(e){c(this,"config");c(this,"stats");c(this,"filterHistory",[]);c(this,"activePromises",new Set);c(this,"eventQueue",[]);c(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 l=[...n];n=[],i=Date.now();const u=this.config.filter?l.filter(h=>this.shouldProcessEvent(h)):l;if(u.length===0)return;this.config.backpressure&&await this.waitForCapacity();const d=this.config.transform?this.config.transform(u):u;return this.stats.batchesProcessed++,this.updateProcessingStats(u),d};try{for await(const u of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(u);this.eventQueue.length>0;){const d=this.dequeueEvent();d&&n.push(d);const f=Date.now()-i;if(n.length>=r||f>=o){const p=await a();p!==void 0&&(yield p);break}}else{n.push(u);const h=Date.now()-i;if(n.length>=r||h>=o){const f=await a();f!==void 0&&(yield f)}}const l=await a();l!==void 0&&(yield l)}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 Dg extends WebSocket{constructor(e){super(e)}}function Ui(t){const e=`
|
|
91
91
|
|
|
92
92
|
`,s=`
|
|
93
|
-
`,r=/:(.*)/s,[o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,l)=>{const[u,d]=l.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}function
|
|
93
|
+
`,r=/:(.*)/s,[o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,l)=>{const[u,d]=l.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}function xg(t){const e=`
|
|
94
94
|
|
|
95
95
|
`,s=`
|
|
96
|
-
`,r=/:(.*)/s,[,o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,l)=>{const[u,d]=l.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}class
|
|
96
|
+
`,r=/:(.*)/s,[,o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,l)=>{const[u,d]=l.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}class $n{constructor({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:n,onConnectionLost:i,Transport:a=Dg}){c(this,"host");c(this,"port");c(this,"protocol");c(this,"socket");c(this,"connectionEstablished");c(this,"alias");c(this,"onConnectionEstablished");c(this,"onConnectionLost");c(this,"offlineMessages",[]);c(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,C("/mock/msg/receive",l=>{var u,d;if(l!=null&&l.body){m.wsReceive(l==null?void 0:l.body);const h={data:l.body};(d=(u=this.socket)==null?void 0:u.onmessage)==null||d.call(u,h)}}),M.makeObservable(this,{connectionEstablished:M.observable})}addOfflineMessage(e){this.offlineMessages.push({msg:e})}processMessageEvent(e){const{data:s}=e;return Ui(s)}onMessage(e){try{m.debug("webSocketTransport: onMessage received");const{headers:s,body:r}=this.processMessageEvent(e);m.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:l}=xg(e.data);n=l,i={...s,...a}}V(o,n,i)}}catch(s){m.error("onMessage exception",s.message,s.stack)}}onOpen(e){m.info("websocket connection opened"),this.socket=e.currentTarget,M.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
|
|
97
97
|
alias:${this.alias}
|
|
98
98
|
|
|
99
|
-
`),m.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;m.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),M.runInAction(()=>{this.connectionEstablished=!1}),m.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(e){var s,r;if(m.wsSend(e),window.kosLogEvents){const{headers:o,body:n}=
|
|
99
|
+
`),m.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;m.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(){this.socket&&this.socket.close(),M.runInAction(()=>{this.connectionEstablished=!1}),m.debug("websocket disconnected. Attempting calling callback"),this.onConnectionLost&&setTimeout(this.onConnectionLost,2500)}send(e){var s,r;if(m.wsSend(e),window.kosLogEvents){const{headers:o,body:n}=Ui(String(e));V(Ls.SEND,{headers:o,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:o,requestId:n}=window.kosTopicIntercept(e);if(o){e=`mocked:true
|
|
100
100
|
${e}`;const a={data:`mocked:true
|
|
101
|
-
${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
|
|
101
|
+
${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 Ag{constructor(e){c(this,"addEventListener");c(this,"dispatchEvent");c(this,"removeEventListener");c(this,"_onclose");c(this,"_onerror");c(this,"_onmessage");c(this,"_onopen");c(this,"messageQueue",[]);c(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 Rg extends $n{constructor({host:s,port:r,alias:o}){super({host:s,port:r,Transport:Ag,alias:o,protocol:"kos://"});c(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class Pg extends $n{constructor({host:s,port:r}){super({host:s,port:r,protocol:"ws://"});c(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class kg extends $n{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});c(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 Fo{static build({host:e,port:s,protocol:r,fos:o,alias:n,onConnectionEstablished:i,onConnectionLost:a}){return m.debug("initializing websocket connection"),m.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),m.warn(`fos: ${o?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!o?(m.warn("Using bridged message transport"),new Rg({host:e,port:s,protocol:r,onConnectionEstablished:i,onConnectionLost:a,alias:n})):o?new Pg({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a}):new kg({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a})}}const Lg=me();Lg.fos&&(window.kosUseFos=!0);const ji=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=ji?parseInt(ji):0;const Ze=D.getLogger("web-socket-transport");var mc=(t=>(t.NOT_INITIALIZED="not_initialized",t.INITIALIZED="initialized",t.OFFLINE="OFFLINE",t.ONLINE="ONLINE",t))(mc||{}),vs=(t=>(t.CONNECTED="websocket.connected",t.DISCONNECTED="websocket.disconnected",t.RELOAD="websocket.reload",t))(vs||{});class Ot{constructor({host:e="localhost",port:s=8080,protocol:r="ws://",token:o,initialize:n,alias:i,fos:a}){c(this,"host");c(this,"port");c(this,"protocol");c(this,"_token");c(this,"webSocketSupported",!!globalThis.WebSocket);c(this,"authorized");c(this,"alias");c(this,"socket");c(this,"fosSocket");c(this,"fosPort");c(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 l=!1;M.makeObservable(this,{authorized:M.observable,socket:M.observable,fosSocket:M.observable,init:M.action,connectionEstablished:M.computed}),M.reaction(()=>this.connectionEstablished,u=>{u&&(Ze.warn("Connection Established"),V("websocket.connected","websocket.connected"),l&&V("websocket.reload","websocket.reload"),l=!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(m.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=Fo.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=Fo.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{Ze.error("Connection Lost"),V("websocket.disconnected","websocket.disconnected"),this.init()}}),globalThis.kosWindowWebsocketOpen){const r={currentTarget:this.socket.socket};(s=(e=this.socket.socket)==null?void 0:e.onopen)==null||s.call(e,r)}return this}_sendSubscriptionMessage(e,s,r=!1,o=!1,n){var f,p,y,w;Ze.debug(`${s} to topic ${e}`);const i=me(),a=i==null?void 0:i.connId,l=n??a??((f=window==null?void 0:window.kosBridge)==null?void 0:f.call(window,"connId"));Ze.debug(`subscribing with connId ${l}`);const u=l?`dst-addr:${l}
|
|
102
102
|
`:"",d=r?`subscribe:${e}`:o?`type:fos.broker
|
|
103
103
|
cmd:${s}
|
|
104
104
|
${u}topics:${e}
|
|
105
105
|
`:`${u}type:kos.broker.${s}
|
|
106
106
|
|
|
107
|
-
["${e}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(w=E==null?void 0:E.socket)==null||w.send(d)}else{We.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(d)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=C(e,s);return We.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:l}=i();We.debug(`Topic ${e} currently has ${l} subscribers`),l===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}}c(It,"_instance");class kg{constructor(e,s,r,o,n){c(this,"disposers",[]);c(this,"activatableDisposers",[]);c(this,"flowControllers",new Map);c(this,"baselineDependencies",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[ee])||{},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 l=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${l}`),i.requiresBaseline&&(this.baselineDependencies.set(l,i.requiresBaseline),this.log.debug(`Registered baseline dependency for ${l}: ${i.requiresBaseline.path}`)),i.flow)this.subscribeWithFlowControl(i,l,a);else{const u=this.createHandler(l,i);this.subscribe(i,l,u,a===x.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,o){const n=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=It.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}=C(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,l=this.extractWildcardCapture(e,r,s),u=this.isBaselineReady(e);if(!this.model.isReady()||!u){u?this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`):this.log.warn(`Baseline not ready for ${e}. Queuing message.`);const d=()=>{const h=ko(r,s.skipParse),f=s.transform(h);if(a&&s.condition(f,this.modelData,r))return this.callHandlerWithWildcard(s,f,l,r)};this.offlineQueue.enqueue(d,e,r)}else{const d=ko(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,l,r)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!Ul(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return Nl(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 Og(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(l=>l==null?void 0:l.abort())};r===x.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;It.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Fi(s)}else i=Fi(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const l=r(a);l instanceof Promise&&await o.trackPromise(l)}}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 l=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(l,e,r)}}catch(l){if(this.log.error(`Error in flow control handler for ${e}:`,l),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,l);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw l}}}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}getResponseStore(){return this.modelData.serviceResponses}isBaselineReady(e){const s=this.baselineDependencies.get(e);if(!s)return!0;const r=this.getResponseStore();if(!r)return this.log.warn(`ServiceResponseStore not found for baseline check on topic: ${e}`),!1;const n=`${(s.method||"get").toUpperCase()}:${s.path}`;return r.has(n)}flushQueueForBaseline(e){const s=this.baselineDependencies.get(e);if(!s){this.log.debug(`No baseline dependency for topic: ${e}`);return}const r=this.getResponseStore();if(!r){this.log.warn("ServiceResponseStore not found, falling back to standard flush"),this.offlineQueue.flush();return}const o=s.method||"get",n=r.getTemporalMetadataByPath(s.path,o);if(!n){this.log.warn(`Baseline temporal metadata not found for ${s.path}, falling back to standard flush`),this.offlineQueue.flush();return}const i=s.replayStrategy||et.AFTER_REQUEST;this.log.info(`Flushing queue with strategy ${i} for topic: ${e}`),this.log.debug(`Baseline timing - requested: ${n.requestedAt}, received: ${n.receivedAt}`),this.offlineQueue.flushWithStrategy(i,n.requestedAt,n.receivedAt)}}function ft(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 Lg(t){return!!(t!=null&&t[tt])&&Object.keys(t[tt]).length>0}function Fg(t){return!!(t!=null&&t[ee])&&Object.keys(t[ee]).length>0}function Ng(t){return!!(t!=null&&t[Pe])&&t[Pe].length>0}function Ug(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[st])&&Object.keys(e[st]).length>0}function jg(t){return t.retention===ue.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function Bg(t,e){return t.has(e)}function Hg(t){return!t.expiresAt||Date.now()<t.expiresAt}function ji(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class Kg{constructor(){c(this,"responses",new Map);c(this,"retentionPolicies",new Map);c(this,"cleanupTimers",new Map)}set(e,s,r={retention:ue.SINGLE},o=Date.now(),n=Date.now()){if(this.shouldExtendTTL(e,r))return this.extendExistingTTL(e,r.ttl),!1;const i=this.createCachedResponse(s,e,r,o,n);return this.storeResponse(e,i,r),!0}get(e){const s=this.responses.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.delete(e);return}return s.data}}getByPath(e,s="get"){return this.get(this.makeKey(e,s))}has(e){return this.get(e)!==void 0}delete(e){this.responses.delete(e),this.retentionPolicies.delete(e);const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}clearPath(e){Array.from(this.responses.keys()).filter(r=>this.extractPath(r)===e).forEach(r=>this.delete(r))}clear(){this.cleanupTimers.forEach(e=>clearTimeout(e)),this.responses.clear(),this.retentionPolicies.clear(),this.cleanupTimers.clear()}get size(){return this.responses.size}shouldCleanupAfterHandler(e){const s=this.retentionPolicies.get(e);return(s==null?void 0:s.retention)===ue.IMMEDIATE}shouldExtendTTL(e,s){if(!jg(s)||!Bg(this.responses,e))return!1;const r=this.responses.get(e);return Hg(r)}extendExistingTTL(e,s){const r=this.responses.get(e);r.expiresAt=Date.now()+s,this.resetCleanupTimer(e,s)}resetCleanupTimer(e,s){this.clearTimerIfExists(e),ji(e,s,this.cleanupTimers,r=>this.delete(r))}clearTimerIfExists(e){const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}createCachedResponse(e,s,r,o,n){return{data:e,timestamp:n,requestedAt:o,receivedAt:n,path:this.extractPath(s),method:this.extractMethod(s),expiresAt:this.calculateExpiresAt(r)}}calculateExpiresAt(e){return e.retention===ue.TTL&&e.ttl?Date.now()+e.ttl:void 0}storeResponse(e,s,r){this.responses.set(e,s),this.retentionPolicies.set(e,r),this.applyRetentionPolicy(e,r)}applyRetentionPolicy(e,s){switch(s.retention){case ue.IMMEDIATE:break;case ue.TTL:s.ttl&&ji(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case ue.SINGLE:break;case ue.PERMANENT:case ue.MANUAL:break}}makeKey(e,s){return`${s.toUpperCase()}:${e}`}extractPath(e){return e.split(":",2)[1]||e}extractMethod(e){return e.split(":",2)[0]||"get"}getTemporalMetadata(e){const s=this.responses.get(e);if(s)return{requestedAt:s.requestedAt,receivedAt:s.receivedAt}}getTemporalMetadataByPath(e,s="get"){return this.getTemporalMetadata(this.makeKey(e,s))}cleanup(){const e=Date.now();Array.from(this.responses.entries()).filter(([r,o])=>o.expiresAt&&e>o.expiresAt).map(([r])=>r).forEach(r=>this.delete(r))}}class qg{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=Sl.create({modelId:s,modelTypeName:r}),i=new ag(e,ft(n,"fsm")),a=new cg(ft(n,"offline-queue")),l=new Jp(e),u=new Xp(e),d=new Kg;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:l,childResolver:u};if(Lg(o)&&(h.effectManager=new eg(r,s,o,ft(n,"effect"))),Fg(o)){const f=ft(n,"subscription");h.subscriptionManager=new kg(e,o,s,a,f),h.onlineLifecycleManager=new ug(e,ft(n,"online"))}return Ng(o)&&(h.httpRouteManager=new In(o,ft(n,"http-routes"))),Ug(o)&&(h.serviceRequestManager=new Eg(o,d)),h}}const U=D.getLogger("kos-model"),zg="kos.extension.model.loader";class pc{constructor({modelTypeName:e,id:s,modelData:r}){c(this,"_id");c(this,"_status");c(this,"_activeStatus");c(this,"_onlineStatus");c(this,"modelData");c(this,"modelTypeName");c(this,"initialized");c(this,"loaded");c(this,"offlineQueue");c(this,"subscriptionManager");c(this,"effectManager");c(this,"httpRouteManager");c(this,"onlineLifecycleManager");c(this,"serviceResponses");c(this,"serviceRequestManager");c(this,"companionManager");c(this,"childResolver");c(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const o=qg.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,this.serviceResponses=o.serviceResponseStore,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),o.serviceRequestManager&&(this.serviceRequestManager=o.serviceRequestManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,serviceRequestManager:!1,serviceResponses:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Qp(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===v.ACTIVE}isOnline(){return this._onlineStatus===v.ONLINE}isReady(){return this._status===v.READY}async deactivate(){var e,s,r;U.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=Y.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw U.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r,o;U.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await Xt(this,x.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.ACTIVATE));const n=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),this.initializeStateMachineForLifecycle(x.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(x.ACTIVATE),this.createLifecycleCompanions(x.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(n){throw U.debug(`Model ${this.modelId} failed to activate`),n}}async whenLoaded(){await wo([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{U.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await wo([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{U.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await wo([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{U.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,o;if(this.fsm.current===v.READY){U.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{U.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await Xt(this,x.READY),await Zl(this,Tn.READY,x.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.READY));const n=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.ready)==null?void 0:r.call(s,n)),this.offlineQueue.flush(),this.initializeStateMachineForLifecycle(x.READY),(o=this.subscriptionManager)==null||o.registerAll(x.READY),this.createLifecycleCompanions(x.READY),U.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};V(Hl(this.modelTypeName,this.modelId),i),V(Kl(this.modelTypeName),i)}catch(n){throw U.error(n),Error(n)}}async load(){var o,n,i,a,l,u;const e=this[Ke];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED||this.fsm.current===v.LOADING){U.debug(`Model ${s} with id ${r} already loaded or loading`);return}U.debug(`Loading model ${s} with id ${r}`),await Xt(this,x.LOAD);try{const d=Y.getContext(r),h=`${zg}.${s}`,f=await $.loader.executeLoader(h,{});f&&(U.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(x.LOAD)),await((i=(n=this.modelData)==null?void 0:n.load)==null?void 0:i.call(n,d)),X(()=>{this.loaded=!0}),U.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(x.LOAD),(a=this.subscriptionManager)==null||a.registerAll(x.LOAD),(l=this.httpRouteManager)==null||l.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(x.LOAD)}catch(d){throw U.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,o,n,i,a;U.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const l=this.getChildren().map(d=>{var h;return(h=d.unload)==null?void 0:h.call(d)}).filter(d=>!!d);await Promise.allSettled(l);const u=Y.getContext(this.modelId);if(await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,u)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),this.modelData){const d=this.modelData;if(d._fsmInitialized=!1,d._fsmConfig){const h=((o=d._fsmOptions)==null?void 0:o.stateProperty)||"currentState";d[h]=void 0}d.stateHistory&&(d.stateHistory=[])}U.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(n=this.effectManager)==null||n.disposeAll(),(i=this.subscriptionManager)==null||i.disposeAll(),(a=this.httpRouteManager)==null||a.dispose()}catch(l){throw U.debug(`Model ${this.modelId} failed to unload`),l}}async init(){var n,i,a,l;const e=this[Ke];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=Y.getContext(s);U.debug(`Initializing model ${r} with id ${s}`),await Xt(this,x.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(x.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,o)),this.initialized=!0,U.debug(`Model ${r} with id ${s} initialized`),(l=this.onlineLifecycleManager)==null||l.register(),this.initializeStateMachineForLifecycle(x.INIT),this.registerSubscribers(x.INIT),this.createLifecycleCompanions(x.INIT)}catch(u){throw U.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;U.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&vl(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;U.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(x.ONLINE)}async offline(){var s,r,o;U.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=Y.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 Eo=m.createLogger({name:"kos-model-instantiator"});class Vg{constructor(e,s){c(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new Kp(e,s,this.createModelInstance.bind(this))}createModelInstance(e,s,r={}){var a;const o=this.registry.models[e];if(!o){const l=`No model registered for type ${e}`;throw Eo.error(l,{modelType:e,requestedId:s,providedOptions:r,availableModelTypes:Object.keys(this.registry.models)}),Mt(new Error(l),{modelType:e,modelId:s,operation:"model instantiation - registry lookup",options:r,metadata:{availableModelTypes:Object.keys(this.registry.models)}})}const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Eo.debug(`Creating model instance: ${e} [${n}]`);const l=r&&Object.keys(r).length>0,u=o.class||o.create;if(((a=u==null?void 0:u.prototype)==null?void 0:a[Us])===!0&&!l){const h=new Error(`Model ${e} requires options but none were provided`);throw Ri(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Mt(h,{modelType:e,modelId:n,operation:"model instantiation - options validation",options:r,metadata:{requiresOptions:!0,hasOptions:!1}})}try{const h=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),f=new pc({modelTypeName:e,id:n,modelData:h});this.cache.addModel(f),this._createCompanionModels(f,r)}catch(h){throw Ri(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Mt(h,{modelType:e,modelId:n,operation:"model instantiation",options:r})}}const i=this.cache.getModelById(n);if(!i)throw Eo.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,r){this.companionInstantiator.createCompanionModels(e,s,r)}_createCompanionModels(e,s){this.createCompanionModels(e,s)}}let Gg=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 Ut(e)}};const gc=10,Bi=m.createLogger({name:"kos-model-manager"});class mc{constructor(){c(this,"cache");c(this,"instantiator");c(this,"dependencies");c(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new jp,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 Gg(e),r.cache=new Bp(e.preloadModels),r.instantiator=new Vg(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Bi.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=>(Bi.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 Ut(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(F.RESET,v.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),jl.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),gc)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}createLifecycleCompanions(e,s,r){this.instantiator.createCompanionModels(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var ar=(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))(ar||{}),bt=(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))(bt||{});const Yg=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,n=>D.debug(n.machine.current)),r=b.createMachine({creating:b.state(b.transition("create","created")),created:b.state(b.immediate("initializing")),initializing:b.invoke(()=>t.init(),b.transition("done","initialized")),initialized:b.state(b.immediate("loading")),loading:b.invoke(()=>t.load(),b.transition("done","loaded")),loaded:b.state(b.immediate("readying"),b.transition("unload","unloading")),readying:b.invoke(()=>t.ready(),b.transition("done","ready",b.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:b.invoke(()=>t.reload(),b.transition("done","loading")),ready:b.state(b.transition("reload","reloading"),b.transition("unload","unloaded",b.action(t.unload.bind(t))),b.transition("go_online","ready",b.action(()=>{s.send("go_online")})),b.transition("go_offline","ready",b.action(()=>{s.send("go_offline")}))),unloaded:b.state()});return{service:b.interpret(r,n=>D.debug(n.machine.current)),online:s}},Q=m.createLogger({name:"kos-core"}),Wg=()=>{const t=me(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},Qg=()=>{const t=window.location.protocol,e=me(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},Zg=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=me(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},Xg=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=me(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},Jg=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?m.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):m.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},Hi=t=>typeof t.reload=="function",em=t=>typeof t.unload=="function";var yc=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(yc||{});class _{constructor(e){c(this,"fsmService");c(this,"status");c(this,"initialized");c(this,"loaded");c(this,"_transport");c(this,"modelManager");c(this,"authState");c(this,"isOnline");c(this,"_reloading");c(this,"_unloading");c(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=ar.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(vs.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(bt.GO_ONLINE)}),C(vs.DISCONNECTED,async()=>{this.fsmService.service.send(bt.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(vs.RELOAD,()=>{Q.warn("WebSocket requested reload"),this.fsmService.service.send(bt.RELOAD)}),C("/studio/project/reload",()=>{Q.warn("Project requested reload"),this.fsmService.service.send(bt.RELOAD)});const s=It.getInstance(),r=Zg(),o=Xg(),n=Qg();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Wg()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Yg(this),this.fsmService.service.send(bt.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){Q.info("reload already in progress");return}this._reloading=!0,Q.warn("reloading KOS Core"),Q.warn("reloading preloaded models");const s=this.modelManager;for(const l of s.preloadedModels)Hi(l.modelData)&&(Q.info(`reloading model ${l.modelId}`),(o=l.unload)==null||o.call(l),await l.modelData.reload(),(n=l.registerSubscribers)==null||n.call(l),Q.info(`reloading model ${l.modelId} complete`));for(const l of s.models)!s.preloadedModels.includes(l)&&Hi(l.modelData)&&((i=l.unload)==null||i.call(l),await l.modelData.reload(),(a=l.registerSubscribers)==null||a.call(l));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{Q.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Q.debug("KOS Core going online"),await this._transport.whenReady(),Q.debug("KOS Transport Ready. Calling online() for models"),V("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Q.debug("KOS Core going offline"),V("/kosCore/offline","/kosCore/offline")}async unload(){var o;Q.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Q.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)em(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===ar.READY)}async ready(){Q.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}=Jg(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Q.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Q.debug("leaving kos-core ready() ")}get isReady(){return this.status===ar.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Q.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Q.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Q.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Q.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,l;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{$.dataMapper.registerDataMapper(u,p)}):$.dataMapper.registerDataMapper(u,d))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&$.propertyMapper.registerPropertyMapper(u,d)}),(l=e.extensions)!=null&&l.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&$.loader.registerLoader(u,d)}),A.model.getAll().forEach(([,u])=>{e.models={...e.models,...u.registration}}),e.models={...e.models,...A.model.getLegacyModels()},A.companion.getAll().forEach(([u,d])=>{e.companionModels={...e.companionModels},e.companionModels[u]=e.companionModels[u]||[];for(const h of d){let f;if(typeof h=="string"){const p=e.models[h];if(p!=null&&p.class){const y=p.class.prototype[Ke];f=y==null?void 0:y.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),A.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=mc.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}}c(_,"_instance");function Fo(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 tm(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 sm(t){return await t.arrayBuffer()}function rm(t,e){return new Blob([t],{type:e})}async function om(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:Fo(i)})}else e[o]=n.toString();return{fields:e,files:s}}function nm(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function im(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:Fo(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await sm(t);return{data:Fo(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await om(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Zs=m.createLogger({name:"kos-fetch"}),am=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,lm=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),cm=t=>t!=null&&t.studio?sc:t!=null&&t.fos?rc:oc,um=async(t,e)=>{const s=_.getInstance().transport;await s.whenReady();const r=it(),o=new URL(t),n=`${o.pathname}${o.search}`;Zs.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||am,a=cm(e),l=await im(e==null?void 0:e.body),u={};l.contentType&&(u["content-type"]=l.contentType),l.encoding&&(u["content-encoding"]=l.encoding);const d=Ge(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,...u}}),l.data);return new Promise(h=>{let f=null,p=null;if(e!=null&&e.signal){if(e.signal.aborted){h({headers:Jt({}),status:0,ok:!1,json:async()=>null,body:es(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}});return}e.signal.addEventListener("abort",()=>{p&&clearTimeout(p),f&&f(),h({headers:Jt({}),status:0,ok:!1,json:async()=>null,body:es(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})})}p=setTimeout(()=>{Zs.error(`Timeout occurred - url: ${t}`),f&&f(),h({headers:Jt({}),status:404,ok:!1,json:async()=>null,body:es(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i);const y=C(r,E=>{p&&clearTimeout(p);const S=(E==null?void 0:E.headers)||{},L=S["content-type"]||"text/plain",R=S["content-encoding"],O=(E==null?void 0:E.body)||"";let I=O;if(R==="base64"&&O)try{I=tm(O)}catch(q){Zs.error("Failed to decode base64 response",q)}const K={headers:Jt(S),status:S.status&&parseInt(S.status)||200,ok:S.status==="200",json:async()=>{try{if(typeof I=="string")return I.length?JSON.parse(I):null;{const J=new TextDecoder().decode(I);return J.length?JSON.parse(J):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof I=="string"?I:new TextDecoder().decode(I),arrayBuffer:async()=>I instanceof ArrayBuffer?I:new TextEncoder().encode(I).buffer,blob:async()=>I instanceof ArrayBuffer?rm(I,L):new Blob([I],{type:L}),formData:async()=>{const q=new FormData;if(L==="multipart/form-data"&&typeof I=="string")try{const J=JSON.parse(I);J.fields&&Object.entries(J.fields).forEach(([Gt,Yt])=>{q.append(Gt,Yt)}),J.files&&Zs.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return q},body:e!=null&&e.stream?nm(async q=>{if(I instanceof ArrayBuffer)q.enqueue(new Uint8Array(I));else{const J=new TextEncoder;q.enqueue(J.encode(I))}q.close()}):es(typeof I=="string"?I:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};y.unsubscribe(),lm().then(()=>h(K))});f=y.unsubscribe;const w=e!=null&&e.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${e}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=um;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const dm=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class hm{constructor(){c(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=_.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)){dm.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)}))}}class bc{constructor(){c(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 fm=async(t,e)=>{const s=new bc;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},Ut=t=>({type:t,build:(e,s)=>_.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=_.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),pm=t=>{_.getInstance().modelManager.registerModel(t)},gm=(t,e)=>{_.getInstance().modelManager.registerCompanionModel(t,e)},Ki="/kos/ui/internal/heartbeat/",mm=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=_.getInstance().transport,i=new AbortController;let a=performance.now();const l=n.subscribeTopic({topic:`${Ki}${t}`,callback:()=>{a=performance.now()}}),u=r??3e3,d=window.setInterval(()=>{let w=performance.now()-a;w=w/1e3,w>u/1e3&&i.abort()},u),h=o??2e3,f=window.setInterval(()=>{dc({msg:{},options:{topic:`${Ki}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),l()},y=()=>{p(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:p}},vc=(...t)=>e=>t.reduce((s,r)=>r(s),e),ym={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function bm(t,e){let s=1;const r={...ym,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(l){if(m.error(`Attempt ${s} failed: ${l}`),s<o)a=n*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw l}throw new Error("All attempts failed")}const vm=m.createLogger({name:"kos-service-request"}),ae=t=>({isMock:!1,URL:exports.BASE_URL}),wm=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:l,bridge:u,destinationAddress:d})=>{const h={method:"DELETE"};t&&(h.destinationAddress=t),o&&(h.tracker=o),jt(h,{ordered:i,studio:a,fos:l,bridge:u,destinationAddress:d});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()},jt=(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),Em=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:l,destinationAddress:u})=>{const d={method:"GET"};t&&(d.destinationAddress=t),jt(d,{timeout:l,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const f=await s(r||e,d);if(!f.ok){let y;try{y=await f.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${f.status}`,y)}return await f.json()},Mm=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:l,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),l&&(h.tracker=l),jt(h,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=r||e;vm.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},Tm=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:l,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),jt(h,{timeout:u,ordered:n,studio:i,fos:a,bridge:l,destinationAddress:d});const f=r||`${e}/${o}`,p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class ge extends Error{constructor(s,r){super(s);c(this,"payload");this.name="FetchException",this.payload=r}}const qi=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:l,bridge:u,timeout:d,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(f.destinationAddress=t),i&&(f.tracker=i),jt(f,{timeout:d,ordered:n,studio:a,fos:l,bridge:u,destinationAddress:h});const p=await s(o||e,f);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},zi=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:l,fos:u,bridge:d,timeout:h,destinationAddress:f})=>{const p={method:t};o&&(p.body=JSON.stringify(o)),e&&(p.destinationAddress=e),jt(p,{timeout:h,ordered:a,studio:l,fos:u,bridge:d,destinationAddress:f});const y=await r(i||`${s}/${n}`,p);if(!y.ok){let E;try{E=await y.json()}catch{}throw new ge(`There was a problem modifying the model; returned status ${y.status}`,E)}return await y.json()},oe={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const l=a?fetch:exports.kosFetch;return{getAll:Em(t,s||e,l),getModelById:Tm(t,r||e,l),getOne:Mm(t,r||e,l),addModel:qi(t,n||e,l),deleteModel:wm(t,o||e,l),modifyModel:zi("POST",t,i||e,l),putModel:zi("PUT",t,i||e,l),postModel:qi(t,n||e,l)}}};function Sm(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function Im(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function _m(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function Om(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function $m(t){const e=t.serviceResponses;e&&e.clear()}const Cm=it(),wc=()=>`kos-${Cm}`,Dm=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(wc()),$n=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=C(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)}),xm=async(t,e,s)=>{const r=$n(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)},Am=async({topic:t,msg:e,requestId:s})=>{const r=s??it(),o=$n(r);V(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},he=new Map;class Ec{constructor(e){c(this,"_context");c(this,"_parent");c(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){X(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=_e(this._parent))==null?void 0:e.model}get companionModels(){const e=_e(this._id);return e!=null&&e.model?Rl(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||!he.has(n.id)?!1:(i=he.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=he.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=he.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const Y={createContext:(t,e)=>{const s=he.get(t)??new Ec(t);if(e){if(!he.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return he.set(t,s),s},getContext:t=>he.get(t),deleteContext:t=>{he.delete(t)},setParentContext:(t,e)=>{var s;if(!he.has(e))throw new Error(`Parent context ${e} does not exist`);(s=he.get(t))==null||s.setParent(e)},rootContext:()=>he.get("root")};Y.createContext("root");const Pm=t=>Y.getContext(t.id),Mo=m.createLogger({name:"kos-data-container"});class Cn{constructor(e){c(this,"_data");c(this,"_sortKey");c(this,"_revision");c(this,"_index");c(this,"_optionsMap");c(this,"_disposerMap",new Map);c(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=Ie(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new En({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??[]:(Mo.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):(Mo.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Mo.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 Rm{constructor({type:e,model:s,childRegistration:r}){c(this,"type");c(this,"childRegistration");c(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ie.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return Te(this.type)}}class km{constructor({type:e,model:s,childRegistration:r}){c(this,"type");c(this,"model");c(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ie.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return Te(this.type)}}class Mc{constructor(){c(this,"_token");M.makeAutoObservable(this),C("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class Tc{constructor(){c(this,"routes",[]);c(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 l of this.routes){const u=this.matchRoute(l.path,r);if(l.method===e.method&&u){i.params=u;let d=0;const h=async()=>{if(d<l.middlewares.length){const f=l.middlewares[d++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),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 Sc=m.createLogger({name:"intent-service"}),Lm=t=>{on(`/kos/intent/${t.type}`)?V(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):Sc.info(`No subscribers for intent ${t.type}. Intent not sent.`)},Fm=async t=>new Promise(e=>{const{type:s,options:r}=t;if(on(`/kos/intent/${t.type}`)){const o=it(),{unsubscribe:n}=C(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);V(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else Sc.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),Ae=m.createLogger({name:"app-startup-service"});async function Ic(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return Ae.warn("No app IDs provided to waitForAppsToStart"),!0;Ae.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(l=>`/kos/app/started/${l}`),i=await ln(n,{getCurrentState:async()=>{try{const{default:l}=await Promise.resolve().then(()=>ec),[u,d]=await l.get("/api/kos/apps/started");return u?(Ae.error("Error fetching started apps:",u),[]):d}catch(l){Ae.error("Failed to fetch app startup status:",l)}return[]},shouldUseFetchedState:l=>t.every(u=>{const d=l.find(h=>h.appId===u);return!(!d||!d.started||o&&!d.postStarted)}),timeout:s}),a=t.filter(l=>{const u=i.find(d=>d.appId===l);return!!(!u||!u.started||o&&!u.postStarted)});if(a.length>0){const l=`Apps not started: ${a.join(", ")}`;if(Ae.error(l),r)throw new Error(`App startup timeout: ${l}`);return!1}return Ae.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Ae.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function Nm(t,e={}){return Ic([t],e)}async function Um(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(l=>l.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){Ae.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function jm(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return Ae.error("Failed to fetch started apps:",t),[]}}const No=M.when,Dn=M.computed,X=M.runInAction,W=M.autorun,_c=M.reaction,xn=M.observable,An="Not Assigned",Bm="kos.trouble.added",Hm="kos.trouble.removed";var ve=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(ve||{}),ws=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(ws||{});const Oc=m.createLogger({name:"config-bean-service",group:"Services"}),Pn=exports.BASE_URL,$c=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:Km,getOne:qm}=oe.build({destinationAddress:"",basePath:`${Pn}/kos/config/`}),Cc=async(t,e,s="/api/kos/config")=>(Oc.debug(`sending modify request for ConfigBean: ${t}`),Km({model:e,urlOverride:`${Pn}${s}/${t}`})),Dc=async(t,e="/api/kos/config")=>(Oc.debug(`sending get request for ConfigBean: ${t}`),await qm({urlOverride:`${Pn}${e}/details/${t}/15`})),Rn=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",Wr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function xc(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Ac(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])?Ac(t[r],o,s):s[o]=t[r]}return s}const Pc=(t,e)=>{const s=t.details[0].bean||xc(t.details[0].scopes),r=Ac(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},Rc=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&Rn(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&Wr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},kc=t=>Object.fromEntries(t.props.entries),zm=t=>e=>s=>t.build(e,s);var Vm=Object.defineProperty,Gm=Object.getOwnPropertyDescriptor,Lc=(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&&Vm(e,s,o),o};function Ym(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const kn="config-bean-model",Xs=m.getLogger(kn),Wm=at("path");let gr=class{constructor(t,e){c(this,"_modifyConfigBean");c(this,"_getConfigBean");c(this,"_schema");c(this,"id");c(this,"path");c(this,"props");c(this,"prevProps");c(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=Cc,getConfigBean:r=Dc}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Ie(),this.prevProps=Ie()}get values(){return this.props.values}async ready(){Xs.debug(`readying config bean ${this.path}`),Xs.debug(`complete readying config bean ${this.path}`)}async load(){Xs.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;Pc(e,this),Xs.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;X(()=>{s&&(this._schema=s)})}}get schemaKeys(){var t;return Object.keys(((t=this._schema)==null?void 0:t.schema)||{})}getSchemaForProperty(t){var s,r;if(this.schemaKeys.includes(t))return(s=this._schema)==null?void 0:s.schema[t];const e=Ym(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=kc(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){Rc(t,this)}};Lc([B({topic:`/kos/config/${Wm}`,websocket:!0})],gr.prototype,"handleConfigBeanUpdated",1);gr=Lc([P(kn)],gr);const Ts=new ye({class:gr,type:kn}),Qr=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[N]=r[N]||{},r[N][o]={modelType:Ts.type,id:`${Ts.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:x.INIT,lazy:e}},{URL:Fc}=ae(),{getOne:Qm,getAll:Zm}=oe.build({basePath:`${Fc}/api/kos/regions/info`}),Nc=async()=>{try{return await Qm({})}catch{return}},Uc=async()=>{try{return await Zm({urlOverride:`${Fc}/api/kos/regions`})}catch{return}},Xm=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Nc,getRegions:Uc},Symbol.toStringTag,{value:"Module"}));var ce=(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))(ce||{});const jc={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 Jm(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},{...jc});return{...t,...r}}function ey(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const l=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=l,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:l,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...jc}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function ty(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 sy=Object.defineProperty,ry=Object.getOwnPropertyDescriptor,Ln=(t,e,s,r)=>{for(var o=r>1?void 0:r?ry(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&&sy(e,s,o),o};const lr="region-info-model",Zt=m.createLogger({name:"region-info-model"});let Ss=class{constructor(t){c(this,"id");c(this,"unitSystemMap");c(this,"measureMap");c(this,"defaultMeasureMap");c(this,"regionMap");c(this,"timeFormats");c(this,"dateFormats");c(this,"unitSystems");c(this,"regionSource");c(this,"region");c(this,"regions",[]);c(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[ce.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[ce.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[ce.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[ce.family]!==s[ce.family])throw new Error(`Cannot convert between units of different families: ${e[ce.family]} and ${s[ce.family]}`);const r=e[ce.offset],o=e[ce.scale],n=s[ce.scale],i=s[ce.offset],a=s[ce.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,l;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 u=this.measureMap[s.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=u[s.system])==null?void 0:a.default,i||Zt.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const u=this.measureMap[e.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(l=u[e.system])==null?void 0:l.default,n||Zt.info("Could not find default unit for measure",e.measure)}return!n||!i?(Zt.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){Zt.debug("initializing region info")}async load(){Zt.debug("loading region info");const t=await Uc();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 Nc();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(Jm,{}),this.measureMap=e.data.unitSystems.reduce(ey,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(ty,{}),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))}};Ln([Qr({path:"kos:service:region:settings"})],Ss.prototype,"regionSource",2);Ln([Qr({path:"kos:service:region"})],Ss.prototype,"region",2);Ss=Ln([P(lr)],Ss);const re={registration:{[lr]:{class:Ss,singleton:!0}},type:lr,factory:ie.Singleton.create(lr)},mr=({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},Fn=(t,e,s)=>{const{model:r}=_e(re.type);if(!r)throw new Error("RegionInfo model not found");if(!pr(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=mr({source:e}),i=mr({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Vi(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 oy=(t,e,s,r)=>{const o=Fn(t,e,s),n=mr({source:e}),{model:i}=_e(re.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),l={system:i.defaultUnitSystem},u=mr({source:s||l,defaultMeasure:i.getUnitMeasure(n.unit||"")}),d=i.getDefaultUnitForMeasure(a,u.system),h=i.getDefaultUnitDecimalPlaces(a,u.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:d||n.unit||"",display:Vi(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:Vi(o,d||n.unit||"",{...f,mode:"short"})}};function Gi({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 Yi({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 pt=(t,e)=>s=>!t||!e?s:Wr(s)?Fn(Number(s),t,e):s,ny=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Gi(t.options).map(pt(s,r));if(t.options.type==="rangeInterval")return Yi(t.options).map(pt(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(pt(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Gi(t.options.unitSystems[e]).map(pt(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Yi(t.options.unitSystems[e]).map(pt(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(pt(s,r))}}return[]},iy=(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 ay=Object.defineProperty,ly=Object.getOwnPropertyDescriptor,Nn=(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};function cy(t){return(t==null?void 0:t.type)==="enum"}function uy(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 dy(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return je.format(r,e)}const cr="config-bean-prop-model",gt=m.createLogger({name:"config-bean-prop-model"}),hy=at("path"),fy=at("serviceBasePath");let Is=class{constructor(t,e){c(this,"id");c(this,"path");c(this,"attribute");c(this,"converter");c(this,"formatter");c(this,"optionsExpander");c(this,"serviceBasePath");c(this,"regionInfo");c(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 $c(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?uy(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=cy(r)?r.values:ny(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 l=this.getFormatterOptions(s);if(l){let u=String(t);return u=l.formatToParts(Number(t))[0].value,Number(u)}}catch(l){gt.info(`error formatting value ${t}`,l)}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(){gt.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 dy(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){gt.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 iy(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 l=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,u=this.formatter||l;if(u){let d=typeof u=="function"?u(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):u;s&&(d={unit:this.getDefaultUnit(t),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...d})}catch(h){gt.error(`error creating formatter ${d}. Returning the raw value`,h)}}else gt.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,l,u,d,h,f,p;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const y=(r=this.converter)==null?void 0:r.measure,w=(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,S=y||w||E||e,L=((u=(l=this.converter)==null?void 0:l.to)==null?void 0:u.unit)||this.regionInfo.getDefaultUnitForMeasure(S,((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),R=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(L),O=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:O,...this.converter.from},to:{...this.converter.to,unit:L,system:R},measure:S}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:w===E?s:y}}}}async updateProperty(t){gt.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)}};Nn([Nt({modelType:re.type})],Is.prototype,"regionInfo",2);Nn([Qr({path:hy,serviceBasePath:fy})],Is.prototype,"bean",2);Is=Nn([P(cr)],Is);const lt={registration:{[cr]:{class:Is,singleton:!1}},type:cr,factory:ie.Factory.create(cr)};function py(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,l=r;return l&&(typeof l!="function"&&typeof l.from=="string"&&(l.from={unit:l.from}),typeof l!="function"&&typeof l.to=="string"&&(l.to={unit:l.to})),(u,d)=>{u[N]=u[N]||{},u[N][d]={modelType:lt.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:l,formatter:o,optionsExpander:i},lifecycle:x.INIT,lazy:n}}}const Bc="future-model",Bt=Ut(Bc),Zr=m.createLogger({name:"future-service",group:"Services"}),{isMock:gy,URL:Bs}=ae();var qe=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(qe||{});const{getAll:my,modifyModel:yy,addModel:by,deleteModel:vy,postModel:wy}=oe.build({destinationAddress:"",basePath:`${Bs}/api/future`,mock:gy}),Ey=async()=>await my({}),Hc=async(t,e="/api/kos/future")=>(Zr.info(`sending delete request for Future: ${t}`),await vy({id:t,urlOverride:`${Bs}${e}/${t}`})),Kc=async(t,e="/api/kos/future")=>(Zr.info("sending add request for Future"),await by({model:t,urlOverride:`${Bs}${e}`})),My=async(t,e,s="/api/kos/future")=>(Zr.info(`sending modify request for Future: ${t}`),yy({model:e,id:t,urlOverride:`${Bs}${s}/${t}`})),qc=async(t,e="/api/kos/future")=>(Zr.info(`sending cancel request for Future: ${t}`),wy({urlOverride:`${Bs}${e}/${t}/cancel`,ordered:!0,model:{}})),Un=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}),jn=(t,e)=>{m.debug(`future dto ${t.id} end state ${t.endState}`),m.debug(`future model ${e.id} end state ${e.endState}`),e.endState?m.debug(`future model ${e.id} is already complete`):(m.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=Un(t);X(()=>{Object.keys(s).forEach(r=>{r==="id"?(e.futureId=s.id,s.tracker||(e.id=s.id)):r==="tracker"?e.id=s.tracker:e[r]=s[r]})})}))},zc=t=>e=>s=>t.build(String(e),s),Bn=t=>e=>vc(Un,zc(t)(e.tracker||e.id))(e);var Ty=Object.defineProperty,Sy=Object.getOwnPropertyDescriptor,Vc=(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 To=m.getLogger(Bt.type);let yr=class{constructor(t,e,s){c(this,"logger");c(this,"_cancelFuture");c(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=qc,No(()=>this.status===qe.Success||this.status===qe.Fail,()=>{To.info(`Future ${this.id} has completed with status ${this.status}`),rt(this)})}async load(){To.debug(`loading Future ${this.id}`)}unload(){To.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await No(()=>this.futureId!==An),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,l;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[u,d]of Object.entries(e))if(Math.abs(t)>=d){s=u,r=Math.round(t/d);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((l=n[2])==null?void 0:l.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),jn(t,this)}};Vc([B({topic:`kos.future/${dr}`})],yr.prototype,"handleFutureUpdated",1);yr=Vc([P(Bt.type)],yr);const Gc=yr,Yc=_n();var Iy=Object.defineProperty,_y=Object.getOwnPropertyDescriptor,Wc=(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&&Iy(e,s,o),o};const Qc="browser-router-model",Oy="kos.http.request",$y="kos.http.response";let br=class{constructor(t,e,s){c(this,"_id");c(this,"logger");c(this,"router");this._id=t,this.logger=s.logger,this.router=new Tc}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 l=200;const u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),hc({msg:d,options:{responseId:i,destinationAddress:s,type:$y,sourceAddress:r,status:l}})},status:function(d){return l=d,this}};if(a.path==="/openapi.json"){u.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,u)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};Wc([B({topic:Oy})],br.prototype,"handleRequest",1);br=Wc([P(Qc)],br);const Hn=new Se({class:br,type:Qc}),Zc="future-container-model",ze=Ut(Zc),Xc=t=>Bn(Bt)(t),Cy=t=>{const e=Xc(t);return ze.build(ze.type,{}).addFutureModel(e),e},Dy=t=>ze.build(ze.type,{}).getFuture(String(t)),ot={buildFutureModel:Xc,initiateFuture:Cy,getFuture:Dy};var xy=Object.defineProperty,Ay=Object.getOwnPropertyDescriptor,Kn=(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&&xy(e,s,o),o};const Js=m.getLogger(ze.type);let _s=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_deleteFuture");c(this,"_addFuture");c(this,"_futures");c(this,"createModel");c(this,"deleteModel");const{deleteFuture:r=Hc,addFuture:o=Kc}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new Ce,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){Js.error("error deleting a Future"),Js.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Bn(Bt)(s);return this.addFutureModel(r),r}}catch(e){throw Js.error("error creating a Future"),Js.error(e),e}}handleFutureUpdated(t,e){const s=ot.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),V(r,e.body,e.headers)}};Kn([$e],_s.prototype,"_futures",2);Kn([B({topic:"kos.future"})],_s.prototype,"handleFutureUpdated",1);_s=Kn([P(ze.type)],_s);const Jc=_s,{URL:Hs}=ae(),{getOne:Py,postModel:Ry,deleteModel:eu}=oe.build({basePath:`${Hs}/api/keyVal`}),Uo=m.createLogger({name:"key-value-service",group:"Services"}),tu=async(t,e)=>{await eu({urlOverride:`${Hs}/api/keyVal/${t}/${e}`,id:e})},su=async(t,e,s)=>{const r=await Ry({urlOverride:`${Hs}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Uo.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},ru=async(t="studio")=>{Uo.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await Py({urlOverride:`${Hs}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Uo.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},ky=async t=>{await eu({urlOverride:`${Hs}/api/keyVal/${t}`,id:""})},Ly=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:tu,deleteKeyValueNamespace:ky,getKeyValue:ru,updateKeyValue:su},Symbol.toStringTag,{value:"Module"}));var Fy=Object.defineProperty,Ny=Object.getOwnPropertyDescriptor,qn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ny(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Fy(e,s,o),o};const ou="key-value-model";let Os=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"namespace");c(this,"data");this.id=t,this.logger=s.logger,this.data=Ie(),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 su(this.namespace,t,e),this.data[t]=e):(await tu(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await ru(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)}};qn([B({topic:"/keyVal/set"})],Os.prototype,"handleStateUpdate",1);qn([B({topic:"/keyVal/remove"})],Os.prototype,"handleStateDelete",1);Os=qn([P(ou)],Os);const zn=new ye({class:Os,type:ou});var fe="INUMBER",Ht="IOP1",Kt="IOP2",qt="IOP3",Re="IVAR",nt="IVARNAME",_t="IFUNCALL",Xr="IFUNDEF",ne="IEXPR",Vn="IEXPREVAL",ct="IMEMBER",Jr="IENDSTATEMENT",Ot="IARRAY";function k(t,e){this.type=t,this.value=e??0}k.prototype.toString=function(){switch(this.type){case fe:case Ht:case Kt:case qt:case Re:case nt:case Jr:return this.value;case _t:return"CALL "+this.value;case Xr:return"DEF "+this.value;case Ot:return"ARRAY "+this.value;case ct:return"."+this.value;default:return"Invalid Instruction"}};function eo(t){return new k(Ht,t)}function Ue(t){return new k(Kt,t)}function nu(t){return new k(qt,t)}function jo(t,e,s,r,o){for(var n=[],i=[],a,l,u,d,h=0;h<t.length;h++){var f=t[h],p=f.type;if(p===fe||p===nt)Array.isArray(f.value)?n.push.apply(n,jo(f.value.map(function(y){return new k(fe,y)}).concat(new k(Ot,f.value.length)),e,s,r,o)):n.push(f);else if(p===Re&&o.hasOwnProperty(f.value))f=new k(fe,o[f.value]),n.push(f);else if(p===Kt&&n.length>1)l=n.pop(),a=n.pop(),d=s[f.value],f=new k(fe,d(a.value,l.value)),n.push(f);else if(p===qt&&n.length>2)u=n.pop(),l=n.pop(),a=n.pop(),f.value==="?"?n.push(a.value?l.value:u.value):(d=r[f.value],f=new k(fe,d(a.value,l.value,u.value)),n.push(f));else if(p===Ht&&n.length>0)a=n.pop(),d=e[f.value],f=new k(fe,d(a.value)),n.push(f);else if(p===ne){for(;n.length>0;)i.push(n.shift());i.push(new k(ne,jo(f.value,e,s,r,o)))}else if(p===ct&&n.length>0)a=n.pop(),n.push(new k(fe,a.value[f.value]));else{for(;n.length>0;)i.push(n.shift());i.push(f)}}for(;n.length>0;)i.push(n.shift());return i}function iu(t,e,s){for(var r=[],o=0;o<t.length;o++){var n=t[o],i=n.type;if(i===Re&&n.value===e)for(var a=0;a<s.tokens.length;a++){var l=s.tokens[a],u;l.type===Ht?u=eo(l.value):l.type===Kt?u=Ue(l.value):l.type===qt?u=nu(l.value):u=new k(l.type,l.value),r.push(u)}else i===ne?r.push(new k(ne,iu(n.value,e,s))):r.push(n)}return r}function Xe(t,e,s){var r=[],o,n,i,a,l,u;if(Gn(t))return xe(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===fe||p===nt)r.push(f.value);else if(p===Kt)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!Xe(n,e,s):!1):f.value==="or"?r.push(o?!0:!!Xe(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,Xe(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(xe(o,s),xe(n,s))));else if(p===qt)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(Xe(o?n:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(xe(o,s),xe(n,s),xe(i,s))));else if(p===Re)if(f.value in e.functions)r.push(e.functions[f.value]);else if(f.value in e.unaryOps&&e.parser.isOperatorEnabled(f.value))r.push(e.unaryOps[f.value]);else{var y=s[f.value];if(y!==void 0)r.push(y);else throw new Error("undefined variable: "+f.value)}else if(p===Ht)o=r.pop(),a=e.unaryOps[f.value],r.push(a(xe(o,s)));else if(p===_t){for(u=f.value,l=[];u-- >0;)l.unshift(xe(r.pop(),s));if(a=r.pop(),a.apply&&a.call)r.push(a.apply(void 0,l));else throw new Error(a+" is not a function")}else if(p===Xr)r.push(function(){for(var w=r.pop(),E=[],S=f.value;S-- >0;)E.unshift(r.pop());var L=r.pop(),R=function(){for(var O=Object.assign({},s),I=0,K=E.length;I<K;I++)O[E[I]]=arguments[I];return Xe(w,e,O)};return Object.defineProperty(R,"name",{value:L,writable:!1}),s[L]=R,R}());else if(p===ne)r.push(Uy(f,e));else if(p===Vn)r.push(f);else if(p===ct)o=r.pop(),r.push(o[f.value]);else if(p===Jr)r.pop();else if(p===Ot){for(u=f.value,l=[];u-- >0;)l.unshift(r.pop());r.push(l)}else throw new Error("invalid Expression")}if(r.length>1)throw new Error("invalid Expression (parity)");return r[0]===0?0:xe(r[0],s)}function Uy(t,e,s){return Gn(t)?t:{type:Vn,value:function(r){return Xe(t.value,e,r)}}}function Gn(t){return t&&t.type===Vn}function xe(t,e){return Gn(t)?t.value(e):t}function Yn(t,e){for(var s=[],r,o,n,i,a,l,u=0;u<t.length;u++){var d=t[u],h=d.type;if(h===fe)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Wi).join(", ")+"]"):s.push(Wi(d.value));else if(h===Kt)o=s.pop(),r=s.pop(),i=d.value,e?i==="^"?s.push("Math.pow("+r+", "+o+")"):i==="and"?s.push("(!!"+r+" && !!"+o+")"):i==="or"?s.push("(!!"+r+" || !!"+o+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+o+")))"):i==="=="?s.push("("+r+" === "+o+")"):i==="!="?s.push("("+r+" !== "+o+")"):i==="["?s.push(r+"[("+o+") | 0]"):s.push("("+r+" "+i+" "+o+")"):i==="["?s.push(r+"["+o+"]"):s.push("("+r+" "+i+" "+o+")");else if(h===qt)if(n=s.pop(),o=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+o+" : "+n+")");else throw new Error("invalid Expression");else if(h===Re||h===nt)s.push(d.value);else if(h===Ht)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):e?i==="not"?s.push("(!"+r+")"):i==="!"?s.push("fac("+r+")"):s.push(i+"("+r+")"):i==="!"?s.push("("+r+"!)"):s.push("("+i+" "+r+")");else if(h===_t){for(l=d.value,a=[];l-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===Xr){for(o=s.pop(),l=d.value,a=[];l-- >0;)a.unshift(s.pop());r=s.pop(),e?s.push("("+r+" = function("+a.join(", ")+") { return "+o+" })"):s.push("("+r+"("+a.join(", ")+") = "+o+")")}else if(h===ct)r=s.pop(),s.push(r+"."+d.value);else if(h===Ot){for(l=d.value,a=[];l-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ne)s.push("("+Yn(d.value,e)+")");else if(h!==Jr)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Wi(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function wt(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function Wn(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===Re||i.type===nt?!r&&!wt(e,i.value)?e.push(i.value):(o!==null&&(wt(e,o)||e.push(o)),o=i.value):i.type===ct&&r&&o!==null?o+="."+i.value:i.type===ne?Wn(i.value,e,s):o!==null&&(wt(e,o)||e.push(o),o=null)}o!==null&&!wt(e,o)&&e.push(o)}function we(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}we.prototype.simplify=function(t){return t=t||{},new we(jo(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};we.prototype.substitute=function(t,e){return e instanceof we||(e=this.parser.parse(String(e))),new we(iu(this.tokens,t,e),this.parser)};we.prototype.evaluate=function(t){return t=t||{},Xe(this.tokens,this,t)};we.prototype.toString=function(){return Yn(this.tokens,!1)};we.prototype.symbols=function(t){t=t||{};var e=[];return Wn(this.tokens,e,t),e};we.prototype.variables=function(t){t=t||{};var e=[];Wn(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};we.prototype.toJSFunction=function(t,e){var s=this,r=new Function(t,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+Yn(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var $s="TEOF",j="TOP",to="TNUMBER",au="TSTRING",ke="TPAREN",$t="TBRACKET",so="TCOMMA",Qn="TNAME",Zn="TSEMICOLON";function lu(t,e,s){this.type=t,this.value=e,this.index=s}lu.prototype.toString=function(){return this.type+": "+this.value};function G(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}G.prototype.newToken=function(t,e,s){return new lu(t,e,s??this.pos)};G.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};G.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};G.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken($s,"EOF");if(this.isWhitespace()||this.isComment())return this.next();if(this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName())return this.current;this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')};G.prototype.isString=function(){var t=!1,e=this.pos,s=this.expression.charAt(e);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,e+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(e+1,r);this.current=this.newToken(au,this.unescape(o),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};G.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(ke,t),this.pos++,!0):!1};G.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken($t,t),this.pos++,!0):!1};G.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(so,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(Zn,";"),this.pos++,!0):!1};G.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(r in this.consts)return this.current=this.newToken(to,this.consts[r]),this.pos+=r.length,!0}return!1};G.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(j,r),this.pos+=r.length,!0}return!1};G.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(t,e);return this.current=this.newToken(Qn,o),this.pos+=o.length,!0}return!1};G.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
|
|
108
|
-
`||e==="\r")&&(t=!0,this.pos++,!(this.pos>=this.expression.length));)e=this.expression.charAt(this.pos);return t};var
|
|
109
|
-
`;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var o=t.substring(e+1,e+5);
|
|
110
|
-
`,s+1);while(s>=0&&s<this.pos);return{line:t,column:e}};G.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)};function H(t,e,s){this.parser=t,this.tokens=e,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}H.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};H.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?wt(e,t.value):typeof e=="function"?e(t):t.value===e};H.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};H.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};H.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};H.prototype.expect=function(t,e){if(!this.accept(t,e)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(e||t))}};H.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.accept(Qn)||this.accept(j,s))t.push(new k(Re,this.current.value));else if(this.accept(to))t.push(new k(fe,this.current.value));else if(this.accept(au))t.push(new k(fe,this.current.value));else if(this.accept(ke,"("))this.parseExpression(t),this.expect(ke,")");else if(this.accept($t,"["))if(this.accept($t,"]"))t.push(new k(Ot,0));else{var r=this.parseArrayList(t);t.push(new k(Ot,r))}else throw new Error("unexpected "+this.nextToken)};H.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};H.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};H.prototype.parseUntilEndStatement=function(t,e){return this.accept(Zn)?(this.nextToken&&this.nextToken.type!==$s&&!(this.nextToken.type===ke&&this.nextToken.value===")")&&e.push(new k(Jr)),this.nextToken.type!==$s&&this.parseExpression(e),t.push(new k(ne,e)),!0):!1};H.prototype.parseArrayList=function(t){for(var e=0;!this.accept($t,"]");)for(this.parseExpression(t),++e;this.accept(so);)this.parseExpression(t),++e;return e};H.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(j,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===_t){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var o=0,n=e.value+1;o<n;o++){var i=r-o;t[i].type===Re&&(t[i]=new k(nt,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new k(ne,s)),t.push(new k(Xr,e.value));continue}if(e.type!==Re&&e.type!==ct)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new k(nt,e.value)),t.push(new k(ne,s)),t.push(Ue("="))}};H.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(j,"?");){var e=[],s=[];this.parseConditionalExpression(e),this.expect(j,":"),this.parseConditionalExpression(s),t.push(new k(ne,e)),t.push(new k(ne,s)),t.push(nu("?"))}};H.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(j,"or");){var e=[];this.parseAndExpression(e),t.push(new k(ne,e)),t.push(Ue("or"))}};H.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(j,"and");){var e=[];this.parseComparison(e),t.push(new k(ne,e)),t.push(Ue("and"))}};var By=["==","!=","<","<=",">=",">","in"];H.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,By);){var e=this.current;this.parseAddSub(t),t.push(Ue(e.value))}};var Hy=["+","-","||"];H.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(j,Hy);){var e=this.current;this.parseTerm(t),t.push(Ue(e.value))}};var Ky=["*","/","%"];H.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,Ky);){var e=this.current;this.parseFactor(t),t.push(Ue(e.value))}};H.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.save(),this.accept(j,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===ke&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===Zn||this.nextToken.type===so||this.nextToken.type===$s||this.nextToken.type===ke&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(eo(r.value))}else this.parseExponential(t)};H.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(j,"^");)this.parseFactor(t),t.push(Ue("^"))};H.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(j,"!");)t.push(eo("!"))};H.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.accept(j,s)){var r=this.current;this.parseAtom(t),t.push(eo(r.value))}else for(this.parseMemberExpression(t);this.accept(ke,"(");)if(this.accept(ke,")"))t.push(new k(_t,0));else{var o=this.parseArgumentList(t);t.push(new k(_t,o))}};H.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(ke,")");)for(this.parseExpression(t),++e;this.accept(so);)this.parseExpression(t),++e;return e};H.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(j,".")||this.accept($t,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(Qn),t.push(new k(ct,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect($t,"]"),t.push(Ue("["))}else throw new Error("unexpected symbol: "+e.value)}};function qy(t,e){return Number(t)+Number(e)}function zy(t,e){return t-e}function Vy(t,e){return t*e}function Gy(t,e){return t/e}function Yy(t,e){return t%e}function Wy(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function Qy(t,e){return t===e}function Zy(t,e){return t!==e}function Xy(t,e){return t>e}function Jy(t,e){return t<e}function eb(t,e){return t>=e}function tb(t,e){return t<=e}function sb(t,e){return!!(t&&e)}function rb(t,e){return!!(t||e)}function ob(t,e){return wt(e,t)}function nb(t){return(Math.exp(t)-Math.exp(-t))/2}function ib(t){return(Math.exp(t)+Math.exp(-t))/2}function ab(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function lb(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function cb(t){return Math.log(t+Math.sqrt(t*t-1))}function ub(t){return Math.log((1+t)/(1-t))/2}function Qi(t){return Math.log(t)*Math.LOG10E}function db(t){return-t}function hb(t){return!t}function fb(t){return t<0?Math.ceil(t):Math.floor(t)}function pb(t){return Math.random()*(t||1)}function Zi(t){return Xn(t+1)}function gb(t){return isFinite(t)&&t===Math.round(t)}var mb=4.7421875,So=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function Xn(t){var e,s;if(gb(t)){if(t<=0)return isFinite(t)?1/0:NaN;if(t>171)return 1/0;for(var r=t-2,o=t-1;r>1;)o*=r,r--;return o===0&&(o=1),o}if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*Xn(1-t));if(t>=171.35)return 1/0;if(t>85){var n=t*t,i=n*t,a=i*t,l=a*t;return Math.sqrt(2*Math.PI/t)*Math.pow(t/Math.E,t)*(1+1/(12*t)+1/(288*n)-139/(51840*i)-571/(2488320*a)+163879/(209018880*l)+5246819/(75246796800*l*t))}--t,s=So[0];for(var u=1;u<So.length;++u)s+=So[u]/(t+u);return e=t+mb+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function yb(t){return Array.isArray(t)?t.length:String(t).length}function Xi(){for(var t=0,e=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),o;e<r?(o=e/r,t=t*o*o+1,e=r):r>0?(o=r/e,t+=o*o):t+=r}return e===1/0?1/0:e*Math.sqrt(t)}function Ji(t,e,s){return t?e:s}function bb(t,e){return typeof e>"u"||+e==0?Math.round(t):(t=+t,e=-+e,isNaN(t)||!(typeof e=="number"&&e%1===0)?NaN:(t=t.toString().split("e"),t=Math.round(+(t[0]+"e"+(t[1]?+t[1]-e:-e))),t=t.toString().split("e"),+(t[0]+"e"+(t[1]?+t[1]+e:e))))}function vb(t,e,s){return s&&(s[t]=e),e}function wb(t,e){return t[e|0]}function Eb(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function Mb(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function Tb(t,e){if(typeof t!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(e))throw new Error("Second argument to map is not an array");return e.map(function(s,r){return t(s,r)})}function Sb(t,e,s){if(typeof t!="function")throw new Error("First argument to fold is not a function");if(!Array.isArray(s))throw new Error("Second argument to fold is not an array");return s.reduce(function(r,o,n){return t(r,o,n)},e)}function Ib(t,e){if(typeof t!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(e))throw new Error("Second argument to filter is not an array");return e.filter(function(s,r){return t(s,r)})}function _b(t,e){if(!(Array.isArray(e)||typeof e=="string"))throw new Error("Second argument to indexOf is not a string or array");return e.indexOf(t)}function Ob(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function $b(t){return(t>0)-(t<0)||+t}var ea=1/3;function Cb(t){return t<0?-Math.pow(-t,ea):Math.pow(t,ea)}function Db(t){return Math.exp(t)-1}function xb(t){return Math.log(1+t)}function Ab(t){return Math.log(t)/Math.LN2}function ut(t){this.options=t||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||nb,cosh:Math.cosh||ib,tanh:Math.tanh||ab,asinh:Math.asinh||lb,acosh:Math.acosh||cb,atanh:Math.atanh||ub,sqrt:Math.sqrt,cbrt:Math.cbrt||Cb,log:Math.log,log2:Math.log2||Ab,ln:Math.log,lg:Math.log10||Qi,log10:Math.log10||Qi,expm1:Math.expm1||Db,log1p:Math.log1p||xb,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||fb,"-":db,"+":Number,exp:Math.exp,not:hb,length:yb,"!":Zi,sign:Math.sign||$b},this.binaryOps={"+":qy,"-":zy,"*":Vy,"/":Gy,"%":Yy,"^":Math.pow,"||":Wy,"==":Qy,"!=":Zy,">":Xy,"<":Jy,">=":eb,"<=":tb,and:sb,or:rb,in:ob,"=":vb,"[":wb},this.ternaryOps={"?":Ji},this.functions={random:pb,fac:Zi,min:Mb,max:Eb,hypot:Math.hypot||Xi,pyt:Math.hypot||Xi,pow:Math.pow,atan2:Math.atan2,if:Ji,gamma:Xn,roundTo:bb,map:Tb,fold:Sb,filter:Ib,indexOf:_b,join:Ob},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}ut.prototype.parse=function(t){var e=[],s=new H(this,new G(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect($s,"EOF"),new we(e,this)};ut.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var cu=new ut;ut.parse=function(t){return cu.parse(t)};ut.evaluate=function(t,e){return cu.parse(t).evaluate(e)};var ta={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"remainder","^":"power","!":"factorial","<":"comparison",">":"comparison","<=":"comparison",">=":"comparison","==":"comparison","!=":"comparison","||":"concatenate",and:"logical",or:"logical",not:"logical","?":"conditional",":":"conditional","=":"assignment","[":"array","()=":"fndef"};function Pb(t){return ta.hasOwnProperty(t)?ta[t]:t}ut.prototype.isOperatorEnabled=function(t){var e=Pb(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var Rb=Object.defineProperty,kb=Object.getOwnPropertyDescriptor,Lb=(t,e,s)=>e in t?Rb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Fb=(t,e,s,r)=>{for(var o=r>1?void 0:r?kb(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},Nb=(t,e,s)=>(Lb(t,e+"",s),s);const Ub="kos-expression-evaluator-model";class jb{constructor(e,s,r,o){c(this,"name");c(this,"expression");c(this,"expr");c(this,"getContextData",null);c(this,"_lastResult",{value:void 0});this.name=e,this.expression=s,this.expr=r,this.getContextData=o,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(e){this._lastResult=e}evaluate(e){try{return{value:this.expr.evaluate(e),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let vr=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"parser");c(this,"_data");c(this,"_expressions",new Map);c(this,"_results");c(this,"_contextRevision",0);this.id=t,this.logger=s.logger,this._data=Ie(),this._results=Ie(),this.parser=new ut}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(t){this._data.setValues(t),X(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(t,e){this._data[t]=e}updateNestedValue(t,e){const s=t.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${t}" - cannot be empty`);return}let o=this._data;for(const n of s)(o[n]===void 0||o[n]===null)&&(o[n]={}),o=o[n];o[r]=e,this.logger.debug(`Updated nested context value "${t}" to:`,e)}addModelToContext(t,e){this._data[t]=e}addExpression(t,e){try{const s=this.parser.parse(e),r=new jb(t,e,s,()=>this.data);this._expressions.set(t,r),this.evaluateExpression(t),this.logger.debug(`Added expression "${t}": ${e}`)}catch(s){throw this.logger.error(`Failed to parse expression "${t}"`,s),s}}removeExpression(t){const e=this._expressions.delete(t);return e?(delete this._results[t],this.logger.debug(`Removed expression "${t}"`)):this.logger.warn(`Attempted to remove non-existent expression "${t}". Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpression(t){const e=this._expressions.get(t);return e||this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpressionValue(t){const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return e.result}getCachedExpressionValue(t){const e=this._expressions.get(t);if(e)return e.result}get expressions(){return Array.from(this._expressions.values())}get expressionNames(){return Array.from(this._expressions.keys())}get results(){return this.evaluateAllExpressions(),this._results}evaluateAllExpressions(){Array.from(this._expressions.keys()).forEach(e=>{this._expressions.get(e)&&this.evaluateExpression(e)})}evaluateExpression(t){this.logger.debug(`Evaluating expression: ${String(t)}`);const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${String(t)}" not found`);return}const s=e.evaluate(this.data);this.logger.debug(`Expression "${String(t)}" evaluated to:`,s);const r=e.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(t)}" result changed from`,r,"to",s),e.updateResult(s),this.updateResult(t,s))}updateResult(t,e){this.logger.debug(`ExpressionEvaluator.updateResult called for "${t}":`,e),X(()=>{this._results[t]=e})}createExpression(t){const e=it();return this.addExpression(e,t),e}};Nb(vr,"Registration");vr=Fb([P({modelTypeId:Ub,singleton:!1})],vr);const uu=vr.Registration,Bb=m.createLogger({name:"kos-log-manager-service",group:"Services"}),Hb="/api/kos/logs/overrides",du=async()=>(Bb.debug("sending GET for kos-log-manager"),await De.get(Hb)),Kb=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:du},Symbol.toStringTag,{value:"Module"}));var qb=Object.defineProperty,zb=Object.getOwnPropertyDescriptor,ro=(t,e,s,r)=>{for(var o=r>1?void 0:r?zb(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&&qb(e,s,o),o};const hu="kos-log-manager-model",Vb="/kos/logs/override/add/*",Gb="/kos/logs/override/remove/*",Yb=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 Ct=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new Cn}updateModel(t){}resolveLoggers(){const t=m.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:Yb(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=m.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=m.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=m.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=m.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await du();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)})}};ro([El("/api/kos/ui/loggers")],Ct.prototype,"getAllLoggers",1);ro([B({topic:Vb,websocket:!0,wildcardName:"nodeType"})],Ct.prototype,"handleOverrideAdded",1);ro([B({topic:Gb,websocket:!0,wildcardName:"nodeType"})],Ct.prototype,"handleOverrideRemoved",1);Ct=ro([P(hu)],Ct);const fu=new Se({class:Ct,type:hu}),{URL:Ks}=ae(),{postModel:Jn,getOne:Wb}=oe.build({basePath:`${Ks}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const pu=async t=>{const e=await Jn({model:t,urlOverride:`${Ks}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},gu=async t=>{const e=await Jn({model:t,urlOverride:`${Ks}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},mu=async t=>{const e=await Jn({model:{},urlOverride:`${Ks}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},yu=async()=>{const t=await Wb({urlOverride:`${Ks}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},Qb=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:yu,setDate:gu,setTime:pu,setTimezone:mu},Symbol.toStringTag,{value:"Module"}));var Zb=Object.defineProperty,Xb=Object.getOwnPropertyDescriptor,oo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Xb(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&&Zb(e,s,o),o};const ts="kos-time-model",Jb="/kos/time/time",ev="/kos/time/day",tv="/kos/time/timezone";let Dt=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await pu(t)}async updateSystemDate(t){await gu(t)}async updateSystemTimezone(t){await mu(t)}handleTimeChange(){V(ws.TIME_CHANGE,{})}handleDayChange(){V(ws.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),V(ws.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await yu();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};oo([B({topic:Jb,websocket:!0})],Dt.prototype,"handleTimeChange",1);oo([B({topic:ev,websocket:!0})],Dt.prototype,"handleDayChange",1);oo([B({topic:tv,websocket:!0})],Dt.prototype,"handleTimeZoneChange",1);Dt=oo([P(ts)],Dt);const wr={registration:{[ts]:{class:Dt,singleton:!0}},type:ts,predicate:Te(ts),factory:ie.Singleton.create(ts)};var sv=Object.defineProperty,rv=Object.getOwnPropertyDescriptor,bu=(t,e,s,r)=>{for(var o=r>1?void 0:r?rv(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&&sv(e,s,o),o};const vu="log-block-container-model";let Er=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t,sortKey:"blockNum"})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};bu([$e],Er.prototype,"_models",2);Er=bu([P(vu)],Er);const ov=m.createLogger({name:"log-stream-container-service",group:"Services"}),wu=()=>{var r;const t=me(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},zt=wu(),nv="/api/kos/logs/node/{nodeId}/streams",Eu=async()=>(ov.debug("sending GET for log-stream-container"),await De.get(nv,{path:{nodeId:"primary"}},{destinationAddress:zt})),Mu=async(t,e="primary")=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:zt})},Tu=async t=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:zt})},iv=async()=>{await De.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:zt})},Su=async t=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:zt}),Iu=async(t,e)=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:zt}),av=Object.freeze(Object.defineProperty({__proto__:null,createOverride:iv,getKosConnectionId:wu,getLogStreamBlock:Iu,getLogStreamBlocks:Su,getLogStreams:Eu,subscribeToLogStream:Mu,unsubscribeFromLogStream:Tu},Symbol.toStringTag,{value:"Module"}));var lv=Object.getOwnPropertyDescriptor,cv=(t,e,s,r)=>{for(var o=r>1?void 0:r?lv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const _u="log-block-model";let Bo=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"nodeId");c(this,"stream");c(this,"blockNum");c(this,"startLineNum");c(this,"endLineNum");c(this,"startTime");c(this,"endTime");c(this,"lineCount");c(this,"lines");c(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 Iu(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}`)}};Bo=cv([P(_u)],Bo);const Cs=new ye({class:Bo,type:_u}),no=new ye({class:Er,type:vu});no.addRelatedModel(Cs);var uv=Object.defineProperty,dv=Object.getOwnPropertyDescriptor,Ou=(t,e,s,r)=>{for(var o=r>1?void 0:r?dv(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&&uv(e,s,o),o};const $u="log-stream-model";let Mr=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"nodeId");c(this,"_blocks");c(this,"name");c(this,"currentBlockId");c(this,"isResetting");c(this,"generatorInstance");c(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=no.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=Cs.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=Cs.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 Mu(this.name)}async unsubscribe(){await Tu(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 Su(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=_c(()=>{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()}}};Ou([$e],Mr.prototype,"_blocks",2);Mr=Ou([P($u)],Mr);const Es=new ye({class:Mr,type:$u});var hv=Object.defineProperty,fv=Object.getOwnPropertyDescriptor,dt=(t,e,s,r)=>{for(var o=r>1?void 0:r?fv(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&&hv(e,s,o),o};const Cu="log-stream-container-model",pv="/kos/logs/subscription/addBlock/*",gv="/kos/logs/subscription/updateBlock/*",mv="/kos/logs/subscription/removeBlock/*",yv="/kos/logs/subscription/lines/*",Du="/kos/logs/streams/add/*";let Le=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"selectedStream");c(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t}),this.selectedStream=void 0}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}updateModel(t){}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}updateSelectedStream(t){this.selectedStream=t}handleStreamAdded(t){this.logger.debug(`Received topic: ${Du}`);const e=t.stream,s=Es.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=Es.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 Eu();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=Es.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};dt([$e],Le.prototype,"_models",2);dt([B({topic:[Du],websocket:!0})],Le.prototype,"handleStreamAdded",1);dt([B({topic:[pv],websocket:!0})],Le.prototype,"handleAddBlock",1);dt([B({topic:[mv],websocket:!0})],Le.prototype,"handleRemoveBlock",1);dt([B({topic:[gv],websocket:!0})],Le.prototype,"handleUpdateBlock",1);dt([B({topic:[yv],websocket:!0})],Le.prototype,"handleLogLine",1);Le=dt([P(Cu)],Le);const qs=new Se({class:Le,type:Cu});qs.addRelatedModel(Es);qs.addRelatedModel(no);qs.addRelatedModel(Cs);const bv=t=>t.rank!==void 0,vv=t=>t.visibleRole!==void 0,wv=t=>t.color!==void 0,Ev=t=>{const e=t.info;return bv(e)?e.rank:0},Mv=t=>{const e=t.info;return wv(e)?e.color:"orange"},Tv=t=>{const e=t.info;return vv(e)?e.visibleRole:"TECHNICIAN"},{URL:io}=ae(),{getAll:Sv,postModel:xu}=oe.build({basePath:`${io}/api/kos/troubles`}),Au=async t=>await Sv({urlOverride:`${io}${t}`}),Pu=async(t,e="/api/kos/troubles",s)=>{try{const r=await xu({model:{},urlOverride:`${io}${e}/resolve/${t}`,tracker:s});return r!=null&&r.data&&ot.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:qe.Fail,tracker:s,reason:"Failed to resolve trouble"};return ot.initiateFuture(o),o}},Iv=async(t,e="/api/kos/troubles",s)=>{try{const r=await xu({model:t,urlOverride:`${io}${e}/resolve/`,tracker:s});return r!=null&&r.data&&ot.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:qe.Fail,tracker:s,reason:"Failed to resolve troubles"};return ot.initiateFuture(o),o}},_v=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Iv,getTroubles:Au,resolveTrouble:Pu},Symbol.toStringTag,{value:"Module"})),Tr="troubleDataMapper",er=new Map;Fs(Tr,{register:(t,e)=>{var s;er.has(t)||er.set(t,[]),(s=er.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=er.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:m.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const zs="troubleMapper",tr=new Map;Fs(zs,{register:(t,e)=>{var s;tr.has(t)||tr.set(t,[]),(s=tr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=tr.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});$[zs].register("nozzle",async t=>[t.data.nozzlePath]);$[zs].register("path",async t=>[t.data.path]);const Ov=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>$[zs].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},Ru=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>$[Tr].execute(i,t)),r=$[Tr].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 $v{constructor(){c(this,"type","ResolvableTrouble");c(this,"title","Resolvable Trouble");c(this,"subtitle","Trouble")}}class Cv{constructor(){c(this,"type","BlockPumpTrouble");c(this,"title","Block Pump Trouble");c(this,"subtitle","Trouble")}}class mt{static getHandler(e){switch(e){case"ResolvableTrouble":return new $v;case"BlockPumpTrouble":return new Cv;default:return}}}var Dv=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,ku=(t,e,s,r)=>{for(var o=r>1?void 0:r?xv(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&&Dv(e,s,o),o};const ss="trouble-model";function sr(t){return typeof t.shouldDefer=="boolean"}let Sr=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:l,group:u,createTime:d,role:h,color:f,servicePath:p,...y},w){c(this,"id");c(this,"logger");c(this,"_troubleId");c(this,"_resolvable");c(this,"type");c(this,"futureHandler");c(this,"ifaces");c(this,"clientData");c(this,"info");c(this,"role");c(this,"color");c(this,"tags");c(this,"data");c(this,"rank");c(this,"servicePath");c(this,"group");c(this,"createTime");c(this,"_mapped",{});this.id=t,this.logger=w.logger,this.type=l,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=u,this.servicePath=p??"/api/kos/troubles",this.createTime=d,this.clientData=n,this.data={},Object.assign(this.data,y),this.futureHandler=new Yr(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=mt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:mt.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=mt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:mt.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=mt.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=mt.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 Ru(this)}get deferredCompanion(){const t=Po(this.id,e=>sr(e));if(t&&sr(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Po(this.id,e=>sr(e));return t&&sr(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 Pu(this._troubleId,this.servicePath,t)}};ku([yi()],Sr.prototype,"resolve",1);Sr=ku([P(ss)],Sr);const Ds={registration:{[ss]:{class:Sr,singleton:!1}},type:ss,predicate:Te(ss),factory:ie.Factory.create(ss)};var Lu=Object.defineProperty,Av=Object.getOwnPropertyDescriptor,Pv=(t,e,s)=>e in t?Lu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ei=(t,e,s,r)=>{for(var o=r>1?void 0:r?Av(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&&Lu(e,s,o),o},Rv=(t,e,s)=>(Pv(t,e+"",s),s);function sa(t){return $.propertyMapper.hasMapper(ve.TroubleRank)?$.propertyMapper.executeMapper(ve.TroubleRank,t):Ev(t)}function ra(t){return($.propertyMapper.hasMapper(ve.TroubleColor)?$.propertyMapper.executeMapper(ve.TroubleColor,t):Mv(t)).toLowerCase()}function oa(t){return($.propertyMapper.hasMapper(ve.TroubleRole)?$.propertyMapper.executeMapper(ve.TroubleRole,t):Tv(t)).toLowerCase()}const kv="trouble-container-model";class pe{}c(pe,"INDEX_TROUBLES_BY_IFACE","byIface"),c(pe,"INDEX_TROUBLES_BY_TYPE","byType"),c(pe,"INDEX_TROUBLES_BY_GROUP","byGroup"),c(pe,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),c(pe,"SORT_KEY_RANK","rank"),c(pe,"TROUBLES_DEFERRED","true");let xt=class{constructor(t,e){c(this,"id");c(this,"servicePath","/api/kos/troubles");this.id=t,this.servicePath=e.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");const t=await Au(this.servicePath);try{t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:sa(e),color:ra(e),role:oa(e),id:String(e.id)},r=Ds.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw this.logger.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&rt(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:sa(t),color:ra(t),role:oa(t),id:String(t.id)};if(e.role==="NONE")return;const s=Ds.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};Rv(xt,"Registration");ei([B({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],xt.prototype,"handleTroubleRemoved",1);ei([B({topic:"/kos/trouble/add",websocket:!0})],xt.prototype,"handleTroubleAdded",1);xt=ei([P({modelTypeId:kv,singleton:!0}),Il(),wl({containerProperty:"troubles",containerOptions:{indexMap:{[pe.INDEX_TROUBLES_BY_IFACE]:Ov,[pe.INDEX_TROUBLES_BY_TYPE]:"type",[pe.INDEX_TROUBLES_BY_GROUP]:"group",[pe.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:pe.SORT_KEY_RANK}})],xt);const At=xt.Registration,{URL:Fu}=ae(),{getAll:Lv}=oe.build({basePath:`${Fu}/api/kos/ota`}),na=m.createLogger({name:"ota-service",group:"Services"}),Fv=async()=>{na.debug("sending GET request to /api/kos/ota/artifacts");const t=await Lv({urlOverride:`${Fu}/api/kos/ota/artifacts`});return na.debug("getArtifacts - response:",t),t==null?void 0:t.data};var Nv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,ao=(t,e,s,r)=>{for(var o=r>1?void 0:r?Uv(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&&Nv(e,s,o),o};const Nu="ota-model",jv=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Io=t=>{const e=t.artifactInfo,s=jv(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 Pt=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"data",new Cn);c(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 Fv();t&&t.forEach(e=>{const s=Io(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=Io(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=Io(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};ao([Nt({modelType:At.type})],Pt.prototype,"troubleContainer",2);ao([B({topic:"/kos/ota/artifacts/all",websocket:!0})],Pt.prototype,"handleAllArtifacts",1);ao([B({topic:"/kos/ota/artifacts/changed",websocket:!0})],Pt.prototype,"handleChangedArtifacts",1);Pt=ao([P(Nu)],Pt);const Ir=new Se({class:Pt,type:Nu});function Bv(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 _o=m.createLogger({name:"software-info-service",group:"Services"}),ti=async t=>{_o.debug("sending GET for software-info");const[e,s]=await Yc.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(_o.debug("Request was aborted"),new ge("Request was aborted")):(_o.error("Failed to fetch software-info",e),new ge("Failed to fetch software-info"));return s},Hv=Bv(ti),Kv=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:ti,getSoftwareInfosWithCancel:Hv},Symbol.toStringTag,{value:"Module"}));var qv=Object.getOwnPropertyDescriptor,zv=(t,e,s,r)=>{for(var o=r>1?void 0:r?qv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const rs="software-info-model";let Ho=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(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 ti(),e=(t==null?void 0:t.nodes)||{};X(()=>{const r=Object.keys(e).map(o=>e[o][0]).map(o=>({nodeName:o.nodeType,kosVersion:o.kosVersion,group:this.groupBy(o.artifacts,"group")}));this.nodes=r})}catch(t){t instanceof ge&&this.logger.error("Failed to fetch software-info",t)}}};Ho=zv([P(rs)],Ho);const _r={registration:{[rs]:{class:Ho,singleton:!1}},type:rs,predicate:Te(rs),factory:ie.Factory.create(rs)},{URL:Uu}=ae(),{getOne:Vv}=oe.build({basePath:`${Uu}/api/kos/state`}),Gv=m.createLogger({name:"state-bean-service",group:"Services"}),ju=async({path:t})=>(Gv.debug("sending GET for state-bean"),await Vv({urlOverride:`${Uu}/api/kos/state/${t}`})),Yv=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:ju},Symbol.toStringTag,{value:"Module"}));var Wv=Object.defineProperty,Qv=Object.getOwnPropertyDescriptor,Bu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Qv(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&&Wv(e,s,o),o};const os="state-bean-model",Zv=at("path");let Or=class{constructor(t,e,s){c(this,"id");c(this,"path");c(this,"props");c(this,"logger");this.id=t,this.logger=s.logger,this.props=xn.map(new Map),Ao(e,this)}updateModel(t){Ao(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&Rn(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&Wr(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 ju({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};Bu([B({topic:`/kos/state/${Zv}`,websocket:!0})],Or.prototype,"handleConfigBeanUpdated",1);Or=Bu([P(os)],Or);const xs={registration:{[os]:{class:Or,singleton:!1}},type:os,predicate:Te(os),factory:ie.Factory.create(os)};var Xv=Object.defineProperty,Jv=Object.getOwnPropertyDescriptor,Hu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Jv(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&&Xv(e,s,o),o};const ns="state-prop-model",ia=at("path");let $r=class{constructor(t,e,s){c(this,"id");c(this,"path");c(this,"attribute");c(this,"logger");c(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())??""}};Hu([Nt({modelType:xs.type,id:`state-bean-${ia}`,options:{path:ia}})],$r.prototype,"stateBean",2);$r=Hu([P(ns)],$r);const si={registration:{[ns]:{class:$r,singleton:!1}},type:ns,predicate:Te(ns),factory:ie.Factory.create(ns)},{URL:ew}=ae(),{getAll:tw}=oe.build({basePath:`${ew}/api/state-prop`}),sw=m.createLogger({name:"state-prop-service",group:"Services"}),rw=async()=>(sw.debug("sending GET for state-prop"),await tw({})),ow=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:rw},Symbol.toStringTag,{value:"Module"})),{URL:ri}=ae(),{getOne:Ku}=oe.build({basePath:`${ri}/api/translation`}),Ms=m.createLogger({name:"translation-service",group:"Services"}),nw=()=>{const t=window.location.origin,e=me();return(e==null?void 0:e.host)||t},qu=async(t,e)=>{Ms.debug(`Loading translations from: ${t}`);const s=e??nw();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Ms.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Ms.error("Error fetching translations",r),r}},iw=async()=>{Ms.debug("Getting system localization descriptor");const t=await Ku({urlOverride:`${ri}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get localization descriptor ${t==null?void 0:t.status}`);return t.data},zu=t=>async()=>{Ms.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await Ku({urlOverride:`${ri}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},Vu="langResolver";var aw=Object.getOwnPropertyDescriptor,lw=(t,e,s,r)=>{for(var o=r>1?void 0:r?aw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const is="translation-model";function cw(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 Gu(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])){const n=Gu(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function Yu(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]=Yu(t[r],e[r]):s[r]=e[r]);return s}const Ko=(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)?Ko(r,e):r},rr=(t,e,s)=>{const r=/{{(.*?)}}/g,n=Ko(t,e).replace(r,(a,l)=>Object.prototype.hasOwnProperty.call(s||{},l.trim())?s==null?void 0:s[l.trim()]:a);return Ko(n,e)},aa=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let qo=class{constructor(t,e,s){c(this,"id");c(this,"namespace");c(this,"descriptor");c(this,"defaultLocale");c(this,"currentLocale");c(this,"bundleResolver");c(this,"data");c(this,"logger");c(this,"resolver");c(this,"disposer");c(this,"context");c(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(Vu),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=Y.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return qu(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);X(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=Yu(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=Gu(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=aa(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}=cw(e),{namespace:n,key:i}=aa(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const l=this.context.getModel(n);return l?l.resolveKey(i,e):i}if(r&&this.data[a]){const l=this.data[a];return Array.isArray(l)?l.map(u=>rr(u,this.data,o)):rr(this.data[a],this.data,o)}if(this.data[i]){const l=this.data[i];return Array.isArray(l)?l.map(u=>rr(u,this.data,o)):rr(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()})}};qo=lw([zr(),P(is)],qo);const Cr={registration:{[is]:{class:qo,singleton:!1}},type:is,predicate:Te(is),factory:ie.Factory.create(is)};var uw=Object.defineProperty,dw=Object.getOwnPropertyDescriptor,Wu=(t,e,s,r)=>{for(var o=r>1?void 0:r?dw(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&&uw(e,s,o),o};const as="translation-container-model",hw=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function fw(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 hw([r,o])}let Dr=class{constructor(t,e,s){c(this,"id");c(this,"lang");c(this,"rootUrl");c(this,"descriptor");c(this,"_defaultNamespace");c(this,"resolver");c(this,"logger");c(this,"descriptorUrl");c(this,"namespaces",[]);c(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||fw.bind(this),s.kosContext.set(Vu,this.resolver),this.logger=s.logger,this._models=new Ce({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(t){return this.logger.debug("getting model "+t),this._models.getModel("translation-"+t)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const t of this.namespaces){const e=this.resolveNamespace(t);await de(e)}}resolveNamespace(t){var s;if((s=this.descriptor.namespaces)==null?void 0:s[t]){const r=Object.keys(this.descriptor.namespaces[t].locales)[0],o=this.descriptor.namespaces[t].locales[r].defaultLocale,n=Cr.factory("translation-"+t)({kosParentId:this.id,namespace:t,rootUrl:this.rootUrl,currentLocale:this.lang,defaultLocale:o,descriptor:this.descriptor.namespaces[t].locales,resolver:this.resolver});return this.addModel(n),this.namespaces.includes(t)||X(()=>{this.namespaces.push(t)}),n}else{this.logger.warn("namespace "+t+" not found in descriptor");const r=Cr.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)}};Wu([$e],Dr.prototype,"_models",2);Dr=Wu([P(as)],Dr);const Fe={registration:{[as]:{class:Dr,singleton:!0}},type:as,predicate:Te(as),factory:ie.Singleton.create(as)},pw={set(t,e){const s=Y.getContext(Fe.type);s&&s.set(t,e)},get(t){const e=Y.getContext(Fe.type);return e==null?void 0:e.get(t)}},Qu={async init(t){const e=Fe.factory(t);return await de(e),{translations:e}}};function gw(t){return(t==null?void 0:t.troubles)!==void 0&&(t==null?void 0:t.troubles)instanceof Array&&(t==null?void 0:t.troublesByType)!==void 0&&typeof(t==null?void 0:t.troublesByType)=="object"}const Zu="kos-ws-event",oi=Ut(Zu);var mw=Object.defineProperty,yw=Object.getOwnPropertyDescriptor,ni=(t,e,s,r)=>{for(var o=r>1?void 0:r?yw(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&&mw(e,s,o),o};const bw=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){c(this,"id");c(this,"events");c(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){m.debug("kos event received");const{body:r,headers: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 u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const l={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:bw({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,l),m.debug(`logged ${this.events.size} events`)}}};ni([B({topic:[Ls.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);ni([B({topic:[Ls.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=ni([P(oi.type)],exports.WsEventModel);const la=me(),vw=la.debug==="true"||la.debug===!0,ww="/api/system/canvas",Xu=async(t,e)=>{const s=e||ww,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:vw?"false":"true"},body:t})},Ew=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Xu},Symbol.toStringTag,{value:"Module"}));function ca(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var Mw=Object.defineProperty,Tw=Object.getOwnPropertyDescriptor,Ju=(t,e,s,r)=>{for(var o=r>1?void 0:r?Tw(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&&Mw(e,s,o),o};const ed="canvas-renderer-model";function Oo(t){return typeof t.onDone=="function"}let xr=class{constructor(t,e,s){c(this,"id");c(this,"router");c(this,"logger");c(this,"_renderer",null);c(this,"_clearOnComplete");c(this,"isStreaming",!1);c(this,"renderLoopId",null);c(this,"sendIntervalId",null);c(this,"timeoutId",null);c(this,"apiPath");c(this,"endpointName");c(this,"width",50);c(this,"height",30);c(this,"fps",10);c(this,"durationMs",null);c(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){Xu(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=ca(t);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=ca(o);this.logger.debug(`Sending clear frame: ${t}x${e}, apiPath: ${this.apiPath}`),this.sendDataFrame(n,this.apiPath),(s=this._onFrame)==null||s.call(this,n)}}isOneShotDone(){var t,e;return Oo(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=Oo(this._renderer);Oo(this._renderer)&&this._renderer.onDone(()=>{var l,u,d;this.logger.debug(`Renderer completed for ${this.id}`),V("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(l=this._renderer)==null?void 0:l.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((d=(u=this._renderer)==null?void 0:u.isOneShot)==null?void 0:d.call(u))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var l,u;const a=(u=(l=this._renderer)==null?void 0:l.readPixels)==null?void 0:u.call(l,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"})})}};Ju([Nt({modelType:Hn.type})],xr.prototype,"router",2);xr=Ju([P(ed)],xr);const ii=new ye({class:xr,type:ed});class td{constructor({src:e}){c(this,"video");c(this,"canvas");c(this,"ctx");c(this,"lastUpdate",0);c(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 Sw{constructor(){c(this,"canvas");c(this,"gl");c(this,"lastWidth",0);c(this,"lastHeight",0);c(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 Iw extends Sw{constructor({speedPx:s=1}={}){super();c(this,"program");c(this,"posBuffer");c(this,"aPosition");c(this,"uMinHue");c(this,"uMaxHue");c(this,"uHueOffset");c(this,"uGridHeight");c(this,"minHue",0);c(this,"maxHue",80);c(this,"hueOffset",0);c(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
|
|
107
|
+
["${e}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(w=E==null?void 0:E.socket)==null||w.send(d)}else{Ze.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(d)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=C(e,s);return Ze.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:l}=i();Ze.debug(`Topic ${e} currently has ${l} subscribers`),l===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}}c(Ot,"_instance");class Fg{constructor(e,s,r,o,n){c(this,"disposers",[]);c(this,"activatableDisposers",[]);c(this,"flowControllers",new Map);c(this,"baselineDependencies",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[ee])||{},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 l=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${l}`),i.requiresBaseline&&(this.baselineDependencies.set(l,i.requiresBaseline),this.log.debug(`Registered baseline dependency for ${l}: ${i.requiresBaseline.path}`)),i.flow)this.subscribeWithFlowControl(i,l,a);else{const u=this.createHandler(l,i);this.subscribe(i,l,u,a===x.ACTIVATE)}})}deactivate(){this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const e of this.activatableDisposers)try{e()}catch(s){this.log.error("Error during subscription disposal",s)}this.activatableDisposers=[]}disposeAll(){const e=[...this.disposers,...this.activatableDisposers];this.log.debug(`Disposing ${e.length} subscriptions for ${this.modelId}`);for(const[s,r]of this.flowControllers)this.log.debug(`Disposing flow controller for ${s}`);this.flowControllers.clear();for(const s of e)try{s()}catch(r){this.log.error("Error during subscription disposal",r)}this.disposers=[],this.activatableDisposers=[]}subscribe(e,s,r,o){const n=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;if(e.websocket){this.log.debug(`Subscribing to WebSocket topic: ${s}`);const i=Ot.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}=C(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,l=this.extractWildcardCapture(e,r,s),u=this.isBaselineReady(e);if(!this.model.isReady()||!u){u?this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`):this.log.warn(`Baseline not ready for ${e}. Queuing message.`);const d=()=>{const h=Lo(r,s.skipParse),f=s.transform(h);if(a&&s.condition(f,this.modelData,r))return this.callHandlerWithWildcard(s,f,l,r)};this.offlineQueue.enqueue(d,e,r)}else{const d=Lo(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,l,r)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!Hl(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return Bl(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 Cg(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(l=>l==null?void 0:l.abort())};r===x.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;Ot.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=Ni(s)}else i=Ni(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const l=r(a);l instanceof Promise&&await o.trackPromise(l)}}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 l=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(l,e,r)}}catch(l){if(this.log.error(`Error in flow control handler for ${e}:`,l),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,l);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw l}}}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}getResponseStore(){return this.modelData.serviceResponses}isBaselineReady(e){const s=this.baselineDependencies.get(e);if(!s)return!0;const r=this.getResponseStore();if(!r)return this.log.warn(`ServiceResponseStore not found for baseline check on topic: ${e}`),!1;const n=`${(s.method||"get").toUpperCase()}:${s.path}`;return r.has(n)}flushQueueForBaseline(e){const s=this.baselineDependencies.get(e);if(!s){this.log.debug(`No baseline dependency for topic: ${e}`);return}const r=this.getResponseStore();if(!r){this.log.warn("ServiceResponseStore not found, falling back to standard flush"),this.offlineQueue.flush();return}const o=s.method||"get",n=r.getTemporalMetadataByPath(s.path,o);if(!n){this.log.warn(`Baseline temporal metadata not found for ${s.path}, falling back to standard flush`),this.offlineQueue.flush();return}const i=s.replayStrategy||st.AFTER_REQUEST;this.log.info(`Flushing queue with strategy ${i} for topic: ${e}`),this.log.debug(`Baseline timing - requested: ${n.requestedAt}, received: ${n.receivedAt}`),this.offlineQueue.flushWithStrategy(i,n.requestedAt,n.receivedAt)}}function gt(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 Ng(t){return!!(t!=null&&t[rt])&&Object.keys(t[rt]).length>0}function Ug(t){return!!(t!=null&&t[ee])&&Object.keys(t[ee]).length>0}function jg(t){return!!(t!=null&&t[Re])&&t[Re].length>0}function Bg(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[ot])&&Object.keys(e[ot]).length>0}function Hg(t){return t.retention===ue.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function Kg(t,e){return t.has(e)}function qg(t){return!t.expiresAt||Date.now()<t.expiresAt}function Bi(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class zg{constructor(){c(this,"responses",new Map);c(this,"retentionPolicies",new Map);c(this,"cleanupTimers",new Map)}set(e,s,r={retention:ue.SINGLE},o=Date.now(),n=Date.now()){if(this.shouldExtendTTL(e,r))return this.extendExistingTTL(e,r.ttl),!1;const i=this.createCachedResponse(s,e,r,o,n);return this.storeResponse(e,i,r),!0}get(e){const s=this.responses.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.delete(e);return}return s.data}}getByPath(e,s="get"){return this.get(this.makeKey(e,s))}has(e){return this.get(e)!==void 0}delete(e){this.responses.delete(e),this.retentionPolicies.delete(e);const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}clearPath(e){Array.from(this.responses.keys()).filter(r=>this.extractPath(r)===e).forEach(r=>this.delete(r))}clear(){this.cleanupTimers.forEach(e=>clearTimeout(e)),this.responses.clear(),this.retentionPolicies.clear(),this.cleanupTimers.clear()}get size(){return this.responses.size}shouldCleanupAfterHandler(e){const s=this.retentionPolicies.get(e);return(s==null?void 0:s.retention)===ue.IMMEDIATE}shouldExtendTTL(e,s){if(!Hg(s)||!Kg(this.responses,e))return!1;const r=this.responses.get(e);return qg(r)}extendExistingTTL(e,s){const r=this.responses.get(e);r.expiresAt=Date.now()+s,this.resetCleanupTimer(e,s)}resetCleanupTimer(e,s){this.clearTimerIfExists(e),Bi(e,s,this.cleanupTimers,r=>this.delete(r))}clearTimerIfExists(e){const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}createCachedResponse(e,s,r,o,n){return{data:e,timestamp:n,requestedAt:o,receivedAt:n,path:this.extractPath(s),method:this.extractMethod(s),expiresAt:this.calculateExpiresAt(r)}}calculateExpiresAt(e){return e.retention===ue.TTL&&e.ttl?Date.now()+e.ttl:void 0}storeResponse(e,s,r){this.responses.set(e,s),this.retentionPolicies.set(e,r),this.applyRetentionPolicy(e,r)}applyRetentionPolicy(e,s){switch(s.retention){case ue.IMMEDIATE:break;case ue.TTL:s.ttl&&Bi(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case ue.SINGLE:break;case ue.PERMANENT:case ue.MANUAL:break}}makeKey(e,s){return`${s.toUpperCase()}:${e}`}extractPath(e){return e.split(":",2)[1]||e}extractMethod(e){return e.split(":",2)[0]||"get"}getTemporalMetadata(e){const s=this.responses.get(e);if(s)return{requestedAt:s.requestedAt,receivedAt:s.receivedAt}}getTemporalMetadataByPath(e,s="get"){return this.getTemporalMetadata(this.makeKey(e,s))}cleanup(){const e=Date.now();Array.from(this.responses.entries()).filter(([r,o])=>o.expiresAt&&e>o.expiresAt).map(([r])=>r).forEach(r=>this.delete(r))}}class Vg{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=Ol.create({modelId:s,modelTypeName:r}),i=new cg(e,gt(n,"fsm")),a=new dg(gt(n,"offline-queue")),l=new tg(e),u=new eg(e),d=new zg;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:l,childResolver:u};if(Ng(o)&&(h.effectManager=new sg(r,s,o,gt(n,"effect"))),Ug(o)){const f=gt(n,"subscription");h.subscriptionManager=new Fg(e,o,s,a,f),h.onlineLifecycleManager=new hg(e,gt(n,"online"))}return jg(o)&&(h.httpRouteManager=new On(o,gt(n,"http-routes"))),Bg(o)&&(h.serviceRequestManager=new Tg(o,d)),h}}const N=D.getLogger("kos-model"),Gg="kos.extension.model.loader";class yc{constructor({modelTypeName:e,id:s,modelData:r}){c(this,"_id");c(this,"_status");c(this,"_activeStatus");c(this,"_onlineStatus");c(this,"modelData");c(this,"modelTypeName");c(this,"initialized");c(this,"loaded");c(this,"offlineQueue");c(this,"subscriptionManager");c(this,"effectManager");c(this,"httpRouteManager");c(this,"onlineLifecycleManager");c(this,"serviceResponses");c(this,"serviceRequestManager");c(this,"companionManager");c(this,"childResolver");c(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=v.CREATED,this._activeStatus=v.INACTIVE,this._onlineStatus=v.OFFLINE;const o=Vg.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,this.serviceResponses=o.serviceResponseStore,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),o.serviceRequestManager&&(this.serviceRequestManager=o.serviceRequestManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,serviceRequestManager:!1,serviceResponses:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Xp(this)}get companionModels(){return this.companionManager}set status(e){this._status=e}get status(){return this._status}get modelId(){return this._id}get id(){return this._id}get activeStatus(){return this._activeStatus}set activeStatus(e){this._activeStatus=e}get onlineStatus(){return this._onlineStatus}set onlineStatus(e){this._onlineStatus=e}get modelManager(){return globalThis.kos.modelManager}isActive(){return this._status===v.ACTIVE}isOnline(){return this._onlineStatus===v.ONLINE}isReady(){return this._status===v.READY}async deactivate(){var e,s,r;N.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=Y.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw N.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r,o;N.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await Xt(this,x.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.ACTIVATE));const n=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),this.initializeStateMachineForLifecycle(x.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(x.ACTIVATE),this.createLifecycleCompanions(x.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(n){throw N.debug(`Model ${this.modelId} failed to activate`),n}}async whenLoaded(){await Eo([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{N.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await Eo([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{N.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Eo([{condition:()=>this.status===v.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===v.READY,onMatch:()=>{N.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,o;if(this.fsm.current===v.READY){N.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{N.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await Xt(this,x.READY),await ec(this,In.READY,x.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(x.READY));const n=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.ready)==null?void 0:r.call(s,n)),this.offlineQueue.flush(),this.initializeStateMachineForLifecycle(x.READY),(o=this.subscriptionManager)==null||o.registerAll(x.READY),this.createLifecycleCompanions(x.READY),N.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};V(zl(this.modelTypeName,this.modelId),i),V(Vl(this.modelTypeName),i)}catch(n){throw N.error(n),Error(n)}}async load(){var o,n,i,a,l,u;const e=this[ze];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===v.LOADED||this.fsm.current===v.LOADING){N.debug(`Model ${s} with id ${r} already loaded or loading`);return}N.debug(`Loading model ${s} with id ${r}`),await Xt(this,x.LOAD);try{const d=Y.getContext(r),h=`${Gg}.${s}`,f=await $.loader.executeLoader(h,{});f&&(N.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(x.LOAD)),await((i=(n=this.modelData)==null?void 0:n.load)==null?void 0:i.call(n,d)),J(()=>{this.loaded=!0}),N.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(x.LOAD),(a=this.subscriptionManager)==null||a.registerAll(x.LOAD),(l=this.httpRouteManager)==null||l.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(x.LOAD)}catch(d){throw N.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,o,n,i,a;N.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const l=this.getChildren().map(d=>{var h;return(h=d.unload)==null?void 0:h.call(d)}).filter(d=>!!d);await Promise.allSettled(l);const u=Y.getContext(this.modelId);if(await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,u)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),this.modelData){const d=this.modelData;if(d._fsmInitialized=!1,d._fsmConfig){const h=((o=d._fsmOptions)==null?void 0:o.stateProperty)||"currentState";d[h]=void 0}d.stateHistory&&(d.stateHistory=[])}N.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(n=this.effectManager)==null||n.disposeAll(),(i=this.subscriptionManager)==null||i.disposeAll(),(a=this.httpRouteManager)==null||a.dispose()}catch(l){throw N.debug(`Model ${this.modelId} failed to unload`),l}}async init(){var n,i,a,l;const e=this[ze];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=Y.getContext(s);N.debug(`Initializing model ${r} with id ${s}`),await Xt(this,x.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(x.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,o)),this.initialized=!0,N.debug(`Model ${r} with id ${s} initialized`),(l=this.onlineLifecycleManager)==null||l.register(),this.initializeStateMachineForLifecycle(x.INIT),this.registerSubscribers(x.INIT),this.createLifecycleCompanions(x.INIT)}catch(u){throw N.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;N.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&Ml(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;N.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=Y.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(x.ONLINE)}async offline(){var s,r,o;N.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=Y.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 Mo=m.createLogger({name:"kos-model-instantiator"});class Yg{constructor(e,s){c(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new zp(e,s,this.createModelInstance.bind(this))}createModelInstance(e,s,r={}){var a;const o=this.registry.models[e];if(!o){const l=`No model registered for type ${e}`;throw Mo.error(l,{modelType:e,requestedId:s,providedOptions:r,availableModelTypes:Object.keys(this.registry.models)}),St(new Error(l),{modelType:e,modelId:s,operation:"model instantiation - registry lookup",options:r,metadata:{availableModelTypes:Object.keys(this.registry.models)}})}const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Mo.debug(`Creating model instance: ${e} [${n}]`);const l=r&&Object.keys(r).length>0,u=o.class||o.create;if(((a=u==null?void 0:u.prototype)==null?void 0:a[Us])===!0&&!l){const h=new Error(`Model ${e} requires options but none were provided`);throw ki(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),St(h,{modelType:e,modelId:n,operation:"model instantiation - options validation",options:r,metadata:{requiresOptions:!0,hasOptions:!1}})}try{const h=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),f=new yc({modelTypeName:e,id:n,modelData:h});this.cache.addModel(f),this._createCompanionModels(f,r)}catch(h){throw ki(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),St(h,{modelType:e,modelId:n,operation:"model instantiation",options:r})}}const i=this.cache.getModelById(n);if(!i)throw Mo.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,r){this.companionInstantiator.createCompanionModels(e,s,r)}_createCompanionModels(e,s){this.createCompanionModels(e,s)}}let Wg=class{constructor(e){this._registry=e}get registry(){return this._registry}getModelTypeRegistry(e){const s=this.registry.models[e];if(!s)throw new Error(`No registration for model type ${e}`);return s}registerModel(e){const s=e.type;this.registry.models[s]||(this.registry.models={...this.registry.models,...e.registration})}registerCompanionModel(e,s){var r,o;(r=this.registry).companionModels??(r.companionModels={}),(o=this.registry.companionModels)[e]??(o[e]=[]),this.registry.companionModels[e].some(n=>n.type===s)||this.registry.companionModels[e].push({type:s})}getModelSubscriptions(e){var s;return((s=this.getModelTypeRegistry(e))==null?void 0:s.subscriptions)||{}}getDataModelBuilder(e){var r;const s=(r=this.getModelTypeRegistry(e))==null?void 0:r.builder;if(!s)throw new Error(`No builder found for model type ${e}`);return s}getModelFactory(e){return Bt(e)}};const bc=10,Hi=m.createLogger({name:"kos-model-manager"});class vc{constructor(){c(this,"cache");c(this,"instantiator");c(this,"dependencies");c(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Hp,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 Wg(e),r.cache=new Kp(e.preloadModels),r.instantiator=new Yg(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(Hi.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=>(Hi.debug(`preloading ${e}`),typeof e=="string"?this.createModelInstance(e).model:this.createModelInstance(e.modelType,e.modelId,e.options).model))}get models(){return this.cache.models}getModelById(e){return this.cache.getModelById(e)}addModel(e){return this.cache.addModel(e)}removeModel(e){this.cache.removeModel(e.modelId)}hasModel(e){return this.cache.hasModel(e)}getModelsByType(e,s){return Array.from(this.models).filter(r=>r.modelTypeName===e).filter(r=>s?s(r.modelData):!0).map(r=>r.modelData)}getModelSubscriptions(e){return this._registry.getModelSubscriptions(e)}getDataModelBuilder(e){return this._registry.getDataModelBuilder(e)}getModelFactory(e){return Bt(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(L.RESET,v.RESETTING)}}async initiateDestroyModel(e){if(!e.id)throw new Error("Model ID is required");if(!this.dependencies.canDestroy(e.id))return;const s=this.getModelById(e.id);s&&(this.cache.markForDeletion(s),Kl.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),bc)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}createLifecycleCompanions(e,s,r){this.instantiator.createCompanionModels(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var lr=(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))(lr||{}),wt=(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))(wt||{});const Qg=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,n=>D.debug(n.machine.current)),r=b.createMachine({creating:b.state(b.transition("create","created")),created:b.state(b.immediate("initializing")),initializing:b.invoke(()=>t.init(),b.transition("done","initialized")),initialized:b.state(b.immediate("loading")),loading:b.invoke(()=>t.load(),b.transition("done","loaded")),loaded:b.state(b.immediate("readying"),b.transition("unload","unloading")),readying:b.invoke(()=>t.ready(),b.transition("done","ready",b.action(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:b.invoke(()=>t.reload(),b.transition("done","loading")),ready:b.state(b.transition("reload","reloading"),b.transition("unload","unloaded",b.action(t.unload.bind(t))),b.transition("go_online","ready",b.action(()=>{s.send("go_online")})),b.transition("go_offline","ready",b.action(()=>{s.send("go_offline")}))),unloaded:b.state()});return{service:b.interpret(r,n=>D.debug(n.machine.current)),online:s}},Q=m.createLogger({name:"kos-core"}),Zg=()=>{const t=me(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},Xg=()=>{const t=window.location.protocol,e=me(),s=e==null?void 0:e.host;let r;try{r=new URL(s).protocol==="https:"?"wss://":"ws://"}catch{}return r||(t==="https:"?"wss://":"ws://")},Jg=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=me(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},em=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=me(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},tm=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?m.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):m.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},Ki=t=>typeof t.reload=="function",sm=t=>typeof t.unload=="function";var wc=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(wc||{});class _{constructor(e){c(this,"fsmService");c(this,"status");c(this,"initialized");c(this,"loaded");c(this,"_transport");c(this,"modelManager");c(this,"authState");c(this,"isOnline");c(this,"_reloading");c(this,"_unloading");c(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=lr.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(vs.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(wt.GO_ONLINE)}),C(vs.DISCONNECTED,async()=>{this.fsmService.service.send(wt.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(vs.RELOAD,()=>{Q.warn("WebSocket requested reload"),this.fsmService.service.send(wt.RELOAD)}),C("/studio/project/reload",()=>{Q.warn("Project requested reload"),this.fsmService.service.send(wt.RELOAD)});const s=Ot.getInstance(),r=Jg(),o=em(),n=Xg();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Zg()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Qg(this),this.fsmService.service.send(wt.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){Q.info("reload already in progress");return}this._reloading=!0,Q.warn("reloading KOS Core"),Q.warn("reloading preloaded models");const s=this.modelManager;for(const l of s.preloadedModels)Ki(l.modelData)&&(Q.info(`reloading model ${l.modelId}`),(o=l.unload)==null||o.call(l),await l.modelData.reload(),(n=l.registerSubscribers)==null||n.call(l),Q.info(`reloading model ${l.modelId} complete`));for(const l of s.models)!s.preloadedModels.includes(l)&&Ki(l.modelData)&&((i=l.unload)==null||i.call(l),await l.modelData.reload(),(a=l.registerSubscribers)==null||a.call(l));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{Q.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Q.debug("KOS Core going online"),await this._transport.whenReady(),Q.debug("KOS Transport Ready. Calling online() for models"),V("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Q.debug("KOS Core going offline"),V("/kosCore/offline","/kosCore/offline")}async unload(){var o;Q.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Q.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)sm(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===lr.READY)}async ready(){Q.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}=tm(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Q.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Q.debug("leaving kos-core ready() ")}get isReady(){return this.status===lr.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Q.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Q.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Q.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Q.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,l;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{$.dataMapper.registerDataMapper(u,p)}):$.dataMapper.registerDataMapper(u,d))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&$.propertyMapper.registerPropertyMapper(u,d)}),(l=e.extensions)!=null&&l.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&$.loader.registerLoader(u,d)}),A.model.getAll().forEach(([,u])=>{e.models={...e.models,...u.registration}}),e.models={...e.models,...A.model.getLegacyModels()},A.companion.getAll().forEach(([u,d])=>{e.companionModels={...e.companionModels},e.companionModels[u]=e.companionModels[u]||[];for(const h of d){let f;if(typeof h=="string"){const p=e.models[h];if(p!=null&&p.class){const y=p.class.prototype[ze];f=y==null?void 0:y.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),A.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=vc.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}}c(_,"_instance");function No(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 rm(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 om(t){return await t.arrayBuffer()}function nm(t,e){return new Blob([t],{type:e})}async function im(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:No(i)})}else e[o]=n.toString();return{fields:e,files:s}}function am(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function lm(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:No(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await om(t);return{data:No(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await im(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Xs=m.createLogger({name:"kos-fetch"}),cm=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,um=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),dm=t=>t!=null&&t.studio?nc:t!=null&&t.fos?ic:ac,hm=async(t,e)=>{const s=_.getInstance().transport;await s.whenReady();const r=lt(),o=new URL(t),n=`${o.pathname}${o.search}`;Xs.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||cm,a=dm(e),l=await lm(e==null?void 0:e.body),u={};l.contentType&&(u["content-type"]=l.contentType),l.encoding&&(u["content-encoding"]=l.encoding);const d=We(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,...u}}),l.data);return new Promise(h=>{let f=null,p=null;if(e!=null&&e.signal){if(e.signal.aborted){h({headers:Jt({}),status:0,ok:!1,json:async()=>null,body:es(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}});return}e.signal.addEventListener("abort",()=>{p&&clearTimeout(p),f&&f(),h({headers:Jt({}),status:0,ok:!1,json:async()=>null,body:es(""),redirected:!1,statusText:"Request aborted",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})})}p=setTimeout(()=>{Xs.error(`Timeout occurred - url: ${t}`),f&&f(),h({headers:Jt({}),status:404,ok:!1,json:async()=>null,body:es(""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){throw new Error("Function not implemented.")},bodyUsed:!1,arrayBuffer:function(){throw new Error("Function not implemented.")},blob:function(){throw new Error("Function not implemented.")},formData:function(){throw new Error("Function not implemented.")},text:function(){throw new Error("Function not implemented.")}})},i);const y=C(r,E=>{p&&clearTimeout(p);const S=(E==null?void 0:E.headers)||{},k=S["content-type"]||"text/plain",U=S["content-encoding"],O=(E==null?void 0:E.body)||"";let I=O;if(U==="base64"&&O)try{I=rm(O)}catch(j){Xs.error("Failed to decode base64 response",j)}const z={headers:Jt(S),status:S.status&&parseInt(S.status)||200,ok:S.status==="200",json:async()=>{try{if(typeof I=="string")return I.length?JSON.parse(I):null;{const Z=new TextDecoder().decode(I);return Z.length?JSON.parse(Z):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?nm(I,k):new Blob([I],{type:k}),formData:async()=>{const j=new FormData;if(k==="multipart/form-data"&&typeof I=="string")try{const Z=JSON.parse(I);Z.fields&&Object.entries(Z.fields).forEach(([je,Be])=>{j.append(je,Be)}),Z.files&&Xs.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return j},body:e!=null&&e.stream?am(async j=>{if(I instanceof ArrayBuffer)j.enqueue(new Uint8Array(I));else{const Z=new TextEncoder;j.enqueue(Z.encode(I))}j.close()}):es(typeof I=="string"?I:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};y.unsubscribe(),um().then(()=>h(z))});f=y.unsubscribe;const w=e!=null&&e.fos?s.fosSocket:s.socket;if(!w)throw Error(`No web socket transport available: ${e}`);w==null||w.send(d)})};exports.BASE_URL="kos:";exports.kosFetch=hm;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const fm=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class pm{constructor(){c(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=_.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)){fm.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)}))}}class Ec{constructor(){c(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 gm=async(t,e)=>{const s=new Ec;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},Bt=t=>({type:t,build:(e,s)=>_.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=_.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),mm=t=>{_.getInstance().modelManager.registerModel(t)},ym=(t,e)=>{_.getInstance().modelManager.registerCompanionModel(t,e)},qi="/kos/ui/internal/heartbeat/",bm=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=_.getInstance().transport,i=new AbortController;let a=performance.now();const l=n.subscribeTopic({topic:`${qi}${t}`,callback:()=>{a=performance.now()}}),u=r??3e3,d=window.setInterval(()=>{let w=performance.now()-a;w=w/1e3,w>u/1e3&&i.abort()},u),h=o??2e3,f=window.setInterval(()=>{pc({msg:{},options:{topic:`${qi}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),l()},y=()=>{p(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:p}},Mc=(...t)=>e=>t.reduce((s,r)=>r(s),e),vm={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function wm(t,e){let s=1;const r={...vm,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(l){if(m.error(`Attempt ${s} failed: ${l}`),s<o)a=n*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw l}throw new Error("All attempts failed")}const Em=m.createLogger({name:"kos-service-request"}),ae=t=>({isMock:!1,URL:exports.BASE_URL}),Mm=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:l,bridge:u,destinationAddress:d})=>{const h={method:"DELETE"};t&&(h.destinationAddress=t),o&&(h.tracker=o),Ht(h,{ordered:i,studio:a,fos:l,bridge:u,destinationAddress:d});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()},Ht=(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),Tm=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:l,destinationAddress:u})=>{const d={method:"GET"};t&&(d.destinationAddress=t),Ht(d,{timeout:l,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:u});const f=await s(r||e,d);if(!f.ok){let y;try{y=await f.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${f.status}`,y)}return await f.json()},Sm=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:l,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),l&&(h.tracker=l),Ht(h,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,destinationAddress:d});const f=r||e;Em.debug(`resolvedUrl: ${f}`);const p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()},Im=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:l,timeout:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),Ht(h,{timeout:u,ordered:n,studio:i,fos:a,bridge:l,destinationAddress:d});const f=r||`${e}/${o}`,p=await s(f,h);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem retrieving the model; returned status ${p.status}`,w)}return await p.json()};class ge extends Error{constructor(s,r){super(s);c(this,"payload");this.name="FetchException",this.payload=r}}const zi=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:l,bridge:u,timeout:d,destinationAddress:h})=>{const f={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(f.destinationAddress=t),i&&(f.tracker=i),Ht(f,{timeout:d,ordered:n,studio:a,fos:l,bridge:u,destinationAddress:h});const p=await s(o||e,f);if(!p.ok){let w;try{w=await p.json()}catch{}throw new ge(`There was a problem sending the POST data; returned status ${p.status}`,w)}return await p.json()},Vi=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:l,fos:u,bridge:d,timeout:h,destinationAddress:f})=>{const p={method:t};o&&(p.body=JSON.stringify(o)),e&&(p.destinationAddress=e),Ht(p,{timeout:h,ordered:a,studio:l,fos:u,bridge:d,destinationAddress:f});const y=await r(i||`${s}/${n}`,p);if(!y.ok){let E;try{E=await y.json()}catch{}throw new ge(`There was a problem modifying the model; returned status ${y.status}`,E)}return await y.json()},oe={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const l=a?fetch:exports.kosFetch;return{getAll:Tm(t,s||e,l),getModelById:Im(t,r||e,l),getOne:Sm(t,r||e,l),addModel:zi(t,n||e,l),deleteModel:Mm(t,o||e,l),modifyModel:Vi("POST",t,i||e,l),putModel:Vi("PUT",t,i||e,l),postModel:zi(t,n||e,l)}}};function _m(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function Om(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function $m(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function Cm(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function Dm(t){const e=t.serviceResponses;e&&e.clear()}const xm=lt(),Tc=()=>`kos-${xm}`,Am=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(Tc()),Cn=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=C(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)}),Rm=async(t,e,s)=>{const r=Cn(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)},Pm=async({topic:t,msg:e,requestId:s})=>{const r=s??lt(),o=Cn(r);V(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},he=new Map;class Sc{constructor(e){c(this,"_context");c(this,"_parent");c(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){J(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=_e(this._parent))==null?void 0:e.model}get companionModels(){const e=_e(this._id);return e!=null&&e.model?Fl(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||!he.has(n.id)?!1:(i=he.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=he.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=he.get(this._parent))==null?void 0:r.get(e)}set(e,s){this._context.set(e,s)}remove(e){this._context.delete(e)}clear(){this._context.clear()}}const Y={createContext:(t,e)=>{const s=he.get(t)??new Sc(t);if(e){if(!he.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return he.set(t,s),s},getContext:t=>he.get(t),deleteContext:t=>{he.delete(t)},setParentContext:(t,e)=>{var s;if(!he.has(e))throw new Error(`Parent context ${e} does not exist`);(s=he.get(t))==null||s.setParent(e)},rootContext:()=>he.get("root")};Y.createContext("root");const km=t=>Y.getContext(t.id),To=m.createLogger({name:"kos-data-container"});class Dn{constructor(e){c(this,"_data");c(this,"_sortKey");c(this,"_revision");c(this,"_index");c(this,"_optionsMap");c(this,"_disposerMap",new Map);c(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=Ie(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Tn({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??[]:(To.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):(To.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return To.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 Lm{constructor({type:e,model:s,childRegistration:r}){c(this,"type");c(this,"childRegistration");c(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ie.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return Te(this.type)}}class Fm{constructor({type:e,model:s,childRegistration:r}){c(this,"type");c(this,"model");c(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return ie.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return Te(this.type)}}class Ic{constructor(){c(this,"_token");M.makeAutoObservable(this),C("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class _c{constructor(){c(this,"routes",[]);c(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 l of this.routes){const u=this.matchRoute(l.path,r);if(l.method===e.method&&u){i.params=u;let d=0;const h=async()=>{if(d<l.middlewares.length){const f=l.middlewares[d++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),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=m.createLogger({name:"intent-service"}),Nm=t=>{nn(`/kos/intent/${t.type}`)?V(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):Oc.info(`No subscribers for intent ${t.type}. Intent not sent.`)},Um=async t=>new Promise(e=>{const{type:s,options:r}=t;if(nn(`/kos/intent/${t.type}`)){const o=lt(),{unsubscribe:n}=C(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);V(`/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}])}),Ae=m.createLogger({name:"app-startup-service"});async function $c(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return Ae.warn("No app IDs provided to waitForAppsToStart"),!0;Ae.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(l=>`/kos/app/started/${l}`),i=await cn(n,{getCurrentState:async()=>{try{const{default:l}=await Promise.resolve().then(()=>rc),[u,d]=await l.get("/api/kos/apps/started");return u?(Ae.error("Error fetching started apps:",u),[]):d}catch(l){Ae.error("Failed to fetch app startup status:",l)}return[]},shouldUseFetchedState:l=>t.every(u=>{const d=l.find(h=>h.appId===u);return!(!d||!d.started||o&&!d.postStarted)}),timeout:s}),a=t.filter(l=>{const u=i.find(d=>d.appId===l);return!!(!u||!u.started||o&&!u.postStarted)});if(a.length>0){const l=`Apps not started: ${a.join(", ")}`;if(Ae.error(l),r)throw new Error(`App startup timeout: ${l}`);return!1}return Ae.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(Ae.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function jm(t,e={}){return $c([t],e)}async function Bm(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(l=>l.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){Ae.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function Hm(){try{const t=await exports.kosFetch("kos:///api/kos/apps/started");if(!t.ok)return[];const e=await t.json();return(e==null?void 0:e.data)??[]}catch(t){return Ae.error("Failed to fetch started apps:",t),[]}}const Uo=M.when,xn=M.computed,J=M.runInAction,W=M.autorun,Cc=M.reaction,An=M.observable,Rn="Not Assigned",Km="kos.trouble.added",qm="kos.trouble.removed";var ve=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(ve||{}),ws=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(ws||{});const Dc=m.createLogger({name:"config-bean-service",group:"Services"}),Pn=exports.BASE_URL,xc=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:zm,getOne:Vm}=oe.build({destinationAddress:"",basePath:`${Pn}/kos/config/`}),Ac=async(t,e,s="/api/kos/config")=>(Dc.debug(`sending modify request for ConfigBean: ${t}`),zm({model:e,urlOverride:`${Pn}${s}/${t}`})),Rc=async(t,e="/api/kos/config")=>(Dc.debug(`sending get request for ConfigBean: ${t}`),await Vm({urlOverride:`${Pn}${e}/details/${t}/15`})),kn=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",Qr=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function Pc(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function kc(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])?kc(t[r],o,s):s[o]=t[r]}return s}const Lc=(t,e)=>{const s=t.details[0].bean||Pc(t.details[0].scopes),r=kc(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},Fc=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&kn(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&Qr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},Nc=t=>Object.fromEntries(t.props.entries),Gm=t=>e=>s=>t.build(e,s);var Ym=Object.defineProperty,Wm=Object.getOwnPropertyDescriptor,Uc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Wm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ym(e,s,o),o};function Qm(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Ln="config-bean-model",Js=m.getLogger(Ln),Zm=ct("path");let mr=class{constructor(t,e){c(this,"_modifyConfigBean");c(this,"_getConfigBean");c(this,"_schema");c(this,"id");c(this,"path");c(this,"props");c(this,"prevProps");c(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=Ac,getConfigBean:r=Rc}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Ie(),this.prevProps=Ie()}get values(){return this.props.values}async ready(){Js.debug(`readying config bean ${this.path}`),Js.debug(`complete readying config bean ${this.path}`)}async load(){Js.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;Lc(e,this),Js.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;J(()=>{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=Qm(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=Nc(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){Fc(t,this)}};Uc([H({topic:`/kos/config/${Zm}`,websocket:!0})],mr.prototype,"handleConfigBeanUpdated",1);mr=Uc([R(Ln)],mr);const Ts=new ye({class:mr,type:Ln}),Zr=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Ts.type,id:`${Ts.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:x.INIT,lazy:e}},{URL:jc}=ae(),{getOne:Xm,getAll:Jm}=oe.build({basePath:`${jc}/api/kos/regions/info`}),Bc=async()=>{try{return await Xm({})}catch{return}},Hc=async()=>{try{return await Jm({urlOverride:`${jc}/api/kos/regions`})}catch{return}},ey=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Bc,getRegions:Hc},Symbol.toStringTag,{value:"Module"}));var ce=(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))(ce||{});const Kc={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 ty(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},{...Kc});return{...t,...r}}function sy(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const l=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=l,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:l,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{...Kc}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function ry(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 oy=Object.defineProperty,ny=Object.getOwnPropertyDescriptor,Fn=(t,e,s,r)=>{for(var o=r>1?void 0:r?ny(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&oy(e,s,o),o};const cr="region-info-model",Zt=m.createLogger({name:"region-info-model"});let Ss=class{constructor(t){c(this,"id");c(this,"unitSystemMap");c(this,"measureMap");c(this,"defaultMeasureMap");c(this,"regionMap");c(this,"timeFormats");c(this,"dateFormats");c(this,"unitSystems");c(this,"regionSource");c(this,"region");c(this,"regions",[]);c(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[ce.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[ce.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[ce.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[ce.family]!==s[ce.family])throw new Error(`Cannot convert between units of different families: ${e[ce.family]} and ${s[ce.family]}`);const r=e[ce.offset],o=e[ce.scale],n=s[ce.scale],i=s[ce.offset],a=s[ce.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,l;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 u=this.measureMap[s.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=u[s.system])==null?void 0:a.default,i||Zt.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const u=this.measureMap[e.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(l=u[e.system])==null?void 0:l.default,n||Zt.info("Could not find default unit for measure",e.measure)}return!n||!i?(Zt.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){Zt.debug("initializing region info")}async load(){Zt.debug("loading region info");const t=await Hc();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(ty,{}),this.measureMap=e.data.unitSystems.reduce(sy,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(ry,{}),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))}};Fn([Zr({path:"kos:service:region:settings"})],Ss.prototype,"regionSource",2);Fn([Zr({path:"kos:service:region"})],Ss.prototype,"region",2);Ss=Fn([R(cr)],Ss);const re={registration:{[cr]:{class:Ss,singleton:!0}},type:cr,factory:ie.Singleton.create(cr)},yr=({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},Nn=(t,e,s)=>{const{model:r}=_e(re.type);if(!r)throw new Error("RegionInfo model not found");if(!gr(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=yr({source:e}),i=yr({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Gi(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 iy=(t,e,s,r)=>{const o=Nn(t,e,s),n=yr({source:e}),{model:i}=_e(re.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),l={system:i.defaultUnitSystem},u=yr({source:s||l,defaultMeasure:i.getUnitMeasure(n.unit||"")}),d=i.getDefaultUnitForMeasure(a,u.system),h=i.getDefaultUnitDecimalPlaces(a,u.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:d||n.unit||"",display:Gi(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:Gi(o,d||n.unit||"",{...f,mode:"short"})}};function Yi({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 Wi({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 mt=(t,e)=>s=>!t||!e?s:Qr(s)?Nn(Number(s),t,e):s,ay=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Yi(t.options).map(mt(s,r));if(t.options.type==="rangeInterval")return Wi(t.options).map(mt(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(mt(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Yi(t.options.unitSystems[e]).map(mt(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Wi(t.options.unitSystems[e]).map(mt(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(mt(s,r))}}return[]},ly=(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 cy=Object.defineProperty,uy=Object.getOwnPropertyDescriptor,Un=(t,e,s,r)=>{for(var o=r>1?void 0:r?uy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&cy(e,s,o),o};function dy(t){return(t==null?void 0:t.type)==="enum"}function hy(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 fy(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return He.format(r,e)}const ur="config-bean-prop-model",yt=m.createLogger({name:"config-bean-prop-model"}),py=ct("path"),gy=ct("serviceBasePath");let Is=class{constructor(t,e){c(this,"id");c(this,"path");c(this,"attribute");c(this,"converter");c(this,"formatter");c(this,"optionsExpander");c(this,"serviceBasePath");c(this,"regionInfo");c(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 xc(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?hy(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=dy(r)?r.values:ay(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 l=this.getFormatterOptions(s);if(l){let u=String(t);return u=l.formatToParts(Number(t))[0].value,Number(u)}}catch(l){yt.info(`error formatting value ${t}`,l)}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(){yt.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 fy(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){yt.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 ly(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 l=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,u=this.formatter||l;if(u){let d=typeof u=="function"?u(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):u;s&&(d={unit:this.getDefaultUnit(t),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...d})}catch(h){yt.error(`error creating formatter ${d}. Returning the raw value`,h)}}else yt.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,l,u,d,h,f,p;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const y=(r=this.converter)==null?void 0:r.measure,w=(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,S=y||w||E||e,k=((u=(l=this.converter)==null?void 0:l.to)==null?void 0:u.unit)||this.regionInfo.getDefaultUnitForMeasure(S,((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),U=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(k),O=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:O,...this.converter.from},to:{...this.converter.to,unit:k,system:U},measure:S}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),w=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:w===E?s:y}}}}async updateProperty(t){yt.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)}};Un([jt({modelType:re.type})],Is.prototype,"regionInfo",2);Un([Zr({path:py,serviceBasePath:gy})],Is.prototype,"bean",2);Is=Un([R(ur)],Is);const ut={registration:{[ur]:{class:Is,singleton:!1}},type:ur,factory:ie.Factory.create(ur)};function my(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,l=r;return l&&(typeof l!="function"&&typeof l.from=="string"&&(l.from={unit:l.from}),typeof l!="function"&&typeof l.to=="string"&&(l.to={unit:l.to})),(u,d)=>{u[F]=u[F]||{},u[F][d]={modelType:ut.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:l,formatter:o,optionsExpander:i},lifecycle:x.INIT,lazy:n}}}const qc="future-model",Kt=Bt(qc),Xr=m.createLogger({name:"future-service",group:"Services"}),{isMock:yy,URL:Hs}=ae();var Ve=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(Ve||{});const{getAll:by,modifyModel:vy,addModel:wy,deleteModel:Ey,postModel:My}=oe.build({destinationAddress:"",basePath:`${Hs}/api/future`,mock:yy}),Ty=async()=>await by({}),zc=async(t,e="/api/kos/future")=>(Xr.info(`sending delete request for Future: ${t}`),await Ey({id:t,urlOverride:`${Hs}${e}/${t}`})),Vc=async(t,e="/api/kos/future")=>(Xr.info("sending add request for Future"),await wy({model:t,urlOverride:`${Hs}${e}`})),Sy=async(t,e,s="/api/kos/future")=>(Xr.info(`sending modify request for Future: ${t}`),vy({model:e,id:t,urlOverride:`${Hs}${s}/${t}`})),Gc=async(t,e="/api/kos/future")=>(Xr.info(`sending cancel request for Future: ${t}`),My({urlOverride:`${Hs}${e}/${t}/cancel`,ordered:!0,model:{}})),jn=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}),Bn=(t,e)=>{m.debug(`future dto ${t.id} end state ${t.endState}`),m.debug(`future model ${e.id} end state ${e.endState}`),e.endState?m.debug(`future model ${e.id} is already complete`):(m.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=jn(t);J(()=>{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]})})}))},Yc=t=>e=>s=>t.build(String(e),s),Hn=t=>e=>Mc(jn,Yc(t)(e.tracker||e.id))(e);var Iy=Object.defineProperty,_y=Object.getOwnPropertyDescriptor,Wc=(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&&Iy(e,s,o),o};const So=m.getLogger(Kt.type);let br=class{constructor(t,e,s){c(this,"logger");c(this,"_cancelFuture");c(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=Gc,Uo(()=>this.status===Ve.Success||this.status===Ve.Fail,()=>{So.info(`Future ${this.id} has completed with status ${this.status}`),nt(this)})}async load(){So.debug(`loading Future ${this.id}`)}unload(){So.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Uo(()=>this.futureId!==Rn),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,l;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[u,d]of Object.entries(e))if(Math.abs(t)>=d){s=u,r=Math.round(t/d);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((l=n[2])==null?void 0:l.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),Bn(t,this)}};Wc([H({topic:`kos.future/${hr}`})],br.prototype,"handleFutureUpdated",1);br=Wc([R(Kt.type)],br);const Qc=br,Zc=Bs();var Oy=Object.defineProperty,$y=Object.getOwnPropertyDescriptor,Xc=(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&&Oy(e,s,o),o};const Jc="browser-router-model",Cy="kos.http.request",Dy="kos.http.response";let vr=class{constructor(t,e,s){c(this,"_id");c(this,"logger");c(this,"router");this._id=t,this.logger=s.logger,this.router=new _c}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 l=200;const u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),gc({msg:d,options:{responseId:i,destinationAddress:s,type:Dy,sourceAddress:r,status:l}})},status:function(d){return l=d,this}};if(a.path==="/openapi.json"){u.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,u)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};Xc([H({topic:Cy})],vr.prototype,"handleRequest",1);vr=Xc([R(Jc)],vr);const Kn=new Se({class:vr,type:Jc}),eu="future-container-model",Ge=Bt(eu),tu=t=>Hn(Kt)(t),xy=t=>{const e=tu(t);return Ge.build(Ge.type,{}).addFutureModel(e),e},Ay=t=>Ge.build(Ge.type,{}).getFuture(String(t)),it={buildFutureModel:tu,initiateFuture:xy,getFuture:Ay};var Ry=Object.defineProperty,Py=Object.getOwnPropertyDescriptor,qn=(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 er=m.getLogger(Ge.type);let _s=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_deleteFuture");c(this,"_addFuture");c(this,"_futures");c(this,"createModel");c(this,"deleteModel");const{deleteFuture:r=zc,addFuture:o=Vc}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new Ce,this.createModel=this.createFuture,this.deleteModel=this.removeFuture}get futures(){return this._futures.data}get models(){return this.futures}getFuture(t){return this._futures.getModel(t)}addFutureModel(t){this._futures.addModel(t)}removeFutureModel(t){this._futures.removeModel(t)}async removeFuture(t){try{await this._deleteFuture(t)}catch(e){er.error("error deleting a Future"),er.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Hn(Kt)(s);return this.addFutureModel(r),r}}catch(e){throw er.error("error creating a Future"),er.error(e),e}}handleFutureUpdated(t,e){const s=it.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),V(r,e.body,e.headers)}};qn([$e],_s.prototype,"_futures",2);qn([H({topic:"kos.future"})],_s.prototype,"handleFutureUpdated",1);_s=qn([R(Ge.type)],_s);const su=_s,{URL:Ks}=ae(),{getOne:ky,postModel:Ly,deleteModel:ru}=oe.build({basePath:`${Ks}/api/keyVal`}),jo=m.createLogger({name:"key-value-service",group:"Services"}),ou=async(t,e)=>{await ru({urlOverride:`${Ks}/api/keyVal/${t}/${e}`,id:e})},nu=async(t,e,s)=>{const r=await Ly({urlOverride:`${Ks}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw jo.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},iu=async(t="studio")=>{jo.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await ky({urlOverride:`${Ks}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw jo.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},Fy=async t=>{await ru({urlOverride:`${Ks}/api/keyVal/${t}`,id:""})},Ny=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:ou,deleteKeyValueNamespace:Fy,getKeyValue:iu,updateKeyValue:nu},Symbol.toStringTag,{value:"Module"}));var Uy=Object.defineProperty,jy=Object.getOwnPropertyDescriptor,zn=(t,e,s,r)=>{for(var o=r>1?void 0:r?jy(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 au="key-value-model";let Os=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"namespace");c(this,"data");this.id=t,this.logger=s.logger,this.data=Ie(),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 nu(this.namespace,t,e),this.data[t]=e):(await ou(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await iu(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)}};zn([H({topic:"/keyVal/set"})],Os.prototype,"handleStateUpdate",1);zn([H({topic:"/keyVal/remove"})],Os.prototype,"handleStateDelete",1);Os=zn([R(au)],Os);const Vn=new ye({class:Os,type:au});var fe="INUMBER",qt="IOP1",zt="IOP2",Vt="IOP3",Pe="IVAR",at="IVARNAME",$t="IFUNCALL",Jr="IFUNDEF",ne="IEXPR",Gn="IEXPREVAL",dt="IMEMBER",eo="IENDSTATEMENT",Ct="IARRAY";function P(t,e){this.type=t,this.value=e??0}P.prototype.toString=function(){switch(this.type){case fe:case qt:case zt:case Vt:case Pe:case at:case eo:return this.value;case $t:return"CALL "+this.value;case Jr:return"DEF "+this.value;case Ct:return"ARRAY "+this.value;case dt:return"."+this.value;default:return"Invalid Instruction"}};function to(t){return new P(qt,t)}function Ue(t){return new P(zt,t)}function lu(t){return new P(Vt,t)}function Bo(t,e,s,r,o){for(var n=[],i=[],a,l,u,d,h=0;h<t.length;h++){var f=t[h],p=f.type;if(p===fe||p===at)Array.isArray(f.value)?n.push.apply(n,Bo(f.value.map(function(y){return new P(fe,y)}).concat(new P(Ct,f.value.length)),e,s,r,o)):n.push(f);else if(p===Pe&&o.hasOwnProperty(f.value))f=new P(fe,o[f.value]),n.push(f);else if(p===zt&&n.length>1)l=n.pop(),a=n.pop(),d=s[f.value],f=new P(fe,d(a.value,l.value)),n.push(f);else if(p===Vt&&n.length>2)u=n.pop(),l=n.pop(),a=n.pop(),f.value==="?"?n.push(a.value?l.value:u.value):(d=r[f.value],f=new P(fe,d(a.value,l.value,u.value)),n.push(f));else if(p===qt&&n.length>0)a=n.pop(),d=e[f.value],f=new P(fe,d(a.value)),n.push(f);else if(p===ne){for(;n.length>0;)i.push(n.shift());i.push(new P(ne,Bo(f.value,e,s,r,o)))}else if(p===dt&&n.length>0)a=n.pop(),n.push(new P(fe,a.value[f.value]));else{for(;n.length>0;)i.push(n.shift());i.push(f)}}for(;n.length>0;)i.push(n.shift());return i}function cu(t,e,s){for(var r=[],o=0;o<t.length;o++){var n=t[o],i=n.type;if(i===Pe&&n.value===e)for(var a=0;a<s.tokens.length;a++){var l=s.tokens[a],u;l.type===qt?u=to(l.value):l.type===zt?u=Ue(l.value):l.type===Vt?u=lu(l.value):u=new P(l.type,l.value),r.push(u)}else i===ne?r.push(new P(ne,cu(n.value,e,s))):r.push(n)}return r}function et(t,e,s){var r=[],o,n,i,a,l,u;if(Yn(t))return xe(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===fe||p===at)r.push(f.value);else if(p===zt)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!et(n,e,s):!1):f.value==="or"?r.push(o?!0:!!et(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,et(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(xe(o,s),xe(n,s))));else if(p===Vt)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(et(o?n:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(xe(o,s),xe(n,s),xe(i,s))));else if(p===Pe)if(f.value in e.functions)r.push(e.functions[f.value]);else if(f.value in e.unaryOps&&e.parser.isOperatorEnabled(f.value))r.push(e.unaryOps[f.value]);else{var y=s[f.value];if(y!==void 0)r.push(y);else throw new Error("undefined variable: "+f.value)}else if(p===qt)o=r.pop(),a=e.unaryOps[f.value],r.push(a(xe(o,s)));else if(p===$t){for(u=f.value,l=[];u-- >0;)l.unshift(xe(r.pop(),s));if(a=r.pop(),a.apply&&a.call)r.push(a.apply(void 0,l));else throw new Error(a+" is not a function")}else if(p===Jr)r.push(function(){for(var w=r.pop(),E=[],S=f.value;S-- >0;)E.unshift(r.pop());var k=r.pop(),U=function(){for(var O=Object.assign({},s),I=0,z=E.length;I<z;I++)O[E[I]]=arguments[I];return et(w,e,O)};return Object.defineProperty(U,"name",{value:k,writable:!1}),s[k]=U,U}());else if(p===ne)r.push(By(f,e));else if(p===Gn)r.push(f);else if(p===dt)o=r.pop(),r.push(o[f.value]);else if(p===eo)r.pop();else if(p===Ct){for(u=f.value,l=[];u-- >0;)l.unshift(r.pop());r.push(l)}else throw new Error("invalid Expression")}if(r.length>1)throw new Error("invalid Expression (parity)");return r[0]===0?0:xe(r[0],s)}function By(t,e,s){return Yn(t)?t:{type:Gn,value:function(r){return et(t.value,e,r)}}}function Yn(t){return t&&t.type===Gn}function xe(t,e){return Yn(t)?t.value(e):t}function Wn(t,e){for(var s=[],r,o,n,i,a,l,u=0;u<t.length;u++){var d=t[u],h=d.type;if(h===fe)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Qi).join(", ")+"]"):s.push(Qi(d.value));else if(h===zt)o=s.pop(),r=s.pop(),i=d.value,e?i==="^"?s.push("Math.pow("+r+", "+o+")"):i==="and"?s.push("(!!"+r+" && !!"+o+")"):i==="or"?s.push("(!!"+r+" || !!"+o+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+o+")))"):i==="=="?s.push("("+r+" === "+o+")"):i==="!="?s.push("("+r+" !== "+o+")"):i==="["?s.push(r+"[("+o+") | 0]"):s.push("("+r+" "+i+" "+o+")"):i==="["?s.push(r+"["+o+"]"):s.push("("+r+" "+i+" "+o+")");else if(h===Vt)if(n=s.pop(),o=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+o+" : "+n+")");else throw new Error("invalid Expression");else if(h===Pe||h===at)s.push(d.value);else if(h===qt)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):e?i==="not"?s.push("(!"+r+")"):i==="!"?s.push("fac("+r+")"):s.push(i+"("+r+")"):i==="!"?s.push("("+r+"!)"):s.push("("+i+" "+r+")");else if(h===$t){for(l=d.value,a=[];l-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===Jr){for(o=s.pop(),l=d.value,a=[];l-- >0;)a.unshift(s.pop());r=s.pop(),e?s.push("("+r+" = function("+a.join(", ")+") { return "+o+" })"):s.push("("+r+"("+a.join(", ")+") = "+o+")")}else if(h===dt)r=s.pop(),s.push(r+"."+d.value);else if(h===Ct){for(l=d.value,a=[];l-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ne)s.push("("+Wn(d.value,e)+")");else if(h!==eo)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Qi(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function Mt(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function Qn(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===Pe||i.type===at?!r&&!Mt(e,i.value)?e.push(i.value):(o!==null&&(Mt(e,o)||e.push(o)),o=i.value):i.type===dt&&r&&o!==null?o+="."+i.value:i.type===ne?Qn(i.value,e,s):o!==null&&(Mt(e,o)||e.push(o),o=null)}o!==null&&!Mt(e,o)&&e.push(o)}function we(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}we.prototype.simplify=function(t){return t=t||{},new we(Bo(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};we.prototype.substitute=function(t,e){return e instanceof we||(e=this.parser.parse(String(e))),new we(cu(this.tokens,t,e),this.parser)};we.prototype.evaluate=function(t){return t=t||{},et(this.tokens,this,t)};we.prototype.toString=function(){return Wn(this.tokens,!1)};we.prototype.symbols=function(t){t=t||{};var e=[];return Qn(this.tokens,e,t),e};we.prototype.variables=function(t){t=t||{};var e=[];Qn(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};we.prototype.toJSFunction=function(t,e){var s=this,r=new Function(t,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+Wn(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var $s="TEOF",B="TOP",so="TNUMBER",uu="TSTRING",ke="TPAREN",Dt="TBRACKET",ro="TCOMMA",Zn="TNAME",Xn="TSEMICOLON";function du(t,e,s){this.type=t,this.value=e,this.index=s}du.prototype.toString=function(){return this.type+": "+this.value};function G(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}G.prototype.newToken=function(t,e,s){return new du(t,e,s??this.pos)};G.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};G.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};G.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken($s,"EOF");if(this.isWhitespace()||this.isComment())return this.next();if(this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName())return this.current;this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')};G.prototype.isString=function(){var t=!1,e=this.pos,s=this.expression.charAt(e);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,e+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(e+1,r);this.current=this.newToken(uu,this.unescape(o),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};G.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(ke,t),this.pos++,!0):!1};G.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(Dt,t),this.pos++,!0):!1};G.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(ro,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(Xn,";"),this.pos++,!0):!1};G.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(r in this.consts)return this.current=this.newToken(so,this.consts[r]),this.pos+=r.length,!0}return!1};G.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(B,r),this.pos+=r.length,!0}return!1};G.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(t,e);return this.current=this.newToken(Zn,o),this.pos+=o.length,!0}return!1};G.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
|
|
108
|
+
`||e==="\r")&&(t=!0,this.pos++,!(this.pos>=this.expression.length));)e=this.expression.charAt(this.pos);return t};var Hy=/^[0-9a-f]{4}$/i;G.prototype.unescape=function(t){var e=t.indexOf("\\");if(e<0)return t;for(var s=t.substring(0,e);e>=0;){var r=t.charAt(++e);switch(r){case"'":s+="'";break;case'"':s+='"';break;case"\\":s+="\\";break;case"/":s+="/";break;case"b":s+="\b";break;case"f":s+="\f";break;case"n":s+=`
|
|
109
|
+
`;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var o=t.substring(e+1,e+5);Hy.test(o)||this.parseError("Illegal escape sequence: \\u"+o),s+=String.fromCharCode(parseInt(o,16)),e+=4;break;default:throw this.parseError('Illegal escape sequence: "\\'+r+'"')}++e;var n=t.indexOf("\\",e);s+=t.substring(e,n<0?t.length:n),e=n}return s};G.prototype.isComment=function(){var t=this.expression.charAt(this.pos);return t==="/"&&this.expression.charAt(this.pos+1)==="*"?(this.pos=this.expression.indexOf("*/",this.pos)+2,this.pos===1&&(this.pos=this.expression.length),!0):!1};G.prototype.isRadixInteger=function(){var t=this.pos;if(t>=this.expression.length-2||this.expression.charAt(t)!=="0")return!1;++t;var e,s;if(this.expression.charAt(t)==="x")e=16,s=/^[0-9a-f]$/i,++t;else if(this.expression.charAt(t)==="b")e=2,s=/^[01]$/i,++t;else return!1;for(var r=!1,o=t;t<this.expression.length;){var n=this.expression.charAt(t);if(s.test(n))t++,r=!0;else break}return r&&(this.current=this.newToken(so,parseInt(this.expression.substring(o,t),e)),this.pos=t),r};G.prototype.isNumber=function(){for(var t=!1,e=this.pos,s=e,r=e,o=!1,n=!1,i;e<this.expression.length&&(i=this.expression.charAt(e),i>="0"&&i<="9"||!o&&i===".");)i==="."?o=!0:n=!0,e++,t=n;if(t&&(r=e),i==="e"||i==="E"){e++;for(var a=!0,l=!1;e<this.expression.length;){if(i=this.expression.charAt(e),a&&(i==="+"||i==="-"))a=!1;else if(i>="0"&&i<="9")l=!0,a=!1;else break;e++}l||(e=r)}return t?(this.current=this.newToken(so,parseFloat(this.expression.substring(s,e))),this.pos=e):this.pos=r,t};G.prototype.isOperator=function(){var t=this.pos,e=this.expression.charAt(this.pos);if(e==="+"||e==="-"||e==="*"||e==="/"||e==="%"||e==="^"||e==="?"||e===":"||e===".")this.current=this.newToken(B,e);else if(e==="∙"||e==="•")this.current=this.newToken(B,"*");else if(e===">")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(B,">="),this.pos++):this.current=this.newToken(B,">");else if(e==="<")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(B,"<="),this.pos++):this.current=this.newToken(B,"<");else if(e==="|")if(this.expression.charAt(this.pos+1)==="|")this.current=this.newToken(B,"||"),this.pos++;else return!1;else if(e==="=")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(B,"=="),this.pos++):this.current=this.newToken(B,e);else if(e==="!")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(B,"!="),this.pos++):this.current=this.newToken(B,e);else return!1;return this.pos++,this.isOperatorEnabled(this.current.value)?!0:(this.pos=t,!1)};G.prototype.isOperatorEnabled=function(t){return this.parser.isOperatorEnabled(t)};G.prototype.getCoordinates=function(){var t=0,e,s=-1;do t++,e=this.pos-s,s=this.expression.indexOf(`
|
|
110
|
+
`,s+1);while(s>=0&&s<this.pos);return{line:t,column:e}};G.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)};function K(t,e,s){this.parser=t,this.tokens=e,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}K.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};K.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?Mt(e,t.value):typeof e=="function"?e(t):t.value===e};K.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};K.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};K.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};K.prototype.expect=function(t,e){if(!this.accept(t,e)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(e||t))}};K.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.accept(Zn)||this.accept(B,s))t.push(new P(Pe,this.current.value));else if(this.accept(so))t.push(new P(fe,this.current.value));else if(this.accept(uu))t.push(new P(fe,this.current.value));else if(this.accept(ke,"("))this.parseExpression(t),this.expect(ke,")");else if(this.accept(Dt,"["))if(this.accept(Dt,"]"))t.push(new P(Ct,0));else{var r=this.parseArrayList(t);t.push(new P(Ct,r))}else throw new Error("unexpected "+this.nextToken)};K.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};K.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};K.prototype.parseUntilEndStatement=function(t,e){return this.accept(Xn)?(this.nextToken&&this.nextToken.type!==$s&&!(this.nextToken.type===ke&&this.nextToken.value===")")&&e.push(new P(eo)),this.nextToken.type!==$s&&this.parseExpression(e),t.push(new P(ne,e)),!0):!1};K.prototype.parseArrayList=function(t){for(var e=0;!this.accept(Dt,"]");)for(this.parseExpression(t),++e;this.accept(ro);)this.parseExpression(t),++e;return e};K.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(B,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===$t){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var o=0,n=e.value+1;o<n;o++){var i=r-o;t[i].type===Pe&&(t[i]=new P(at,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new P(ne,s)),t.push(new P(Jr,e.value));continue}if(e.type!==Pe&&e.type!==dt)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new P(at,e.value)),t.push(new P(ne,s)),t.push(Ue("="))}};K.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(B,"?");){var e=[],s=[];this.parseConditionalExpression(e),this.expect(B,":"),this.parseConditionalExpression(s),t.push(new P(ne,e)),t.push(new P(ne,s)),t.push(lu("?"))}};K.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(B,"or");){var e=[];this.parseAndExpression(e),t.push(new P(ne,e)),t.push(Ue("or"))}};K.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(B,"and");){var e=[];this.parseComparison(e),t.push(new P(ne,e)),t.push(Ue("and"))}};var Ky=["==","!=","<","<=",">=",">","in"];K.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(B,Ky);){var e=this.current;this.parseAddSub(t),t.push(Ue(e.value))}};var qy=["+","-","||"];K.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(B,qy);){var e=this.current;this.parseTerm(t),t.push(Ue(e.value))}};var zy=["*","/","%"];K.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(B,zy);){var e=this.current;this.parseFactor(t),t.push(Ue(e.value))}};K.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.save(),this.accept(B,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===ke&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===Xn||this.nextToken.type===ro||this.nextToken.type===$s||this.nextToken.type===ke&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(to(r.value))}else this.parseExponential(t)};K.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(B,"^");)this.parseFactor(t),t.push(Ue("^"))};K.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(B,"!");)t.push(to("!"))};K.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.accept(B,s)){var r=this.current;this.parseAtom(t),t.push(to(r.value))}else for(this.parseMemberExpression(t);this.accept(ke,"(");)if(this.accept(ke,")"))t.push(new P($t,0));else{var o=this.parseArgumentList(t);t.push(new P($t,o))}};K.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(ke,")");)for(this.parseExpression(t),++e;this.accept(ro);)this.parseExpression(t),++e;return e};K.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(B,".")||this.accept(Dt,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(Zn),t.push(new P(dt,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(Dt,"]"),t.push(Ue("["))}else throw new Error("unexpected symbol: "+e.value)}};function Vy(t,e){return Number(t)+Number(e)}function Gy(t,e){return t-e}function Yy(t,e){return t*e}function Wy(t,e){return t/e}function Qy(t,e){return t%e}function Zy(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function Xy(t,e){return t===e}function Jy(t,e){return t!==e}function eb(t,e){return t>e}function tb(t,e){return t<e}function sb(t,e){return t>=e}function rb(t,e){return t<=e}function ob(t,e){return!!(t&&e)}function nb(t,e){return!!(t||e)}function ib(t,e){return Mt(e,t)}function ab(t){return(Math.exp(t)-Math.exp(-t))/2}function lb(t){return(Math.exp(t)+Math.exp(-t))/2}function cb(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function ub(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function db(t){return Math.log(t+Math.sqrt(t*t-1))}function hb(t){return Math.log((1+t)/(1-t))/2}function Zi(t){return Math.log(t)*Math.LOG10E}function fb(t){return-t}function pb(t){return!t}function gb(t){return t<0?Math.ceil(t):Math.floor(t)}function mb(t){return Math.random()*(t||1)}function Xi(t){return Jn(t+1)}function yb(t){return isFinite(t)&&t===Math.round(t)}var bb=4.7421875,Io=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function Jn(t){var e,s;if(yb(t)){if(t<=0)return isFinite(t)?1/0:NaN;if(t>171)return 1/0;for(var r=t-2,o=t-1;r>1;)o*=r,r--;return o===0&&(o=1),o}if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*Jn(1-t));if(t>=171.35)return 1/0;if(t>85){var n=t*t,i=n*t,a=i*t,l=a*t;return Math.sqrt(2*Math.PI/t)*Math.pow(t/Math.E,t)*(1+1/(12*t)+1/(288*n)-139/(51840*i)-571/(2488320*a)+163879/(209018880*l)+5246819/(75246796800*l*t))}--t,s=Io[0];for(var u=1;u<Io.length;++u)s+=Io[u]/(t+u);return e=t+bb+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function vb(t){return Array.isArray(t)?t.length:String(t).length}function Ji(){for(var t=0,e=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),o;e<r?(o=e/r,t=t*o*o+1,e=r):r>0?(o=r/e,t+=o*o):t+=r}return e===1/0?1/0:e*Math.sqrt(t)}function ea(t,e,s){return t?e:s}function wb(t,e){return typeof e>"u"||+e==0?Math.round(t):(t=+t,e=-+e,isNaN(t)||!(typeof e=="number"&&e%1===0)?NaN:(t=t.toString().split("e"),t=Math.round(+(t[0]+"e"+(t[1]?+t[1]-e:-e))),t=t.toString().split("e"),+(t[0]+"e"+(t[1]?+t[1]+e:e))))}function Eb(t,e,s){return s&&(s[t]=e),e}function Mb(t,e){return t[e|0]}function Tb(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function Sb(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function Ib(t,e){if(typeof t!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(e))throw new Error("Second argument to map is not an array");return e.map(function(s,r){return t(s,r)})}function _b(t,e,s){if(typeof t!="function")throw new Error("First argument to fold is not a function");if(!Array.isArray(s))throw new Error("Second argument to fold is not an array");return s.reduce(function(r,o,n){return t(r,o,n)},e)}function Ob(t,e){if(typeof t!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(e))throw new Error("Second argument to filter is not an array");return e.filter(function(s,r){return t(s,r)})}function $b(t,e){if(!(Array.isArray(e)||typeof e=="string"))throw new Error("Second argument to indexOf is not a string or array");return e.indexOf(t)}function Cb(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function Db(t){return(t>0)-(t<0)||+t}var ta=1/3;function xb(t){return t<0?-Math.pow(-t,ta):Math.pow(t,ta)}function Ab(t){return Math.exp(t)-1}function Rb(t){return Math.log(1+t)}function Pb(t){return Math.log(t)/Math.LN2}function ht(t){this.options=t||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||ab,cosh:Math.cosh||lb,tanh:Math.tanh||cb,asinh:Math.asinh||ub,acosh:Math.acosh||db,atanh:Math.atanh||hb,sqrt:Math.sqrt,cbrt:Math.cbrt||xb,log:Math.log,log2:Math.log2||Pb,ln:Math.log,lg:Math.log10||Zi,log10:Math.log10||Zi,expm1:Math.expm1||Ab,log1p:Math.log1p||Rb,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||gb,"-":fb,"+":Number,exp:Math.exp,not:pb,length:vb,"!":Xi,sign:Math.sign||Db},this.binaryOps={"+":Vy,"-":Gy,"*":Yy,"/":Wy,"%":Qy,"^":Math.pow,"||":Zy,"==":Xy,"!=":Jy,">":eb,"<":tb,">=":sb,"<=":rb,and:ob,or:nb,in:ib,"=":Eb,"[":Mb},this.ternaryOps={"?":ea},this.functions={random:mb,fac:Xi,min:Sb,max:Tb,hypot:Math.hypot||Ji,pyt:Math.hypot||Ji,pow:Math.pow,atan2:Math.atan2,if:ea,gamma:Jn,roundTo:wb,map:Ib,fold:_b,filter:Ob,indexOf:$b,join:Cb},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}ht.prototype.parse=function(t){var e=[],s=new K(this,new G(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect($s,"EOF"),new we(e,this)};ht.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var hu=new ht;ht.parse=function(t){return hu.parse(t)};ht.evaluate=function(t,e){return hu.parse(t).evaluate(e)};var sa={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"remainder","^":"power","!":"factorial","<":"comparison",">":"comparison","<=":"comparison",">=":"comparison","==":"comparison","!=":"comparison","||":"concatenate",and:"logical",or:"logical",not:"logical","?":"conditional",":":"conditional","=":"assignment","[":"array","()=":"fndef"};function kb(t){return sa.hasOwnProperty(t)?sa[t]:t}ht.prototype.isOperatorEnabled=function(t){var e=kb(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var Lb=Object.defineProperty,Fb=Object.getOwnPropertyDescriptor,Nb=(t,e,s)=>e in t?Lb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ub=(t,e,s,r)=>{for(var o=r>1?void 0:r?Fb(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},jb=(t,e,s)=>(Nb(t,e+"",s),s);const Bb="kos-expression-evaluator-model";class Hb{constructor(e,s,r,o){c(this,"name");c(this,"expression");c(this,"expr");c(this,"getContextData",null);c(this,"_lastResult",{value:void 0});this.name=e,this.expression=s,this.expr=r,this.getContextData=o,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(e){this._lastResult=e}evaluate(e){try{return{value:this.expr.evaluate(e),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let wr=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"parser");c(this,"_data");c(this,"_expressions",new Map);c(this,"_results");c(this,"_contextRevision",0);this.id=t,this.logger=s.logger,this._data=Ie(),this._results=Ie(),this.parser=new ht}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(t){this._data.setValues(t),J(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(t,e){this._data[t]=e}updateNestedValue(t,e){const s=t.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${t}" - cannot be empty`);return}let o=this._data;for(const n of s)(o[n]===void 0||o[n]===null)&&(o[n]={}),o=o[n];o[r]=e,this.logger.debug(`Updated nested context value "${t}" to:`,e)}addModelToContext(t,e){this._data[t]=e}addExpression(t,e){try{const s=this.parser.parse(e),r=new Hb(t,e,s,()=>this.data);this._expressions.set(t,r),this.evaluateExpression(t),this.logger.debug(`Added expression "${t}": ${e}`)}catch(s){throw this.logger.error(`Failed to parse expression "${t}"`,s),s}}removeExpression(t){const e=this._expressions.delete(t);return e?(delete this._results[t],this.logger.debug(`Removed expression "${t}"`)):this.logger.warn(`Attempted to remove non-existent expression "${t}". Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpression(t){const e=this._expressions.get(t);return e||this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpressionValue(t){const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return e.result}getCachedExpressionValue(t){const e=this._expressions.get(t);if(e)return e.result}get expressions(){return Array.from(this._expressions.values())}get expressionNames(){return Array.from(this._expressions.keys())}get results(){return this.evaluateAllExpressions(),this._results}evaluateAllExpressions(){Array.from(this._expressions.keys()).forEach(e=>{this._expressions.get(e)&&this.evaluateExpression(e)})}evaluateExpression(t){this.logger.debug(`Evaluating expression: ${String(t)}`);const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${String(t)}" not found`);return}const s=e.evaluate(this.data);this.logger.debug(`Expression "${String(t)}" evaluated to:`,s);const r=e.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(t)}" result changed from`,r,"to",s),e.updateResult(s),this.updateResult(t,s))}updateResult(t,e){this.logger.debug(`ExpressionEvaluator.updateResult called for "${t}":`,e),J(()=>{this._results[t]=e})}createExpression(t){const e=lt();return this.addExpression(e,t),e}};jb(wr,"Registration");wr=Ub([R({modelTypeId:Bb,singleton:!1})],wr);const fu=wr.Registration,Kb=m.createLogger({name:"kos-log-manager-service",group:"Services"}),qb="/api/kos/logs/overrides",pu=async()=>(Kb.debug("sending GET for kos-log-manager"),await De.get(qb)),zb=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:pu},Symbol.toStringTag,{value:"Module"}));var Vb=Object.defineProperty,Gb=Object.getOwnPropertyDescriptor,oo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gb(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&&Vb(e,s,o),o};const gu="kos-log-manager-model",Yb="/kos/logs/override/add/*",Wb="/kos/logs/override/remove/*",Qb=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 xt=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new Dn}updateModel(t){}resolveLoggers(){const t=m.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:Qb(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=m.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=m.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=m.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=m.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await pu();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)})}};oo([Sl("/api/kos/ui/loggers")],xt.prototype,"getAllLoggers",1);oo([H({topic:Yb,websocket:!0,wildcardName:"nodeType"})],xt.prototype,"handleOverrideAdded",1);oo([H({topic:Wb,websocket:!0,wildcardName:"nodeType"})],xt.prototype,"handleOverrideRemoved",1);xt=oo([R(gu)],xt);const mu=new Se({class:xt,type:gu}),{URL:qs}=ae(),{postModel:ei,getOne:Zb}=oe.build({basePath:`${qs}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const yu=async t=>{const e=await ei({model:t,urlOverride:`${qs}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},bu=async t=>{const e=await ei({model:t,urlOverride:`${qs}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},vu=async t=>{const e=await ei({model:{},urlOverride:`${qs}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},wu=async()=>{const t=await Zb({urlOverride:`${qs}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},Xb=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:wu,setDate:bu,setTime:yu,setTimezone:vu},Symbol.toStringTag,{value:"Module"}));var Jb=Object.defineProperty,ev=Object.getOwnPropertyDescriptor,no=(t,e,s,r)=>{for(var o=r>1?void 0:r?ev(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&&Jb(e,s,o),o};const ts="kos-time-model",tv="/kos/time/time",sv="/kos/time/day",rv="/kos/time/timezone";let At=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await yu(t)}async updateSystemDate(t){await bu(t)}async updateSystemTimezone(t){await vu(t)}handleTimeChange(){V(ws.TIME_CHANGE,{})}handleDayChange(){V(ws.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),V(ws.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await wu();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};no([H({topic:tv,websocket:!0})],At.prototype,"handleTimeChange",1);no([H({topic:sv,websocket:!0})],At.prototype,"handleDayChange",1);no([H({topic:rv,websocket:!0})],At.prototype,"handleTimeZoneChange",1);At=no([R(ts)],At);const Er={registration:{[ts]:{class:At,singleton:!0}},type:ts,predicate:Te(ts),factory:ie.Singleton.create(ts)};var ov=Object.defineProperty,nv=Object.getOwnPropertyDescriptor,Eu=(t,e,s,r)=>{for(var o=r>1?void 0:r?nv(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&&ov(e,s,o),o};const Mu="log-block-container-model";let Mr=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t,sortKey:"blockNum"})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing log-block-container container ${this.id}`)}async load(){this.logger.debug(`loading log-block-container container ${this.id}`)}};Eu([$e],Mr.prototype,"_models",2);Mr=Eu([R(Mu)],Mr);const iv=m.createLogger({name:"log-stream-container-service",group:"Services"}),Tu=()=>{var r;const t=me(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},Gt=Tu(),av="/api/kos/logs/node/{nodeId}/streams",Su=async()=>(iv.debug("sending GET for log-stream-container"),await De.get(av,{path:{nodeId:"primary"}},{destinationAddress:Gt})),Iu=async(t,e="primary")=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:Gt})},_u=async t=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:Gt})},lv=async()=>{await De.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:Gt})},Ou=async t=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:Gt}),$u=async(t,e)=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:Gt}),cv=Object.freeze(Object.defineProperty({__proto__:null,createOverride:lv,getKosConnectionId:Tu,getLogStreamBlock:$u,getLogStreamBlocks:Ou,getLogStreams:Su,subscribeToLogStream:Iu,unsubscribeFromLogStream:_u},Symbol.toStringTag,{value:"Module"}));var uv=Object.getOwnPropertyDescriptor,dv=(t,e,s,r)=>{for(var o=r>1?void 0:r?uv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Cu="log-block-model";let Ho=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"nodeId");c(this,"stream");c(this,"blockNum");c(this,"startLineNum");c(this,"endLineNum");c(this,"startTime");c(this,"endTime");c(this,"lineCount");c(this,"lines");c(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 $u(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}`)}};Ho=dv([R(Cu)],Ho);const Cs=new ye({class:Ho,type:Cu}),io=new ye({class:Mr,type:Mu});io.addRelatedModel(Cs);var hv=Object.defineProperty,fv=Object.getOwnPropertyDescriptor,Du=(t,e,s,r)=>{for(var o=r>1?void 0:r?fv(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&&hv(e,s,o),o};const xu="log-stream-model";let Tr=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"nodeId");c(this,"_blocks");c(this,"name");c(this,"currentBlockId");c(this,"isResetting");c(this,"generatorInstance");c(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=io.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=Cs.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=Cs.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 Iu(this.name)}async unsubscribe(){await _u(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 Ou(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=Cc(()=>{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()}}};Du([$e],Tr.prototype,"_blocks",2);Tr=Du([R(xu)],Tr);const Es=new ye({class:Tr,type:xu});var pv=Object.defineProperty,gv=Object.getOwnPropertyDescriptor,ft=(t,e,s,r)=>{for(var o=r>1?void 0:r?gv(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&&pv(e,s,o),o};const Au="log-stream-container-model",mv="/kos/logs/subscription/addBlock/*",yv="/kos/logs/subscription/updateBlock/*",bv="/kos/logs/subscription/removeBlock/*",vv="/kos/logs/subscription/lines/*",Ru="/kos/logs/streams/add/*";let Le=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"selectedStream");c(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t}),this.selectedStream=void 0}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}updateModel(t){}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}updateSelectedStream(t){this.selectedStream=t}handleStreamAdded(t){this.logger.debug(`Received topic: ${Ru}`);const e=t.stream,s=Es.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=Es.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 Su();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=Es.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};ft([$e],Le.prototype,"_models",2);ft([H({topic:[Ru],websocket:!0})],Le.prototype,"handleStreamAdded",1);ft([H({topic:[mv],websocket:!0})],Le.prototype,"handleAddBlock",1);ft([H({topic:[bv],websocket:!0})],Le.prototype,"handleRemoveBlock",1);ft([H({topic:[yv],websocket:!0})],Le.prototype,"handleUpdateBlock",1);ft([H({topic:[vv],websocket:!0})],Le.prototype,"handleLogLine",1);Le=ft([R(Au)],Le);const zs=new Se({class:Le,type:Au});zs.addRelatedModel(Es);zs.addRelatedModel(io);zs.addRelatedModel(Cs);const wv=t=>t.rank!==void 0,Ev=t=>t.visibleRole!==void 0,Mv=t=>t.color!==void 0,Tv=t=>{const e=t.info;return wv(e)?e.rank:0},Sv=t=>{const e=t.info;return Mv(e)?e.color:"orange"},Iv=t=>{const e=t.info;return Ev(e)?e.visibleRole:"TECHNICIAN"},{URL:ao}=ae(),{getAll:_v,postModel:Pu}=oe.build({basePath:`${ao}/api/kos/troubles`}),ku=async t=>await _v({urlOverride:`${ao}${t}`}),Lu=async(t,e="/api/kos/troubles",s)=>{try{const r=await Pu({model:{},urlOverride:`${ao}${e}/resolve/${t}`,tracker:s});return r!=null&&r.data&&it.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ve.Fail,tracker:s,reason:"Failed to resolve trouble"};return it.initiateFuture(o),o}},Ov=async(t,e="/api/kos/troubles",s)=>{try{const r=await Pu({model:t,urlOverride:`${ao}${e}/resolve/`,tracker:s});return r!=null&&r.data&&it.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:Ve.Fail,tracker:s,reason:"Failed to resolve troubles"};return it.initiateFuture(o),o}},$v=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Ov,getTroubles:ku,resolveTrouble:Lu},Symbol.toStringTag,{value:"Module"})),Sr="troubleDataMapper",tr=new Map;Fs(Sr,{register:(t,e)=>{var s;tr.has(t)||tr.set(t,[]),(s=tr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=tr.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:m.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const Vs="troubleMapper",sr=new Map;Fs(Vs,{register:(t,e)=>{var s;sr.has(t)||sr.set(t,[]),(s=sr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=sr.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});$[Vs].register("nozzle",async t=>[t.data.nozzlePath]);$[Vs].register("path",async t=>[t.data.path]);const Cv=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>$[Vs].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},Fu=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>$[Sr].execute(i,t)),r=$[Sr].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 Dv{constructor(){c(this,"type","ResolvableTrouble");c(this,"title","Resolvable Trouble");c(this,"subtitle","Trouble")}}class xv{constructor(){c(this,"type","BlockPumpTrouble");c(this,"title","Block Pump Trouble");c(this,"subtitle","Trouble")}}class bt{static getHandler(e){switch(e){case"ResolvableTrouble":return new Dv;case"BlockPumpTrouble":return new xv;default:return}}}var Av=Object.defineProperty,Rv=Object.getOwnPropertyDescriptor,Nu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Rv(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&&Av(e,s,o),o};const ss="trouble-model";function rr(t){return typeof t.shouldDefer=="boolean"}let Ir=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:l,group:u,createTime:d,role:h,color:f,servicePath:p,...y},w){c(this,"id");c(this,"logger");c(this,"_troubleId");c(this,"_resolvable");c(this,"type");c(this,"futureHandler");c(this,"ifaces");c(this,"clientData");c(this,"info");c(this,"role");c(this,"color");c(this,"tags");c(this,"data");c(this,"rank");c(this,"servicePath");c(this,"group");c(this,"createTime");c(this,"_mapped",{});this.id=t,this.logger=w.logger,this.type=l,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=u,this.servicePath=p??"/api/kos/troubles",this.createTime=d,this.clientData=n,this.data={},Object.assign(this.data,y),this.futureHandler=new Wr(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=bt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:bt.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=bt.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:bt.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=bt.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=bt.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 Fu(this)}get deferredCompanion(){const t=Po(this.id,e=>rr(e));if(t&&rr(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Po(this.id,e=>rr(e));return t&&rr(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 Lu(this._troubleId,this.servicePath,t)}};Nu([bi()],Ir.prototype,"resolve",1);Ir=Nu([R(ss)],Ir);const Ds={registration:{[ss]:{class:Ir,singleton:!1}},type:ss,predicate:Te(ss),factory:ie.Factory.create(ss)};var Uu=Object.defineProperty,Pv=Object.getOwnPropertyDescriptor,kv=(t,e,s)=>e in t?Uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ti=(t,e,s,r)=>{for(var o=r>1?void 0:r?Pv(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&&Uu(e,s,o),o},Lv=(t,e,s)=>(kv(t,e+"",s),s);function ra(t){return $.propertyMapper.hasMapper(ve.TroubleRank)?$.propertyMapper.executeMapper(ve.TroubleRank,t):Tv(t)}function oa(t){return($.propertyMapper.hasMapper(ve.TroubleColor)?$.propertyMapper.executeMapper(ve.TroubleColor,t):Sv(t)).toLowerCase()}function na(t){return($.propertyMapper.hasMapper(ve.TroubleRole)?$.propertyMapper.executeMapper(ve.TroubleRole,t):Iv(t)).toLowerCase()}const Fv="trouble-container-model";class pe{}c(pe,"INDEX_TROUBLES_BY_IFACE","byIface"),c(pe,"INDEX_TROUBLES_BY_TYPE","byType"),c(pe,"INDEX_TROUBLES_BY_GROUP","byGroup"),c(pe,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),c(pe,"SORT_KEY_RANK","rank"),c(pe,"TROUBLES_DEFERRED","true");let Rt=class{constructor(t,e){c(this,"id");c(this,"servicePath","/api/kos/troubles");this.id=t,this.servicePath=e.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");const t=await ku(this.servicePath);try{t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:ra(e),color:oa(e),role:na(e),id:String(e.id)},r=Ds.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw this.logger.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&nt(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:ra(t),color:oa(t),role:na(t),id:String(t.id)};if(e.role==="NONE")return;const s=Ds.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};Lv(Rt,"Registration");ti([H({topic:"/kos/trouble/remove",websocket:!0,lifecycle:x.INIT})],Rt.prototype,"handleTroubleRemoved",1);ti([H({topic:"/kos/trouble/add",websocket:!0})],Rt.prototype,"handleTroubleAdded",1);Rt=ti([R({modelTypeId:Fv,singleton:!0}),$l(),Tl({containerProperty:"troubles",containerOptions:{indexMap:{[pe.INDEX_TROUBLES_BY_IFACE]:Cv,[pe.INDEX_TROUBLES_BY_TYPE]:"type",[pe.INDEX_TROUBLES_BY_GROUP]:"group",[pe.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:pe.SORT_KEY_RANK}})],Rt);const Pt=Rt.Registration,{URL:ju}=ae(),{getAll:Nv}=oe.build({basePath:`${ju}/api/kos/ota`}),ia=m.createLogger({name:"ota-service",group:"Services"}),Uv=async()=>{ia.debug("sending GET request to /api/kos/ota/artifacts");const t=await Nv({urlOverride:`${ju}/api/kos/ota/artifacts`});return ia.debug("getArtifacts - response:",t),t==null?void 0:t.data};var jv=Object.defineProperty,Bv=Object.getOwnPropertyDescriptor,lo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Bv(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&&jv(e,s,o),o};const Bu="ota-model",Hv=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},_o=t=>{const e=t.artifactInfo,s=Hv(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 kt=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"data",new Dn);c(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 Uv();t&&t.forEach(e=>{const s=_o(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=_o(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=_o(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};lo([jt({modelType:Pt.type})],kt.prototype,"troubleContainer",2);lo([H({topic:"/kos/ota/artifacts/all",websocket:!0})],kt.prototype,"handleAllArtifacts",1);lo([H({topic:"/kos/ota/artifacts/changed",websocket:!0})],kt.prototype,"handleChangedArtifacts",1);kt=lo([R(Bu)],kt);const _r=new Se({class:kt,type:Bu});function Kv(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 Oo=m.createLogger({name:"software-info-service",group:"Services"}),si=async t=>{Oo.debug("sending GET for software-info");const[e,s]=await Zc.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Oo.debug("Request was aborted"),new ge("Request was aborted")):(Oo.error("Failed to fetch software-info",e),new ge("Failed to fetch software-info"));return s},qv=Kv(si),zv=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:si,getSoftwareInfosWithCancel:qv},Symbol.toStringTag,{value:"Module"}));var Vv=Object.getOwnPropertyDescriptor,Gv=(t,e,s,r)=>{for(var o=r>1?void 0:r?Vv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const rs="software-info-model";let Ko=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(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 si(),e=(t==null?void 0:t.nodes)||{};J(()=>{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 ge&&this.logger.error("Failed to fetch software-info",t)}}};Ko=Gv([R(rs)],Ko);const Or={registration:{[rs]:{class:Ko,singleton:!1}},type:rs,predicate:Te(rs),factory:ie.Factory.create(rs)},{URL:Hu}=ae(),{getOne:Yv}=oe.build({basePath:`${Hu}/api/kos/state`}),Wv=m.createLogger({name:"state-bean-service",group:"Services"}),Ku=async({path:t})=>(Wv.debug("sending GET for state-bean"),await Yv({urlOverride:`${Hu}/api/kos/state/${t}`})),Qv=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Ku},Symbol.toStringTag,{value:"Module"}));var Zv=Object.defineProperty,Xv=Object.getOwnPropertyDescriptor,qu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Xv(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&&Zv(e,s,o),o};const os="state-bean-model",Jv=ct("path");let $r=class{constructor(t,e,s){c(this,"id");c(this,"path");c(this,"props");c(this,"logger");this.id=t,this.logger=s.logger,this.props=An.map(new Map),Ro(e,this)}updateModel(t){Ro(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&kn(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&Qr(r)&&(r=Number(r)),this.props.set(e,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(t){Object.entries(t).forEach(([e,s])=>{this.props.set(e,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const t=await Ku({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};qu([H({topic:`/kos/state/${Jv}`,websocket:!0})],$r.prototype,"handleConfigBeanUpdated",1);$r=qu([R(os)],$r);const xs={registration:{[os]:{class:$r,singleton:!1}},type:os,predicate:Te(os),factory:ie.Factory.create(os)};var ew=Object.defineProperty,tw=Object.getOwnPropertyDescriptor,zu=(t,e,s,r)=>{for(var o=r>1?void 0:r?tw(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&&ew(e,s,o),o};const ns="state-prop-model",aa=ct("path");let Cr=class{constructor(t,e,s){c(this,"id");c(this,"path");c(this,"attribute");c(this,"logger");c(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())??""}};zu([jt({modelType:xs.type,id:`state-bean-${aa}`,options:{path:aa}})],Cr.prototype,"stateBean",2);Cr=zu([R(ns)],Cr);const ri={registration:{[ns]:{class:Cr,singleton:!1}},type:ns,predicate:Te(ns),factory:ie.Factory.create(ns)},{URL:sw}=ae(),{getAll:rw}=oe.build({basePath:`${sw}/api/state-prop`}),ow=m.createLogger({name:"state-prop-service",group:"Services"}),nw=async()=>(ow.debug("sending GET for state-prop"),await rw({})),iw=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:nw},Symbol.toStringTag,{value:"Module"})),{URL:oi}=ae(),{getOne:Vu}=oe.build({basePath:`${oi}/api/translation`}),Ms=m.createLogger({name:"translation-service",group:"Services"}),aw=()=>{const t=window.location.origin,e=me();return(e==null?void 0:e.host)||t},Gu=async(t,e)=>{Ms.debug(`Loading translations from: ${t}`);const s=e??aw();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Ms.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Ms.error("Error fetching translations",r),r}},lw=async()=>{Ms.debug("Getting system localization descriptor");const t=await Vu({urlOverride:`${oi}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get localization descriptor ${t==null?void 0:t.status}`);return t.data},Yu=t=>async()=>{Ms.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await Vu({urlOverride:`${oi}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},Wu="langResolver";var cw=Object.getOwnPropertyDescriptor,uw=(t,e,s,r)=>{for(var o=r>1?void 0:r?cw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const is="translation-model";function dw(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 Qu(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])){const n=Qu(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function Zu(t,e){const s={...t};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(typeof e[r]=="object"&&e[r]!==null&&typeof t[r]=="object"&&t[r]!==null?s[r]=Zu(t[r],e[r]):s[r]=e[r]);return s}const qo=(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)?qo(r,e):r},or=(t,e,s)=>{const r=/{{(.*?)}}/g,n=qo(t,e).replace(r,(a,l)=>Object.prototype.hasOwnProperty.call(s||{},l.trim())?s==null?void 0:s[l.trim()]:a);return qo(n,e)},la=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let zo=class{constructor(t,e,s){c(this,"id");c(this,"namespace");c(this,"descriptor");c(this,"defaultLocale");c(this,"currentLocale");c(this,"bundleResolver");c(this,"data");c(this,"logger");c(this,"resolver");c(this,"disposer");c(this,"context");c(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(Wu),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=Y.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return Gu(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);J(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=Zu(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=Qu(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=la(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}=dw(e),{namespace:n,key:i}=la(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const l=this.context.getModel(n);return l?l.resolveKey(i,e):i}if(r&&this.data[a]){const l=this.data[a];return Array.isArray(l)?l.map(u=>or(u,this.data,o)):or(this.data[a],this.data,o)}if(this.data[i]){const l=this.data[i];return Array.isArray(l)?l.map(u=>or(u,this.data,o)):or(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()})}};zo=uw([Vr(),R(is)],zo);const Dr={registration:{[is]:{class:zo,singleton:!1}},type:is,predicate:Te(is),factory:ie.Factory.create(is)};var hw=Object.defineProperty,fw=Object.getOwnPropertyDescriptor,Xu=(t,e,s,r)=>{for(var o=r>1?void 0:r?fw(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&&hw(e,s,o),o};const as="translation-container-model",pw=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function gw(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 pw([r,o])}let xr=class{constructor(t,e,s){c(this,"id");c(this,"lang");c(this,"rootUrl");c(this,"descriptor");c(this,"_defaultNamespace");c(this,"resolver");c(this,"logger");c(this,"descriptorUrl");c(this,"namespaces",[]);c(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||gw.bind(this),s.kosContext.set(Wu,this.resolver),this.logger=s.logger,this._models=new Ce({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(t){return this.logger.debug("getting model "+t),this._models.getModel("translation-"+t)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const t of this.namespaces){const e=this.resolveNamespace(t);await de(e)}}resolveNamespace(t){var s;if((s=this.descriptor.namespaces)==null?void 0:s[t]){const r=Object.keys(this.descriptor.namespaces[t].locales)[0],o=this.descriptor.namespaces[t].locales[r].defaultLocale,n=Dr.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)||J(()=>{this.namespaces.push(t)}),n}else{this.logger.warn("namespace "+t+" not found in descriptor");const r=Dr.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)}};Xu([$e],xr.prototype,"_models",2);xr=Xu([R(as)],xr);const Fe={registration:{[as]:{class:xr,singleton:!0}},type:as,predicate:Te(as),factory:ie.Singleton.create(as)},mw={set(t,e){const s=Y.getContext(Fe.type);s&&s.set(t,e)},get(t){const e=Y.getContext(Fe.type);return e==null?void 0:e.get(t)}},Ju={async init(t){const e=Fe.factory(t);return await de(e),{translations:e}}};function yw(t){return(t==null?void 0:t.troubles)!==void 0&&(t==null?void 0:t.troubles)instanceof Array&&(t==null?void 0:t.troublesByType)!==void 0&&typeof(t==null?void 0:t.troublesByType)=="object"}const ed="kos-ws-event",ni=Bt(ed);var bw=Object.defineProperty,vw=Object.getOwnPropertyDescriptor,ii=(t,e,s,r)=>{for(var o=r>1?void 0:r?vw(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&&bw(e,s,o),o};const ww=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){c(this,"id");c(this,"events");c(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){m.debug("kos event received");const{body:r,headers: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 u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const l={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:ww({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,l),m.debug(`logged ${this.events.size} events`)}}};ii([H({topic:[Ls.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);ii([H({topic:[Ls.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=ii([R(ni.type)],exports.WsEventModel);const ca=me(),Ew=ca.debug==="true"||ca.debug===!0,Mw="/api/system/canvas",td=async(t,e)=>{const s=e||Mw,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Ew?"false":"true"},body:t})},Tw=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:td},Symbol.toStringTag,{value:"Module"}));function ua(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var Sw=Object.defineProperty,Iw=Object.getOwnPropertyDescriptor,sd=(t,e,s,r)=>{for(var o=r>1?void 0:r?Iw(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&&Sw(e,s,o),o};const rd="canvas-renderer-model";function $o(t){return typeof t.onDone=="function"}let Ar=class{constructor(t,e,s){c(this,"id");c(this,"router");c(this,"logger");c(this,"_renderer",null);c(this,"_clearOnComplete");c(this,"isStreaming",!1);c(this,"renderLoopId",null);c(this,"sendIntervalId",null);c(this,"timeoutId",null);c(this,"apiPath");c(this,"endpointName");c(this,"width",50);c(this,"height",30);c(this,"fps",10);c(this,"durationMs",null);c(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){td(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=ua(t);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=ua(o);this.logger.debug(`Sending clear frame: ${t}x${e}, apiPath: ${this.apiPath}`),this.sendDataFrame(n,this.apiPath),(s=this._onFrame)==null||s.call(this,n)}}isOneShotDone(){var t,e;return $o(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=$o(this._renderer);$o(this._renderer)&&this._renderer.onDone(()=>{var l,u,d;this.logger.debug(`Renderer completed for ${this.id}`),V("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(l=this._renderer)==null?void 0:l.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((d=(u=this._renderer)==null?void 0:u.isOneShot)==null?void 0:d.call(u))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var l,u;const a=(u=(l=this._renderer)==null?void 0:l.readPixels)==null?void 0:u.call(l,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"})})}};sd([jt({modelType:Kn.type})],Ar.prototype,"router",2);Ar=sd([R(rd)],Ar);const ai=new ye({class:Ar,type:rd});class od{constructor({src:e}){c(this,"video");c(this,"canvas");c(this,"ctx");c(this,"lastUpdate",0);c(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 _w{constructor(){c(this,"canvas");c(this,"gl");c(this,"lastWidth",0);c(this,"lastHeight",0);c(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 Ow extends _w{constructor({speedPx:s=1}={}){super();c(this,"program");c(this,"posBuffer");c(this,"aPosition");c(this,"uMinHue");c(this,"uMaxHue");c(this,"uHueOffset");c(this,"uGridHeight");c(this,"minHue",0);c(this,"maxHue",80);c(this,"hueOffset",0);c(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
|
|
111
111
|
attribute vec2 a_position;
|
|
112
112
|
void main() {
|
|
113
113
|
gl_Position = vec4(a_position, 0, 1);
|
|
@@ -141,8 +141,8 @@ ${u}topics:${e}
|
|
|
141
141
|
vec3 rgb = hslToRgb(hue, 1.0, 0.5);
|
|
142
142
|
gl_FragColor = vec4(rgb, 1.0);
|
|
143
143
|
}
|
|
144
|
-
`,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 ht{constructor(){c(this,"canvas");c(this,"ctx");c(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 ai(t){class e extends t{constructor(){super(...arguments);c(this,"doneCallback",null);c(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 _w=ai(ht);class Ow extends _w{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();c(this,"offset",0);c(this,"speed");c(this,"colors");c(this,"direction");c(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((l,u)=>{i.addColorStop(u*a,l)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const $w=ai(ht);class sd extends $w{constructor({src:s}){super();c(this,"img");c(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 Cw extends td{constructor(s){super(s);c(this,"loopConfig");c(this,"currentLoopCount",0);c(this,"startTime");c(this,"endTime");c(this,"completionCallback",null);this.loopConfig=s.loop??!1,this.startTime=s.startTime??0,this.endTime=s.endTime??null,this.video.removeEventListener("ended",this.handleEnded),this.video.addEventListener("ended",this.handleVideoEnd.bind(this)),this.startTime>0&&(this.video.currentTime=this.startTime),this.endTime!==null&&this.video.addEventListener("timeupdate",this.handleTimeUpdate.bind(this))}handleTimeUpdate(){this.endTime!==null&&this.video.currentTime>=this.endTime&&this.handleVideoEnd()}handleVideoEnd(){this.loopConfig===!0?(this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):(this.video.pause(),this.completionCallback&&this.completionCallback())}reset(){super.reset(),this.currentLoopCount=0,this.video.currentTime=this.startTime}onDone(s){this.completionCallback=s}isOneShot(){return this.loopConfig===!1||this.loopConfig===1}dispose(){this.video.removeEventListener("ended",this.handleVideoEnd),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.completionCallback=null,super.dispose()}}function Dw(t){const e=t.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(e))throw new Error(`Invalid hex color: ${t}`);let s,r,o;return e.length===3?(s=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),o=parseInt(e[2]+e[2],16)):(s=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),o=parseInt(e.substring(4,6),16)),{r:s,g:r,b:o}}function rd(t){return typeof t=="string"?Dw(t):t}function Ar(t){const e=rd(t);return`rgb(${e.r},${e.g},${e.b})`}class xw extends ht{constructor(s={}){super();c(this,"columns",[]);c(this,"fallChance");c(this,"speed");c(this,"baseColor");c(this,"trailColors");this.speed=s.speed??1,this.fallChance=s.fallChance??.7,s.baseColor?this.baseColor=rd(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let o=0;o<=5;o++){const n=1-o/5*.6;r.push({r:Math.floor(this.baseColor.r*n),g:Math.floor(this.baseColor.g*n),b:Math.floor(this.baseColor.b*n)})}return r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const l=this.columns[a];let u=0,d=0,h=0;if(i===l)u=this.baseColor.r,d=this.baseColor.g,h=this.baseColor.b;else if(i<l&&i>l-this.trailColors.length){const p=l-i;if(p<this.trailColors.length){const y=this.trailColors[p];u=y.r,d=y.g,h=y.b}}const f=(i*s+a)*4;n[f]=u,n[f+1]=d,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(o,0,0)}}class Aw{constructor(e,s){c(this,"baseRenderer");c(this,"overlayIcons",new Map);c(this,"overlayConfigs");c(this,"loadedIcons",new Set);c(this,"canvas");c(this,"ctx");c(this,"persistOverlaysOnComplete");c(this,"baseRendererCompleted",!1);c(this,"completionCallback",null);c(this,"hasSignaledCompletion",!1);this.baseRenderer=s(e.baseRenderer.type,e.baseRenderer.data),this.overlayConfigs=e.overlays,this.persistOverlaysOnComplete=e.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const e of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(e.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${e.src}`,r)},s.src=e.src,this.overlayIcons.set(e.src,s)}}calculateOverlayPosition(e,s,r){let o,n;if(typeof e.position=="string")switch(e.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-e.size)/2,n=0;break;case"top-right":o=s-e.size,n=0;break;case"center-left":o=0,n=(r-e.size)/2;break;case"center":o=(s-e.size)/2,n=(r-e.size)/2;break;case"center-right":o=s-e.size,n=(r-e.size)/2;break;case"bottom-left":o=0,n=r-e.size;break;case"bottom-center":o=(s-e.size)/2,n=r-e.size;break;case"bottom-right":o=s-e.size,n=r-e.size;break;default:o=0,n=0}else o=e.position.x,n=e.position.y;return e.offset&&(o+=e.offset.x||0,n+=e.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(e,s){if(this.canvas.width=e,this.canvas.height=s,this.ctx.clearRect(0,0,e,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(e,s);else{this.baseRenderer.renderFrame(e,s);const r=this.baseRenderer.readPixels(e,s);if(r&&r.length>0){const o=new ImageData(r,e,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(e,s)}}renderOverlays(e,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const o=this.overlayIcons.get(r.src);if(!o||!this.loadedIcons.has(r.src))continue;const n=this.calculateOverlayPosition(r,e,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(o,n.x,n.y,r.size,r.size),this.ctx.restore()}}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(e){this.completionCallback=e,this.hasSignaledCompletion&&e()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class od extends ht{constructor(s){super();c(this,"img");c(this,"loaded",!1);c(this,"scrollConfig");c(this,"loopConfig");c(this,"duration");c(this,"pauseDuration");c(this,"colorOverride");c(this,"originalSvgData",null);c(this,"position",0);c(this,"startTime",0);c(this,"lastFrameTime",0);c(this,"currentLoopCount",0);c(this,"completionCallback",null);c(this,"isPlaying",!1);c(this,"completed",!1);c(this,"isPaused",!1);c(this,"pauseStartTime",0);this.img=new Image,this.img.crossOrigin="anonymous",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,this.colorOverride=s.colorOverride,this.colorOverride&&s.src.toLowerCase().includes(".svg")?this.loadAndProcessSvg(s.src):this.img.src=s.src,this.img.onload=()=>{this.loaded=!0},this.img.onerror=r=>{console.error("Failed to load image:",r)}}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(!this.loaded||this.completed)return;if(this.isPaused){this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.ctx.drawImage(this.img,0,0,s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const l=performance.now(),u=(l-this.lastFrameTime)/1e3;this.lastFrameTime=l;const d=n*u;switch(o){case"left":this.position+=d;break;case"right":this.position+=d;break;case"up":this.position+=d;break;case"down":this.position+=d;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(s,r,o,i)}drawScrollingImage(s,r,o,n){var h,f,p,y,w,E,S,L,R;const i=this.img.width/this.img.height;let a,l;((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(l=this.scrollConfig.height,a=l*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,l=a/i):o==="left"||o==="right"?(l=r,a=l*i):(a=s,l=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,l=((w=this.scrollConfig)==null?void 0:w.height)||r);let u,d;switch(o==="left"||o==="right"?(u=0,((E=this.scrollConfig)==null?void 0:E.offsetY)==="center"||((S=this.scrollConfig)==null?void 0:S.offsetY)===void 0?d=(r-l)/2:d=this.scrollConfig.offsetY):(((L=this.scrollConfig)==null?void 0:L.offsetX)==="center"||((R=this.scrollConfig)==null?void 0:R.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),o){case"left":{const O=s-this.position;if(O<s&&O>-a&&this.ctx.drawImage(this.img,O,d,a,l),this.loopConfig&&this.pauseDuration===0&&this.position>n){const I=O+a+n;I<s&&this.ctx.drawImage(this.img,I,d,a,l)}break}case"right":{const O=-a+this.position;if(O>-a&&O<s&&this.ctx.drawImage(this.img,O,d,a,l),this.loopConfig&&this.pauseDuration===0&&O-n-a>-a){const I=O-a-n;I<s&&this.ctx.drawImage(this.img,I,d,a,l)}break}case"up":{const O=r-this.position;if(O>-l&&O<r&&this.ctx.drawImage(this.img,u,O,a,l),this.loopConfig&&this.pauseDuration===0&&O+l+n<r){const I=O+l+n;I>-l&&this.ctx.drawImage(this.img,u,I,a,l)}break}case"down":{const O=-l+this.position;if(O>-l&&O<r&&this.ctx.drawImage(this.img,u,O,a,l),this.loopConfig&&this.pauseDuration===0&&O-n-l>-l){const I=O-l-n;I<r&&this.ctx.drawImage(this.img,u,I,a,l)}break}}}checkScrollCompletion(s,r,o,n){var h,f,p,y,w;if(!this.isPlaying)return;const i=this.img.width/this.img.height;let a,l;switch(((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(l=this.scrollConfig.height,a=l*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,l=a/i):o==="left"||o==="right"?(l=r,a=l*i):(a=s,l=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,l=((w=this.scrollConfig)==null?void 0:w.height)||r),o){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let u=!1;const d=1;switch(o){case"left":u=s-this.position<-a-d;break;case"right":u=-a+this.position>s+d;break;case"up":u=r-this.position<-l-d;break;case"down":u=-l+this.position>r+d;break}u&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}async loadAndProcessSvg(s){try{const o=await(await fetch(s)).text();this.originalSvgData=o;const n=this.applySvgColorOverride(o),i=`data:image/svg+xml;base64,${btoa(n)}`;this.img.src=i}catch(r){console.error("Failed to load and process SVG:",r),this.img.src=s}}applySvgColorOverride(s){if(!this.colorOverride)return s;const r=Ar(this.colorOverride);return s.replace(/fill\s*=\s*["'][^"']*["']/gi,`fill="${r}"`).replace(/fill\s*:\s*[^;"]*/gi,`fill:${r}`).replace(/stroke\s*=\s*["'][^"']*["']/gi,`stroke="${r}"`).replace(/stroke\s*:\s*[^;"]*/gi,`stroke:${r}`)}dispose(){this.img.removeAttribute("src"),this.completionCallback=null,this.originalSvgData=null}}class Pw extends ht{constructor(s){super();c(this,"text");c(this,"lines");c(this,"fontSize");c(this,"fontFamily");c(this,"lineHeight");c(this,"textColor");c(this,"scrollConfig");c(this,"loopConfig");c(this,"duration");c(this,"pauseDuration");c(this,"position",0);c(this,"startTime",0);c(this,"lastFrameTime",0);c(this,"currentLoopCount",0);c(this,"completionCallback",null);c(this,"isPlaying",!1);c(this,"completed",!1);c(this,"isPaused",!1);c(this,"pauseStartTime",0);c(this,"textWidth",0);c(this,"textHeight",0);c(this,"lineWidths",[]);c(this,"textMeasured",!1);this.text=s.text,this.lines=s.text.split(`
|
|
145
|
-
`),this.fontSize=s.fontSize??8,this.lineHeight=s.lineHeight??this.fontSize+2,this.fontFamily=s.fontFamily??"monospace, 'Lucida Console', 'Courier New', Courier",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,s.color?this.textColor=Ar(s.color):this.textColor="rgb(255,255,255)"}measureText(){if(this.textMeasured)return;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.lineWidths=[];let s=0;for(const r of this.lines){const n=this.ctx.measureText(r).width;this.lineWidths.push(n),s=Math.max(s,n)}this.textWidth=s,this.textHeight=this.lines.length*this.lineHeight,this.textMeasured=!0}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0,this.textMeasured=!1,this.lineWidths=[]}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(this.canvas.width=s,this.canvas.height=r,this.measureText(),this.completed)return;if(this.isPaused){this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.drawStaticText(s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const l=performance.now(),u=(l-this.lastFrameTime)/1e3;this.lastFrameTime=l;const d=n*u;switch(o){case"left":case"right":case"up":case"down":this.position+=d;break}}this.drawScrollingText(s,r,o,i),this.checkScrollCompletion(s,r,o)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const o=this.textHeight;let n=(r-o)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],l=this.lineWidths[i],u=(s-l)/2,d=n+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,o,n){var l,u,d,h;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";let i,a;o==="left"||o==="right"?(i=0,((l=this.scrollConfig)==null?void 0:l.offsetY)==="center"||((u=this.scrollConfig)==null?void 0:u.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((d=this.scrollConfig)==null?void 0:d.offsetX)==="center"||((h=this.scrollConfig)==null?void 0:h.offsetX)===void 0?(i=s/2,this.ctx.textAlign="center"):(i=this.scrollConfig.offsetX,this.ctx.textAlign="left"),a=0),this.drawMultiLineScrollText(o,s,r,n,i,a)}drawMultiLineScrollText(s,r,o,n,i,a){switch(s){case"left":{const l=r-this.position;if(l<r&&l>-this.textWidth&&this.drawTextBlock(l,a,"left"),this.loopConfig&&this.pauseDuration===0&&this.position>n){const u=l+this.textWidth+n;u<r&&this.drawTextBlock(u,a,"left")}break}case"right":{const l=-this.textWidth+this.position;if(l>-this.textWidth&&l<r&&this.drawTextBlock(l,a,"left"),this.loopConfig&&this.pauseDuration===0&&l-n-this.textWidth>-this.textWidth){const u=l-this.textWidth-n;u<r&&this.drawTextBlock(u,a,"left")}break}case"up":{const l=o-this.position;if(l>-this.textHeight&&l<o&&this.drawTextBlock(i,l,"center"),this.loopConfig&&this.pauseDuration===0&&l+this.textHeight+n<o){const u=l+this.textHeight+n;u>-this.textHeight&&this.drawTextBlock(i,u,"center")}break}case"down":{const l=-this.textHeight+this.position;if(l>-this.textHeight&&l<o&&this.drawTextBlock(i,l,"center"),this.loopConfig&&this.pauseDuration===0&&l-n-this.textHeight>-this.textHeight){const u=l-this.textHeight-n;u<o&&this.drawTextBlock(i,u,"center")}break}}}drawTextBlock(s,r,o){for(let n=0;n<this.lines.length;n++){const i=this.lines[n],a=this.lineWidths[n];let l;o==="center"?l=s-a/2:l=s;const u=r+n*this.lineHeight;this.ctx.fillText(i,l,u)}}checkScrollCompletion(s,r,o){if(!this.isPlaying)return;let n=!1;const i=1;switch(o){case"left":n=s-this.position<-this.textWidth-i;break;case"right":n=-this.textWidth+this.position>s+i;break;case"up":n=r-this.position<-this.textHeight-i;break;case"down":n=-this.textHeight+this.position>r+i;break}n&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}dispose(){this.completionCallback=null}}class Rw{constructor(e){c(this,"patterns");c(this,"currentPatternIndex",0);c(this,"currentRenderer",null);c(this,"loopConfig");c(this,"currentLoopCount",0);c(this,"transitionDuration");c(this,"patternOverrides");c(this,"completionCallback",null);c(this,"patternStore");c(this,"canvas");c(this,"ctx");c(this,"width",0);c(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,l;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=Pr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(l=(a=this.currentRenderer).play)==null||l.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(u){console.error(`Failed to create renderer for pattern "${e}":`,u),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const kw=ai(ht);class Lw extends kw{constructor(s={r:0,g:0,b:0}){super();c(this,"color");let r;s.color!==void 0?r=s.color:s.r!==void 0&&s.g!==void 0&&s.b!==void 0?r={r:s.r,g:s.g,b:s.b}:r={r:0,g:0,b:0},this.color=Ar(r)}setColor(s){this.color=Ar(s),this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,r){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,r),this.signalDoneIfNeeded())}}class Fw extends ht{constructor({minHue:s=0,maxHue:r=360,speed:o=1}={}){super();c(this,"offset",0);c(this,"minHue");c(this,"maxHue");c(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 l=(h,f,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?h+(f-h)*6*p:p<.5?f:p<.6666666666666666?h+(f-h)*(.6666666666666666-p)*6:h),u=o<.5?o*(1+r):o+r-o*r,d=2*o-u;n=l(d,u,s+1/3),i=l(d,u,s),a=l(d,u,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let l=0;l<s;l++){const u=(l+this.offset)%s/s,d=this.minHue/360+u*((this.maxHue-this.minHue)/360),[h,f,p]=this.hslToRgb(d,1,.5);n[i++]=h,n[i++]=f,n[i++]=p,n[i++]=255}this.ctx.putImageData(o,0,0)}}const ua=new Map;Fs(te,{register(t,e){ua.set(t,e)},execute(t,e){const s=ua.get(t);return s?new s(e):null}});$.canvas.registerRenderer("video",Cw);$.canvas.registerRenderer("video-basic",td);$[te].register("image-static",sd);$[te].register("image-scrolling",od);const Nw=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new od(t):new sd(t)}};$[te].register("image",Nw);$[te].register("color",Lw);$[te].register("matrix",xw);$[te].register("sweep",Fw);$[te].register("gradient",Ow);$[te].register("drop",Iw);$[te].register("sequence",Rw);$[te].register("text",Pw);const Uw=class{constructor(t){const e=(s,r)=>{const o=Pr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new Aw(t,e)}};$[te].register("overlay",Uw);const Pr=({mode:t,data:e})=>{const s=$[te].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var jw=Object.defineProperty,Bw=Object.getOwnPropertyDescriptor,Vt=(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 nd="canvas-dispatcher-model";function Hw(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 Ve=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_content",new Map);c(this,"_patterns",new Map);c(this,"_endpointRenderers");c(this,"pattern");c(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new Ce}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=ii.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 u,d,h;const s=t.params.pattern,r=t.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=e.status)==null||d.call(e,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=t.body||{};this.data={...n.data,...a};const l=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=Pr({mode:i,data:l}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var u,d,h;const s=t.params.color,r=Hw(s);if(!r){(u=e.status)==null||u.call(e,400).send({error:"Invalid color format"});return}const o=t.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(d=e.status)==null||d.call(e,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:l}=r;n.renderer=Pr({mode:"color",data:{r:i,g:l,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(Rt.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)}))}};Vt([$e],Ve.prototype,"_endpointRenderers",2);Vt([js("/api/ui/canvas/patterns")],Ve.prototype,"handlePatternsPost",1);Vt([js("/api/ui/canvas/pattern/:endpoint/:pattern")],Ve.prototype,"handlePatternApplication",1);Vt([js("/api/ui/canvas/color/:endpoint/:color")],Ve.prototype,"handleColorApplication",1);Vt([js("/api/ui/canvas/endpoint")],Ve.prototype,"handleEndpointCreation",1);Ve=Vt([P(nd)],Ve);const Rt=new Se({class:Ve,type:nd}),{URL:li}=ae(),{getOne:id}=oe.build({basePath:`${li}/api/device`}),Rr=m.createLogger({name:"device-service",group:"Services"}),ad=async()=>{Rr.debug("sending GET for device serial number");try{const t=await id({urlOverride:`${li}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof ge)return Rr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},ld=async()=>{Rr.debug("sending GET for device details");try{const t=await id({urlOverride:`${li}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof ge)return Rr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Kw=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:ld,getSerialNumber:ad},Symbol.toStringTag,{value:"Module"}));var qw=Object.defineProperty,zw=Object.getOwnPropertyDescriptor,cd=(t,e,s,r)=>{for(var o=r>1?void 0:r?zw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&qw(e,s,o),o};const ud="device-model",Vw="/kos/criticalData/changed",Gw="/kos/criticalData/available";let kr=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_serialNumber");c(this,"_name");c(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 ld();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 ad();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()}};cd([B({topic:[Vw,Gw],websocket:!0})],kr.prototype,"handleCriticalDataChanged",1);kr=cd([P(ud)],kr);const Lr=new Se({class:kr,type:ud});var Yw=Object.getOwnPropertyDescriptor,Ww=(t,e,s,r)=>{for(var o=r>1?void 0:r?Yw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const dd="network-interface-model";let zo=class{constructor(t,e,s){c(this,"id");c(this,"name");c(this,"type");c(this,"nmdevicestate");c(this,"hwaddress");c(this,"mtu");c(this,"configured");c(this,"wifi");c(this,"ethernet");c(this,"ip4settings");c(this,"category");c(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}`)}};zo=Ww([P(dd)],zo);const ci=new ye({class:zo,type:dd}),{URL:Qw}=ae(),{getAll:Zw}=oe.build({basePath:`${Qw}/api/kos/network/interfaces`}),da=m.createLogger({name:"network-interface-service",group:"Services"}),hd=async()=>{da.debug("sending GET for copy-logs");try{const t=await Zw({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof ge)return da.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Xw=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:hd},Symbol.toStringTag,{value:"Module"}));var Jw=Object.defineProperty,eE=Object.getOwnPropertyDescriptor,fd=(t,e,s,r)=>{for(var o=r>1?void 0:r?eE(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 pd="network-interface-container-model";let Fr=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await hd();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=ci.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};fd([$e],Fr.prototype,"_models",2);Fr=fd([P(pd)],Fr);const As=new Se({class:Fr,type:pd});As.addRelatedModel(ci);const{URL:tE}=ae(),{getAll:sE}=oe.build({basePath:`${tE}/api/kos/storage/devices`}),ha=m.createLogger({name:"storage-device-service",group:"Services"}),gd=async()=>{ha.debug("sending GET for storage-device");const t=await sE({});return!(t!=null&&t.data)||t.status!==200?(ha.error("Failed to retrieve storage-device data",t),[]):t.data},rE=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:gd},Symbol.toStringTag,{value:"Module"}));var oE=Object.getOwnPropertyDescriptor,nE=(t,e,s,r)=>{for(var o=r>1?void 0:r?oE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const md="storage-device-model";let Vo=class{constructor(t,e,s){c(this,"id");c(this,"mountDir");c(this,"removed");c(this,"vendor");c(this,"runTimeMs");c(this,"model");c(this,"nodeId");c(this,"local");c(this,"label");c(this,"syspath");c(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}`)}};Vo=nE([zr(),P(md)],Vo);const Nr=new ye({class:Vo,type:md});var iE=Object.defineProperty,aE=Object.getOwnPropertyDescriptor,ui=(t,e,s,r)=>{for(var o=r>1?void 0:r?aE(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&&iE(e,s,o),o};const yd="storage-device-container-model",lE="/kos/storage";let Ps=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=Nr.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await gd()).forEach(e=>{if(e.deviceType!=="disk"){const s={...e,kosParentId:this.id},r=Nr.instance(e.id).options(s).build();this.addModel(r)}})}};ui([$e],Ps.prototype,"_models",2);ui([B({topic:lE,websocket:!0})],Ps.prototype,"handleStorageAvailability",1);Ps=ui([P(yd)],Ps);const kt=new Se({class:Ps,type:yd});kt.addRelatedModel(Nr);const{URL:di}=ae(),{getAll:cE,postModel:uE}=oe.build({basePath:`${di}/api/kos/update/available`}),fa=m.createLogger({name:"usb-update-service",group:"Services"}),bd=async()=>{fa.debug("sending GET for usb-update");const t=await cE({urlOverride:`${di}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(fa.error("Failed to retrieve usb-update data",t),[]):t.data},vd=async(t,e,s)=>{const r=await uE({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${di}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},dE=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:bd,installUpdate:vd},Symbol.toStringTag,{value:"Module"}));var hE=Object.defineProperty,fE=Object.getOwnPropertyDescriptor,wd=(t,e,s,r)=>{for(var o=r>1?void 0:r?fE(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&&hE(e,s,o),o};const Ed="usb-update-model";let Ur=class{constructor(t,e,s){c(this,"id");c(this,"active");c(this,"blocked");c(this,"createTime");c(this,"deviceId");c(this,"manifestId");c(this,"notes");c(this,"futureHandler");c(this,"logger");this.id=t,this.logger=s.logger,this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes,this.futureHandler=new Yr(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),vd(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}`)}};wd([yi()],Ur.prototype,"install",1);Ur=wd([P(Ed)],Ur);const hi=new ye({class:Ur,type:Ed});var pE=Object.defineProperty,gE=Object.getOwnPropertyDescriptor,lo=(t,e,s,r)=>{for(var o=r>1?void 0:r?gE(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&&pE(e,s,o),o};const Md="usb-update-container-model";let Lt=class{constructor(t,e,s){c(this,"id");c(this,"disposer");c(this,"storageService");c(this,"_activeUpdate");c(this,"logger");c(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await bd();X(()=>{const e=t.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!e.includes(s.id)).forEach(s=>this.removeModel(s.id)),t.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=hi.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}`)}};lo([Nt({modelType:kt.type})],Lt.prototype,"storageService",2);lo([$e],Lt.prototype,"_models",2);lo([_l({dependencies:t=>[t.isUsbInserted]})],Lt.prototype,"usbInsertedEffect",1);Lt=lo([P(Md)],Lt);const Rs=new Se({class:Lt,type:Md});Rs.addRelatedModel(hi);const mE=()=>({...{[Bt.type]:{class:Gc},[ze.type]:{class:Jc,singleton:!0},...re.registration,...lt.registration,...At.registration,...Cr.registration,...Fe.registration,[oi.type]:{class:exports.WsEventModel,singleton:!0},...xs.registration,...si.registration,...wr.registration}}),fi=mE(),yE={models:fi,preloadModels:[]},pa=!0,Td=t=>()=>{const e=fi;return Ll(Go)(Ds).model(At).model(kt).model(Rs).model(Lr).model(Ir).model(Ts).model(_r).model(zn).model(As).model(Rt).model(ii).model(uu).model(Hn,pa).model(qs).model(fu,pa),Object.keys(e).forEach(s=>{const r=e[s];kl(Go)(s,r)}),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t)}},Me={};Me.core={models:Td(Me)};Me.preload=A.model.preloadModel(Me);Me.model=A.model.register(Me);Me.companion=A.companion.register(Me);Me.legacy=A.model.registerLegacyModel(Me);const Go=Me;class bE{registerTroubleRankMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleRank,e),this}registerTroubleRoleMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleRole,e),this}registerTroubleColorMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleColor,e),this}registerModelLoader(e,s){$.loader.registerLoader(e,s)}registerCanvasPatternLoader(e){$.loader.registerLoader(Rt.loader,e)}}const vE=async(t,e)=>{const s=zn.instance(t).options({}).build(),r=e?`${e}-`:"";return await de(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:()=>{rt(s)}}},Sd="kos:service:region",Id="regionId",wE=`${Sd}-${Id}`,_d=async t=>{const e=lt.factory(wE)({path:Sd,attribute:Id});await de(e),e.updateProperty(t)},pi="/kos-timer-event",gi="/kos-timer-event/tick",mi="defaultTimerEnd",ls=m.createLogger({name:"timer-manager"}),EE=t=>t.updateProperty!==void 0;class Od{constructor(e,s,r){c(this,"name");c(this,"timeout");c(this,"timer");c(this,"state","inactive");c(this,"decrementValue",1);c(this,"remainingTime");c(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,EE(s)&&W(()=>{m.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:mi}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){ls.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&&(ls.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;ls.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(ls.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){V(`${gi}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){V(pi,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const cs=new Map,yt=(t,e)=>{const s=cs.get(t);if(!s){ls.error(`Timer ${t} not found`);return}e(s)},$d={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(cs.has(t))return cs.get(t);const r=new Od(t,e,s);return cs.set(t,r),r},getTimer(t){return cs.get(t)},clearTimer(t){yt(t,e=>e.pause())},restartTimer(t){yt(t,e=>e.restart())},resetTimer(t){yt(t,e=>e.reset())},addTimeoutAction(t,e){yt(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){yt(t,s=>s.removeTimeoutAction(e))},startTimer(t){yt(t,e=>e.start())}},Cd="kos:service:region:settings",Dd="timeZone",ME=`${Cd}-${Dd}`,Yo=async t=>{const e=lt.factory(ME)({path:Cd,attribute:Dd});await de(e),e.updateProperty(t)},TE=t=>!t||!t.data;function yi(t={}){const{alias:e,namespace:s,abortController:r=!1,trackerPolicy:o="id"}=t;return(n,i,a)=>{n[hs]=n[hs]||{},e&&(n[gs]=n[gs]||new Map,n[gs].set(i,e));const l=a.value,u=async function(...d){const h=it();m.debug(`Calling future service ${i} with tracker ${h}`);let f,p;r&&(f=new AbortController);const y=ot.initiateFuture({tracker:h,id:An});s&&(y.namespace=s),m.debug(`waiting for future ${y.id} to be ready`),await de(y),m.debug(`future ${y.id} is ready`),X(()=>{m.debug(`Adding future ${y.id} to futureHandler`),this.futureHandler.addFuture(y,e)}),r&&f&&(p=W(()=>{(y.status==="CANCELLED"||y.endState===qe.Canceled)&&(m.debug(`Future ${y.id} cancelled, aborting request`),f==null||f.abort())}),f.signal.addEventListener("abort",async()=>{if(y.status!=="CANCELLED"&&y.endState!==qe.Canceled&&!y.endState){m.debug(`AbortController aborted, cancelling future ${y.id}`);try{await y.cancelFuture()}catch(E){m.error(`Failed to cancel future ${y.id}:`,E)}}},{once:!0}));const w=()=>{p&&(p(),p=void 0)};try{const E=[...d];if(r&&f){const R=E[E.length-1];R&&typeof R=="object"&&"aborted"in R?E[E.length-1]=f.signal:E.push(f.signal)}if(o==="context"){const R=E[E.length-1];if(wn(R))R.$tracker=h;else{const O={[Vr]:!0,$tracker:h};E.push(O)}}else E.push(h);const S=await l.apply(this,E);m.debug(`received future response for ${h}`,S);const L=TE(S)?S:S==null?void 0:S.data;return L?(L.progress=1,m.debug("mapping future response to future model"),y.endState?m.debug(`future ${y.id} has already completed. Not updating the model`):jn(L,y)):this.futureHandler.removeFuture(e),w(),L}catch(E){if(w(),r&&(f!=null&&f.signal.aborted)){const S=new Error("Operation cancelled");throw m.debug(`Operation ${i} was cancelled`),S}throw m.error(E),E}};n[hs][i]={handler:u}}}const SE=({path:t})=>(e,s)=>{e[N]=e[N]||{},e[N][s]={modelType:xs.type,id:`${xs.type}-${t}`,options:{path:t},lifecycle:x.INIT}};function IE(t){const{path:e,attribute:s}=t;return(r,o)=>{r[N]=r[N]||{},r[N][o]={modelType:si.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:x.INIT}}}const Tt=m.createLogger({name:"services",group:"Services"}),_E=async(t,e)=>xd(t,e,`${exports.BASE_URL}/api/server/login`),xd=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()},OE=async t=>Ad(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Ad=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()},$E=async(t,e)=>Pd(t,e,`${exports.BASE_URL}/api/server/resetPassword`),Pd=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{Tt.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(Tt.debug(`password reset returned status ${r.status}`),!r.ok){Tt.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()},CE=async(t,e,s)=>Rd(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),Rd=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Tt.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(Tt.debug(`invitation accept returned status ${o.status}`),!o.ok){Tt.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 DE(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:l}=o,u=n;let d=0,h="PENDING",f=!0;const p=new Set;let y;return l&&typeof l=="object"&&(y=M.autorun(()=>{const w=l.progress||0,E=l.status||"PENDING",S=!l.endState;(w!==d||E!==h||S!==f)&&(d=w,h=E,f=S,p.forEach(L=>{try{L(d,h)}catch(R){console.warn("Progress callback error:",R)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(w=>{try{w(d,h)}catch(E){console.warn("Progress callback error:",E)}})),y&&y(),p.clear()}),u.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",p.forEach(w=>{try{w(d,h)}catch(E){console.warn("Progress callback error:",E)}}),y&&y()},u.getController=()=>i,u.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(u,"progress",{get:()=>d,enumerable:!0}),Object.defineProperty(u,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(u,"isRunning",{get:()=>f,enumerable:!0}),u.onProgressUpdate=w=>(p.add(w),w(d,h),()=>p.delete(w)),u}const xE=Ze.keyframes`
|
|
144
|
+
`,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 pt{constructor(){c(this,"canvas");c(this,"ctx");c(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 li(t){class e extends t{constructor(){super(...arguments);c(this,"doneCallback",null);c(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 $w=li(pt);class Cw extends $w{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();c(this,"offset",0);c(this,"speed");c(this,"colors");c(this,"direction");c(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((l,u)=>{i.addColorStop(u*a,l)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const Dw=li(pt);class nd extends Dw{constructor({src:s}){super();c(this,"img");c(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 xw extends od{constructor(s){super(s);c(this,"loopConfig");c(this,"currentLoopCount",0);c(this,"startTime");c(this,"endTime");c(this,"completionCallback",null);this.loopConfig=s.loop??!1,this.startTime=s.startTime??0,this.endTime=s.endTime??null,this.video.removeEventListener("ended",this.handleEnded),this.video.addEventListener("ended",this.handleVideoEnd.bind(this)),this.startTime>0&&(this.video.currentTime=this.startTime),this.endTime!==null&&this.video.addEventListener("timeupdate",this.handleTimeUpdate.bind(this))}handleTimeUpdate(){this.endTime!==null&&this.video.currentTime>=this.endTime&&this.handleVideoEnd()}handleVideoEnd(){this.loopConfig===!0?(this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):(this.video.pause(),this.completionCallback&&this.completionCallback())}reset(){super.reset(),this.currentLoopCount=0,this.video.currentTime=this.startTime}onDone(s){this.completionCallback=s}isOneShot(){return this.loopConfig===!1||this.loopConfig===1}dispose(){this.video.removeEventListener("ended",this.handleVideoEnd),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.completionCallback=null,super.dispose()}}function Aw(t){const e=t.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(e))throw new Error(`Invalid hex color: ${t}`);let s,r,o;return e.length===3?(s=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),o=parseInt(e[2]+e[2],16)):(s=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),o=parseInt(e.substring(4,6),16)),{r:s,g:r,b:o}}function id(t){return typeof t=="string"?Aw(t):t}function Rr(t){const e=id(t);return`rgb(${e.r},${e.g},${e.b})`}class Rw extends pt{constructor(s={}){super();c(this,"columns",[]);c(this,"fallChance");c(this,"speed");c(this,"baseColor");c(this,"trailColors");this.speed=s.speed??1,this.fallChance=s.fallChance??.7,s.baseColor?this.baseColor=id(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let o=0;o<=5;o++){const n=1-o/5*.6;r.push({r:Math.floor(this.baseColor.r*n),g:Math.floor(this.baseColor.g*n),b:Math.floor(this.baseColor.b*n)})}return r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const l=this.columns[a];let u=0,d=0,h=0;if(i===l)u=this.baseColor.r,d=this.baseColor.g,h=this.baseColor.b;else if(i<l&&i>l-this.trailColors.length){const p=l-i;if(p<this.trailColors.length){const y=this.trailColors[p];u=y.r,d=y.g,h=y.b}}const f=(i*s+a)*4;n[f]=u,n[f+1]=d,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(o,0,0)}}class Pw{constructor(e,s){c(this,"baseRenderer");c(this,"overlayIcons",new Map);c(this,"overlayConfigs");c(this,"loadedIcons",new Set);c(this,"canvas");c(this,"ctx");c(this,"persistOverlaysOnComplete");c(this,"baseRendererCompleted",!1);c(this,"completionCallback",null);c(this,"hasSignaledCompletion",!1);this.baseRenderer=s(e.baseRenderer.type,e.baseRenderer.data),this.overlayConfigs=e.overlays,this.persistOverlaysOnComplete=e.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const e of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(e.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${e.src}`,r)},s.src=e.src,this.overlayIcons.set(e.src,s)}}calculateOverlayPosition(e,s,r){let o,n;if(typeof e.position=="string")switch(e.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-e.size)/2,n=0;break;case"top-right":o=s-e.size,n=0;break;case"center-left":o=0,n=(r-e.size)/2;break;case"center":o=(s-e.size)/2,n=(r-e.size)/2;break;case"center-right":o=s-e.size,n=(r-e.size)/2;break;case"bottom-left":o=0,n=r-e.size;break;case"bottom-center":o=(s-e.size)/2,n=r-e.size;break;case"bottom-right":o=s-e.size,n=r-e.size;break;default:o=0,n=0}else o=e.position.x,n=e.position.y;return e.offset&&(o+=e.offset.x||0,n+=e.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(e,s){if(this.canvas.width=e,this.canvas.height=s,this.ctx.clearRect(0,0,e,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(e,s);else{this.baseRenderer.renderFrame(e,s);const r=this.baseRenderer.readPixels(e,s);if(r&&r.length>0){const o=new ImageData(r,e,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(e,s)}}renderOverlays(e,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const o=this.overlayIcons.get(r.src);if(!o||!this.loadedIcons.has(r.src))continue;const n=this.calculateOverlayPosition(r,e,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(o,n.x,n.y,r.size,r.size),this.ctx.restore()}}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(e){this.completionCallback=e,this.hasSignaledCompletion&&e()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class ad extends pt{constructor(s){super();c(this,"img");c(this,"loaded",!1);c(this,"scrollConfig");c(this,"loopConfig");c(this,"duration");c(this,"pauseDuration");c(this,"colorOverride");c(this,"originalSvgData",null);c(this,"position",0);c(this,"startTime",0);c(this,"lastFrameTime",0);c(this,"currentLoopCount",0);c(this,"completionCallback",null);c(this,"isPlaying",!1);c(this,"completed",!1);c(this,"isPaused",!1);c(this,"pauseStartTime",0);this.img=new Image,this.img.crossOrigin="anonymous",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,this.colorOverride=s.colorOverride,this.colorOverride&&s.src.toLowerCase().includes(".svg")?this.loadAndProcessSvg(s.src):this.img.src=s.src,this.img.onload=()=>{this.loaded=!0},this.img.onerror=r=>{console.error("Failed to load image:",r)}}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(!this.loaded||this.completed)return;if(this.isPaused){this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.ctx.drawImage(this.img,0,0,s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const l=performance.now(),u=(l-this.lastFrameTime)/1e3;this.lastFrameTime=l;const d=n*u;switch(o){case"left":this.position+=d;break;case"right":this.position+=d;break;case"up":this.position+=d;break;case"down":this.position+=d;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(s,r,o,i)}drawScrollingImage(s,r,o,n){var h,f,p,y,w,E,S,k,U;const i=this.img.width/this.img.height;let a,l;((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(l=this.scrollConfig.height,a=l*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,l=a/i):o==="left"||o==="right"?(l=r,a=l*i):(a=s,l=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,l=((w=this.scrollConfig)==null?void 0:w.height)||r);let u,d;switch(o==="left"||o==="right"?(u=0,((E=this.scrollConfig)==null?void 0:E.offsetY)==="center"||((S=this.scrollConfig)==null?void 0:S.offsetY)===void 0?d=(r-l)/2:d=this.scrollConfig.offsetY):(((k=this.scrollConfig)==null?void 0:k.offsetX)==="center"||((U=this.scrollConfig)==null?void 0:U.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),o){case"left":{const O=s-this.position;if(O<s&&O>-a&&this.ctx.drawImage(this.img,O,d,a,l),this.loopConfig&&this.pauseDuration===0&&this.position>n){const I=O+a+n;I<s&&this.ctx.drawImage(this.img,I,d,a,l)}break}case"right":{const O=-a+this.position;if(O>-a&&O<s&&this.ctx.drawImage(this.img,O,d,a,l),this.loopConfig&&this.pauseDuration===0&&O-n-a>-a){const I=O-a-n;I<s&&this.ctx.drawImage(this.img,I,d,a,l)}break}case"up":{const O=r-this.position;if(O>-l&&O<r&&this.ctx.drawImage(this.img,u,O,a,l),this.loopConfig&&this.pauseDuration===0&&O+l+n<r){const I=O+l+n;I>-l&&this.ctx.drawImage(this.img,u,I,a,l)}break}case"down":{const O=-l+this.position;if(O>-l&&O<r&&this.ctx.drawImage(this.img,u,O,a,l),this.loopConfig&&this.pauseDuration===0&&O-n-l>-l){const I=O-l-n;I<r&&this.ctx.drawImage(this.img,u,I,a,l)}break}}}checkScrollCompletion(s,r,o,n){var h,f,p,y,w;if(!this.isPlaying)return;const i=this.img.width/this.img.height;let a,l;switch(((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(l=this.scrollConfig.height,a=l*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,l=a/i):o==="left"||o==="right"?(l=r,a=l*i):(a=s,l=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,l=((w=this.scrollConfig)==null?void 0:w.height)||r),o){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let u=!1;const d=1;switch(o){case"left":u=s-this.position<-a-d;break;case"right":u=-a+this.position>s+d;break;case"up":u=r-this.position<-l-d;break;case"down":u=-l+this.position>r+d;break}u&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}async loadAndProcessSvg(s){try{const o=await(await fetch(s)).text();this.originalSvgData=o;const n=this.applySvgColorOverride(o),i=`data:image/svg+xml;base64,${btoa(n)}`;this.img.src=i}catch(r){console.error("Failed to load and process SVG:",r),this.img.src=s}}applySvgColorOverride(s){if(!this.colorOverride)return s;const r=Rr(this.colorOverride);return s.replace(/fill\s*=\s*["'][^"']*["']/gi,`fill="${r}"`).replace(/fill\s*:\s*[^;"]*/gi,`fill:${r}`).replace(/stroke\s*=\s*["'][^"']*["']/gi,`stroke="${r}"`).replace(/stroke\s*:\s*[^;"]*/gi,`stroke:${r}`)}dispose(){this.img.removeAttribute("src"),this.completionCallback=null,this.originalSvgData=null}}class kw extends pt{constructor(s){super();c(this,"text");c(this,"lines");c(this,"fontSize");c(this,"fontFamily");c(this,"lineHeight");c(this,"textColor");c(this,"scrollConfig");c(this,"loopConfig");c(this,"duration");c(this,"pauseDuration");c(this,"position",0);c(this,"startTime",0);c(this,"lastFrameTime",0);c(this,"currentLoopCount",0);c(this,"completionCallback",null);c(this,"isPlaying",!1);c(this,"completed",!1);c(this,"isPaused",!1);c(this,"pauseStartTime",0);c(this,"textWidth",0);c(this,"textHeight",0);c(this,"lineWidths",[]);c(this,"textMeasured",!1);this.text=s.text,this.lines=s.text.split(`
|
|
145
|
+
`),this.fontSize=s.fontSize??8,this.lineHeight=s.lineHeight??this.fontSize+2,this.fontFamily=s.fontFamily??"monospace, 'Lucida Console', 'Courier New', Courier",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,s.color?this.textColor=Rr(s.color):this.textColor="rgb(255,255,255)"}measureText(){if(this.textMeasured)return;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.lineWidths=[];let s=0;for(const r of this.lines){const n=this.ctx.measureText(r).width;this.lineWidths.push(n),s=Math.max(s,n)}this.textWidth=s,this.textHeight=this.lines.length*this.lineHeight,this.textMeasured=!0}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0,this.textMeasured=!1,this.lineWidths=[]}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(this.canvas.width=s,this.canvas.height=r,this.measureText(),this.completed)return;if(this.isPaused){this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.drawStaticText(s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const l=performance.now(),u=(l-this.lastFrameTime)/1e3;this.lastFrameTime=l;const d=n*u;switch(o){case"left":case"right":case"up":case"down":this.position+=d;break}}this.drawScrollingText(s,r,o,i),this.checkScrollCompletion(s,r,o)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const o=this.textHeight;let n=(r-o)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],l=this.lineWidths[i],u=(s-l)/2,d=n+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,o,n){var l,u,d,h;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";let i,a;o==="left"||o==="right"?(i=0,((l=this.scrollConfig)==null?void 0:l.offsetY)==="center"||((u=this.scrollConfig)==null?void 0:u.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((d=this.scrollConfig)==null?void 0:d.offsetX)==="center"||((h=this.scrollConfig)==null?void 0:h.offsetX)===void 0?(i=s/2,this.ctx.textAlign="center"):(i=this.scrollConfig.offsetX,this.ctx.textAlign="left"),a=0),this.drawMultiLineScrollText(o,s,r,n,i,a)}drawMultiLineScrollText(s,r,o,n,i,a){switch(s){case"left":{const l=r-this.position;if(l<r&&l>-this.textWidth&&this.drawTextBlock(l,a,"left"),this.loopConfig&&this.pauseDuration===0&&this.position>n){const u=l+this.textWidth+n;u<r&&this.drawTextBlock(u,a,"left")}break}case"right":{const l=-this.textWidth+this.position;if(l>-this.textWidth&&l<r&&this.drawTextBlock(l,a,"left"),this.loopConfig&&this.pauseDuration===0&&l-n-this.textWidth>-this.textWidth){const u=l-this.textWidth-n;u<r&&this.drawTextBlock(u,a,"left")}break}case"up":{const l=o-this.position;if(l>-this.textHeight&&l<o&&this.drawTextBlock(i,l,"center"),this.loopConfig&&this.pauseDuration===0&&l+this.textHeight+n<o){const u=l+this.textHeight+n;u>-this.textHeight&&this.drawTextBlock(i,u,"center")}break}case"down":{const l=-this.textHeight+this.position;if(l>-this.textHeight&&l<o&&this.drawTextBlock(i,l,"center"),this.loopConfig&&this.pauseDuration===0&&l-n-this.textHeight>-this.textHeight){const u=l-this.textHeight-n;u<o&&this.drawTextBlock(i,u,"center")}break}}}drawTextBlock(s,r,o){for(let n=0;n<this.lines.length;n++){const i=this.lines[n],a=this.lineWidths[n];let l;o==="center"?l=s-a/2:l=s;const u=r+n*this.lineHeight;this.ctx.fillText(i,l,u)}}checkScrollCompletion(s,r,o){if(!this.isPlaying)return;let n=!1;const i=1;switch(o){case"left":n=s-this.position<-this.textWidth-i;break;case"right":n=-this.textWidth+this.position>s+i;break;case"up":n=r-this.position<-this.textHeight-i;break;case"down":n=-this.textHeight+this.position>r+i;break}n&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}dispose(){this.completionCallback=null}}class Lw{constructor(e){c(this,"patterns");c(this,"currentPatternIndex",0);c(this,"currentRenderer",null);c(this,"loopConfig");c(this,"currentLoopCount",0);c(this,"transitionDuration");c(this,"patternOverrides");c(this,"completionCallback",null);c(this,"patternStore");c(this,"canvas");c(this,"ctx");c(this,"width",0);c(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,l;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=Pr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(l=(a=this.currentRenderer).play)==null||l.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(u){console.error(`Failed to create renderer for pattern "${e}":`,u),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const Fw=li(pt);class Nw extends Fw{constructor(s={r:0,g:0,b:0}){super();c(this,"color");let r;s.color!==void 0?r=s.color:s.r!==void 0&&s.g!==void 0&&s.b!==void 0?r={r:s.r,g:s.g,b:s.b}:r={r:0,g:0,b:0},this.color=Rr(r)}setColor(s){this.color=Rr(s),this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,r){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,r),this.signalDoneIfNeeded())}}class Uw extends pt{constructor({minHue:s=0,maxHue:r=360,speed:o=1}={}){super();c(this,"offset",0);c(this,"minHue");c(this,"maxHue");c(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 l=(h,f,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?h+(f-h)*6*p:p<.5?f:p<.6666666666666666?h+(f-h)*(.6666666666666666-p)*6:h),u=o<.5?o*(1+r):o+r-o*r,d=2*o-u;n=l(d,u,s+1/3),i=l(d,u,s),a=l(d,u,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let l=0;l<s;l++){const u=(l+this.offset)%s/s,d=this.minHue/360+u*((this.maxHue-this.minHue)/360),[h,f,p]=this.hslToRgb(d,1,.5);n[i++]=h,n[i++]=f,n[i++]=p,n[i++]=255}this.ctx.putImageData(o,0,0)}}const da=new Map;Fs(te,{register(t,e){da.set(t,e)},execute(t,e){const s=da.get(t);return s?new s(e):null}});$.canvas.registerRenderer("video",xw);$.canvas.registerRenderer("video-basic",od);$[te].register("image-static",nd);$[te].register("image-scrolling",ad);const jw=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new ad(t):new nd(t)}};$[te].register("image",jw);$[te].register("color",Nw);$[te].register("matrix",Rw);$[te].register("sweep",Uw);$[te].register("gradient",Cw);$[te].register("drop",Ow);$[te].register("sequence",Lw);$[te].register("text",kw);const Bw=class{constructor(t){const e=(s,r)=>{const o=Pr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new Pw(t,e)}};$[te].register("overlay",Bw);const Pr=({mode:t,data:e})=>{const s=$[te].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var Hw=Object.defineProperty,Kw=Object.getOwnPropertyDescriptor,Yt=(t,e,s,r)=>{for(var o=r>1?void 0:r?Kw(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&&Hw(e,s,o),o};const ld="canvas-dispatcher-model";function qw(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 Ye=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_content",new Map);c(this,"_patterns",new Map);c(this,"_endpointRenderers");c(this,"pattern");c(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new Ce}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=ai.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 u,d,h;const s=t.params.pattern,r=t.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=e.status)==null||d.call(e,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=t.body||{};this.data={...n.data,...a};const l=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=Pr({mode:i,data:l}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var u,d,h;const s=t.params.color,r=qw(s);if(!r){(u=e.status)==null||u.call(e,400).send({error:"Invalid color format"});return}const o=t.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(d=e.status)==null||d.call(e,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:l}=r;n.renderer=Pr({mode:"color",data:{r:i,g:l,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(Lt.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([$e],Ye.prototype,"_endpointRenderers",2);Yt([js("/api/ui/canvas/patterns")],Ye.prototype,"handlePatternsPost",1);Yt([js("/api/ui/canvas/pattern/:endpoint/:pattern")],Ye.prototype,"handlePatternApplication",1);Yt([js("/api/ui/canvas/color/:endpoint/:color")],Ye.prototype,"handleColorApplication",1);Yt([js("/api/ui/canvas/endpoint")],Ye.prototype,"handleEndpointCreation",1);Ye=Yt([R(ld)],Ye);const Lt=new Se({class:Ye,type:ld}),{URL:ci}=ae(),{getOne:cd}=oe.build({basePath:`${ci}/api/device`}),kr=m.createLogger({name:"device-service",group:"Services"}),ud=async()=>{kr.debug("sending GET for device serial number");try{const t=await cd({urlOverride:`${ci}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof ge)return kr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},dd=async()=>{kr.debug("sending GET for device details");try{const t=await cd({urlOverride:`${ci}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof ge)return kr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},zw=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:dd,getSerialNumber:ud},Symbol.toStringTag,{value:"Module"}));var Vw=Object.defineProperty,Gw=Object.getOwnPropertyDescriptor,hd=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Vw(e,s,o),o};const fd="device-model",Yw="/kos/criticalData/changed",Ww="/kos/criticalData/available";let Lr=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_serialNumber");c(this,"_name");c(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 dd();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 ud();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()}};hd([H({topic:[Yw,Ww],websocket:!0})],Lr.prototype,"handleCriticalDataChanged",1);Lr=hd([R(fd)],Lr);const Fr=new Se({class:Lr,type:fd});var Qw=Object.getOwnPropertyDescriptor,Zw=(t,e,s,r)=>{for(var o=r>1?void 0:r?Qw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const pd="network-interface-model";let Vo=class{constructor(t,e,s){c(this,"id");c(this,"name");c(this,"type");c(this,"nmdevicestate");c(this,"hwaddress");c(this,"mtu");c(this,"configured");c(this,"wifi");c(this,"ethernet");c(this,"ip4settings");c(this,"category");c(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}`)}};Vo=Zw([R(pd)],Vo);const ui=new ye({class:Vo,type:pd}),{URL:Xw}=ae(),{getAll:Jw}=oe.build({basePath:`${Xw}/api/kos/network/interfaces`}),ha=m.createLogger({name:"network-interface-service",group:"Services"}),gd=async()=>{ha.debug("sending GET for copy-logs");try{const t=await Jw({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof ge)return ha.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},eE=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:gd},Symbol.toStringTag,{value:"Module"}));var tE=Object.defineProperty,sE=Object.getOwnPropertyDescriptor,md=(t,e,s,r)=>{for(var o=r>1?void 0:r?sE(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&&tE(e,s,o),o};const yd="network-interface-container-model";let Nr=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await gd();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=ui.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};md([$e],Nr.prototype,"_models",2);Nr=md([R(yd)],Nr);const As=new Se({class:Nr,type:yd});As.addRelatedModel(ui);const{URL:rE}=ae(),{getAll:oE}=oe.build({basePath:`${rE}/api/kos/storage/devices`}),fa=m.createLogger({name:"storage-device-service",group:"Services"}),bd=async()=>{fa.debug("sending GET for storage-device");const t=await oE({});return!(t!=null&&t.data)||t.status!==200?(fa.error("Failed to retrieve storage-device data",t),[]):t.data},nE=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:bd},Symbol.toStringTag,{value:"Module"}));var iE=Object.getOwnPropertyDescriptor,aE=(t,e,s,r)=>{for(var o=r>1?void 0:r?iE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const vd="storage-device-model";let Go=class{constructor(t,e,s){c(this,"id");c(this,"mountDir");c(this,"removed");c(this,"vendor");c(this,"runTimeMs");c(this,"model");c(this,"nodeId");c(this,"local");c(this,"label");c(this,"syspath");c(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}`)}};Go=aE([Vr(),R(vd)],Go);const Ur=new ye({class:Go,type:vd});var lE=Object.defineProperty,cE=Object.getOwnPropertyDescriptor,di=(t,e,s,r)=>{for(var o=r>1?void 0:r?cE(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&&lE(e,s,o),o};const wd="storage-device-container-model",uE="/kos/storage";let Rs=class{constructor(t,e,s){c(this,"id");c(this,"logger");c(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=Ur.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await bd()).forEach(e=>{if(e.deviceType!=="disk"){const s={...e,kosParentId:this.id},r=Ur.instance(e.id).options(s).build();this.addModel(r)}})}};di([$e],Rs.prototype,"_models",2);di([H({topic:uE,websocket:!0})],Rs.prototype,"handleStorageAvailability",1);Rs=di([R(wd)],Rs);const Ft=new Se({class:Rs,type:wd});Ft.addRelatedModel(Ur);const{URL:hi}=ae(),{getAll:dE,postModel:hE}=oe.build({basePath:`${hi}/api/kos/update/available`}),pa=m.createLogger({name:"usb-update-service",group:"Services"}),Ed=async()=>{pa.debug("sending GET for usb-update");const t=await dE({urlOverride:`${hi}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(pa.error("Failed to retrieve usb-update data",t),[]):t.data},Md=async(t,e,s)=>{const r=await hE({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${hi}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},fE=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:Ed,installUpdate:Md},Symbol.toStringTag,{value:"Module"}));var pE=Object.defineProperty,gE=Object.getOwnPropertyDescriptor,Td=(t,e,s,r)=>{for(var o=r>1?void 0:r?gE(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&&pE(e,s,o),o};const Sd="usb-update-model";let jr=class{constructor(t,e,s){c(this,"id");c(this,"active");c(this,"blocked");c(this,"createTime");c(this,"deviceId");c(this,"manifestId");c(this,"notes");c(this,"futureHandler");c(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 Wr(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),Md(this.manifestId,this.deviceId,t)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};Td([bi()],jr.prototype,"install",1);jr=Td([R(Sd)],jr);const fi=new ye({class:jr,type:Sd});var mE=Object.defineProperty,yE=Object.getOwnPropertyDescriptor,co=(t,e,s,r)=>{for(var o=r>1?void 0:r?yE(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&&mE(e,s,o),o};const Id="usb-update-container-model";let Nt=class{constructor(t,e,s){c(this,"id");c(this,"disposer");c(this,"storageService");c(this,"_activeUpdate");c(this,"logger");c(this,"_models");this.id=t,this.logger=s.logger,this._models=new Ce({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await Ed();J(()=>{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=fi.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}`)}};co([jt({modelType:Ft.type})],Nt.prototype,"storageService",2);co([$e],Nt.prototype,"_models",2);co([Cl({dependencies:t=>[t.isUsbInserted]})],Nt.prototype,"usbInsertedEffect",1);Nt=co([R(Id)],Nt);const Ps=new Se({class:Nt,type:Id});Ps.addRelatedModel(fi);const bE=()=>({...{[Kt.type]:{class:Qc},[Ge.type]:{class:su,singleton:!0},...re.registration,...ut.registration,...Pt.registration,...Dr.registration,...Fe.registration,[ni.type]:{class:exports.WsEventModel,singleton:!0},...xs.registration,...ri.registration,...Er.registration}}),pi=bE(),vE={models:pi,preloadModels:[]},ga=!0,_d=t=>()=>{const e=pi;return Ul(Yo)(Ds).model(Pt).model(Ft).model(Ps).model(Fr).model(_r).model(Ts).model(Or).model(Vn).model(As).model(Lt).model(ai).model(fu).model(Kn,ga).model(zs).model(mu,ga),Object.keys(e).forEach(s=>{const r=e[s];Nl(Yo)(s,r)}),{preload:A.model.preloadModel(t),model:A.model.register(t),companion:A.companion.register(t),legacy:A.model.registerLegacyModel(t)}},Me={};Me.core={models:_d(Me)};Me.preload=A.model.preloadModel(Me);Me.model=A.model.register(Me);Me.companion=A.companion.register(Me);Me.legacy=A.model.registerLegacyModel(Me);const Yo=Me;class wE{registerTroubleRankMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleRank,e),this}registerTroubleRoleMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleRole,e),this}registerTroubleColorMapper(e){return $.propertyMapper.registerPropertyMapper(ve.TroubleColor,e),this}registerModelLoader(e,s){$.loader.registerLoader(e,s)}registerCanvasPatternLoader(e){$.loader.registerLoader(Lt.loader,e)}}const EE=async(t,e)=>{const s=Vn.instance(t).options({}).build(),r=e?`${e}-`:"";return await de(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:()=>{nt(s)}}},Od="kos:service:region",$d="regionId",ME=`${Od}-${$d}`,Cd=async t=>{const e=ut.factory(ME)({path:Od,attribute:$d});await de(e),e.updateProperty(t)};function TE(t){return Mn(t)}const ma=Bs(),SE=Object.freeze(Object.defineProperty({__proto__:null,api:ma,default:ma,kosServiceRequest:TE},Symbol.toStringTag,{value:"Module"}));function IE(t){return Mn(t)}const ya=Bs(),_E=Object.freeze(Object.defineProperty({__proto__:null,api:ya,default:ya,kosServiceRequest:IE},Symbol.toStringTag,{value:"Module"})),gi="/kos-timer-event",mi="/kos-timer-event/tick",yi="defaultTimerEnd",ls=m.createLogger({name:"timer-manager"}),OE=t=>t.updateProperty!==void 0;class Dd{constructor(e,s,r){c(this,"name");c(this,"timeout");c(this,"timer");c(this,"state","inactive");c(this,"decrementValue",1);c(this,"remainingTime");c(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,OE(s)&&W(()=>{m.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:yi}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){ls.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&&(ls.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;ls.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(ls.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){V(`${mi}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){V(gi,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const cs=new Map,vt=(t,e)=>{const s=cs.get(t);if(!s){ls.error(`Timer ${t} not found`);return}e(s)},xd={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(cs.has(t))return cs.get(t);const r=new Dd(t,e,s);return cs.set(t,r),r},getTimer(t){return cs.get(t)},clearTimer(t){vt(t,e=>e.pause())},restartTimer(t){vt(t,e=>e.restart())},resetTimer(t){vt(t,e=>e.reset())},addTimeoutAction(t,e){vt(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){vt(t,s=>s.removeTimeoutAction(e))},startTimer(t){vt(t,e=>e.start())}},Ad="kos:service:region:settings",Rd="timeZone",$E=`${Ad}-${Rd}`,Wo=async t=>{const e=ut.factory($E)({path:Ad,attribute:Rd});await de(e),e.updateProperty(t)},CE=t=>!t||!t.data;function bi(t={}){const{alias:e,namespace:s,abortController:r=!1,trackerPolicy:o="id"}=t;return(n,i,a)=>{n[hs]=n[hs]||{},e&&(n[gs]=n[gs]||new Map,n[gs].set(i,e));const l=a.value,u=async function(...d){const h=lt();m.debug(`Calling future service ${i} with tracker ${h}`);let f,p;r&&(f=new AbortController);const y=it.initiateFuture({tracker:h,id:Rn});s&&(y.namespace=s),m.debug(`waiting for future ${y.id} to be ready`),await de(y),m.debug(`future ${y.id} is ready`),J(()=>{m.debug(`Adding future ${y.id} to futureHandler`),this.futureHandler.addFuture(y,e)}),r&&f&&(p=W(()=>{(y.status==="CANCELLED"||y.endState===Ve.Canceled)&&(m.debug(`Future ${y.id} cancelled, aborting request`),f==null||f.abort())}),f.signal.addEventListener("abort",async()=>{if(y.status!=="CANCELLED"&&y.endState!==Ve.Canceled&&!y.endState){m.debug(`AbortController aborted, cancelling future ${y.id}`);try{await y.cancelFuture()}catch(E){m.error(`Failed to cancel future ${y.id}:`,E)}}},{once:!0}));const w=()=>{p&&(p(),p=void 0)};try{const E=[...d];if(r&&f){const U=E[E.length-1];U&&typeof U=="object"&&"aborted"in U?E[E.length-1]=f.signal:E.push(f.signal)}if(o==="context"){const U=E[E.length-1];if(En(U))U.$tracker=h;else{const O={[Gr]:!0,$tracker:h};E.push(O)}}else E.push(h);const S=await l.apply(this,E);m.debug(`received future response for ${h}`,S);const k=CE(S)?S:S==null?void 0:S.data;return k?(k.progress=1,m.debug("mapping future response to future model"),y.endState?m.debug(`future ${y.id} has already completed. Not updating the model`):Bn(k,y)):this.futureHandler.removeFuture(e),w(),k}catch(E){if(w(),r&&(f!=null&&f.signal.aborted)){const S=new Error("Operation cancelled");throw m.debug(`Operation ${i} was cancelled`),S}throw m.error(E),E}};n[hs][i]={handler:u}}}const DE=({path:t})=>(e,s)=>{e[F]=e[F]||{},e[F][s]={modelType:xs.type,id:`${xs.type}-${t}`,options:{path:t},lifecycle:x.INIT}};function xE(t){const{path:e,attribute:s}=t;return(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:ri.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:x.INIT}}}const It=m.createLogger({name:"services",group:"Services"}),AE=async(t,e)=>Pd(t,e,`${exports.BASE_URL}/api/server/login`),Pd=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()},RE=async t=>kd(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),kd=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()},PE=async(t,e)=>Ld(t,e,`${exports.BASE_URL}/api/server/resetPassword`),Ld=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{It.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(It.debug(`password reset returned status ${r.status}`),!r.ok){It.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()},kE=async(t,e,s)=>Fd(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),Fd=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{It.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(It.debug(`invitation accept returned status ${o.status}`),!o.ok){It.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 LE(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:l}=o,u=n;let d=0,h="PENDING",f=!0;const p=new Set;let y;return l&&typeof l=="object"&&(y=M.autorun(()=>{const w=l.progress||0,E=l.status||"PENDING",S=!l.endState;(w!==d||E!==h||S!==f)&&(d=w,h=E,f=S,p.forEach(k=>{try{k(d,h)}catch(U){console.warn("Progress callback error:",U)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(w=>{try{w(d,h)}catch(E){console.warn("Progress callback error:",E)}})),y&&y(),p.clear()}),u.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",p.forEach(w=>{try{w(d,h)}catch(E){console.warn("Progress callback error:",E)}}),y&&y()},u.getController=()=>i,u.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(u,"progress",{get:()=>d,enumerable:!0}),Object.defineProperty(u,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(u,"isRunning",{get:()=>f,enumerable:!0}),u.onProgressUpdate=w=>(p.add(w),w(d,h),()=>p.delete(w)),u}const FE=Je.keyframes`
|
|
146
146
|
0% {
|
|
147
147
|
left: -90px;
|
|
148
148
|
color: #eee;
|
|
@@ -154,13 +154,13 @@ ${u}topics:${e}
|
|
|
154
154
|
left: 90px;
|
|
155
155
|
color: #eee;
|
|
156
156
|
}
|
|
157
|
-
`,
|
|
157
|
+
`,NE=Je.css`
|
|
158
158
|
font-size: 100px;
|
|
159
159
|
margin-top: -80px;
|
|
160
160
|
position: relative;
|
|
161
|
-
animation: ${
|
|
161
|
+
animation: ${FE} ease-in-out infinite alternate;
|
|
162
162
|
animation-duration: 1.2s;
|
|
163
|
-
`,
|
|
163
|
+
`,UE=({children:t})=>Ea.createPortal(t,document.body);function Nd({message:t="Wait a moment while we load your app.",theme:e="light"}){return T.jsx(UE,{children:T.jsxs(jE,{theme:e,children:[t,T.jsx("div",{css:NE,children:"."})]})})}const jE=Jo.div`
|
|
164
164
|
padding-inline: 20px;
|
|
165
165
|
width: 100%;
|
|
166
166
|
height: 100vh;
|
|
@@ -174,31 +174,31 @@ ${u}topics:${e}
|
|
|
174
174
|
left: 0;
|
|
175
175
|
color: ${({theme:t})=>t==="light"?"black":"white"};
|
|
176
176
|
z-index: 10000;
|
|
177
|
-
`;class
|
|
177
|
+
`;class Ud extends g.Component{constructor(e){super(e),this.state={error:null,errorInfo:null}}componentDidCatch(e,s){this.setState({error:e,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||T.jsxs("div",{children:[T.jsx("h2",{children:"Something went wrong."}),T.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),T.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const BE={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},HE=({value:t=0,title:e,status:s="normal",subtitle:r})=>{const o=Je.css`
|
|
178
178
|
display: flex;
|
|
179
179
|
flex-direction: column;
|
|
180
|
-
`,n=
|
|
180
|
+
`,n=Je.css`
|
|
181
181
|
position: relative;
|
|
182
182
|
height: 18px;
|
|
183
183
|
width: 100%;
|
|
184
184
|
background-color: #ddd;
|
|
185
185
|
border-radius: 5px;
|
|
186
186
|
overflow: hidden;
|
|
187
|
-
`,i=
|
|
187
|
+
`,i=Je.css`
|
|
188
188
|
position: absolute;
|
|
189
189
|
top: 50%; /* position the top edge of the element at the middle of the parent */
|
|
190
190
|
left: 50%; /* position the left edge of the element at the middle of the parent */
|
|
191
191
|
z-index: 5;
|
|
192
192
|
transform: translate(-50%, -50%);
|
|
193
193
|
font-size: smaller;
|
|
194
|
-
`,a=
|
|
194
|
+
`,a=Je.css`
|
|
195
195
|
width: ${t}%;
|
|
196
196
|
height: 35px;
|
|
197
|
-
background-color: ${
|
|
197
|
+
background-color: ${BE[s]};
|
|
198
198
|
text-align: center;
|
|
199
199
|
line-height: 32px;
|
|
200
200
|
color: black;
|
|
201
|
-
`,l=
|
|
201
|
+
`,l=Je.css`
|
|
202
202
|
animation: indeterminateAnimation 1s infinite linear;
|
|
203
203
|
transform-origin: 0% 50%;
|
|
204
204
|
@keyframes indeterminateAnimation {
|
|
@@ -212,7 +212,7 @@ ${u}topics:${e}
|
|
|
212
212
|
transform: translateX(100%) scaleX(0.5);
|
|
213
213
|
}
|
|
214
214
|
}
|
|
215
|
-
`;return T.jsxs("div",{css:o,children:[T.jsxs("div",{css:n,children:[T.jsx("div",{css:i,children:e}),T.jsx("div",{css:[a,t<0?l:""]})]}),T.jsx("div",{children:r})]})},
|
|
215
|
+
`;return T.jsxs("div",{css:o,children:[T.jsxs("div",{css:n,children:[T.jsx("div",{css:i,children:e}),T.jsx("div",{css:[a,t<0?l:""]})]}),T.jsx("div",{children:r})]})},KE={setModel:()=>!1},uo=g.createContext(KE),qE=()=>{const t=g.useContext(uo);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},jd=({children:t})=>{const[e,s]=g.useState(),r=g.useCallback(o=>(s(o),!0),[s]);return T.jsx(uo.Provider,{value:{model:e,setModel:r},children:t})},Bd=m.createLogger({name:"kos-model-hierarchy-context"}),zE={models:[],addModel:()=>{Bd.debug("Default implementation being used. Do Nothing.")}},ho=g.createContext(zE),VE=({children:t})=>{const[e,s]=g.useState([]),r=g.useCallback(o=>{e.includes(o)||(Bd.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[e]);return T.jsx(ho.Provider,{value:{models:e,addModel:r},children:t})},GE=()=>!0,Hd=t=>{const e=g.useContext(ho);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||GE;return g.useMemo(()=>e.models.filter(s),[e.models,s])},YE=t=>Hd({filter:s=>{const r=_e(s.id);return(r==null?void 0:r.type)===t}})[0],WE=m.createLogger({name:"kos-model-loader"}),QE=()=>T.jsx("div",{}),Kd=({fallback:t,children:e,...s})=>T.jsx(jd,{children:T.jsx(Ud,{fallback:t,children:T.jsx(g.Suspense,{children:T.jsx(qd,{...s,children:e})})})}),qd=t=>{const[e,s]=g.useState(),[r,o]=g.useState(!1),{setModel:n}=g.useContext(uo),i=g.useContext(ho);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 WE.error(t.error),new Error(t.error);const a=t.loading||T.jsx(QE,{});return T.jsx(T.Fragment,{children:e&&r?t.children:a})},dr={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},zd=g.createContext(dr),ZE=({translations:t=dr,children:e})=>{const s={header:{...dr.header,...t.header},createModal:{...dr.createModal,...t.createModal}};return T.jsx(zd.Provider,{value:s,children:e})};function XE(t,e){const s=_.create(t,!1,e),r=s.whenReady().then(()=>s);return un(r)}const Vd=g.createContext(void 0),JE=(t={models:{},preloadModels:[]},e)=>{const s=XE(t,e),r=({children:o})=>{const n=s.read(),[i,a]=g.useState(n.isOnline);return g.useEffect(()=>{const l=W(()=>{a(n.isOnline)});return()=>{l()}},[n]),T.jsx(Vd.Provider,{value:{kosCore:n,online:i},children:o})};return{KosCoreContextProvider:en.observer(r)}},Gd=()=>{const t=g.useContext(Vd);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},eM=8,tM=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),tt=new Map;function sM(t,e){if(tt.has(t)){const s=tt.get(t);if(s.status==="finished"){const r=_.getInstance().modelManager.getModelById(t);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=e().then(()=>{tt.set(t,{status:"finished",key:t})},o=>{throw tt.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw tt.set(t,r),s}}function rM(t,e){return sM(t,e)}async function oM(t,e){const{modelId:s,factory:r,modelType:o,options:n,activate:i}=e;let a=0;await t.whenReady();let l;if(n){const d=typeof o=="string"?t.modelManager.getModelFactory(o):r;if(!d)throw Error("No Factory Specified. Cannot create a new instance");l=d.build(s,n)}const u=t.modelManager.getModelById(s);if(!u){if(a>eM)throw Error(`KOS Model ${s} has not been found`);await tM(a),a=a+1}return await(u==null?void 0:u.whenReady()),u?(l=u.modelData,{kosModel:u,model:l}):{kosModel:void 0,model:void 0}}const X=t=>{const{modelId:e,modelType:s,activate:r,destroyOnUnmount:o}=t,n=Gd(),[i,a]=g.useState(!1),[l,u]=g.useState(),{kosModel:d,model:h}=rM(e||s||"",()=>oM(n.kosCore,t));return g.useEffect(()=>{t.forceUpdate&&h&&Sn(h)&&h.updateModel(t.options||{})},[h]),g.useEffect(()=>{async function f(){try{return await n.kosCore.whenReady(),r&&await(d==null?void 0:d.fsm.transitionTo(L.GO_ACTIVE,v.ACTIVE)),a(!0),d}catch(y){throw u(y.message),y}}let p;return n.kosCore&&e&&f().then(y=>{p=W(()=>{const w=(y==null?void 0:y.status)===v.READY;a(w)})}).catch(y=>{console.error(y)}),()=>{if(r){if(h!=null&&h.id){const y=n.kosCore.modelManager.getModelById(h.id);y==null||y.fsm.transitionTo(L.GO_INACTIVE,v.INACTIVE).then(()=>{if(o){const w=h.id;nt(h).then(()=>{tt.delete(w),p==null||p()})}})}}else o&&h&&nt(h).then(()=>{tt.delete(e),p==null||p()})}},[r,o,n.kosCore,d,h,e]),{model:h,ready:i,error:l,status:{model:h,ready:i,error:l},KosModelLoader:Kd}},vi=()=>{const t=Er.type;return X({modelId:t,modelType:Er.type,options:{}})},wi=g.createContext(void 0),nM=({children:t})=>{const{model:e,ready:s}=vi(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(wi.Provider,{value:r,children:t})},iM=()=>{const t=g.useContext(wi);if(!t)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return t},Ei=()=>{const t=Or.type;return X({modelId:t,modelType:Or.type,options:{}})};function aM(t){return()=>e=>{const{model:s,status:r,KosModelLoader:o}=Ei();return T.jsx(o,{...r,children:T.jsx(t,{...e,softwareInfo:s})})}}const Mi=g.createContext(void 0),lM=({children:t})=>{const{model:e,ready:s}=Ei(),r=g.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(Mi.Provider,{value:r,children:t})},cM=()=>{const t=g.useContext(Mi);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Yd=new Ic,Wd=g.createContext(Yd);function uM({children:t}){return T.jsx(Wd.Provider,{value:Yd,children:t})}const Ti=g.createContext(void 0),dM=()=>{const t=window.location.origin,e=me();return(e==null?void 0:e.host)||t},hM=({children:t,appContext:e,locale:s="en",resolver:r,rootUrl:o,descriptorResolver:n})=>{const[i,a]=g.useState(!1),[l,u]=g.useState(),[d,h]=g.useState(),f=o||dM(),p=g.useMemo(()=>e??"app/system",[e]);g.useEffect(()=>{async function E(){const k=(Array.isArray(p)?p:[p]).map(z=>(n||Yu(z))()),I=(await Promise.allSettled(k)).map(z=>{if(z.status==="rejected"){m.warn("Failed to load localization descriptor",z.reason);return}return z.value}).filter(z=>!!z).reverse().reduce((z,j)=>{const Z=j.path;return Object.keys(j.namespaces).forEach(je=>{const Be=j.namespaces[je];Be.basePath=Z}),{...z,namespaces:{...z.namespaces,...j.namespaces}}},{});u(I)}E()},[p,n]),g.useEffect(()=>{async function E(){if(l){const S=f,{translations:k}=await Ju.init({lang:s,descriptor:l,defaultNamespace:"common",resolver:r,rootUrl:S});h(k),a(!0)}}E()},[s,l,r,f]);const y=g.useMemo(()=>i?{setLocale:E=>{d&&(d.currentLocale=E)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,d]),w=i?t:null;return T.jsx(Ti.Provider,{value:y,children:w})},fM=()=>{const t=g.useContext(Ti);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},pM=()=>{const t=Lt.type;return X({modelId:t,modelType:Lt.type,options:{}})};function gM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=pM();return T.jsx(o,{...r,children:T.jsx(t,{...e,canvasDispatcher:s})})}}const mM=(t,e,s)=>{const r=atob(t),o=new Uint8ClampedArray(e*s*4);for(let n=0,i=0;n<r.length&&i<o.length;n+=3,i+=4)o[i]=r.charCodeAt(n),o[i+1]=r.charCodeAt(n+1),o[i+2]=r.charCodeAt(n+2),o[i+3]=255;return o};function yM({ctx:t,format:e,dataString:s,width:r,height:o,pixelSize:n}){const i=mM(s,r,o),a=new ImageData(i,r,o),l=document.createElement("canvas");l.width=r,l.height=o;const u=l.getContext("2d");u==null||u.putImageData(a,0,0),t.imageSmoothingEnabled=!1,t.clearRect(0,0,r*n,o*n),t.drawImage(l,0,0,r*n,o*n)}const bM=m.createLogger({name:"canvas-streamer"});bM.debug("main-view component loaded");const Co=10,Qd=en.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),[l,u]=g.useState();g.useEffect(()=>{const h=t.addNamedEndpoint(n,{apiPath:i,fps:r,width:s,height:e,id:n});u(h)},[t]);const d=g.useCallback(h=>{if(a.current&&o){const f=a.current.getContext("2d");f&&yM({ctx:f,format:"base64",dataString:h,height:e,width:s,pixelSize:Co})}},[s,e,o]);return g.useEffect(()=>{l&&(l.onFrame=d,l.width=s,l.height=e,l.fps=r)},[l,d,s,e,r]),o&&Ea.createPortal(T.jsx(wM,{children:T.jsx(EM,{children:T.jsx("canvas",{ref:a,width:s*Co,height:e*Co,style:{border:"1px solid black"}})})}),document.body)}),vM=gM(Qd),wM=Jo.div`
|
|
216
216
|
display: flex;
|
|
217
217
|
flex-direction: column;
|
|
218
218
|
gap: 8px;
|
|
@@ -220,9 +220,9 @@ ${u}topics:${e}
|
|
|
220
220
|
width: 100%;
|
|
221
221
|
justify-content: space-between;
|
|
222
222
|
align-items: center;
|
|
223
|
-
`,
|
|
223
|
+
`,EM=Jo.div`
|
|
224
224
|
display: flex;
|
|
225
225
|
flex-direction: column;
|
|
226
226
|
align-items: center;
|
|
227
|
-
`,Yd=()=>{const t=Lr.type;return Z({modelId:t,modelType:Lr.type,options:{}})};function mM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Yd();return T.jsx(o,{...r,children:T.jsx(t,{...e,device:s})})}}function yM(t,e,s){const r=new Promise(o=>{_.getInstance().whenReady().then(()=>{const{model:n}=_.getInstance().modelManager.createModelInstance(t,e??t,s);return n.whenReady().then(()=>{o(n.modelData)})})});return cn(r)}function bM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=bi();return T.jsx(o,{...r,children:T.jsx(t,{...e,kosTime:s})})}}const Wd=()=>{const t=As.type;return Z({modelId:t,modelType:As.type,options:{}})};function vM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Wd();return T.jsx(o,{...r,children:T.jsx(t,{...e,networkInterfaceContainer:s})})}}const Qd=()=>{const t=Ir.type;return Z({modelId:t,modelType:Ir.type,options:{}})};function wM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Qd();return T.jsx(o,{...r,children:T.jsx(t,{...e,oTA:s})})}}function EM(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 MM(t){const e=g.useRef(null),s=t.onAlert;return EM(e,s),T.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const TM=t=>{var u;const{stateProp:e}=t,[s,r]=g.useState((u=t.stateProp)==null?void 0:u.value),[o,n]=g.useState(!1),[i,a]=g.useState(void 0);return g.useEffect(()=>{async function d(h){try{h&&(await de(h),n(!0))}catch(f){a(f.message)}}d(e)},[e]),g.useEffect(()=>{const d=W(()=>{e&&o&&r(e.value)});return()=>{d()}},[o,e]),[s,{ready:o,error:i}]},Zd=()=>{const[t,e]=g.useState(!1),[s,r]=g.useState([]),o=kt.type,n=Z({modelId:o,modelType:kt.type,options:{}});return g.useEffect(()=>{const i=W(()=>{var a,l;e(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((l=n.model)==null?void 0:l.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:t,devices:s}};function SM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Zd();return T.jsx(o,{...r,children:T.jsx(t,{...e,storageDeviceContainer:s})})}}const Co=m.createLogger({name:"use-timer"}),IM=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=$d.getTimer(t);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const u=C(pi,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===t&&(f===mi?e({name:h,action:f,remainingTime:p,timer:n}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:p,timer:n}))});return o&&n.start(),()=>{u.unsubscribe()}},[o,e,r,t,n]),g.useEffect(()=>{if(!n||!s)return;const u=`${gi}/${t}`,d=C(u,h=>{const{name:f,remainingTime:p}=h==null?void 0:h.body;f===t&&s({name:f,remainingTime:p,timer:n})});return()=>{d.unsubscribe()}},[s,t,n]);const i=g.useCallback(()=>{n?n.start():Co.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=g.useCallback(()=>{n?n.reset():Co.warn(`Timer with name ${t} does not exist.`)},[n,t]),l=g.useCallback(()=>{n?n.pause():Co.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:l}},_M=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},OM=t=>t instanceof RegExp,$M=t=>typeof t=="string",CM=(t,e,s)=>{if(t===""||e==="")return t;let r=e;OM(r)||(r=new RegExp("("+_M(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},Xd=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>$M(o)?CM(o,e,s):o)};function DM(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=Xd(s,n,(i,a)=>o.type==="br"?T.jsx("br",{}):g.cloneElement(o,{key:`${r}-${a}`},i))}),s}const xM=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}),l=DM(a,o||{});return T.jsx("span",{className:t.className,children:l})},vt=new Map;function AM(t,e){if(vt.has(t)){const s=vt.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{vt.set(t,{status:"finished",result:o})},o=>{throw vt.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw vt.set(t,r),s}}function Wo(t,e){return AM(t,e)}const PM=async()=>{const t=await Al(Fe.type);return await de(t.model),t.model},RM=async(t,e,s)=>{const r=t.resolveNamespace(e);await de(r);for(const o of s){const n=t.resolveNamespace(o);await de(n),vt.set(o,{status:"finished",result:n})}return r},kM=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=Wo(Fe.type,PM),i=s.join("__"),a=Wo(i,()=>RM(n,r,o)),l=g.useMemo(()=>({exists:d=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:g.useCallback((d,h)=>{const f=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(m.debug(`Translation model ${t} not ready for key: ${f}`),f)},[e==null?void 0:e.keyPrefix,t,a]),i18n:l}},Jd=()=>{const t=Fe.type;return Z({modelId:t,modelType:Fe.type,options:{}})};function LM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Jd();return T.jsx(o,{...r,children:T.jsx(t,{...e,translationContainer:s})})}}const FM=t=>Z({modelId:t,modelType:Ds.type}),Ti=()=>Z({modelId:At.type,modelType:At.type,options:{}}),NM=({troubleType:t,condition:e})=>{const{model:s}=Ti(),[r,o]=g.useState(!1),[n,i]=g.useState([]),a=g.useCallback(()=>{var l,u;return n.length>0&&((l=n[0])!=null&&l.resolvable)?(u=n[0])==null?void 0:u.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>W(()=>{const u=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],d=e?u.filter(e):u;o(d.length>0),i(d)}),[e,s,t]),[r,a,n.length>0?n[0]:void 0,n]};function UM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Ti();return T.jsx(o,{...r,children:T.jsx(t,{...e,troubleContainer:s})})}}const eh=()=>{const t=Rs.type,e=Z({modelId:t,modelType:Rs.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=g.useState(!1),[o,n]=g.useState(!1),[i,a]=g.useState([]);return g.useEffect(()=>{const l=W(()=>{var u,d,h;r(((u=e.model)==null?void 0:u.isUsbInserted)??!1),n(((d=e.model)==null?void 0:d.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{l()}},[e.model]),{...e,inserted:s,updateAvailable:o,updates:i}};function jM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=eh();return T.jsx(o,{...r,children:T.jsx(t,{...e,usbUpdateContainer:s})})}}const BM=({path:t,propKey:e})=>{const{status:s}=Z({modelType:Ts.type,modelId:t,options:{path:t}}),[r,o]=g.useState(!1),[n,i]=g.useState(),[a,l]=g.useState(""),[u,d]=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)?l(s.model.props[e]):d(`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];l(f||"")})},[n,e]),{config:n,ready:r,value:a,error:u,updateValue:h}},HM=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},th=({configProperty:t,optionsTransformer:e})=>{const[s,r]=g.useState(!1),[o,n]=g.useState(""),[i,a]=g.useReducer(HM,{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}),l=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&(t==null||t.updateProperty(d))},[t]);return g.useEffect(()=>{async function u(d){try{d&&(await de(d),r(!0))}catch(h){n(h.message)}}u(t)},[t]),g.useEffect(()=>{const u=W(()=>{if(t&&s){let d=[];e&&(d=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:d,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{u()}},[t,e,s]),{...i,configSelectProps:{onChange:l,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function KM(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 qM(t,e){return new Date(t,e,0).getDate()}function sh(t,e){const s=KM(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function rh(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function oh(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function nh(t,e=[2018,2028]){const s=oh(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function Si(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 zM({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),l=new Intl.DateTimeFormat(t,{month:o.month}).format(a),u=new Intl.DateTimeFormat(t,{year:o.year}).format(a),d=new Intl.DateTimeFormat(t,{day:o.day}).format(a);return n?n=="MMDDYY"?`${l} ${d} ${u}`:n==="DDMMYY"?`${d} ${l} ${u}`:n==="YYMMDD"?`${u} ${l} ${d}`:`${u} ${d} ${l}`:new Intl.DateTimeFormat(t,o).format(a)}function be(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function VM(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function ih(t,e,s){const r=be(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 us(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 ds(t,e){return new Date(t,e,0).getDate()}function ah(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 lh({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 l=Ii(n,r),u=ch(n,r,t),d=uh(i,t),h=dh(i,t),f=_i(e,s),p=hh(e,s,t,o),y=gh(s,e,p),w=fh(t,a);return{daysArray:f,monthsArray:d,yearsArray:l,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:y,dayNamesArray:w}}function Ii(t="long",e=[2018,2028]){return g.useMemo(()=>nh(t,e),[t,e])}function ch(t="long",e=[2018,2028],s="en-US"){const r=Ii(t,e);return g.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function uh(t,e="en-US"){return g.useMemo(()=>Si(t,e),[t,e])}function dh(t,e="en-US"){const s=g.useMemo(()=>rh(),[]),r=g.useMemo(()=>Si(t,e),[t,e]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function _i(t,e){const s=be(t);return g.useMemo(()=>sh(s,e),[e,s])}const GM=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function hh(t,e,s="en-US",r=[]){const o=_i(t,e);return g.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:GM(t,e,i,r)})),[r,s,e,o,t])}function fh(t="en-US",e="short"){return g.useMemo(()=>ah(t,e),[t,e])}function ph({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:je.format(n,r)}}function gh(t,e,s){return g.useMemo(()=>ih(t,e,s),[t,e,s])}var mh=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(mh||{});function YM({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:l=[2018,2028],daysOfWeekFilter:u=[]}={}}){const[d,h]=g.useState(e),[f,p]=g.useState(l),[y,w]=g.useState(s),[E,S]=g.useState(r);g.useEffect(()=>{h(e)},[e]),g.useEffect(()=>{w(s)},[s]),g.useEffect(()=>{S(r)},[r]);const{yearsArray:L,yearsOptionsArray:R,monthsArray:O,monthsOptionsArray:I,daysArray:K,daysOptionsArray:q,calendarDayArray:J,dayNamesArray:Gt}=lh({locale:t,year:d,yearRange:f,month:y,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:Yt}=ph({year:d,month:y,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:w,setDay:S,nextMonth:()=>{const se=y<11?be(d):be(d+1),le=y<11?y+1:0;if(!us(se,le,E)){const Ye=ds(se,le);S(Ye)}le===0&&h(se),w(le)},previousMonth:()=>{const se=be(y===0?d-1:d),le=y===0?11:y-1;if(!us(se,le,E)){const Ye=ds(se,le);S(Ye)}le===11&&h(se),w(le)},nextYear:()=>{const se=d<f[1]?d+1:f[0],le=be(se);if(us(le,y,E))h(se);else{const Ye=ds(be(d+1),y);S(Ye),h(se)}},previousYear:()=>{const se=d>f[0]?d-1:f[0],le=be(se);if(us(le,y,E))h(se);else{const Ye=ds(be(d-1),y);S(Ye),h(se)}}},dateState:{year:d,yearRange:f,month:y,day:E,yearsArray:L,yearsOptionsArray:R,monthsArray:O,monthsOptionsArray:I,daysArray:K,daysOptionsArray:q,calendarDayNames:Gt,calendarDayArray:J,formattedDate:Yt}}}function yh({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[o,n]=g.useState("Formatting Time..."),[i,a]=g.useState("Formatting Date..."),l=!!r.ignoreDateFormat,{model:u,ready:d}=Z({modelId:re.type,modelType:re.type,options:{}}),h=typeof t=="string"?je.parseISO(t):t;return g.useEffect(()=>{l?a(""):e?a(je.format(h,e)):d&&a(je.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[l,t,e,h,u,d]),g.useEffect(()=>{s?n(je.format(h,s)):d&&n(je.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[t,s,h,u,d]),{formattedDate:i,formattedTime:o}}const bh=({secondsFromMidnight:t=0})=>{const[e,s]=g.useState(0),[r,o]=g.useState(0),[n,i]=g.useState(0),[a,l]=g.useState(new Date),{formattedTime:u}=yh({date:a,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const d=Number(t),h=Math.floor(d/3600),f=Math.floor(d%3600/60),p=d%60;s(h),o(f),i(p);const y=new Date;y.setHours(0,0,0,0);const w=new Date(y.getTime()+d*1e3);l(new Date(w))},[t]),{hours:e,minutes:r,seconds:n,formattedTime:u,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},WM=({configProperty:t})=>{const{value:e}=th({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=bh({secondsFromMidnight:s}),l=g.useRef();return g.useEffect(()=>{const u=r*3600+o*60+n;return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{t&&t.updateProperty(u.toString())},100),()=>{l.current&&clearTimeout(l.current)}},[t,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function QM(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 ZM=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),XM=(t=ZM)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const l=W(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{l()}},[n,i,t]),g.useEffect(()=>{const l=W(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&o({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{l()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const a=g.useCallback(l=>{var d;let u="";typeof l=="string"?u=l:(d=l==null?void 0:l.target)!=null&&d.value&&(u=l.target.value),u&&(n==null||n.setSelectedDateFormat(u))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(l=>l.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}}},JM=t=>T.jsx("option",{title:t,value:t,children:t},t),vh="kos:service:region:settings",wh="timeZone",eT=`${vh}-${wh}`,tT=(t=JM)=>{const[e,s]=g.useState([]),[r,o]=g.useState(""),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=lt.factory(eT)({path:vh,attribute:wh});g.useEffect(()=>{const u=W(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&Yo(n==null?void 0:n.timeZones[0])});return()=>{u()}},[n,i,t]),g.useEffect(()=>{const u=W(()=>{o(a.value||"")});return()=>{u()}},[a.value]);const l=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&Yo(d)},[]);return{options:e,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:l,selectProps:{onChange:l,value:r,options:e}}},Eh="kos:service:region",Mh="regionId",sT=`${Eh}-${Mh}`,rT=t=>T.jsx("option",{title:t,value:t,children:t},t),Th=(t=rT)=>{const[e,s]=g.useState([]),[r,o]=g.useState("factory"),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}}),a=lt.factory(sT)({path:Eh,attribute:Mh});g.useEffect(()=>{const u=W(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{u()}},[n,i,t]),g.useEffect(()=>{const u=W(()=>{o(a.value||"factory")});return()=>{u()}},[a.value]);const l=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&_d(d)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:l,regionSelectProps:{onChange:l,value:r,options:e}}},oT=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),nT=(t=oT)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=Z({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const l=W(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{l()}},[n,i,t]),g.useEffect(()=>{const l=W(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&o({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{l()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const a=g.useCallback(l=>{var d;let u="";typeof l=="string"?u=l:(d=l==null?void 0:l.target)!=null&&d.value&&(u=l.target.value),u&&(n==null||n.setSelectedTimeFormat(u))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(l=>l.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}}},iT=(t,e)=>g.useMemo(()=>Dn(t),e),aT={config:{attributes:!0,childList:!0,subtree:!0}};function lT(t,e,s=aT){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){m.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const Sh={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}},Do=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function cT({onPressed:t,onRelease:e,intersectionStrategy:s=Sh}){const r=g.useRef(!1),o=kh.useGesture({onDragStart:l=>{Do.info("onDragStart",l.type),s.validateStart(l)&&(t&&t(),r.current=!0)},onDrag:l=>{Do.info("onDrag",l.type),r.current&&s.validateStop(l)&&(e&&e(),r.current=!1)},onDragEnd:l=>{Do.info("onDragEnd",l.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 Ih=()=>{const[t,e]=g.useState(!1),s=_.getInstance();return g.useEffect(()=>{const r=W(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function _h(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 Qo(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 Oh(t="en-US"){return g.useMemo(()=>["AM","PM"].map(e=>{const s=new Intl.DateTimeFormat(t,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(e==="AM"?0:12))[2].value;return{id:s,label:s}}),[t])}function $h({formatOptions:{hour12:t=!0,hour:e="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=_h(t,e),i=Qo(60,s),a=Qo(60,r),l=Oh(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:l}}function Ch(t,e){return je.format(t,e)}function Dh({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=g.useState(e),i=g.useCallback(w=>{n(E=>{const S=new Date(E);return S.setHours(Number(w)),S})},[]),a=g.useCallback(w=>{n(E=>{const S=new Date(E);return S.setMinutes(Number(w)),S})},[]),l=g.useCallback(w=>{n(E=>{const S=new Date(E);return S.setSeconds(Number(w)),S})},[]),u=g.useCallback(w=>{const E=new Date(w);n(E)},[]),d=Ch(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:y}=$h({formatOptions:t,locale:s});return{amPmOptions:y,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:l,setTime:u,time:new Date(o)}}const uT=t=>{const{regionModel:e}=Th(),s=g.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return Dh({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function dT(t){return e=>{const[s]=Ih();return s?T.jsx(kd,{message:"Wait a moment while your project reloads..."}):T.jsx(t,{...e})}}const ga=m.createLogger({name:"studio-properties-service",group:"Services"}),hT="/api/kos/studio/properties",xh=async t=>{if(ga.debug("sending GET for studio-properties"),!t)throw ga.error("connectionId is undefined"),new Error("connectionId is undefined");return await De.get(hT,{},{destinationAddress:t,timeout:500})},fT=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:xh},Symbol.toStringTag,{value:"Module"}));var pT=Object.getOwnPropertyDescriptor,gT=(t,e,s,r)=>{for(var o=r>1?void 0:r?pT(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Ah="studio-properties-model",mT="/kos/studio/properties",ma={"kos.studio.tool.legacy":1};let Zo=class{constructor(t,e,s){c(this,"id");c(this,"connectionId");c(this,"unsubscribe",null);c(this,"logger");c(this,"data");this.id=t,this.logger=s.logger,this.data=Ie(),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=It.getInstance().subscribeTopic({topic:mT,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await xh(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(ma);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??ma),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return Dn(()=>this.get(t))}};Zo=gT([P(Ah)],Zo);const yT=new ye({class:Zo,type:Ah});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:()=>Jo.observer});exports.AuthState=yc;exports.BrowserKosRouter=Tc;exports.BrowserRouter=Hn;exports.CanvasDispatcher=Rt;exports.CanvasDispatcherServices=Ew;exports.CanvasRenderer=ii;exports.CanvasStreamer=fM;exports.CanvasStreamerBase=Gd;exports.ChildModels=He;exports.CompanionParentModel=Ke;exports.ConfigBean=Ts;exports.ContainerAwareSetup=vn;exports.CoreExtensionManager=bE;exports.CoreModels=fi;exports.CreateModelTranslationsContext=Hd;exports.CreateModelTranslationsProvider=zE;exports.DateDisplayFormat=mh;exports.DateHelpers=Zh;exports.DependencyLifecycle=x;exports.DependencyModels=N;exports.DependencyResolutionPolicy=Be;exports.Device=Lr;exports.DeviceServices=Kw;exports.DomIntersectionStrategy=Sh;exports.EVENT_KOS_MODEL_READY=rn;exports.EVENT_TROUBLE_ADDED=Bm;exports.EVENT_TROUBLE_REMOVED=Hm;exports.EXTENSION_CANVAS_RENDERER=te;exports.EXTENSION_FEATURE_FLAG_RESOLVER=hl;exports.EXTENSION_TROUBLE_DATA_MAPPER=Tr;exports.EXTENSION_TROUBLE_MAPPER=zs;exports.ErrorBoundaryWithFallback=Ld;exports.EventBus=Uh;exports.EventBusFunctional=Bh;exports.EventBusState=Kh;exports.ExtensionManager=$;exports.FUTURE_CONTAINER_MODEL_TYPE=Zc;exports.FUTURE_MODEL_TYPE=Bc;exports.FUTURE_NOT_ASSIGNED=An;exports.FeatureFlagService=fl;exports.FetchError=ge;exports.FutureAliases=gs;exports.FutureContainerFactory=ze;exports.FutureContainerModel=Jc;exports.FutureContainerSetup=gn;exports.FutureEndState=qe;exports.FutureFactory=Bt;exports.FutureHandler=Yr;exports.FutureManager=ot;exports.FutureModel=Gc;exports.FutureService=hs;exports.HEADER_CACHE_CONTROL=Ma;exports.HEADER_CONTENT_TYPE=Ea;exports.HEADER_DESTINATION_ADDR=Ne;exports.HEADER_FOS_REQUEST_ID=Ta;exports.HEADER_METHOD=jr;exports.HEADER_ORDERED=tn;exports.HEADER_REQUEST_ID=ks;exports.HEADER_REQUEST_TYPE=Oe;exports.HEADER_RESPONSE_ID=Br;exports.HEADER_SOURCE_ADDR=wa;exports.HEADER_TOPIC=va;exports.HEADER_URL=Ft;exports.HEADER_WORK_TRACKER=sn;exports.HttpRouteHandlers=Pe;exports.KOS_EXECUTION_CONTEXT=Vr;exports.KOS_MODEL_ID=dr;exports.KeyValue=zn;exports.KeyValueServices=Ly;exports.Kos=ie;exports.KosConfigPropertySpec=lt;exports.KosContainerIndex=En;exports.KosContextBean=Ec;exports.KosContextManager=Y;exports.KosCore=_;exports.KosCoreModelPropertyMapper=ve;exports.KosDataContainer=Cn;exports.KosDependencyTypes=zf;exports.KosExpressionEvaluator=uu;exports.KosExtensionUtils=tf;exports.KosFeatureFlags=pl;exports.KosFetchMethods=Ol;exports.KosGlobalConfig=fn;exports.KosHttpRouteManager=In;exports.KosLog=m;exports.KosLogManager=fu;exports.KosLogManagerServices=Kb;exports.KosMockEvents=_a;exports.KosModel=pc;exports.KosModelCollectionProvider=jE;exports.KosModelContainer=Ce;exports.KosModelContext=co;exports.KosModelEvents=F;exports.KosModelFactory=ys;exports.KosModelLoader=jd;exports.KosModelLoaderDisplay=Bd;exports.KosModelManager=mc;exports.KosModelProvider=Fd;exports.KosModelRegistrationFactory=ye;exports.KosModelRegistry=Go;exports.KosModelState=v;exports.KosModelSymbol=pn;exports.KosModelVisitor=hm;exports.KosObservableData=Dl;exports.KosRegistration=Rm;exports.KosSingletonRegistration=km;exports.KosTime=wr;exports.KosTimeContext=vi;exports.KosTimeProvider=JE;exports.KosTimeServices=Qb;exports.KosTimer=Od;exports.KosToken=Mc;exports.KosTranslationProvider=iM;exports.KosTranslations=Qu;exports.KosWSTransportStatus=fc;exports.KosWsEvents=Ls;exports.LOADER_FEATURE_FLAG=pf;exports.LOGIN_HOST=Sa;exports.LOGIN_URL=Lh;exports.LoadingMessage=kd;exports.LogBlock=Cs;exports.LogBlockContainer=no;exports.LogConfig=ps;exports.LogStream=Es;exports.LogStreamContainer=qs;exports.LogStreamServices=av;exports.LoggerSetup=bn;exports.MODEL_DELETION_DELAY=gc;exports.MiddlewareChain=bc;exports.ModelEffects=tt;exports.ModelError=zl;exports.MultipleFutureContainerSetup=mn;exports.MultipleFutureHandler=$l;exports.NestedModelContext=uo;exports.NetworkInterface=ci;exports.NetworkInterfaceContainer=As;exports.NetworkInterfaceServices=Xw;exports.ObservableData=Ie;exports.OptionsRequired=Us;exports.Ota=Ir;exports.OutsideAlerter=MM;exports.PLUGIN_EXTENSION_NAME=sf;exports.PORT=Ia;exports.PROFILE_LOG_DEBUG=sl;exports.PROFILE_LOG_INFO=rl;exports.PROFILE_RELAX_STORE_VALIDATION=of;exports.PROFILE_TOOLS_PREVIEW=tl;exports.ParentModel=fs;exports.PluginExtensionManager=rf;exports.ProgressBar=LE;exports.ReferenceConfig=or;exports.RegionInfo=re;exports.RegionServices=Xm;exports.RegistrationManager=A;exports.Registry=yE;exports.ReplayStrategy=et;exports.ResponseRetention=ue;exports.STATUS=en;exports.ServiceFactory=oe;exports.ServiceRequestHandlers=st;exports.SingletonKosModelRegistrationFactory=Se;exports.SoftwareInfo=_r;exports.SoftwareInfoContext=Ei;exports.SoftwareInfoProvider=sM;exports.SoftwareInfoServices=Kv;exports.StateActionHandlers=yf;exports.StateBean=xs;exports.StateBeanServices=Yv;exports.StateEntryHandlers=Et;exports.StateExitHandlers=ms;exports.StateMachineSetup=Ns;exports.StateProp=si;exports.StatePropServices=ow;exports.StorageDevice=Nr;exports.StorageDeviceContainer=kt;exports.StorageDeviceServices=rE;exports.StudioProperties=yT;exports.StudioPropertiesServices=fT;exports.SubscriptionHandlers=ee;exports.TIMER_END=mi;exports.TIMER_EVENT=pi;exports.TOPIC_TIMER_TICK_EVENT=gi;exports.TimerManager=$d;exports.TokenContext=Vd;exports.TokenProvider=oM;exports.Topics=ws;exports.Trans=xM;exports.TransitionMap=ir;exports.Transitions=Tn;exports.Translation=Cr;exports.TranslationContainer=Fe;exports.TranslationContainerContext=Mi;exports.TranslationContext=pw;exports.TransportFactory=Lo;exports.Trouble=Ds;exports.TroubleAwareSetup=yn;exports.TroubleContainer=At;exports.TroubleServices=_v;exports.Troubles=pe;exports.UsbUpdate=hi;exports.UsbUpdateContainer=Rs;exports.UsbUpdateServices=dE;exports.WS_EVENT_TYPE=Zu;exports.WebSocketEvents=vs;exports.WebSocketTransport=It;exports.WsEventFactory=oi;exports.acceptOrgInvitation=Rd;exports.addDaysToDate=Ga;exports.addFuture=Kc;exports.addMonthsToDate=Va;exports.api=Yc;exports.applyMixins=zh;exports.arraysEqual=Vh;exports.buildConfigBeanModel=zm;exports.buildFuture=Bn;exports.buildFutureModel=zc;exports.cancelFuture=qc;exports.checkAppsStarted=Um;exports.checkWildcardPattern=Ul;exports.clearAllServiceResponses=$m;exports.clearPath=Om;exports.clearServiceResponse=_m;exports.convert=Fn;exports.convertFileSizeRaw=qh;exports.convertWithUnits=oy;exports.createBaseMessage=oc;exports.createBroadcastMessageResponse=lc;exports.createCancellablePromise=DE;exports.createClient=_n;exports.createFosBaseMessage=rc;exports.createHeaders=Jt;exports.createKosHtpMessageResponse=cc;exports.createKosMessage=ic;exports.createKosMessageResponse=uc;exports.createMessageBody=Ge;exports.createModelDependency=Yl;exports.createOptionKey=Uf;exports.createPropKey=at;exports.createReadableStream=es;exports.createStudioMessage=sc;exports.createStudioMessageRequest=nc;exports.createStudioMessageResponse=ac;exports.debounce=Ja;exports.del=Ml;exports.deleteFuture=Hc;exports.destroyKosModel=rt;exports.evaluateScopes=xc;exports.executeChildrenModelLifecycle=Zl;exports.executeDependentModelLifecycle=Xt;exports.executeListLifecycle=Ql;exports.fetchModel=yM;exports.findModel=cp;exports.findModels=Pl;exports.formatDate=Qa;exports.formatDateSince=za;exports.formatDateTime=Xa;exports.formatTime=Za;exports.get=El;exports.getAllKosCompanionModels=Rl;exports.getCalendarMonthArray=ih;exports.getConfigBean=Dc;exports.getDayStrings=ah;exports.getDays=qM;exports.getDaysArray=sh;exports.getDaysInMonth=hn;exports.getDependenciesByLifecycle=Wl;exports.getFormattedDate=zM;exports.getFormattedMonth=VM;exports.getFormattedMonthsArray=Si;exports.getFormattedYear=be;exports.getFormattedYearsArray=nh;exports.getFutures=Ey;exports.getHttpRouteHandlers=Tl;exports.getKosCompanionModel=up;exports.getKosLocalizationDescriptor=zu;exports.getKosMessageLogging=al;exports.getKosModel=Al;exports.getKosModelSync=_e;exports.getKosModelType=lp;exports.getKosSessionKey=wc;exports.getLastDayOfMonth=ds;exports.getLocalizationDescriptor=iw;exports.getLogLevel=il;exports.getLogMessageToStudio=ll;exports.getMessageBody=ko;exports.getMonthsArray=rh;exports.getObservableCompanions=dp;exports.getQueryParams=me;exports.getServiceResponse=Sm;exports.getStartedApps=jm;exports.getTranslations=qu;exports.getYearsArray=oh;exports.hasCachedResponse=Im;exports.hasDecimals=$c;exports.hasHttpRouteHandlers=fr;exports.hasKosProfile=xo;exports.hslStringToHex=ml;exports.hslToHex=gl;exports.httpDelete=Gf;exports.initKosProvider=GE;exports.initializeStateMachine=vl;exports.injectStateMachineSupport=bl;exports.isBoolean=Rn;exports.isKosCompanionTypeFactory=Bl;exports.isKosDataModel=bs;exports.isKosExecutionContext=wn;exports.isKosLoggingEnabled=lf;exports.isKosModel=Te;exports.isKosModelContainer=Sn;exports.isKosModelReady=pr;exports.isLeapYear=dn;exports.isLocalRefId=Dm;exports.isNumber=Wr;exports.isPrintable=Wp;exports.isTroubleAware=gw;exports.isValidDate=us;exports.kosAction=X;exports.kosAutoEffect=W;exports.kosChild=$e;exports.kosCompanion=Bf;exports.kosComputed=Dn;exports.kosConfigBean=Qr;exports.kosConfigProperty=py;exports.kosContainerAware=wl;exports.kosContext=Hf;exports.kosDependency=Nt;exports.kosEffect=_c;exports.kosFuture=yi;exports.kosFutureAware=Kf;exports.kosLogger=Yf;exports.kosLoggerAware=Il;exports.kosModel=P;exports.kosModelEffect=_l;exports.kosMultipleFutureAware=qf;exports.kosObservable=xn;exports.kosParentAware=zr;exports.kosReference=Wf;exports.kosServiceRequest=Qf;exports.kosStateBean=SE;exports.kosStateEntry=Jf;exports.kosStateExit=ep;exports.kosStateGuard=tp;exports.kosStateMachine=Xf;exports.kosStateProp=IE;exports.kosSubscribe=Ip;exports.kosTopicHandler=B;exports.kosTroubleAware=sp;exports.kosWhen=No;exports.login=xd;exports.mapConfigBeanModelToDto=kc;exports.mapDataToModel=Ao;exports.mapDtoToConfigBeanModel=Pc;exports.mapDtoToFutureModel=jn;exports.mapDtoToFutureOptions=Un;exports.mapUpdateDtoToConfigBeanModel=Rc;exports.modelEventTopicFactory=Hl;exports.modelFactory=Ut;exports.modelTypeEventTopicFactory=Kl;exports.modifyConfigBean=Cc;exports.modifyFuture=My;exports.pairedClientHeartbeat=mm;exports.parseWildcardSegment=Nl;exports.pipe=vc;exports.post=js;exports.preloadKosModel=pp;exports.processId=Qh;exports.processMiddleware=fm;exports.put=Vf;exports.registerCompanionModel=fp;exports.registerCoreModels=Td;exports.registerExtensionPoint=Fs;exports.registerHttpRoutes=lg;exports.registerKosModel=Ll;exports.registerLegacyModel=kl;exports.resetKosModel=ap;exports.resetPassword=Pd;exports.resolveBaseUrl=Jl;exports.resolveChild=Gl;exports.resolveContainerDeltas=Gh;exports.resolveItemListDeltas=Wh;exports.resolveKosCompanion=Po;exports.resolveKosContext=Pm;exports.resolveKosProfiles=nl;exports.resolveListDeltas=Yh;exports.resolveServiceUrl=ae;exports.resolveVariable=yl;exports.retryWithExponentialBackoff=bm;exports.sendAsyncIntent=Fm;exports.sendBroadcastMessage=_g;exports.sendIntent=Lm;exports.sendKosHttpMessageResponse=hc;exports.sendKosMessage=Tg;exports.sendKosMessageResponse=dc;exports.sendRequest=xm;exports.sendStudioMessage=Ig;exports.sendStudioMessageRequest=Sg;exports.startPasswordReset=Ad;exports.stringComponentInsert=Xd;exports.studioAcceptOrgInvitation=CE;exports.studioLogin=_E;exports.studioResetPassword=$E;exports.studioStartPasswordReset=OE;exports.subscribeStore=vE;exports.syncPublish=Am;exports.troubleByTypeReducer=Cl;exports.troubleDataFactory=Ru;exports.unloadKosModel=ip;exports.updateCompanionModelRegistration=gm;exports.updateModelRegistration=pm;exports.updateRegion=_d;exports.updateTimeZone=Yo;exports.useAmPmValues=Oh;exports.useCalendarDayArray=gh;exports.useConfigBean=BM;exports.useConfigProperty=th;exports.useContextModel=NE;exports.useContextModelHierarchy=Ud;exports.useDateArrays=lh;exports.useDateProps=YM;exports.useDateRelativeConfig=WM;exports.useDateRelativeData=bh;exports.useDayNames=fh;exports.useDayOptions=hh;exports.useDays=_i;exports.useDevice=Yd;exports.useFormattedDate=ph;exports.useFormattedTime=Ch;exports.useFunctionWarmup=QM;exports.useHourValues=_h;exports.useKosCore=qd;exports.useKosDateFormats=XM;exports.useKosModel=Z;exports.useKosRegions=Th;exports.useKosTime=bi;exports.useKosTimeContext=eM;exports.useKosTimeFormats=nT;exports.useKosTimeZones=tT;exports.useKosTranslation=kM;exports.useKosTranslationContext=aM;exports.useLocalComputed=iT;exports.useModelFromHierarchy=HE;exports.useMonths=uh;exports.useMonthsOptions=dh;exports.useMutationObserver=lT;exports.useNetworkInterfaceContainer=Wd;exports.useOta=Qd;exports.usePressGesture=cT;exports.useProjectReload=Ih;exports.useRegionTimeProps=uT;exports.useRegionalTimeDate=yh;exports.useSoftwareInfo=wi;exports.useSoftwareInfoContext=rM;exports.useStateProperty=TM;exports.useStorageDeviceContainer=Zd;exports.useSuspenseData=Wo;exports.useTimeOptions=$h;exports.useTimeProps=Dh;exports.useTimeValues=Qo;exports.useTimer=IM;exports.useTranslationContainer=Jd;exports.useTroubleContainerModel=Ti;exports.useTroubleModel=FM;exports.useTroublePresence=NM;exports.useUsbUpdateContainer=eh;exports.useYears=Ii;exports.useYearsOptions=ch;exports.uuid=it;exports.variableToHex=gf;exports.waitForAppToStart=Nm;exports.waitForAppsToStart=Ic;exports.waitForRequest=$n;exports.whenReady=de;exports.withDevice=mM;exports.withKosTime=bM;exports.withNetworkInterfaceContainer=vM;exports.withOta=wM;exports.withProjectReloading=dT;exports.withSoftwareInfo=tM;exports.withStorageDeviceContainer=SM;exports.withTranslationContainer=LM;exports.withTroubleContainer=UM;exports.withUsbUpdateContainer=jM;exports.wrapPromise=cn;
|
|
227
|
+
`,Zd=()=>{const t=Fr.type;return X({modelId:t,modelType:Fr.type,options:{}})};function MM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Zd();return T.jsx(o,{...r,children:T.jsx(t,{...e,device:s})})}}function TM(t,e,s){const r=new Promise(o=>{_.getInstance().whenReady().then(()=>{const{model:n}=_.getInstance().modelManager.createModelInstance(t,e??t,s);return n.whenReady().then(()=>{o(n.modelData)})})});return un(r)}function SM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=vi();return T.jsx(o,{...r,children:T.jsx(t,{...e,kosTime:s})})}}const Xd=()=>{const t=As.type;return X({modelId:t,modelType:As.type,options:{}})};function IM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Xd();return T.jsx(o,{...r,children:T.jsx(t,{...e,networkInterfaceContainer:s})})}}const Jd=()=>{const t=_r.type;return X({modelId:t,modelType:_r.type,options:{}})};function _M(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Jd();return T.jsx(o,{...r,children:T.jsx(t,{...e,oTA:s})})}}function OM(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 $M(t){const e=g.useRef(null),s=t.onAlert;return OM(e,s),T.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const CM=t=>{var u;const{stateProp:e}=t,[s,r]=g.useState((u=t.stateProp)==null?void 0:u.value),[o,n]=g.useState(!1),[i,a]=g.useState(void 0);return g.useEffect(()=>{async function d(h){try{h&&(await de(h),n(!0))}catch(f){a(f.message)}}d(e)},[e]),g.useEffect(()=>{const d=W(()=>{e&&o&&r(e.value)});return()=>{d()}},[o,e]),[s,{ready:o,error:i}]},eh=()=>{const[t,e]=g.useState(!1),[s,r]=g.useState([]),o=Ft.type,n=X({modelId:o,modelType:Ft.type,options:{}});return g.useEffect(()=>{const i=W(()=>{var a,l;e(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((l=n.model)==null?void 0:l.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:t,devices:s}};function DM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=eh();return T.jsx(o,{...r,children:T.jsx(t,{...e,storageDeviceContainer:s})})}}const Do=m.createLogger({name:"use-timer"}),xM=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=xd.getTimer(t);g.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const u=C(gi,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===t&&(f===yi?e({name:h,action:f,remainingTime:p,timer:n}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:p,timer:n}))});return o&&n.start(),()=>{u.unsubscribe()}},[o,e,r,t,n]),g.useEffect(()=>{if(!n||!s)return;const u=`${mi}/${t}`,d=C(u,h=>{const{name:f,remainingTime:p}=h==null?void 0:h.body;f===t&&s({name:f,remainingTime:p,timer:n})});return()=>{d.unsubscribe()}},[s,t,n]);const i=g.useCallback(()=>{n?n.start():Do.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=g.useCallback(()=>{n?n.reset():Do.warn(`Timer with name ${t} does not exist.`)},[n,t]),l=g.useCallback(()=>{n?n.pause():Do.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:l}},AM=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},RM=t=>t instanceof RegExp,PM=t=>typeof t=="string",kM=(t,e,s)=>{if(t===""||e==="")return t;let r=e;RM(r)||(r=new RegExp("("+AM(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},th=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>PM(o)?kM(o,e,s):o)};function LM(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=th(s,n,(i,a)=>o.type==="br"?T.jsx("br",{}):g.cloneElement(o,{key:`${r}-${a}`},i))}),s}const FM=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}),l=LM(a,o||{});return T.jsx("span",{className:t.className,children:l})},Et=new Map;function NM(t,e){if(Et.has(t)){const s=Et.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{Et.set(t,{status:"finished",result:o})},o=>{throw Et.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Et.set(t,r),s}}function Qo(t,e){return NM(t,e)}const UM=async()=>{const t=await kl(Fe.type);return await de(t.model),t.model},jM=async(t,e,s)=>{const r=t.resolveNamespace(e);await de(r);for(const o of s){const n=t.resolveNamespace(o);await de(n),Et.set(o,{status:"finished",result:n})}return r},BM=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=Qo(Fe.type,UM),i=s.join("__"),a=Qo(i,()=>jM(n,r,o)),l=g.useMemo(()=>({exists:d=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:g.useCallback((d,h)=>{const f=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(m.debug(`Translation model ${t} not ready for key: ${f}`),f)},[e==null?void 0:e.keyPrefix,t,a]),i18n:l}},sh=()=>{const t=Fe.type;return X({modelId:t,modelType:Fe.type,options:{}})};function HM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=sh();return T.jsx(o,{...r,children:T.jsx(t,{...e,translationContainer:s})})}}const KM=t=>X({modelId:t,modelType:Ds.type}),Si=()=>X({modelId:Pt.type,modelType:Pt.type,options:{}}),qM=({troubleType:t,condition:e})=>{const{model:s}=Si(),[r,o]=g.useState(!1),[n,i]=g.useState([]),a=g.useCallback(()=>{var l,u;return n.length>0&&((l=n[0])!=null&&l.resolvable)?(u=n[0])==null?void 0:u.resolve():Promise.resolve(void 0)},[n]);return g.useEffect(()=>W(()=>{const u=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],d=e?u.filter(e):u;o(d.length>0),i(d)}),[e,s,t]),[r,a,n.length>0?n[0]:void 0,n]};function zM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Si();return T.jsx(o,{...r,children:T.jsx(t,{...e,troubleContainer:s})})}}const rh=()=>{const t=Ps.type,e=X({modelId:t,modelType:Ps.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=g.useState(!1),[o,n]=g.useState(!1),[i,a]=g.useState([]);return g.useEffect(()=>{const l=W(()=>{var u,d,h;r(((u=e.model)==null?void 0:u.isUsbInserted)??!1),n(((d=e.model)==null?void 0:d.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{l()}},[e.model]),{...e,inserted:s,updateAvailable:o,updates:i}};function VM(t){return e=>{const{model:s,status:r,KosModelLoader:o}=rh();return T.jsx(o,{...r,children:T.jsx(t,{...e,usbUpdateContainer:s})})}}const GM=({path:t,propKey:e})=>{const{status:s}=X({modelType:Ts.type,modelId:t,options:{path:t}}),[r,o]=g.useState(!1),[n,i]=g.useState(),[a,l]=g.useState(""),[u,d]=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)?l(s.model.props[e]):d(`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];l(f||"")})},[n,e]),{config:n,ready:r,value:a,error:u,updateValue:h}},YM=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},oh=({configProperty:t,optionsTransformer:e})=>{const[s,r]=g.useState(!1),[o,n]=g.useState(""),[i,a]=g.useReducer(YM,{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}),l=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&(t==null||t.updateProperty(d))},[t]);return g.useEffect(()=>{async function u(d){try{d&&(await de(d),r(!0))}catch(h){n(h.message)}}u(t)},[t]),g.useEffect(()=>{const u=W(()=>{if(t&&s){let d=[];e&&(d=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:d,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{u()}},[t,e,s]),{...i,configSelectProps:{onChange:l,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function WM(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 QM(t,e){return new Date(t,e,0).getDate()}function nh(t,e){const s=WM(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function ih(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function ah(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function lh(t,e=[2018,2028]){const s=ah(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function Ii(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 ZM({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),l=new Intl.DateTimeFormat(t,{month:o.month}).format(a),u=new Intl.DateTimeFormat(t,{year:o.year}).format(a),d=new Intl.DateTimeFormat(t,{day:o.day}).format(a);return n?n=="MMDDYY"?`${l} ${d} ${u}`:n==="DDMMYY"?`${d} ${l} ${u}`:n==="YYMMDD"?`${u} ${l} ${d}`:`${u} ${d} ${l}`:new Intl.DateTimeFormat(t,o).format(a)}function be(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function XM(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function ch(t,e,s){const r=be(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 us(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 ds(t,e){return new Date(t,e,0).getDate()}function uh(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 dh({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 l=_i(n,r),u=hh(n,r,t),d=fh(i,t),h=ph(i,t),f=Oi(e,s),p=gh(e,s,t,o),y=bh(s,e,p),w=mh(t,a);return{daysArray:f,monthsArray:d,yearsArray:l,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:y,dayNamesArray:w}}function _i(t="long",e=[2018,2028]){return g.useMemo(()=>lh(t,e),[t,e])}function hh(t="long",e=[2018,2028],s="en-US"){const r=_i(t,e);return g.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function fh(t,e="en-US"){return g.useMemo(()=>Ii(t,e),[t,e])}function ph(t,e="en-US"){const s=g.useMemo(()=>ih(),[]),r=g.useMemo(()=>Ii(t,e),[t,e]);return g.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function Oi(t,e){const s=be(t);return g.useMemo(()=>nh(s,e),[e,s])}const JM=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function gh(t,e,s="en-US",r=[]){const o=Oi(t,e);return g.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:JM(t,e,i,r)})),[r,s,e,o,t])}function mh(t="en-US",e="short"){return g.useMemo(()=>uh(t,e),[t,e])}function yh({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:He.format(n,r)}}function bh(t,e,s){return g.useMemo(()=>ch(t,e,s),[t,e,s])}var vh=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(vh||{});function eT({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:l=[2018,2028],daysOfWeekFilter:u=[]}={}}){const[d,h]=g.useState(e),[f,p]=g.useState(l),[y,w]=g.useState(s),[E,S]=g.useState(r);g.useEffect(()=>{h(e)},[e]),g.useEffect(()=>{w(s)},[s]),g.useEffect(()=>{S(r)},[r]);const{yearsArray:k,yearsOptionsArray:U,monthsArray:O,monthsOptionsArray:I,daysArray:z,daysOptionsArray:j,calendarDayArray:Z,dayNamesArray:je}=dh({locale:t,year:d,yearRange:f,month:y,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:Be}=yh({year:d,month:y,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:w,setDay:S,nextMonth:()=>{const se=y<11?be(d):be(d+1),le=y<11?y+1:0;if(!us(se,le,E)){const Qe=ds(se,le);S(Qe)}le===0&&h(se),w(le)},previousMonth:()=>{const se=be(y===0?d-1:d),le=y===0?11:y-1;if(!us(se,le,E)){const Qe=ds(se,le);S(Qe)}le===11&&h(se),w(le)},nextYear:()=>{const se=d<f[1]?d+1:f[0],le=be(se);if(us(le,y,E))h(se);else{const Qe=ds(be(d+1),y);S(Qe),h(se)}},previousYear:()=>{const se=d>f[0]?d-1:f[0],le=be(se);if(us(le,y,E))h(se);else{const Qe=ds(be(d-1),y);S(Qe),h(se)}}},dateState:{year:d,yearRange:f,month:y,day:E,yearsArray:k,yearsOptionsArray:U,monthsArray:O,monthsOptionsArray:I,daysArray:z,daysOptionsArray:j,calendarDayNames:je,calendarDayArray:Z,formattedDate:Be}}}function wh({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[o,n]=g.useState("Formatting Time..."),[i,a]=g.useState("Formatting Date..."),l=!!r.ignoreDateFormat,{model:u,ready:d}=X({modelId:re.type,modelType:re.type,options:{}}),h=typeof t=="string"?He.parseISO(t):t;return g.useEffect(()=>{l?a(""):e?a(He.format(h,e)):d&&a(He.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[l,t,e,h,u,d]),g.useEffect(()=>{s?n(He.format(h,s)):d&&n(He.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[t,s,h,u,d]),{formattedDate:i,formattedTime:o}}const Eh=({secondsFromMidnight:t=0})=>{const[e,s]=g.useState(0),[r,o]=g.useState(0),[n,i]=g.useState(0),[a,l]=g.useState(new Date),{formattedTime:u}=wh({date:a,options:{ignoreDateFormat:!0}});return g.useEffect(()=>{const d=Number(t),h=Math.floor(d/3600),f=Math.floor(d%3600/60),p=d%60;s(h),o(f),i(p);const y=new Date;y.setHours(0,0,0,0);const w=new Date(y.getTime()+d*1e3);l(new Date(w))},[t]),{hours:e,minutes:r,seconds:n,formattedTime:u,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},tT=({configProperty:t})=>{const{value:e}=oh({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=Eh({secondsFromMidnight:s}),l=g.useRef();return g.useEffect(()=>{const u=r*3600+o*60+n;return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{t&&t.updateProperty(u.toString())},100),()=>{l.current&&clearTimeout(l.current)}},[t,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function sT(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 rT=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),oT=(t=rT)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=X({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const l=W(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{l()}},[n,i,t]),g.useEffect(()=>{const l=W(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&o({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{l()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const a=g.useCallback(l=>{var d;let u="";typeof l=="string"?u=l:(d=l==null?void 0:l.target)!=null&&d.value&&(u=l.target.value),u&&(n==null||n.setSelectedDateFormat(u))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(l=>l.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}}},nT=t=>T.jsx("option",{title:t,value:t,children:t},t),Mh="kos:service:region:settings",Th="timeZone",iT=`${Mh}-${Th}`,aT=(t=nT)=>{const[e,s]=g.useState([]),[r,o]=g.useState(""),{model:n,ready:i}=X({modelType:re.type,modelId:re.type,options:{}}),a=ut.factory(iT)({path:Mh,attribute:Th});g.useEffect(()=>{const u=W(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&Wo(n==null?void 0:n.timeZones[0])});return()=>{u()}},[n,i,t]),g.useEffect(()=>{const u=W(()=>{o(a.value||"")});return()=>{u()}},[a.value]);const l=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&Wo(d)},[]);return{options:e,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:l,selectProps:{onChange:l,value:r,options:e}}},Sh="kos:service:region",Ih="regionId",lT=`${Sh}-${Ih}`,cT=t=>T.jsx("option",{title:t,value:t,children:t},t),_h=(t=cT)=>{const[e,s]=g.useState([]),[r,o]=g.useState("factory"),{model:n,ready:i}=X({modelType:re.type,modelId:re.type,options:{}}),a=ut.factory(lT)({path:Sh,attribute:Ih});g.useEffect(()=>{const u=W(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{u()}},[n,i,t]),g.useEffect(()=>{const u=W(()=>{o(a.value||"factory")});return()=>{u()}},[a.value]);const l=g.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&Cd(d)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:l,regionSelectProps:{onChange:l,value:r,options:e}}},uT=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),dT=(t=uT)=>{const[e,s]=g.useState([]),[r,o]=g.useState(),{model:n,ready:i}=X({modelType:re.type,modelId:re.type,options:{}});g.useEffect(()=>{const l=W(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{l()}},[n,i,t]),g.useEffect(()=>{const l=W(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&o({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{l()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const a=g.useCallback(l=>{var d;let u="";typeof l=="string"?u=l:(d=l==null?void 0:l.target)!=null&&d.value&&(u=l.target.value),u&&(n==null||n.setSelectedTimeFormat(u))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(l=>l.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}}},hT=(t,e)=>g.useMemo(()=>xn(t),e),fT={config:{attributes:!0,childList:!0,subtree:!0}};function pT(t,e,s=fT){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){m.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const Oh={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}},xo=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function gT({onPressed:t,onRelease:e,intersectionStrategy:s=Oh}){const r=g.useRef(!1),o=Nh.useGesture({onDragStart:l=>{xo.info("onDragStart",l.type),s.validateStart(l)&&(t&&t(),r.current=!0)},onDrag:l=>{xo.info("onDrag",l.type),r.current&&s.validateStop(l)&&(e&&e(),r.current=!1)},onDragEnd:l=>{xo.info("onDragEnd",l.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 $h=()=>{const[t,e]=g.useState(!1),s=_.getInstance();return g.useEffect(()=>{const r=W(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function Ch(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 Zo(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 Dh(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 xh({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=Ch(t,e),i=Zo(60,s),a=Zo(60,r),l=Dh(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:l}}function Ah(t,e){return He.format(t,e)}function Rh({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=g.useState(e),i=g.useCallback(w=>{n(E=>{const S=new Date(E);return S.setHours(Number(w)),S})},[]),a=g.useCallback(w=>{n(E=>{const S=new Date(E);return S.setMinutes(Number(w)),S})},[]),l=g.useCallback(w=>{n(E=>{const S=new Date(E);return S.setSeconds(Number(w)),S})},[]),u=g.useCallback(w=>{const E=new Date(w);n(E)},[]),d=Ah(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:y}=xh({formatOptions:t,locale:s});return{amPmOptions:y,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:l,setTime:u,time:new Date(o)}}const mT=t=>{const{regionModel:e}=_h(),s=g.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return Rh({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function yT(t){return e=>{const[s]=$h();return s?T.jsx(Nd,{message:"Wait a moment while your project reloads..."}):T.jsx(t,{...e})}}const ba=m.createLogger({name:"studio-properties-service",group:"Services"}),bT="/api/kos/studio/properties",Ph=async t=>{if(ba.debug("sending GET for studio-properties"),!t)throw ba.error("connectionId is undefined"),new Error("connectionId is undefined");return await De.get(bT,{},{destinationAddress:t,timeout:500})},vT=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Ph},Symbol.toStringTag,{value:"Module"}));var wT=Object.getOwnPropertyDescriptor,ET=(t,e,s,r)=>{for(var o=r>1?void 0:r?wT(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const kh="studio-properties-model",MT="/kos/studio/properties",va={"kos.studio.tool.legacy":1};let Xo=class{constructor(t,e,s){c(this,"id");c(this,"connectionId");c(this,"unsubscribe",null);c(this,"logger");c(this,"data");this.id=t,this.logger=s.logger,this.data=Ie(),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=Ot.getInstance().subscribeTopic({topic:MT,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await Ph(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(va);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??va),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return xn(()=>this.get(t))}};Xo=ET([R(kh)],Xo);const TT=new ye({class:Xo,type:kh});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:()=>en.observer});exports.AuthState=wc;exports.BrowserKosRouter=_c;exports.BrowserRouter=Kn;exports.CanvasDispatcher=Lt;exports.CanvasDispatcherServices=Tw;exports.CanvasRenderer=ai;exports.CanvasStreamer=vM;exports.CanvasStreamerBase=Qd;exports.ChildModels=qe;exports.CompanionParentModel=ze;exports.ConfigBean=Ts;exports.ContainerAwareSetup=wn;exports.CoreExtensionManager=wE;exports.CoreModels=pi;exports.CreateModelTranslationsContext=zd;exports.CreateModelTranslationsProvider=ZE;exports.DateDisplayFormat=vh;exports.DateHelpers=ef;exports.DependencyLifecycle=x;exports.DependencyModels=F;exports.DependencyResolutionPolicy=Ke;exports.Device=Fr;exports.DeviceServices=zw;exports.DomIntersectionStrategy=Oh;exports.EVENT_KOS_MODEL_READY=on;exports.EVENT_TROUBLE_ADDED=Km;exports.EVENT_TROUBLE_REMOVED=qm;exports.EXTENSION_CANVAS_RENDERER=te;exports.EXTENSION_FEATURE_FLAG_RESOLVER=gl;exports.EXTENSION_TROUBLE_DATA_MAPPER=Sr;exports.EXTENSION_TROUBLE_MAPPER=Vs;exports.ErrorBoundaryWithFallback=Ud;exports.EventBus=Hh;exports.EventBusFunctional=qh;exports.EventBusState=Vh;exports.ExtensionManager=$;exports.FUTURE_CONTAINER_MODEL_TYPE=eu;exports.FUTURE_MODEL_TYPE=qc;exports.FUTURE_NOT_ASSIGNED=Rn;exports.FeatureFlagService=ml;exports.FetchError=ge;exports.FutureAliases=gs;exports.FutureContainerFactory=Ge;exports.FutureContainerModel=su;exports.FutureContainerSetup=mn;exports.FutureEndState=Ve;exports.FutureFactory=Kt;exports.FutureHandler=Wr;exports.FutureManager=it;exports.FutureModel=Qc;exports.FutureService=hs;exports.HEADER_CACHE_CONTROL=Ia;exports.HEADER_CONTENT_TYPE=Sa;exports.HEADER_DESTINATION_ADDR=Ne;exports.HEADER_FOS_REQUEST_ID=_a;exports.HEADER_METHOD=Br;exports.HEADER_ORDERED=sn;exports.HEADER_REQUEST_ID=ks;exports.HEADER_REQUEST_TYPE=Oe;exports.HEADER_RESPONSE_ID=Hr;exports.HEADER_SOURCE_ADDR=Ta;exports.HEADER_TOPIC=Ma;exports.HEADER_URL=Ut;exports.HEADER_WORK_TRACKER=rn;exports.HttpRouteHandlers=Re;exports.KOS_EXECUTION_CONTEXT=Gr;exports.KOS_MODEL_ID=hr;exports.KOS_SERVICE=SE;exports.KeyValue=Vn;exports.KeyValueServices=Ny;exports.Kos=ie;exports.KosConfigPropertySpec=ut;exports.KosContainerIndex=Tn;exports.KosContextBean=Sc;exports.KosContextManager=Y;exports.KosCore=_;exports.KosCoreModelPropertyMapper=ve;exports.KosDataContainer=Dn;exports.KosDependencyTypes=Yf;exports.KosExpressionEvaluator=fu;exports.KosExtensionUtils=of;exports.KosFeatureFlags=yl;exports.KosFetchMethods=Dl;exports.KosGlobalConfig=pn;exports.KosHttpRouteManager=On;exports.KosLog=m;exports.KosLogManager=mu;exports.KosLogManagerServices=zb;exports.KosMockEvents=Ca;exports.KosModel=yc;exports.KosModelCollectionProvider=VE;exports.KosModelContainer=Ce;exports.KosModelContext=uo;exports.KosModelEvents=L;exports.KosModelFactory=ys;exports.KosModelLoader=Kd;exports.KosModelLoaderDisplay=qd;exports.KosModelManager=vc;exports.KosModelProvider=jd;exports.KosModelRegistrationFactory=ye;exports.KosModelRegistry=Yo;exports.KosModelState=v;exports.KosModelSymbol=gn;exports.KosModelVisitor=pm;exports.KosObservableData=Rl;exports.KosRegistration=Lm;exports.KosSingletonRegistration=Fm;exports.KosTime=Er;exports.KosTimeContext=wi;exports.KosTimeProvider=nM;exports.KosTimeServices=Xb;exports.KosTimer=Dd;exports.KosToken=Ic;exports.KosTranslationProvider=hM;exports.KosTranslations=Ju;exports.KosWSTransportStatus=mc;exports.KosWsEvents=Ls;exports.LOADER_FEATURE_FLAG=yf;exports.LOGIN_HOST=Oa;exports.LOGIN_URL=Uh;exports.LoadingMessage=Nd;exports.LogBlock=Cs;exports.LogBlockContainer=io;exports.LogConfig=ps;exports.LogStream=Es;exports.LogStreamContainer=zs;exports.LogStreamServices=cv;exports.LoggerSetup=vn;exports.MODEL_DELETION_DELAY=bc;exports.MiddlewareChain=Ec;exports.ModelEffects=rt;exports.ModelError=Yl;exports.MultipleFutureContainerSetup=yn;exports.MultipleFutureHandler=xl;exports.NestedModelContext=ho;exports.NetworkInterface=ui;exports.NetworkInterfaceContainer=As;exports.NetworkInterfaceServices=eE;exports.ObservableData=Ie;exports.OptionsRequired=Us;exports.Ota=_r;exports.OutsideAlerter=$M;exports.PLUGIN_EXTENSION_NAME=nf;exports.PORT=$a;exports.PROFILE_LOG_DEBUG=nl;exports.PROFILE_LOG_INFO=il;exports.PROFILE_RELAX_STORE_VALIDATION=lf;exports.PROFILE_TOOLS_PREVIEW=ol;exports.ParentModel=fs;exports.PluginExtensionManager=af;exports.ProgressBar=HE;exports.ReferenceConfig=nr;exports.RegionInfo=re;exports.RegionServices=ey;exports.RegistrationManager=A;exports.Registry=vE;exports.ReplayStrategy=st;exports.ResponseRetention=ue;exports.STATUS=tn;exports.ServiceFactory=oe;exports.ServiceRequestHandlers=ot;exports.SingletonKosModelRegistrationFactory=Se;exports.SoftwareInfo=Or;exports.SoftwareInfoContext=Mi;exports.SoftwareInfoProvider=lM;exports.SoftwareInfoServices=zv;exports.StateActionHandlers=wf;exports.StateBean=xs;exports.StateBeanServices=Qv;exports.StateEntryHandlers=Tt;exports.StateExitHandlers=ms;exports.StateMachineSetup=Ns;exports.StateProp=ri;exports.StatePropServices=iw;exports.StorageDevice=Ur;exports.StorageDeviceContainer=Ft;exports.StorageDeviceServices=nE;exports.StudioProperties=TT;exports.StudioPropertiesServices=vT;exports.SubscriptionHandlers=ee;exports.TIMER_END=yi;exports.TIMER_EVENT=gi;exports.TOPIC_TIMER_TICK_EVENT=mi;exports.TimerManager=xd;exports.TokenContext=Wd;exports.TokenProvider=uM;exports.Topics=ws;exports.Trans=FM;exports.TransitionMap=ar;exports.Transitions=In;exports.Translation=Dr;exports.TranslationContainer=Fe;exports.TranslationContainerContext=Ti;exports.TranslationContext=mw;exports.TransportFactory=Fo;exports.Trouble=Ds;exports.TroubleAwareSetup=bn;exports.TroubleContainer=Pt;exports.TroubleServices=$v;exports.Troubles=pe;exports.UsbUpdate=fi;exports.UsbUpdateContainer=Ps;exports.UsbUpdateServices=fE;exports.VFS_SERVICE=_E;exports.WS_EVENT_TYPE=ed;exports.WebSocketEvents=vs;exports.WebSocketTransport=Ot;exports.WsEventFactory=ni;exports.acceptOrgInvitation=Fd;exports.addDaysToDate=Qa;exports.addFuture=Vc;exports.addMonthsToDate=Wa;exports.api=Zc;exports.applyMixins=Yh;exports.arraysEqual=Wh;exports.buildConfigBeanModel=Gm;exports.buildFuture=Hn;exports.buildFutureModel=Yc;exports.cancelFuture=Gc;exports.checkAppsStarted=Bm;exports.checkWildcardPattern=Hl;exports.clearAllServiceResponses=Dm;exports.clearPath=Cm;exports.clearServiceResponse=$m;exports.convert=Nn;exports.convertFileSizeRaw=Gh;exports.convertWithUnits=iy;exports.createBaseMessage=ac;exports.createBroadcastMessageResponse=dc;exports.createCancellablePromise=LE;exports.createClient=Bs;exports.createFosBaseMessage=ic;exports.createHeaders=Jt;exports.createKosHtpMessageResponse=hc;exports.createKosMessage=cc;exports.createKosMessageResponse=fc;exports.createMessageBody=We;exports.createModelDependency=Zl;exports.createOptionKey=Hf;exports.createPropKey=ct;exports.createReadableStream=es;exports.createStudioMessage=nc;exports.createStudioMessageRequest=lc;exports.createStudioMessageResponse=uc;exports.debounce=sl;exports.del=Il;exports.deleteFuture=zc;exports.destroyKosModel=nt;exports.evaluateScopes=Pc;exports.executeChildrenModelLifecycle=ec;exports.executeDependentModelLifecycle=Xt;exports.executeListLifecycle=Jl;exports.fetchModel=TM;exports.findModel=dp;exports.findModels=Ll;exports.formatDate=Ja;exports.formatDateSince=Ya;exports.formatDateTime=tl;exports.formatTime=el;exports.get=Sl;exports.getAllKosCompanionModels=Fl;exports.getCalendarMonthArray=ch;exports.getConfigBean=Rc;exports.getDayStrings=uh;exports.getDays=QM;exports.getDaysArray=nh;exports.getDaysInMonth=fn;exports.getDependenciesByLifecycle=Xl;exports.getFormattedDate=ZM;exports.getFormattedMonth=XM;exports.getFormattedMonthsArray=Ii;exports.getFormattedYear=be;exports.getFormattedYearsArray=lh;exports.getFutures=Ty;exports.getHttpRouteHandlers=_l;exports.getKosCompanionModel=hp;exports.getKosLocalizationDescriptor=Yu;exports.getKosMessageLogging=ul;exports.getKosModel=kl;exports.getKosModelSync=_e;exports.getKosModelType=up;exports.getKosSessionKey=Tc;exports.getLastDayOfMonth=ds;exports.getLocalizationDescriptor=lw;exports.getLogLevel=cl;exports.getLogMessageToStudio=dl;exports.getMessageBody=Lo;exports.getMonthsArray=ih;exports.getObservableCompanions=fp;exports.getQueryParams=me;exports.getServiceResponse=_m;exports.getStartedApps=Hm;exports.getTranslations=Gu;exports.getYearsArray=ah;exports.hasCachedResponse=Om;exports.hasDecimals=xc;exports.hasHttpRouteHandlers=pr;exports.hasKosProfile=Ao;exports.hslStringToHex=vl;exports.hslToHex=bl;exports.httpDelete=Qf;exports.initKosProvider=JE;exports.initializeStateMachine=Ml;exports.injectStateMachineSupport=El;exports.isBoolean=kn;exports.isKosCompanionTypeFactory=ql;exports.isKosDataModel=bs;exports.isKosExecutionContext=En;exports.isKosLoggingEnabled=df;exports.isKosModel=Te;exports.isKosModelContainer=_n;exports.isKosModelReady=gr;exports.isLeapYear=hn;exports.isLocalRefId=Am;exports.isNumber=Qr;exports.isPrintable=Zp;exports.isTroubleAware=yw;exports.isValidDate=us;exports.kosAction=J;exports.kosAutoEffect=W;exports.kosChild=$e;exports.kosCompanion=qf;exports.kosComputed=xn;exports.kosConfigBean=Zr;exports.kosConfigProperty=my;exports.kosContainerAware=Tl;exports.kosContext=zf;exports.kosDependency=jt;exports.kosEffect=Cc;exports.kosFuture=bi;exports.kosFutureAware=Vf;exports.kosLogger=Zf;exports.kosLoggerAware=$l;exports.kosModel=R;exports.kosModelEffect=Cl;exports.kosMultipleFutureAware=Gf;exports.kosObservable=An;exports.kosParentAware=Vr;exports.kosReference=Xf;exports.kosServiceRequest=Mn;exports.kosStateBean=DE;exports.kosStateEntry=tp;exports.kosStateExit=sp;exports.kosStateGuard=rp;exports.kosStateMachine=ep;exports.kosStateProp=xE;exports.kosSubscribe=Op;exports.kosTopicHandler=H;exports.kosTroubleAware=op;exports.kosWhen=Uo;exports.login=Pd;exports.mapConfigBeanModelToDto=Nc;exports.mapDataToModel=Ro;exports.mapDtoToConfigBeanModel=Lc;exports.mapDtoToFutureModel=Bn;exports.mapDtoToFutureOptions=jn;exports.mapUpdateDtoToConfigBeanModel=Fc;exports.modelEventTopicFactory=zl;exports.modelFactory=Bt;exports.modelTypeEventTopicFactory=Vl;exports.modifyConfigBean=Ac;exports.modifyFuture=Sy;exports.pairedClientHeartbeat=bm;exports.parseWildcardSegment=Bl;exports.pipe=Mc;exports.post=js;exports.preloadKosModel=mp;exports.processId=Jh;exports.processMiddleware=gm;exports.put=Wf;exports.registerCompanionModel=gp;exports.registerCoreModels=_d;exports.registerExtensionPoint=Fs;exports.registerHttpRoutes=ug;exports.registerKosModel=Ul;exports.registerLegacyModel=Nl;exports.resetKosModel=cp;exports.resetPassword=Ld;exports.resolveBaseUrl=sc;exports.resolveChild=Ql;exports.resolveContainerDeltas=Qh;exports.resolveItemListDeltas=Xh;exports.resolveKosCompanion=Po;exports.resolveKosContext=km;exports.resolveKosProfiles=ll;exports.resolveListDeltas=Zh;exports.resolveServiceUrl=ae;exports.resolveVariable=wl;exports.retryWithExponentialBackoff=wm;exports.sendAsyncIntent=Um;exports.sendBroadcastMessage=$g;exports.sendIntent=Nm;exports.sendKosHttpMessageResponse=gc;exports.sendKosMessage=Ig;exports.sendKosMessageResponse=pc;exports.sendRequest=Rm;exports.sendStudioMessage=Og;exports.sendStudioMessageRequest=_g;exports.startPasswordReset=kd;exports.stringComponentInsert=th;exports.studioAcceptOrgInvitation=kE;exports.studioLogin=AE;exports.studioResetPassword=PE;exports.studioStartPasswordReset=RE;exports.subscribeStore=EE;exports.syncPublish=Pm;exports.troubleByTypeReducer=Al;exports.troubleDataFactory=Fu;exports.unloadKosModel=lp;exports.updateCompanionModelRegistration=ym;exports.updateModelRegistration=mm;exports.updateRegion=Cd;exports.updateTimeZone=Wo;exports.useAmPmValues=Dh;exports.useCalendarDayArray=bh;exports.useConfigBean=GM;exports.useConfigProperty=oh;exports.useContextModel=qE;exports.useContextModelHierarchy=Hd;exports.useDateArrays=dh;exports.useDateProps=eT;exports.useDateRelativeConfig=tT;exports.useDateRelativeData=Eh;exports.useDayNames=mh;exports.useDayOptions=gh;exports.useDays=Oi;exports.useDevice=Zd;exports.useFormattedDate=yh;exports.useFormattedTime=Ah;exports.useFunctionWarmup=sT;exports.useHourValues=Ch;exports.useKosCore=Gd;exports.useKosDateFormats=oT;exports.useKosModel=X;exports.useKosRegions=_h;exports.useKosTime=vi;exports.useKosTimeContext=iM;exports.useKosTimeFormats=dT;exports.useKosTimeZones=aT;exports.useKosTranslation=BM;exports.useKosTranslationContext=fM;exports.useLocalComputed=hT;exports.useModelFromHierarchy=YE;exports.useMonths=fh;exports.useMonthsOptions=ph;exports.useMutationObserver=pT;exports.useNetworkInterfaceContainer=Xd;exports.useOta=Jd;exports.usePressGesture=gT;exports.useProjectReload=$h;exports.useRegionTimeProps=mT;exports.useRegionalTimeDate=wh;exports.useSoftwareInfo=Ei;exports.useSoftwareInfoContext=cM;exports.useStateProperty=CM;exports.useStorageDeviceContainer=eh;exports.useSuspenseData=Qo;exports.useTimeOptions=xh;exports.useTimeProps=Rh;exports.useTimeValues=Zo;exports.useTimer=xM;exports.useTranslationContainer=sh;exports.useTroubleContainerModel=Si;exports.useTroubleModel=KM;exports.useTroublePresence=qM;exports.useUsbUpdateContainer=rh;exports.useYears=_i;exports.useYearsOptions=hh;exports.uuid=lt;exports.variableToHex=bf;exports.waitForAppToStart=jm;exports.waitForAppsToStart=$c;exports.waitForRequest=Cn;exports.whenReady=de;exports.withDevice=MM;exports.withKosTime=SM;exports.withNetworkInterfaceContainer=IM;exports.withOta=_M;exports.withProjectReloading=yT;exports.withSoftwareInfo=aM;exports.withStorageDeviceContainer=DM;exports.withTranslationContainer=HM;exports.withTroubleContainer=zM;exports.withUsbUpdateContainer=VM;exports.wrapPromise=un;
|
|
228
228
|
//# sourceMappingURL=index.cjs.map
|