@kosdev-code/kos-ui-sdk 2.0.42 → 2.0.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +1 -1
- package/index.cjs.map +1 -1
- package/index.js +4 -1
- package/index.js.map +1 -1
- package/models/models/config-bean-prop/config-bean-prop-model.d.ts.map +1 -1
- package/package.json +2 -2
package/index.cjs
CHANGED
|
@@ -74,7 +74,7 @@ cmd:${s}
|
|
|
74
74
|
${d}topics:${e}
|
|
75
75
|
`:`${d}type:kos.broker.${s}
|
|
76
76
|
|
|
77
|
-
["${e}"]`;if(r?(m=this.fosSocket)==null?void 0:m.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(v=E==null?void 0:E.socket)==null||v.send(u)}else{Ne.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(u)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=O(e,s);return Ne.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();Ne.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(nt,"_instance");class Xh{constructor(e){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=e,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(e){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of e)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(e,s)}async*processSingleEvent(e){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(e))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(e),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([e]):[e],this.updateProcessingStats([e])}}async*processBatchedEvents(e,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const d=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(d.length===0)return;this.config.backpressure&&await this.waitForCapacity();const u=this.config.transform?this.config.transform(d):d;return this.stats.batchesProcessed++,this.updateProcessingStats(d),u};try{for await(const d of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(d);this.eventQueue.length>0;){const u=this.dequeueEvent();u&&n.push(u);const g=Date.now()-i;if(n.length>=r||g>=o){const m=await a();m!==void 0&&(yield m);break}}else{n.push(d);const h=Date.now()-i;if(n.length>=r||h>=o){const g=await a();g!==void 0&&(yield g)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(e){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(e,s);return this.config.filter.historySize&&(this.filterHistory.push(e),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const e=Date.now(),s=Math.floor(e/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const e=Date.now(),o=(Math.floor(e/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-e;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=e;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-e;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(e){if(this.eventQueue.push(e),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const e=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,e}updateProcessingStats(e){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+e.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?e.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(e){return this.activePromises.add(e),e.finally(()=>this.activePromises.delete(e)),e}getStats(){return{...this.stats}}}class Jh{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(e){var o;const s=((o=this.modelData)==null?void 0:o[J])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.flow)this.subscribeWithFlowControl(i,c,a);else{const d=this.createHandler(c,i);this.subscribe(i,c,d,a===H.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=nt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=O(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(e,r,s);if(this.model.isReady()){const d=Gr(r,s.skipParse),u=s.transform(d);if(a&&s.condition(u,this.modelData,r))return this.callHandlerWithWildcard(s,u,c,r)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`);const d=()=>{const u=Gr(r,s.skipParse),h=s.transform(u);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)};this.offlineQueue.enqueue(d)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!da(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return la(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 Xh(e.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===H.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;nt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=$n(s)}else i=$n(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const o=e.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}}function We(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 ef(t){return!!(t!=null&&t[Ke])&&Object.keys(t[Ke]).length>0}function tf(t){return!!(t!=null&&t[J])&&Object.keys(t[J]).length>0}function sf(t){return!!(t!=null&&t[Ie])&&t[Ie].length>0}class rf{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=Fh.create({modelId:s,modelTypeName:r}),i=new Lh(e,We(n,"fsm")),a=new Nh(We(n,"offline-queue")),c=new Oh(e),d=new Sh(e),u={fsm:i,offlineQueue:a,companionManager:c,childResolver:d};if(ef(o)&&(u.effectManager=new $h(r,s,o,We(n,"effect"))),tf(o)){const h=We(n,"subscription");u.subscriptionManager=new Jh(e,o,s,a,h),u.onlineLifecycleManager=new Uh(e,We(n,"online"))}return sf(o)&&(u.httpRouteManager=new So(o,We(n,"http-routes"))),u}}const k=$.getLogger("kos-model"),of="kos.extension.model.loader";class ja{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=w.CREATED,this._activeStatus=w.INACTIVE,this._onlineStatus=w.OFFLINE;const o=rf.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),_h(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===w.ACTIVE}isOnline(){return this._onlineStatus===w.ONLINE}isReady(){return this._status===w.READY}async deactivate(){var e,s,r;k.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw k.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r;k.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await It(this,H.ACTIVATE);try{const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.activate)==null?void 0:s.call(e,o)),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(r=this.subscriptionManager)==null||r.registerAll(H.ACTIVATE),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw k.debug(`Model ${this.modelId} failed to activate`),o}}async whenLoaded(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{k.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{k.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===w.READY,onMatch:()=>{k.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r;if(this.fsm.current===w.READY){k.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{k.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await It(this,H.READY),await Ea(this,_o.READY,H.READY);const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.ready)==null?void 0:s.call(e,o)),this.offlineQueue.flush(),(r=this.subscriptionManager)==null||r.registerAll(H.READY),k.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};j(ua(this.modelTypeName,this.modelId),n),j(ha(this.modelTypeName),n)}catch(o){throw k.error(o),Error(o)}}async load(){var o,n,i,a,c;const e=this[Ls];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===w.LOADED||this.fsm.current===w.LOADING){k.debug(`Model ${s} with id ${r} already loaded or loading`);return}k.debug(`Loading model ${s} with id ${r}`),await It(this,H.LOAD);try{const d=z.getContext(r),u=`${of}.${s}`,h=await S.loader.executeLoader(u,{});h&&(k.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(u,h)),await((n=(o=this.modelData)==null?void 0:o.load)==null?void 0:n.call(o,d)),X(()=>{this.loaded=!0}),k.debug(`Model ${s} with id ${r} successfully loaded`),(i=this.subscriptionManager)==null||i.registerAll(H.LOAD),(a=this.httpRouteManager)==null||a.registerAll(),(c=this.effectManager)==null||c.setup()}catch(d){throw k.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,o,n,i;k.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const a=this.getChildren().map(d=>{var u;return(u=d.unload)==null?void 0:u.call(d)}).filter(d=>!!d);await Promise.allSettled(a);const c=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,c)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(o=this.effectManager)==null||o.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll(),(i=this.httpRouteManager)==null||i.dispose()}catch(a){throw k.debug(`Model ${this.modelId} failed to unload`),a}}async init(){var n,i,a;const e=this[Ls];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=z.getContext(s);k.debug(`Initializing model ${r} with id ${s}`),await It(this,H.INIT);try{await((i=(n=this.modelData)==null?void 0:n.init)==null?void 0:i.call(n,o)),this.initialized=!0,k.debug(`Model ${r} with id ${s} initialized`),(a=this.onlineLifecycleManager)==null||a.register(),this.registerSubscribers(H.INIT)}catch(c){throw k.error(`Model ${s} failed to initialize`,c),c}}async registerSubscribers(e){var s;k.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}async online(){var s,r;k.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=z.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e))}async offline(){var s,r,o;k.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=z.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 Ba=t=>typeof t=="function",Rn=p.createLogger({name:"kos-model-instantiator"});class nf{constructor(e,s){this.registry=e,this.cache=s}createModelInstance(e,s,r={}){const o=this.registry.models[e];if(!o)throw new Error(`No model registered for type ${e}`);const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Rn.debug(`Creating model instance: ${e} [${n}]`);const a=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),c=new ja({modelTypeName:e,id:n,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(n);if(!i)throw Rn.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}_createCompanionModels(e,s){var n;const r=e.modelTypeName,o=((n=this.registry.companionModels)==null?void 0:n[r])||[];for(const{type:i}of o){const a=Ba(i)?i(e.modelData,s):i;if(!a)continue;const c=`${a}-${e.modelId}`,d=this.createModelInstance(a,c,{data:s,companionParent:e.modelData,kosParentId:e.modelId});d!=null&&d.model&&(d.model[Ls]=e,e.addCompanionModel(d.model))}}}let af=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 yt(e)}};const Ka=10,An=p.createLogger({name:"kos-model-manager"});class Ha{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Xu,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 af(e),r.cache=new Ju(e.preloadModels),r.instantiator=new nf(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(An.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=>(An.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 yt(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(A.RESET,w.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),ra.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),Ka)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var Ds=(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))(Ds||{}),et=(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))(et||{});const cf=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=>$.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=>$.debug(n.machine.current)),online:s}},ae=async t=>{if(t.id){const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},He=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(t)},lf=async t=>{if(await I.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(A.UNLOAD,w.UNLOADED)},za=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(t),p.debug(`reload model initiated for model ${t.id}, model ready: ${Fs(t)} - ${Date.now()} `),await ae(t),p.debug(`reload model complete for model ${t.id}, model ready: ${Fs(t)} - ${Date.now()} `)},df=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},Ga=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},ve=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Va=(t,e)=>{if(!t)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},uf=(t,e)=>Va(t,e)[0],hf=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},Ya=t=>{if(!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},ff=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},Yr=(t,e)=>{const s=I.getInstance().modelManager.getModelById(t);if(!s){p.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},he=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,Fs=t=>{const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},gf=p.createLogger({name:"kos-model-factory"}),Kt={byModelType:t=>I.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=Kt.byModelType(e);if(!r)throw gf.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)}},te={Factory:{create:t=>e=>(s,r)=>(r&&z.setParentContext(e,r),Kt.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&z.setParentContext(t,s),Kt.getModelInstance(t,t,e))},Model:{instance:t=>e=>Kt.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const xn=window.KosRegistry.coreModels,Ar=window.KosRegistry.preloadModels,xr=window.KosRegistry.companionModels,ys=window.KosRegistry.models,C={model:{registerLegacyModel:t=>(e,s)=>(xn.set(e,s),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(Ar.includes(e)||Ar.push(e),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=Pr(e)?e.registration():e;return ys.set(r.type,r),Pr(e)&&e.relatedModels.forEach(o=>ys.set(o.type,o.registration())),I.getInstance().isReady&&(I.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),I.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],Pr(e)&&e.relatedModels.forEach(o=>I.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&C.model.preloadModel(t)(r.type),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},get:t=>ys.get(t),getAll:()=>Array.from(ys.entries()),getPreloadModels:()=>Ar,getLegacyModels:()=>Array.from(xn.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=xr.get(e)||[];return r.push(s),xr.set(e,r),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(xr.entries())}},qa=C.model.registerLegacyModel,Wa=C.model.register,pf=C.companion.register,mf=C.model.preloadModel,Qa=t=>typeof t.updateModel=="function",Pr=t=>t.registration!==void 0&&typeof t.registration=="function";class Za{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=he(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){C.model.register({})(this.registration()),this.registerRelatedModels()}}class we extends Za{constructor(e){super({...e,singleton:!1,factory:te.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=ve(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(Qa(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 Ee extends Za{constructor(e){super({...e,singleton:!0,factory:te.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=ve(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(Qa(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 Y=p.createLogger({name:"kos-core"}),yf=()=>{const t=ue(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},bf=()=>{const t=window.location.protocol,e=ue(),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://")},wf=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=ue(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},vf=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=ue(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},Mf=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?p.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):p.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},Pn=t=>typeof t.reload=="function",Ef=t=>typeof t.unload=="function";var Xa=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(Xa||{});class I{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=Ds.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),O("token",a=>{a&&(this.transport.token=a.body)}),O(pe.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(et.GO_ONLINE)}),O(pe.DISCONNECTED,async()=>{this.fsmService.service.send(et.GO_OFFLINE)}),O("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),O("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),O(pe.RELOAD,()=>{this.fsmService.service.send(et.RELOAD)}),O("/studio/project/reload",()=>{this.fsmService.service.send(et.RELOAD)});const s=nt.getInstance(),r=wf(),o=vf(),n=bf();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=yf()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=cf(this),this.fsmService.service.send(et.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){Y.info("reload already in progress");return}this._reloading=!0,Y.warn("reloading KOS Core"),Y.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Pn(c.modelData)&&(Y.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),Y.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Pn(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{Y.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Y.debug("KOS Core going online"),await this._transport.whenReady(),Y.debug("KOS Transport Ready. Calling online() for models"),j("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Y.debug("KOS Core going offline"),j("/kosCore/offline","/kosCore/offline")}async unload(){var o;Y.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Y.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Ef(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===Ds.READY)}async ready(){Y.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(e.map(o=>{const{promise:n,cancel:i}=Mf(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Y.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Y.debug("leaving kos-core ready() ")}get isReady(){return this.status===Ds.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Y.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Y.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Y.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Y.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:g[d];u&&(Array.isArray(u)?u.forEach(m=>{S.dataMapper.registerDataMapper(d,m)}):S.dataMapper.registerDataMapper(d,u))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:g[d];u&&S.propertyMapper.registerPropertyMapper(d,u)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:g[d];u&&S.loader.registerLoader(d,u)}),C.model.getAll().forEach(([,d])=>{e.models={...e.models,...d.registration}}),e.models={...e.models,...C.model.getLegacyModels()},C.companion.getAll().forEach(([d,u])=>{e.companionModels={...e.companionModels},e.companionModels[d]=e.companionModels[d]||[];for(const h of u)e.companionModels[d].push({type:h})}),C.model.getPreloadModels().forEach(d=>{e.preloadModels.includes(d)||e.preloadModels.push(d)});const n=Ha.create(e,s);return o.modelManager=n,o}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function qr(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 Tf(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 _f(t){return await t.arrayBuffer()}function If(t,e){return new Blob([t],{type:e})}async function Sf(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:qr(i)})}else e[o]=n.toString();return{fields:e,files:s}}function Of(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function $f(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:qr(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await _f(t);return{data:qr(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await Sf(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Ue=p.createLogger({name:"kos-fetch"}),Df=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Cf=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),Rf=t=>{if("timeout"in AbortSignal)return AbortSignal.timeout(t);const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException(`Request timed out after ${t}ms`,"TimeoutError"))},t),e.signal},Af=t=>{if("any"in AbortSignal)return AbortSignal.any(t);const e=new AbortController;for(const s of t){if(s.aborted)return e.abort(s.reason),e.signal;s.addEventListener("abort",()=>e.abort(s.reason),{once:!0})}return e.signal},xf=t=>t!=null&&t.studio?Sa:t!=null&&t.fos?Oa:$a,Pf=async(t,e)=>{const s=I.getInstance().transport;await s.whenReady();const r=pt(),o=new URL(t),n=`${o.pathname}${o.search}`;Ue.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||Df,a=xf(e),c=Rf(i),d=e!=null&&e.signal?Af([e.signal,c]):c,u=await $f(e==null?void 0:e.body),h={};u.contentType&&(h["content-type"]=u.contentType),u.encoding&&(h["content-encoding"]=u.encoding);const g=ke(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,...h}}),u.data);return new Promise((m,y)=>{let v=null;if(d.aborted){const x=d.reason;(x==null?void 0:x.name)==="TimeoutError"?Ue.error(`Timeout occurred - url: ${t}`):Ue.debug(`Request aborted - url: ${t}`),y(x||new DOMException("Aborted","AbortError"));return}const E=()=>{v&&v();const x=d.reason;(x==null?void 0:x.name)==="TimeoutError"?Ue.error(`Timeout occurred - url: ${t}`):Ue.debug(`Request aborted - url: ${t}`),y(x||new DOMException("Aborted","AbortError"))};d.addEventListener("abort",E,{once:!0});const _=O(r,x=>{d.removeEventListener("abort",E);const D=(x==null?void 0:x.headers)||{},P=D["content-type"]||"text/plain",W=D["content-encoding"],re=(x==null?void 0:x.body)||"";let L=re;if(W==="base64"&&re)try{L=Tf(re)}catch(V){Ue.error("Failed to decode base64 response",V)}const Ce={headers:Da(D),status:D.status&&parseInt(D.status)||200,ok:D.status==="200",json:async()=>{try{if(typeof L=="string")return L.length?JSON.parse(L):null;{const ce=new TextDecoder().decode(L);return ce.length?JSON.parse(ce):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof L=="string"?L:new TextDecoder().decode(L),arrayBuffer:async()=>L instanceof ArrayBuffer?L:new TextEncoder().encode(L).buffer,blob:async()=>L instanceof ArrayBuffer?If(L,P):new Blob([L],{type:P}),formData:async()=>{const V=new FormData;if(P==="multipart/form-data"&&typeof L=="string")try{const ce=JSON.parse(L);ce.fields&&Object.entries(ce.fields).forEach(([gs,Et])=>{V.append(gs,Et)}),ce.files&&Ue.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return V},body:e!=null&&e.stream?Of(async V=>{if(L instanceof ArrayBuffer)V.enqueue(new Uint8Array(L));else{const ce=new TextEncoder;V.enqueue(ce.encode(L))}V.close()}):Ca(typeof L=="string"?L:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};_.unsubscribe(),Cf().then(()=>m(Ce))});v=_.unsubscribe;const N=e!=null&&e.fos?s.fosSocket:s.socket;if(!N)throw Error(`No web socket transport available: ${e}`);N==null||N.send(g)})};exports.BASE_URL="kos:";exports.kosFetch=Pf;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const Lf=p.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class kf{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){Lf.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}const Ja=()=>({isMock:!1,URL:exports.BASE_URL}),bs=p.createLogger({name:"kos-service-request"}),Ln="errUnknown";async function ws(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((d,u)=>String(d).replace(`{${u}}`,r==null?void 0:r.path[u]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(d=>`${d}=${r.query[d]}`).join("&"):"",a=`${Ja().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;bs.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));try{const d=await exports.kosFetch(a,c);return d.status<200||d.status>=400?[`${d.statusText||Ln}`,null]:[null,(await d.json()).data]}catch(d){if(d instanceof DOMException){if(d.name==="TimeoutError")return bs.error(`Request timed out: ${a}`),["Request timed out",null];if(d.name==="AbortError")return bs.debug(`Request aborted: ${a}`),["Request aborted",null]}return bs.error(`Unexpected error during fetch: ${d}`),[d instanceof Error?d.message:Ln,null]}}function Oo(){return{get:(t,e,s)=>ws(t,"get",s,e),post:(t,e,s,r)=>ws(t,"post",r,e,s),put:(t,e,s,r)=>ws(t,"put",r,e,s),delete:(t,e,s,r)=>ws(t,"delete",r,e,s)}}class ec{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const Ff=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},yt=t=>({type:t,build:(e,s)=>I.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=I.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),Nf=t=>{I.getInstance().modelManager.registerModel(t)},Uf=(t,e)=>{I.getInstance().modelManager.registerCompanionModel(t,e)},tc=Symbol("KosObservableData");class sc{constructor(){l(this,"map");l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var o;return this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=M.observable.map(new Map)}setValue(e,s){this.map.set(e,s)}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}sc.prototype[tc]=!0;function jf(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const Ae=t=>{const e=jf(sc,t);return new e(t)},kn="/kos/ui/internal/heartbeat/",Bf=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${kn}${t}`,callback:()=>{a=performance.now()}}),d=r??3e3,u=window.setInterval(()=>{let v=performance.now()-a;v=v/1e3,v>d/1e3&&i.abort()},d),h=o??2e3,g=window.setInterval(()=>{Fa({msg:{},options:{topic:`${kn}${t}`,destinationAddress:e}})},h),m=()=>{window.clearInterval(g),window.clearInterval(u),c()},y=()=>{m(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:m}},rc=(...t)=>e=>t.reduce((s,r)=>r(s),e),Kf={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Hf(t,e){let s=1;const r={...Kf,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(p.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(d=>setTimeout(d,a)),s++;else throw c}throw new Error("All attempts failed")}const zf=p.createLogger({name:"kos-service-request"}),oe=t=>({isMock:!1,URL:exports.BASE_URL}),Gf=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g})=>{const m={method:"DELETE"};t&&(m.destinationAddress=t),o&&(m.tracker=o),bt(m,{ordered:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g});try{const y=await s(n||`${e}/${r}`,m);if(!y.ok)throw Error(`There was a problem deleting the model; returned status ${y.status}`);return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while deleting model");if(y.name==="AbortError")throw new B("Request was cancelled while deleting model")}throw y}},bt=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i,signal:a})=>(i&&(t.timeout=i),a&&(t.signal=a),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),Vf=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,signal:d,destinationAddress:u})=>{const h={method:"GET"};t&&(h.destinationAddress=t),bt(h,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,signal:d,destinationAddress:u});const g=r||e;try{const m=await s(g,h);if(!m.ok){let v;try{v=await m.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${m.status}`,v??void 0)}return await m.json()??void 0}catch(m){if(m instanceof DOMException){if(m.name==="TimeoutError")throw new B("Request timed out while retrieving models");if(m.name==="AbortError")throw new B("Request was cancelled while retrieving models")}throw m}},Yf=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:d,signal:u,destinationAddress:h})=>{const g={method:"GET"};t&&(g.destinationAddress=t),c&&(g.tracker=c),bt(g,{timeout:d,ordered:o,studio:n,fos:i,bridge:a,signal:u,destinationAddress:h});const m=r||e;zf.debug(`resolvedUrl: ${m}`);try{const y=await s(m,g);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while retrieving model");if(y.name==="AbortError")throw new B("Request was cancelled while retrieving model")}throw y}},qf=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:d,signal:u,destinationAddress:h})=>{const g={method:"GET"};t&&(g.destinationAddress=t),bt(g,{timeout:d,ordered:n,studio:i,fos:a,bridge:c,signal:u,destinationAddress:h});const m=r||`${e}/${o}`;try{const y=await s(m,g);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while retrieving model by ID");if(y.name==="AbortError")throw new B("Request was cancelled while retrieving model by ID")}throw y}};class B extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Fn=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g})=>{const m={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(m.destinationAddress=t),i&&(m.tracker=i),bt(m,{timeout:u,ordered:n,studio:a,fos:c,bridge:d,signal:h,destinationAddress:g});try{const y=await s(o||e,m);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem sending the POST data; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while adding model");if(y.name==="AbortError")throw new B("Request was cancelled while adding model")}throw y}},Nn=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:d,bridge:u,timeout:h,signal:g,destinationAddress:m})=>{const y={method:t};o&&(y.body=JSON.stringify(o)),e&&(y.destinationAddress=e),bt(y,{timeout:h,ordered:a,studio:c,fos:d,bridge:u,signal:g,destinationAddress:m});try{const v=await r(i||`${s}/${n}`,y);if(!v.ok){let _;try{_=await v.json()}catch{}throw new B(`There was a problem modifying the model; returned status ${v.status}`,_??void 0)}return await v.json()??void 0}catch(v){if(v instanceof DOMException){if(v.name==="TimeoutError")throw new B("Request timed out while modifying model");if(v.name==="AbortError")throw new B("Request was cancelled while modifying model")}throw v}},se={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:Vf(t,s||e,c),getModelById:qf(t,r||e,c),getOne:Yf(t,r||e,c),addModel:Fn(t,n||e,c),deleteModel:Gf(t,o||e,c),modifyModel:Nn("POST",t,i||e,c),putModel:Nn("PUT",t,i||e,c),postModel:Fn(t,n||e,c)}}},Wf=pt(),oc=()=>`kos-${Wf}`,Qf=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(oc()),$o=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=O(t,i=>{$.debug(`recieved response for refId ${t}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),Zf=async(t,e,s)=>{const r=$o(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)},Xf=async({topic:t,msg:e,requestId:s})=>{const r=s??pt(),o=$o(r);j(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},le=new Map;class nc{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){X(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=ve(this._parent))==null?void 0:e.model}get companionModels(){const e=ve(this._id);return e!=null&&e.model?Ya(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||!le.has(n.id)?!1:(i=le.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=le.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=le.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 z={createContext:(t,e)=>{const s=le.get(t)??new nc(t);if(e){if(!le.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return le.set(t,s),s},getContext:t=>le.get(t),deleteContext:t=>{le.delete(t)},setParentContext:(t,e)=>{var s;if(!le.has(e))throw new Error(`Parent context ${e} does not exist`);(s=le.get(t))==null||s.setParent(e)},rootContext:()=>le.get("root")};z.createContext("root");const Jf=t=>z.getContext(t.id);function eg(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class Do{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=Ae(),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(eg(n,i))p.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=e.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){M.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,e,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,e,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function tg(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>M.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const Tt=p.createLogger({name:"kos-container-model"});class Te{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?S.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const o=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=M.observable.map(o),this.idx=Ae(),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 Do({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&&z.setParentContext(e.id,this._parentId),s||this.increment();const r=this._disposerMap.get(e.id);r&&(r(),this._disposerMap.delete(e.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([u,h])=>[h,u])),a=u=>{var g,m;n.includes(u.name)&&((g=this.index.get(i.get(u.name)))==null||g.refresh());const h=o.filter(([,y])=>typeof y=="function");for(const[y]of h)(m=this.index.get(y))==null||m.refresh()},c=tg(e,a,n.filter(u=>typeof u=="string")),d=M.observe(e,a);this._disposerMap.set(e.id||"",()=>[d,...c].forEach(u=>u()))}removeModel(e,s){this._data.delete(e),s||this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Tt.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):(Tt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Tt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(e=>{const s=e.id;He(e).then(()=>{Tt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Tt.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const Lr=p.createLogger({name:"kos-data-container"});class Co{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=Ae(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Do({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??[]:(Lr.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):(Lr.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Lr.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 sg{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return te.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return he(this.type)}}class rg{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return te.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return he(this.type)}}class ic{constructor(){l(this,"_token");M.makeAutoObservable(this),O("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class ac{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:o})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===e&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===e&&o.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(e.path),i={...e,params:n,query:o};for(const c of this.routes){const d=this.matchRoute(c.path,r);if(c.method===e.method&&d){i.params=d;let u=0;const h=async()=>{if(u<c.middlewares.length){const g=c.middlewares[u++];await g(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 cc=p.createLogger({name:"intent-service"}),og=t=>{po(`/kos/intent/${t.type}`)?j(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):cc.info(`No subscribers for intent ${t.type}. Intent not sent.`)},ng=async t=>new Promise(e=>{const{type:s,options:r}=t;if(po(`/kos/intent/${t.type}`)){const o=pt(),{unsubscribe:n}=O(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);j(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else cc.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),_e=p.createLogger({name:"app-startup-service"});async function lc(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return _e.warn("No app IDs provided to waitForAppsToStart"),!0;_e.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await bo(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>cp),[d,u]=await c.get("/api/kos/apps/started");return d?(_e.error("Error fetching started apps:",d),[]):u}catch(c){_e.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(d=>{const u=c.find(h=>h.appId===d);return!(!u||!u.started||o&&!u.postStarted)}),timeout:s}),a=t.filter(c=>{const d=i.find(u=>u.appId===c);return!!(!d||!d.started||o&&!d.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(_e.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return _e.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(_e.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function ig(t,e={}){return lc([t],e)}async function ag(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];t.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){_e.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function cg(){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 _e.error("Failed to fetch started apps:",t),[]}}const Wr=M.when,Ro=M.computed,X=M.runInAction,G=M.autorun,dc=M.reaction,Ao=M.observable,xo="Not Assigned",lg="kos.trouble.added",dg="kos.trouble.removed";var me=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(me||{}),Ht=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Ht||{});const uc=p.createLogger({name:"config-bean-service",group:"Services"}),Po=exports.BASE_URL,hc=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:ug,getOne:hg}=se.build({destinationAddress:"",basePath:`${Po}/kos/config/`}),fc=async(t,e,s="/api/kos/config")=>(uc.debug(`sending modify request for ConfigBean: ${t}`),ug({model:e,urlOverride:`${Po}${s}/${t}`})),gc=async(t,e="/api/kos/config")=>(uc.debug(`sending get request for ConfigBean: ${t}`),await hg({urlOverride:`${Po}${e}/details/${t}/15`})),Lo=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",pr=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 mc(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])?mc(t[r],o,s):s[o]=t[r]}return s}const yc=(t,e)=>{const s=t.details[0].bean||pc(t.details[0].scopes),r=mc(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},bc=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&Lo(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&pr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},wc=t=>Object.fromEntries(t.props.entries),fg=t=>e=>s=>t.build(e,s);var gg=Object.defineProperty,pg=Object.getOwnPropertyDescriptor,vc=(t,e,s,r)=>{for(var o=r>1?void 0:r?pg(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&&gg(e,s,o),o};function mg(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const ko="config-bean-model",vs=p.getLogger(ko),yg=Ge("path");let Ns=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=fc,getConfigBean:r=gc}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Ae(),this.prevProps=Ae()}get values(){return this.props.values}async ready(){vs.debug(`readying config bean ${this.path}`),vs.debug(`complete readying config bean ${this.path}`)}async load(){vs.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;yc(e,this),vs.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=mg(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=wc(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){bc(t,this)}};vc([U({topic:`/kos/config/${yg}`,websocket:!0})],Ns.prototype,"handleConfigBeanUpdated",1);Ns=vc([R(ko)],Ns);const Yt=new we({class:Ns,type:ko}),mr=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Yt.type,id:`${Yt.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:H.INIT,lazy:e}},{URL:Mc}=oe(),{getOne:bg,getAll:wg}=se.build({basePath:`${Mc}/api/kos/regions/info`}),Ec=async()=>await bg({}),Tc=async()=>await wg({urlOverride:`${Mc}/api/kos/regions`}),vg=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Ec,getRegions:Tc},Symbol.toStringTag,{value:"Module"}));var ie=(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))(ie||{});const _c={s:["time",1,0,0],second:["time",1,0,0],m:["time",1/60,0,0],minute:["time",1/60,0,0],h:["time",1/3600,0,0],hour:["time",1/3600,0,0],day:["time",1/86400,0,0],week:["time",1/604800,0,0],month:["time",1/2628e3,0,0],year:["time",1/31536e3,0,0],default:["time",1/.001,0,0],ms:["time",1/.001,0,0],millisecond:["time",1/.001,0,0],microsecond:["time",1/1e-6,0,0],nanosecond:["time",1/1e-9,0,0],picosecond:["time",1/1e-12,0,0]};function Mg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{..._c});return{...t,...r}}function Eg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{..._c}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function Tg(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 _g=Object.defineProperty,Ig=Object.getOwnPropertyDescriptor,Fo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ig(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&_g(e,s,o),o};const Cs="region-info-model",_t=p.createLogger({name:"region-info-model"});let qt=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[ie.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[ie.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[ie.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[ie.family]!==s[ie.family])throw new Error(`Cannot convert between units of different families: ${e[ie.family]} and ${s[ie.family]}`);const r=e[ie.offset],o=e[ie.scale],n=s[ie.scale],i=s[ie.offset],a=s[ie.decimals];return((t-r)/(o/n)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,o)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];if(!i&&s.measure&&s.system){const d=this.measureMap[s.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=d[s.system])==null?void 0:a.default,i||_t.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const d=this.measureMap[e.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=d[e.system])==null?void 0:c.default,n||_t.info("Could not find default unit for measure",e.measure)}return!n||!i?(_t.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){_t.debug("initializing region info")}async load(){_t.debug("loading region info");const t=await Tc();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 Ec();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(Mg,{}),this.measureMap=e.data.unitSystems.reduce(Eg,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(Tg,{}),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))}};Fo([mr({path:"kos:service:region:settings"})],qt.prototype,"regionSource",2);Fo([mr({path:"kos:service:region"})],qt.prototype,"region",2);qt=Fo([R(Cs)],qt);const ee={registration:{[Cs]:{class:qt,singleton:!0}},type:Cs,factory:te.Singleton.create(Cs)},Us=({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},No=(t,e,s)=>{const{model:r}=ve(ee.type);if(!r)throw new Error("RegionInfo model not found");if(!Fs(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=Us({source:e}),i=Us({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Un(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 Sg=(t,e,s,r)=>{const o=No(t,e,s),n=Us({source:e}),{model:i}=ve(ee.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},d=Us({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),u=i.getDefaultUnitForMeasure(a,d.system),h=i.getDefaultUnitDecimalPlaces(a,d.system),g={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:u||n.unit||"",display:Un(o,u||n.unit||"",{...g,mode:"long"}),shortDisplay:Un(o,u||n.unit||"",{...g,mode:"short"})}};function jn({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 Bn({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 Qe=(t,e)=>s=>!t||!e?s:pr(s)?No(Number(s),t,e):s,Og=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return jn(t.options).map(Qe(s,r));if(t.options.type==="rangeInterval")return Bn(t.options).map(Qe(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(Qe(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return jn(t.options.unitSystems[e]).map(Qe(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Bn(t.options.unitSystems[e]).map(Qe(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(Qe(s,r))}}return[]},$g=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var Dg=Object.defineProperty,Cg=Object.getOwnPropertyDescriptor,Uo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cg(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&&Dg(e,s,o),o};function Rg(t){return(t==null?void 0:t.type)==="enum"}function Ag(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 xg(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return Re.format(r,e)}const Rs="config-bean-prop-model",Ze=p.createLogger({name:"config-bean-prop-model"}),Pg=Ge("path"),Lg=Ge("serviceBasePath");let Wt=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return hc(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?Ag(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=Rg(r)?r.values:Og(r,s,e==null?void 0:e.from,e==null?void 0:e.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,o=(t==null?void 0:t.system)||e,n=t==null?void 0:t.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),o=this.convertUnit(e.to,t,s);return{backend:r,display:o}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let d=String(t);return d=c.formatToParts(Number(t))[0].value,Number(d)}}catch(c){Ze.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,o)}return e||""}async activate(){Ze.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 xg(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){Ze.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var o;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??e;return $g(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,o;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=t==null?void 0:t.to)==null?void 0:o.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var n,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,d=this.formatter||c;if(d){let u=typeof d=="function"?d(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):d;s&&(u={unit:this.getDefaultUnit(t),...u},u.style==="unit"&&(u.maximumFractionDigits=u.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...u})}catch(h){Ze.error(`error creating formatter ${u}. Returning the raw value`,h)}}else Ze.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,d,u,h,g,m;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,v=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=y||v||E||e,N=((d=(c=this.converter)==null?void 0:c.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(_,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),x=((m=(g=this.converter)==null?void 0:g.to)==null?void 0:m.system)??this.regionInfo.getUnitSystem(N),D=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:D,...this.converter.from},to:{...this.converter.to,unit:N,system:x},measure:_}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),v=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:v===E?s:y}}}}async updateProperty(t){Ze.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)}};Uo([mt({modelType:ee.type})],Wt.prototype,"regionInfo",2);Uo([mr({path:Pg,serviceBasePath:Lg})],Wt.prototype,"bean",2);Wt=Uo([R(Rs)],Wt);const Ve={registration:{[Rs]:{class:Wt,singleton:!1}},type:Rs,factory:te.Factory.create(Rs)};function kg(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(d,u)=>{d[F]=d[F]||{},d[F][u]={modelType:Ve.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:H.INIT,lazy:n}}}class Fg{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=Ao.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=G(()=>{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){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=G(()=>{var r,o;(e.endState||e.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw p.error(e),e}}}const Ic="future-model",wt=yt(Ic),br=p.createLogger({name:"future-service",group:"Services"}),{isMock:Ng,URL:cs}=oe();var xe=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(xe||{});const{getAll:Ug,modifyModel:jg,addModel:Bg,deleteModel:Kg,postModel:Hg}=se.build({destinationAddress:"",basePath:`${cs}/api/future`,mock:Ng}),zg=async()=>await Ug({}),Sc=async(t,e="/api/kos/future")=>(br.info(`sending delete request for Future: ${t}`),await Kg({id:t,urlOverride:`${cs}${e}/${t}`})),Oc=async(t,e="/api/kos/future")=>(br.info("sending add request for Future"),await Bg({model:t,urlOverride:`${cs}${e}`})),Gg=async(t,e,s="/api/kos/future")=>(br.info(`sending modify request for Future: ${t}`),jg({model:e,id:t,urlOverride:`${cs}${s}/${t}`})),$c=async(t,e="/api/kos/future")=>(br.info(`sending cancel request for Future: ${t}`),Hg({urlOverride:`${cs}${e}/${t}/cancel`,ordered:!0,model:{}})),jo=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}),Bo=(t,e)=>{p.debug(`future dto ${t.id} end state ${t.endState}`),p.debug(`future model ${e.id} end state ${e.endState}`),e.endState?p.debug(`future model ${e.id} is already complete`):(p.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=jo(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]})})}))},Dc=t=>e=>s=>t.build(String(e),s),Ko=t=>e=>rc(jo,Dc(t)(e.tracker||e.id))(e);var Vg=Object.defineProperty,Yg=Object.getOwnPropertyDescriptor,Cc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Yg(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&&Vg(e,s,o),o};const kr=p.getLogger(wt.type);let js=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=$c,Wr(()=>this.status===xe.Success||this.status===xe.Fail,()=>{kr.info(`Future ${this.id} has completed with status ${this.status}`),He(this)})}async load(){kr.debug(`loading Future ${this.id}`)}unload(){kr.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Wr(()=>this.futureId!==xo),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[d,u]of Object.entries(e))if(Math.abs(t)>=u){s=d,r=Math.round(t/u);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),Bo(t,this)}};Cc([U({topic:`kos.future/${xs}`})],js.prototype,"handleFutureUpdated",1);js=Cc([R(wt.type)],js);const Rc=js,Ac=Oo();var qg=Object.defineProperty,Wg=Object.getOwnPropertyDescriptor,xc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Wg(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&&qg(e,s,o),o};const Pc="browser-router-model",Qg="kos.http.request",Zg="kos.http.response";let Bs=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new ac}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],o=e.headers.url,n=e.headers.method,i=e.headers["request-id"],a={id:i,method:n,path:o,body:t};let c=200;const d={send:u=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(u),Na({msg:u,options:{responseId:i,destinationAddress:s,type:Zg,sourceAddress:r,status:c}})},status:function(u){return c=u,this}};if(a.path==="/openapi.json"){d.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,d)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};xc([U({topic:Qg})],Bs.prototype,"handleRequest",1);Bs=xc([R(Pc)],Bs);const Ho=new Ee({class:Bs,type:Pc}),Lc="future-container-model",Pe=yt(Lc),kc=t=>Ko(wt)(t),Xg=t=>{const e=kc(t);return Pe.build(Pe.type,{}).addFutureModel(e),e},Jg=t=>Pe.build(Pe.type,{}).getFuture(String(t)),ze={buildFutureModel:kc,initiateFuture:Xg,getFuture:Jg};var ep=Object.defineProperty,tp=Object.getOwnPropertyDescriptor,zo=(t,e,s,r)=>{for(var o=r>1?void 0:r?tp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ep(e,s,o),o};const Ms=p.getLogger(Pe.type);let Qt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=Sc,addFuture:o=Oc}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new Te,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){Ms.error("error deleting a Future"),Ms.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Ko(wt)(s);return this.addFutureModel(r),r}}catch(e){throw Ms.error("error creating a Future"),Ms.error(e),e}}handleFutureUpdated(t,e){const s=ze.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),j(r,e.body,e.headers)}};zo([be],Qt.prototype,"_futures",2);zo([U({topic:"kos.future"})],Qt.prototype,"handleFutureUpdated",1);Qt=zo([R(Pe.type)],Qt);const Fc=Qt,{URL:ls}=oe(),{getOne:sp,postModel:rp,deleteModel:Nc}=se.build({basePath:`${ls}/api/keyVal`}),Qr=p.createLogger({name:"key-value-service",group:"Services"}),Uc=async(t,e)=>{await Nc({urlOverride:`${ls}/api/keyVal/${t}/${e}`,id:e})},jc=async(t,e,s)=>{const r=await rp({urlOverride:`${ls}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Qr.error("Failed to update studio-state data",r),new Error(`Failed to update studio-state data for namespace ${t}`);return r.data},Bc=async(t="studio")=>{Qr.debug("sending GET for studio-state");const e=await sp({urlOverride:`${ls}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Qr.error("Failed to retrieve studio-state data",e),new Error(`Failed to retrieve studio-state data for namespace ${t}`);return e.data},op=async t=>{await Nc({urlOverride:`${ls}/api/keyVal/${t}}`,id:""})},np=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Uc,deleteKeyValueNamespace:op,getKeyValue:Bc,updateKeyValue:jc},Symbol.toStringTag,{value:"Module"}));var ip=Object.defineProperty,ap=Object.getOwnPropertyDescriptor,Go=(t,e,s,r)=>{for(var o=r>1?void 0:r?ap(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ip(e,s,o),o};const Kc="key-value-model";let Zt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=Ae(),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 jc(this.namespace,t,e),this.data[t]=e):(await Uc(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await Bc(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)}};Go([U({topic:"/keyVal/set"})],Zt.prototype,"handleStateUpdate",1);Go([U({topic:"/keyVal/remove"})],Zt.prototype,"handleStateDelete",1);Zt=Go([R(Kc)],Zt);const Vo=new we({class:Zt,type:Kc}),De=Oo(),cp=Object.freeze(Object.defineProperty({__proto__:null,default:De},Symbol.toStringTag,{value:"Module"})),lp=p.createLogger({name:"kos-log-manager-service",group:"Services"}),dp="/api/kos/logs/overrides",Hc=async()=>(lp.debug("sending GET for kos-log-manager"),await De.get(dp)),up=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:Hc},Symbol.toStringTag,{value:"Module"}));var hp=Object.defineProperty,fp=Object.getOwnPropertyDescriptor,wr=(t,e,s,r)=>{for(var o=r>1?void 0:r?fp(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&&hp(e,s,o),o};const zc="kos-log-manager-model",gp="/kos/logs/override/add/*",pp="/kos/logs/override/remove/*",mp=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 it=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new Co}updateModel(t){}resolveLoggers(){const t=p.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:mp(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=p.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=p.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await Hc();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)})}};wr([na("/api/kos/ui/loggers")],it.prototype,"getAllLoggers",1);wr([U({topic:gp,websocket:!0,wildcardName:"nodeType"})],it.prototype,"handleOverrideAdded",1);wr([U({topic:pp,websocket:!0,wildcardName:"nodeType"})],it.prototype,"handleOverrideRemoved",1);it=wr([R(zc)],it);const Gc=new Ee({class:it,type:zc}),{URL:ds}=oe(),{postModel:Yo,getOne:yp}=se.build({basePath:`${ds}/api/kos-time`});p.createLogger({name:"kos-time-service",group:"Services"});const Vc=async t=>{const e=await Yo({model:t,urlOverride:`${ds}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Yc=async t=>{const e=await Yo({model:t,urlOverride:`${ds}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},qc=async t=>{const e=await Yo({model:{},urlOverride:`${ds}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},Wc=async()=>{const t=await yp({urlOverride:`${ds}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},bp=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Wc,setDate:Yc,setTime:Vc,setTimezone:qc},Symbol.toStringTag,{value:"Module"}));var wp=Object.defineProperty,vp=Object.getOwnPropertyDescriptor,vr=(t,e,s,r)=>{for(var o=r>1?void 0:r?vp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&wp(e,s,o),o};const St="kos-time-model",Mp="/kos/time/time",Ep="/kos/time/day",Tp="/kos/time/timezone";let at=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await Vc(t)}async updateSystemDate(t){await Yc(t)}async updateSystemTimezone(t){await qc(t)}handleTimeChange(){j(Ht.TIME_CHANGE,{})}handleDayChange(){j(Ht.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),j(Ht.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await Wc();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};vr([U({topic:Mp,websocket:!0})],at.prototype,"handleTimeChange",1);vr([U({topic:Ep,websocket:!0})],at.prototype,"handleDayChange",1);vr([U({topic:Tp,websocket:!0})],at.prototype,"handleTimeZoneChange",1);at=vr([R(St)],at);const Ks={registration:{[St]:{class:at,singleton:!0}},type:St,predicate:he(St),factory:te.Singleton.create(St)};var _p=Object.defineProperty,Ip=Object.getOwnPropertyDescriptor,Qc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ip(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&_p(e,s,o),o};const Zc="log-block-container-model";let Hs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({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}`)}};Qc([be],Hs.prototype,"_models",2);Hs=Qc([R(Zc)],Hs);const Sp=p.createLogger({name:"log-stream-container-service",group:"Services"}),Xc=()=>{var r;const t=ue(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return p.error(`getKosConnectionId: ${s}`),s},vt=Xc(),Op="/api/kos/logs/node/{nodeId}/streams",Jc=async()=>(Sp.debug("sending GET for log-stream-container"),await De.get(Op,{path:{nodeId:"primary"}},{destinationAddress:vt})),el=async(t,e="primary")=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:vt})},tl=async t=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:vt})},$p=async()=>{await De.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:vt})},sl=async t=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:vt}),rl=async(t,e)=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:vt}),Dp=Object.freeze(Object.defineProperty({__proto__:null,createOverride:$p,getKosConnectionId:Xc,getLogStreamBlock:rl,getLogStreamBlocks:sl,getLogStreams:Jc,subscribeToLogStream:el,unsubscribeFromLogStream:tl},Symbol.toStringTag,{value:"Module"}));var Cp=Object.getOwnPropertyDescriptor,Rp=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ol="log-block-model";let Zr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await rl(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}`)}};Zr=Rp([R(ol)],Zr);const Xt=new we({class:Zr,type:ol}),Mr=new we({class:Hs,type:Zc});Mr.addRelatedModel(Xt);var Ap=Object.defineProperty,xp=Object.getOwnPropertyDescriptor,nl=(t,e,s,r)=>{for(var o=r>1?void 0:r?xp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ap(e,s,o),o};const il="log-stream-model";let zs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"_blocks");l(this,"name");l(this,"currentBlockId");l(this,"isResetting");l(this,"generatorInstance");l(this,"shouldStop",!1);this.id=t,this.logger=s.logger,this.currentBlockId="",this.name=e.name,this.nodeId=e.nodeId,this.isResetting=!0,this._blocks=Mr.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=Xt.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=Xt.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 el(this.name)}async unsubscribe(){await tl(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 sl(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=dc(()=>{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()}}};nl([be],zs.prototype,"_blocks",2);zs=nl([R(il)],zs);const zt=new we({class:zs,type:il});var Pp=Object.defineProperty,Lp=Object.getOwnPropertyDescriptor,Ye=(t,e,s,r)=>{for(var o=r>1?void 0:r?Lp(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&&Pp(e,s,o),o};const al="log-stream-container-model",kp="/kos/logs/subscription/addBlock/*",Fp="/kos/logs/subscription/updateBlock/*",Np="/kos/logs/subscription/removeBlock/*",Up="/kos/logs/subscription/lines/*",cl="/kos/logs/streams/add/*";let Se=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({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: ${cl}`);const e=t.stream,s=zt.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=zt.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 Jc();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=zt.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};Ye([be],Se.prototype,"_models",2);Ye([U({topic:[cl],websocket:!0})],Se.prototype,"handleStreamAdded",1);Ye([U({topic:[kp],websocket:!0})],Se.prototype,"handleAddBlock",1);Ye([U({topic:[Np],websocket:!0})],Se.prototype,"handleRemoveBlock",1);Ye([U({topic:[Fp],websocket:!0})],Se.prototype,"handleUpdateBlock",1);Ye([U({topic:[Up],websocket:!0})],Se.prototype,"handleLogLine",1);Se=Ye([R(al)],Se);const us=new Ee({class:Se,type:al});us.addRelatedModel(zt);us.addRelatedModel(Mr);us.addRelatedModel(Xt);const jp=t=>t.rank!==void 0,Bp=t=>t.visibleRole!==void 0,Kp=t=>t.color!==void 0,Hp=t=>{const e=t.info;return jp(e)?e.rank:0},zp=t=>{const e=t.info;return Kp(e)?e.color:"orange"},Gp=t=>{const e=t.info;return Bp(e)?e.visibleRole:"TECHNICIAN"},{URL:qo}=oe(),{getAll:Vp,postModel:ll}=se.build({basePath:`${qo}/api/kos/troubles`}),dl=async()=>await Vp({}),ul=async(t,e)=>{try{const s=await ll({model:{},urlOverride:`${qo}/api/kos/troubles/resolve/${t}`,tracker:e});return s!=null&&s.data&&ze.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:xe.Fail,tracker:e,reason:"Failed to resolve trouble"};return ze.initiateFuture(r),r}},Yp=async(t,e)=>{try{const s=await ll({model:t,urlOverride:`${qo}/api/kos/troubles/resolve/`,tracker:e});return s!=null&&s.data&&ze.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:xe.Fail,tracker:e,reason:"Failed to resolve troubles"};return ze.initiateFuture(r),r}},qp=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Yp,getTroubles:dl,resolveTrouble:ul},Symbol.toStringTag,{value:"Module"})),Gs="troubleDataMapper",Es=new Map;is(Gs,{register:(t,e)=>{var s;Es.has(t)||Es.set(t,[]),(s=Es.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Es.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:p.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const hs="troubleMapper",Ts=new Map;is(hs,{register:(t,e)=>{var s;Ts.has(t)||Ts.set(t,[]),(s=Ts.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Ts.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(p.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});S[hs].register("nozzle",async t=>[t.data.nozzlePath]);S[hs].register("path",async t=>[t.data.path]);const Wp=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>S[hs].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},hl=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>S[Gs].execute(i,t)),r=S[Gs].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 Qp{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class Zp{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class Xe{static getHandler(e){switch(e){case"ResolvableTrouble":return new Qp;case"BlockPumpTrouble":return new Zp;default:return}}}var Xp=Object.defineProperty,Jp=Object.getOwnPropertyDescriptor,fl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Jp(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&&Xp(e,s,o),o};const Ot="trouble-model";function _s(t){return typeof t.shouldDefer=="boolean"}let Vs=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:d,createTime:u,role:h,color:g,...m},y){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=y.logger,this.type=c,this._troubleId=o,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=g,this.tags=s,this.info=r,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,m),this.futureHandler=new yr(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=Xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Xe.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=Xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Xe.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=Xe.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=Xe.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 hl(this)}get deferredCompanion(){const t=Yr(this.id,e=>_s(e));if(t&&_s(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Yr(this.id,e=>_s(e));return t&&_s(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 ul(this._troubleId,t)}};fl([hn()],Vs.prototype,"resolve",1);Vs=fl([R(Ot)],Vs);const Jt={registration:{[Ot]:{class:Vs,singleton:!1}},type:Ot,predicate:he(Ot),factory:te.Factory.create(Ot)};var em=Object.defineProperty,tm=Object.getOwnPropertyDescriptor,Er=(t,e,s,r)=>{for(var o=r>1?void 0:r?tm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&em(e,s,o),o};const Kn=p.createLogger({name:"trouble-container-model"});function Hn(t){return S.propertyMapper.hasMapper(me.TroubleRank)?S.propertyMapper.executeMapper(me.TroubleRank,t):Hp(t)}function zn(t){return(S.propertyMapper.hasMapper(me.TroubleColor)?S.propertyMapper.executeMapper(me.TroubleColor,t):zp(t)).toLowerCase()}function Gn(t){return(S.propertyMapper.hasMapper(me.TroubleRole)?S.propertyMapper.executeMapper(me.TroubleRole,t):Gp(t)).toLowerCase()}const sm="trouble-container-model";class de{}l(de,"INDEX_TROUBLES_BY_IFACE","byIface"),l(de,"INDEX_TROUBLES_BY_TYPE","byType"),l(de,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(de,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(de,"SORT_KEY_RANK","rank"),l(de,"TROUBLES_DEFERRED","true");let ct=class{constructor(t){l(this,"id");l(this,"troubles");this.id=t,this.troubles=new Te({indexMap:{[de.INDEX_TROUBLES_BY_IFACE]:Wp,[de.INDEX_TROUBLES_BY_TYPE]:"type",[de.INDEX_TROUBLES_BY_GROUP]:"group",[de.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:de.SORT_KEY_RANK,parentId:t})}async load(){Kn.debug("loading trouble container");const t=await dl();try{t==null||t.data.forEach(e=>{const s={...e,rank:Hn(e),color:zn(e),role:Gn(e),id:String(e.id)},r=Jt.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw Kn.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&He(s)}handleTroubleAdded(t){const e={...t,rank:Hn(t),color:zn(t),role:Gn(t),id:String(t.id)};if(e.role==="NONE")return;const s=Jt.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};Er([be],ct.prototype,"troubles",2);Er([U({topic:"/kos/trouble/remove",websocket:!0,lifecycle:H.INIT})],ct.prototype,"handleTroubleRemoved",1);Er([U({topic:"/kos/trouble/add",websocket:!0})],ct.prototype,"handleTroubleAdded",1);ct=Er([R(sm)],ct);const Is="trouble-container-model",lt={registration:{[Is]:{class:ct,singleton:!0}},type:Is,predicate:he(Is),factory:te.Singleton.create(Is)},{URL:gl}=oe(),{getAll:rm}=se.build({basePath:`${gl}/api/kos/ota`}),Vn=p.createLogger({name:"ota-service",group:"Services"}),om=async()=>{Vn.debug("sending GET request to /api/kos/ota/artifacts");const t=await rm({urlOverride:`${gl}/api/kos/ota/artifacts`});return Vn.debug("getArtifacts - response:",t),t==null?void 0:t.data};var nm=Object.defineProperty,im=Object.getOwnPropertyDescriptor,Tr=(t,e,s,r)=>{for(var o=r>1?void 0:r?im(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&&nm(e,s,o),o};const pl="ota-model",am=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Fr=t=>{const e=t.artifactInfo,s=am(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 dt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new Co);l(this,"troubleContainer");this.id=t,this.logger=s.logger}get downloadInProgressTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:e[0]}get updatePendingTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:e[0]}get pausedDueToErrorsTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:e[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var t;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(t=this.updatePendingTrouble)==null||t.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const t=await om();t&&t.forEach(e=>{const s=Fr(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=Fr(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=Fr(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};Tr([mt({modelType:lt.type})],dt.prototype,"troubleContainer",2);Tr([U({topic:"/kos/ota/artifacts/all",websocket:!0})],dt.prototype,"handleAllArtifacts",1);Tr([U({topic:"/kos/ota/artifacts/changed",websocket:!0})],dt.prototype,"handleChangedArtifacts",1);dt=Tr([R(pl)],dt);const Ys=new Ee({class:dt,type:pl});function cm(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 Nr=p.createLogger({name:"software-info-service",group:"Services"}),Wo=async t=>{Nr.debug("sending GET for software-info");const[e,s]=await Ac.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Nr.debug("Request was aborted"),new B("Request was aborted")):(Nr.error("Failed to fetch software-info",e),new B("Failed to fetch software-info"));return s},lm=cm(Wo),dm=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Wo,getSoftwareInfosWithCancel:lm},Symbol.toStringTag,{value:"Module"}));var um=Object.getOwnPropertyDescriptor,hm=(t,e,s,r)=>{for(var o=r>1?void 0:r?um(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const $t="software-info-model";let Xr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=t,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(t,e){return t.reduce((s,r)=>(s[r[e]]=[...s[r[e]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const t=await Wo(),e=(t==null?void 0:t.nodes)||{};X(()=>{const r=Object.keys(e).map(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 B&&this.logger.error("Failed to fetch software-info",t)}}};Xr=hm([R($t)],Xr);const qs={registration:{[$t]:{class:Xr,singleton:!1}},type:$t,predicate:he($t),factory:te.Factory.create($t)},{URL:ml}=oe(),{getOne:fm}=se.build({basePath:`${ml}/api/kos/state`}),gm=p.createLogger({name:"state-bean-service",group:"Services"}),yl=async({path:t})=>(gm.debug("sending GET for state-bean"),await fm({urlOverride:`${ml}/api/kos/state/${t}`})),pm=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:yl},Symbol.toStringTag,{value:"Module"}));var mm=Object.defineProperty,ym=Object.getOwnPropertyDescriptor,bl=(t,e,s,r)=>{for(var o=r>1?void 0:r?ym(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&mm(e,s,o),o};const Dt="state-bean-model",bm=Ge("path");let Ws=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=t,this.logger=s.logger,this.props=Ao.map(new Map),zr(e,this)}updateModel(t){zr(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&Lo(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&pr(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 yl({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};bl([U({topic:`/kos/state/${bm}`,websocket:!0})],Ws.prototype,"handleConfigBeanUpdated",1);Ws=bl([R(Dt)],Ws);const es={registration:{[Dt]:{class:Ws,singleton:!1}},type:Dt,predicate:he(Dt),factory:te.Factory.create(Dt)};var wm=Object.defineProperty,vm=Object.getOwnPropertyDescriptor,wl=(t,e,s,r)=>{for(var o=r>1?void 0:r?vm(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&&wm(e,s,o),o};const Ct="state-prop-model",Yn=Ge("path");let Qs=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=t,this.logger=s.logger,this.path=e.path,this.attribute=e.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var t;return((t=this.value)==null?void 0:t.toString())??""}};wl([mt({modelType:es.type,id:`state-bean-${Yn}`,options:{path:Yn}})],Qs.prototype,"stateBean",2);Qs=wl([R(Ct)],Qs);const Qo={registration:{[Ct]:{class:Qs,singleton:!1}},type:Ct,predicate:he(Ct),factory:te.Factory.create(Ct)},{URL:Mm}=oe(),{getAll:Em}=se.build({basePath:`${Mm}/api/state-prop`}),Tm=p.createLogger({name:"state-prop-service",group:"Services"}),_m=async()=>(Tm.debug("sending GET for state-prop"),await Em({})),Im=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:_m},Symbol.toStringTag,{value:"Module"})),{URL:Zo}=oe(),{getOne:vl}=se.build({basePath:`${Zo}/api/translation`}),Gt=p.createLogger({name:"translation-service",group:"Services"}),Sm=()=>{const t=window.location.origin,e=ue();return(e==null?void 0:e.host)||t},Ml=async(t,e)=>{Gt.debug("sending GET for translation");const s=e??Sm();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Gt.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Gt.error("Error fetching translations",r),r}},Om=async()=>{Gt.debug("getting localization descriptor");const t=await vl({urlOverride:`${Zo}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get tool localization descriptor ${t==null?void 0:t.status}`);return t.data},El=t=>async()=>{Gt.debug("getting kos localization descriptor");const e=await vl({urlOverride:`${Zo}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get tool localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},Tl="langResolver";var $m=Object.getOwnPropertyDescriptor,Dm=(t,e,s,r)=>{for(var o=r>1?void 0:r?$m(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Rt="translation-model";function Cm(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 _l(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null){const n=_l(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function Il(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]=Il(t[r],e[r]):s[r]=e[r]);return s}const Jr=(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)?Jr(r,e):r},Ss=(t,e,s)=>{const r=/{{(.*?)}}/g,n=Jr(t,e).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return Jr(n,e)},qn=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let eo=class{constructor(t,e,s){l(this,"id");l(this,"namespace");l(this,"descriptor");l(this,"defaultLocale");l(this,"currentLocale");l(this,"bundleResolver");l(this,"data");l(this,"logger");l(this,"resolver");l(this,"disposer");l(this,"context");l(this,"rootUrl");this.id=t,this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.currentLocale||"en",this.namespace=e.namespace,this.descriptor=e.descriptor,this.rootUrl=e.rootUrl,this.data={},this.resolver=e.resolver||s.kosContext.get(Tl),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=z.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return Ml(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);X(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=Il(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=_l(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=qn(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}=Cm(e),{namespace:n,key:i}=qn(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Ss(d,this.data,o)):Ss(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Ss(d,this.data,o)):Ss(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()})}};eo=Dm([fr(),R(Rt)],eo);const Zs={registration:{[Rt]:{class:eo,singleton:!1}},type:Rt,predicate:he(Rt),factory:te.Factory.create(Rt)};var Rm=Object.defineProperty,Am=Object.getOwnPropertyDescriptor,Sl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Am(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&&Rm(e,s,o),o};const At="translation-container-model",xm=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function Pm(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error(`namespace ${t} not found in descriptor`);const r=s.basePath,o=s.locales[e].file;return xm([r,o])}let Xs=class{constructor(t,e,s){l(this,"id");l(this,"lang");l(this,"rootUrl");l(this,"descriptor");l(this,"_defaultNamespace");l(this,"resolver");l(this,"logger");l(this,"descriptorUrl");l(this,"namespaces",[]);l(this,"_models");this.id=t,this.lang=e.lang||"en",this.descriptor=e.descriptor,this._defaultNamespace=e.defaultNamespace,this.descriptorUrl=e.descriptorUrl,this.rootUrl=e.rootUrl,this.resolver=e.resolver||Pm.bind(this),s.kosContext.set(Tl,this.resolver),this.logger=s.logger,this._models=new Te({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel(`translation-${this._defaultNamespace}`):void 0}getModel(t){return this.logger.debug(`getting model ${t}`),this._models.getModel(`translation-${t}`)}get models(){return this._models}get data(){return this._models.data}async reload(){this._models.clear(),await za(this);for(const t of this.namespaces){const e=this.resolveNamespace(t);await ae(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=Zs.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=Zs.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}`)}};Sl([be],Xs.prototype,"_models",2);Xs=Sl([R(At)],Xs);const Oe={registration:{[At]:{class:Xs,singleton:!0}},type:At,predicate:he(At),factory:te.Singleton.create(At)},Lm={set(t,e){const s=z.getContext(Oe.type);s&&s.set(t,e)},get(t){const e=z.getContext(Oe.type);return e==null?void 0:e.get(t)}},Ol={async init(t){const e=Oe.factory(t);return await ae(e),{translations:e}}};function km(t){return t.troubles!==void 0&&t.troubles instanceof Array&&t.troublesByType!==void 0&&typeof t.troublesByType=="object"}const Fm=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},$l="kos-ws-event",Xo=yt($l);var Nm=Object.defineProperty,Um=Object.getOwnPropertyDescriptor,Jo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Um(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Nm(e,s,o),o};const jm=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){p.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const d=this._topicMap.get(i)||0;a=`${a}-${d+1}`,this._topicMap.set(i,d+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:jm({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),p.debug(`logged ${this.events.size} events`)}}};Jo([U({topic:[ns.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Jo([U({topic:[ns.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Jo([R(Xo.type)],exports.WsEventModel);const Wn=ue(),Bm=Wn.debug==="true"||Wn.debug===!0,Km="/api/system/canvas",Dl=async(t,e)=>{const s=e||Km,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Bm?"false":"true"},body:t})},Hm=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Dl},Symbol.toStringTag,{value:"Module"}));function Qn(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var zm=Object.defineProperty,Gm=Object.getOwnPropertyDescriptor,Cl=(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&&zm(e,s,o),o};const Rl="canvas-renderer-model";function Ur(t){return typeof t.onDone=="function"}let Js=class{constructor(t,e,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);l(this,"_clearOnComplete");l(this,"isStreaming",!1);l(this,"renderLoopId",null);l(this,"sendIntervalId",null);l(this,"timeoutId",null);l(this,"apiPath");l(this,"endpointName");l(this,"width",50);l(this,"height",30);l(this,"fps",10);l(this,"durationMs",null);l(this,"_onFrame",null);this.id=t,this.logger=s.logger,this.width=e.width??50,this.height=e.height??30,this.fps=e.fps??10,this.durationMs=e.durationMs??null,this.apiPath=e.apiPath??"/api/system/canvas",this.endpointName=e.endpoint}set onFrame(t){this._onFrame=t}set renderer(t){var e,s;this._renderer&&(this.stopStreaming(),(s=(e=this._renderer).dispose)==null||s.call(e)),this._renderer=t,this.isStreaming&&this.startStreaming()}setClearOnComplete(t){this._clearOnComplete=t}sendDataFrame(t,e){Dl(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=Qn(t);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=Qn(o);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 Ur(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=Ur(this._renderer);Ur(this._renderer)&&this._renderer.onDone(()=>{var c,d,u;this.logger.debug(`Renderer completed for ${this.id}`),j("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((u=(d=this._renderer)==null?void 0:d.isOneShot)==null?void 0:u.call(d))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,d;const a=(d=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:d.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(t,e)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),e.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(t,e)=>{this.startStreaming(),e.send({status:"OK"})})}};Cl([mt({modelType:Ho.type})],Js.prototype,"router",2);Js=Cl([R(Rl)],Js);const en=new we({class:Js,type:Rl});class Al{constructor({src:e}){l(this,"video");l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);l(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=e,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(e,s){this.canvas.width=e,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,e,s)}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}onDone(e){this.doneCallback=e}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}}class Vm{constructor(){l(this,"canvas");l(this,"gl");l(this,"lastWidth",0);l(this,"lastHeight",0);l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl");if(!e)throw new Error("WebGL not supported");this.gl=e}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(e*s*4);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const o=new Uint8ClampedArray(r.length);for(let n=0;n<s;n++){const i=n*e*4,a=(s-1-n)*e*4;o.set(r.subarray(i,i+e*4),a)}return o}}class Ym extends Vm{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
|
|
77
|
+
["${e}"]`;if(r?(m=this.fosSocket)==null?void 0:m.connectionEstablished:(y=this.socket)==null?void 0:y.connectionEstablished){const E=r?this.fosSocket:this.socket;(v=E==null?void 0:E.socket)==null||v.send(u)}else{Ne.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(u)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=O(e,s);return Ne.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();Ne.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(nt,"_instance");class Xh{constructor(e){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=e,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(e){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of e)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(e,s)}async*processSingleEvent(e){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(e))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(e),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([e]):[e],this.updateProcessingStats([e])}}async*processBatchedEvents(e,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const d=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(d.length===0)return;this.config.backpressure&&await this.waitForCapacity();const u=this.config.transform?this.config.transform(d):d;return this.stats.batchesProcessed++,this.updateProcessingStats(d),u};try{for await(const d of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(d);this.eventQueue.length>0;){const u=this.dequeueEvent();u&&n.push(u);const g=Date.now()-i;if(n.length>=r||g>=o){const m=await a();m!==void 0&&(yield m);break}}else{n.push(d);const h=Date.now()-i;if(n.length>=r||h>=o){const g=await a();g!==void 0&&(yield g)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(e){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(e,s);return this.config.filter.historySize&&(this.filterHistory.push(e),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const e=Date.now(),s=Math.floor(e/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const e=Date.now(),o=(Math.floor(e/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-e;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=e;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-e;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(e){if(this.eventQueue.push(e),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const e=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,e}updateProcessingStats(e){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+e.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?e.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(e){return this.activePromises.add(e),e.finally(()=>this.activePromises.delete(e)),e}getStats(){return{...this.stats}}}class Jh{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);this.model=e,this.modelData=s,this.modelId=r,this.offlineQueue=o,this.log=n}registerAll(e){var o;const s=((o=this.modelData)==null?void 0:o[J])||{},r=Object.keys(s);this.log.debug(`Found ${r.length} subscriptions in ${this.modelId} (lifecycle: ${e??"any"})`),r.forEach(n=>{const i=s[n],a=i.lifecycle;if(e&&e!==a)return;const c=this.resolvePropKey(n);if(this.log.debug(`Resolved topic: ${n} → ${c}`),i.flow)this.subscribeWithFlowControl(i,c,a);else{const d=this.createHandler(c,i);this.subscribe(i,c,d,a===H.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=nt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=O(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(e,r,s);if(this.model.isReady()){const d=Gr(r,s.skipParse),u=s.transform(d);if(a&&s.condition(u,this.modelData,r))return this.callHandlerWithWildcard(s,u,c,r)}else{this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`);const d=()=>{const u=Gr(r,s.skipParse),h=s.transform(u);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)};this.offlineQueue.enqueue(d)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!da(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return la(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 Xh(e.flow);this.flowControllers.set(s,o);const n=this.createFlowControlHandler(s,e),i=this.startFlowProcessing(e,s,n,o),a=()=>{this.flowControllers.delete(s),i.then(c=>c==null?void 0:c.abort())};r===H.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;nt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=$n(s)}else i=$n(s);return(async()=>{try{for await(const a of o.processEvents(i)){if(n.signal.aborted)break;const c=r(a);c instanceof Promise&&await o.trackPromise(c)}}catch(a){this.log.error(`Flow control error for ${s}:`,a)}})(),n}catch(i){return this.log.error(`Failed to start flow processing for ${s}:`,i),null}}createFlowControlHandler(e,s){return async r=>{var o,n,i,a;try{if(s.condition&&!s.condition(r,this.modelData,r))return;if(this.model.isReady())return s.handler.call(this.modelData,r,r,this.modelData);{this.log.warn(`Model ${this.modelId} not ready. Queuing flow-controlled message for ${e}`);const c=()=>s.handler.call(this.modelData,r,r,this.modelData);this.offlineQueue.enqueue(c)}}catch(c){if(this.log.error(`Error in flow control handler for ${e}:`,c),(n=(o=s.flow)==null?void 0:o.errorHandling)!=null&&n.retry)await this.retryHandler(s,r,c);else if(!((a=(i=s.flow)==null?void 0:i.errorHandling)!=null&&a.continueOnError))throw c}}}async retryHandler(e,s,r){const o=e.flow.errorHandling.retry;let n=r;for(let i=1;i<=o.attempts;i++)try{return this.log.debug(`Retry attempt ${i}/${o.attempts} for handler`),await new Promise(a=>setTimeout(a,o.backoffMs*i)),e.handler.call(this.modelData,s,s,this.modelData)}catch(a){n=a,this.log.warn(`Retry attempt ${i} failed:`,a)}throw this.log.error("All retry attempts failed, throwing last error:",n),n}getFlowControlStats(){const e={};for(const[s,r]of this.flowControllers)e[s]=r.getStats();return e}}function We(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 ef(t){return!!(t!=null&&t[Ke])&&Object.keys(t[Ke]).length>0}function tf(t){return!!(t!=null&&t[J])&&Object.keys(t[J]).length>0}function sf(t){return!!(t!=null&&t[Ie])&&t[Ie].length>0}class rf{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=Fh.create({modelId:s,modelTypeName:r}),i=new Lh(e,We(n,"fsm")),a=new Nh(We(n,"offline-queue")),c=new Oh(e),d=new Sh(e),u={fsm:i,offlineQueue:a,companionManager:c,childResolver:d};if(ef(o)&&(u.effectManager=new $h(r,s,o,We(n,"effect"))),tf(o)){const h=We(n,"subscription");u.subscriptionManager=new Jh(e,o,s,a,h),u.onlineLifecycleManager=new Uh(e,We(n,"online"))}return sf(o)&&(u.httpRouteManager=new So(o,We(n,"http-routes"))),u}}const k=$.getLogger("kos-model"),of="kos.extension.model.loader";class ja{constructor({modelTypeName:e,id:s,modelData:r}){l(this,"_id");l(this,"_status");l(this,"_activeStatus");l(this,"_onlineStatus");l(this,"modelData");l(this,"modelTypeName");l(this,"initialized");l(this,"loaded");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this.modelData=r,this._status=w.CREATED,this._activeStatus=w.INACTIVE,this._onlineStatus=w.OFFLINE;const o=rf.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),_h(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===w.ACTIVE}isOnline(){return this._onlineStatus===w.ONLINE}isReady(){return this._status===w.READY}async deactivate(){var e,s,r;k.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw k.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r;k.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await It(this,H.ACTIVATE);try{const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.activate)==null?void 0:s.call(e,o)),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(r=this.subscriptionManager)==null||r.registerAll(H.ACTIVATE),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(o){throw k.debug(`Model ${this.modelId} failed to activate`),o}}async whenLoaded(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{k.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{k.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Rr([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===w.READY,onMatch:()=>{k.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r;if(this.fsm.current===w.READY){k.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{k.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await It(this,H.READY),await Ea(this,_o.READY,H.READY);const o=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.ready)==null?void 0:s.call(e,o)),this.offlineQueue.flush(),(r=this.subscriptionManager)==null||r.registerAll(H.READY),k.debug(`Model ${this.modelId} is ready`);const n={modelId:this.modelId,modelType:this.modelTypeName};j(ua(this.modelTypeName,this.modelId),n),j(ha(this.modelTypeName),n)}catch(o){throw k.error(o),Error(o)}}async load(){var o,n,i,a,c;const e=this[Ls];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===w.LOADED||this.fsm.current===w.LOADING){k.debug(`Model ${s} with id ${r} already loaded or loading`);return}k.debug(`Loading model ${s} with id ${r}`),await It(this,H.LOAD);try{const d=z.getContext(r),u=`${of}.${s}`,h=await S.loader.executeLoader(u,{});h&&(k.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(u,h)),await((n=(o=this.modelData)==null?void 0:o.load)==null?void 0:n.call(o,d)),X(()=>{this.loaded=!0}),k.debug(`Model ${s} with id ${r} successfully loaded`),(i=this.subscriptionManager)==null||i.registerAll(H.LOAD),(a=this.httpRouteManager)==null||a.registerAll(),(c=this.effectManager)==null||c.setup()}catch(d){throw k.error(`Model ${r} failed to load`,d),d}}async unload(){var e,s,r,o,n,i;k.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const a=this.getChildren().map(d=>{var u;return(u=d.unload)==null?void 0:u.call(d)}).filter(d=>!!d);await Promise.allSettled(a);const c=z.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,c)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),k.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(o=this.effectManager)==null||o.disposeAll(),(n=this.subscriptionManager)==null||n.disposeAll(),(i=this.httpRouteManager)==null||i.dispose()}catch(a){throw k.debug(`Model ${this.modelId} failed to unload`),a}}async init(){var n,i,a;const e=this[Ls];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=z.getContext(s);k.debug(`Initializing model ${r} with id ${s}`),await It(this,H.INIT);try{await((i=(n=this.modelData)==null?void 0:n.init)==null?void 0:i.call(n,o)),this.initialized=!0,k.debug(`Model ${r} with id ${s} initialized`),(a=this.onlineLifecycleManager)==null||a.register(),this.registerSubscribers(H.INIT)}catch(c){throw k.error(`Model ${s} failed to initialize`,c),c}}async registerSubscribers(e){var s;k.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}async online(){var s,r;k.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=z.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e))}async offline(){var s,r,o;k.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=z.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 Ba=t=>typeof t=="function",Rn=p.createLogger({name:"kos-model-instantiator"});class nf{constructor(e,s){this.registry=e,this.cache=s}createModelInstance(e,s,r={}){const o=this.registry.models[e];if(!o)throw new Error(`No model registered for type ${e}`);const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Rn.debug(`Creating model instance: ${e} [${n}]`);const a=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),c=new ja({modelTypeName:e,id:n,modelData:a});this.cache.addModel(c),this._createCompanionModels(c,r)}const i=this.cache.getModelById(n);if(!i)throw Rn.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}_createCompanionModels(e,s){var n;const r=e.modelTypeName,o=((n=this.registry.companionModels)==null?void 0:n[r])||[];for(const{type:i}of o){const a=Ba(i)?i(e.modelData,s):i;if(!a)continue;const c=`${a}-${e.modelId}`,d=this.createModelInstance(a,c,{data:s,companionParent:e.modelData,kosParentId:e.modelId});d!=null&&d.model&&(d.model[Ls]=e,e.addCompanionModel(d.model))}}}let af=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 yt(e)}};const Ka=10,An=p.createLogger({name:"kos-model-manager"});class Ha{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Xu,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 af(e),r.cache=new Ju(e.preloadModels),r.instantiator=new nf(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(An.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=>(An.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 yt(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(A.RESET,w.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),ra.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),Ka)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var Ds=(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))(Ds||{}),et=(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))(et||{});const cf=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=>$.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=>$.debug(n.machine.current)),online:s}},ae=async t=>{if(t.id){const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},He=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(t)},lf=async t=>{if(await I.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(A.UNLOAD,w.UNLOADED)},za=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(t),p.debug(`reload model initiated for model ${t.id}, model ready: ${Fs(t)} - ${Date.now()} `),await ae(t),p.debug(`reload model complete for model ${t.id}, model ready: ${Fs(t)} - ${Date.now()} `)},df=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},Ga=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},ve=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Va=(t,e)=>{if(!t)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},uf=(t,e)=>Va(t,e)[0],hf=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},Ya=t=>{if(!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},ff=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},Yr=(t,e)=>{const s=I.getInstance().modelManager.getModelById(t);if(!s){p.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},he=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,Fs=t=>{const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},gf=p.createLogger({name:"kos-model-factory"}),Kt={byModelType:t=>I.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=Kt.byModelType(e);if(!r)throw gf.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)}},te={Factory:{create:t=>e=>(s,r)=>(r&&z.setParentContext(e,r),Kt.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&z.setParentContext(t,s),Kt.getModelInstance(t,t,e))},Model:{instance:t=>e=>Kt.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const xn=window.KosRegistry.coreModels,Ar=window.KosRegistry.preloadModels,xr=window.KosRegistry.companionModels,ys=window.KosRegistry.models,C={model:{registerLegacyModel:t=>(e,s)=>(xn.set(e,s),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(Ar.includes(e)||Ar.push(e),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=Pr(e)?e.registration():e;return ys.set(r.type,r),Pr(e)&&e.relatedModels.forEach(o=>ys.set(o.type,o.registration())),I.getInstance().isReady&&(I.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),I.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],Pr(e)&&e.relatedModels.forEach(o=>I.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&C.model.preloadModel(t)(r.type),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},get:t=>ys.get(t),getAll:()=>Array.from(ys.entries()),getPreloadModels:()=>Ar,getLegacyModels:()=>Array.from(xn.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=xr.get(e)||[];return r.push(s),xr.set(e,r),{preload:C.model.preloadModel(t),model:C.model.register(t),companion:C.companion.register(t),legacy:C.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(xr.entries())}},qa=C.model.registerLegacyModel,Wa=C.model.register,pf=C.companion.register,mf=C.model.preloadModel,Qa=t=>typeof t.updateModel=="function",Pr=t=>t.registration!==void 0&&typeof t.registration=="function";class Za{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=he(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){C.model.register({})(this.registration()),this.registerRelatedModels()}}class we extends Za{constructor(e){super({...e,singleton:!1,factory:te.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=ve(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(Qa(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 Ee extends Za{constructor(e){super({...e,singleton:!0,factory:te.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=ve(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(Qa(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 Y=p.createLogger({name:"kos-core"}),yf=()=>{const t=ue(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},bf=()=>{const t=window.location.protocol,e=ue(),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://")},wf=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=ue(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},vf=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=ue(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},Mf=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?p.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):p.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},Pn=t=>typeof t.reload=="function",Ef=t=>typeof t.unload=="function";var Xa=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(Xa||{});class I{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=Ds.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),O("token",a=>{a&&(this.transport.token=a.body)}),O(pe.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(et.GO_ONLINE)}),O(pe.DISCONNECTED,async()=>{this.fsmService.service.send(et.GO_OFFLINE)}),O("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0}),O("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),O(pe.RELOAD,()=>{this.fsmService.service.send(et.RELOAD)}),O("/studio/project/reload",()=>{this.fsmService.service.send(et.RELOAD)});const s=nt.getInstance(),r=wf(),o=vf(),n=bf();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=yf()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=cf(this),this.fsmService.service.send(et.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){Y.info("reload already in progress");return}this._reloading=!0,Y.warn("reloading KOS Core"),Y.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)Pn(c.modelData)&&(Y.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),Y.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&Pn(c.modelData)&&((i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{Y.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Y.debug("KOS Core going online"),await this._transport.whenReady(),Y.debug("KOS Transport Ready. Calling online() for models"),j("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Y.debug("KOS Core going offline"),j("/kosCore/offline","/kosCore/offline")}async unload(){var o;Y.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Y.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)Ef(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===Ds.READY)}async ready(){Y.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(e.map(o=>{const{promise:n,cancel:i}=Mf(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Y.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Y.debug("leaving kos-core ready() ")}get isReady(){return this.status===Ds.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Y.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Y.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Y.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Y.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:g[d];u&&(Array.isArray(u)?u.forEach(m=>{S.dataMapper.registerDataMapper(d,m)}):S.dataMapper.registerDataMapper(d,u))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:g[d];u&&S.propertyMapper.registerPropertyMapper(d,u)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(d=>{var h,g;const u=(g=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:g[d];u&&S.loader.registerLoader(d,u)}),C.model.getAll().forEach(([,d])=>{e.models={...e.models,...d.registration}}),e.models={...e.models,...C.model.getLegacyModels()},C.companion.getAll().forEach(([d,u])=>{e.companionModels={...e.companionModels},e.companionModels[d]=e.companionModels[d]||[];for(const h of u)e.companionModels[d].push({type:h})}),C.model.getPreloadModels().forEach(d=>{e.preloadModels.includes(d)||e.preloadModels.push(d)});const n=Ha.create(e,s);return o.modelManager=n,o}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");function qr(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 Tf(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 _f(t){return await t.arrayBuffer()}function If(t,e){return new Blob([t],{type:e})}async function Sf(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:qr(i)})}else e[o]=n.toString();return{fields:e,files:s}}function Of(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function $f(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:qr(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await _f(t);return{data:qr(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await Sf(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Ue=p.createLogger({name:"kos-fetch"}),Df=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Cf=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),Rf=t=>{if("timeout"in AbortSignal)return AbortSignal.timeout(t);const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException(`Request timed out after ${t}ms`,"TimeoutError"))},t),e.signal},Af=t=>{if("any"in AbortSignal)return AbortSignal.any(t);const e=new AbortController;for(const s of t){if(s.aborted)return e.abort(s.reason),e.signal;s.addEventListener("abort",()=>e.abort(s.reason),{once:!0})}return e.signal},xf=t=>t!=null&&t.studio?Sa:t!=null&&t.fos?Oa:$a,Pf=async(t,e)=>{const s=I.getInstance().transport;await s.whenReady();const r=pt(),o=new URL(t),n=`${o.pathname}${o.search}`;Ue.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||Df,a=xf(e),c=Rf(i),d=e!=null&&e.signal?Af([e.signal,c]):c,u=await $f(e==null?void 0:e.body),h={};u.contentType&&(h["content-type"]=u.contentType),u.encoding&&(h["content-encoding"]=u.encoding);const g=ke(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,...h}}),u.data);return new Promise((m,y)=>{let v=null;if(d.aborted){const x=d.reason;(x==null?void 0:x.name)==="TimeoutError"?Ue.error(`Timeout occurred - url: ${t}`):Ue.debug(`Request aborted - url: ${t}`),y(x||new DOMException("Aborted","AbortError"));return}const E=()=>{v&&v();const x=d.reason;(x==null?void 0:x.name)==="TimeoutError"?Ue.error(`Timeout occurred - url: ${t}`):Ue.debug(`Request aborted - url: ${t}`),y(x||new DOMException("Aborted","AbortError"))};d.addEventListener("abort",E,{once:!0});const _=O(r,x=>{d.removeEventListener("abort",E);const D=(x==null?void 0:x.headers)||{},P=D["content-type"]||"text/plain",W=D["content-encoding"],re=(x==null?void 0:x.body)||"";let L=re;if(W==="base64"&&re)try{L=Tf(re)}catch(V){Ue.error("Failed to decode base64 response",V)}const Ce={headers:Da(D),status:D.status&&parseInt(D.status)||200,ok:D.status==="200",json:async()=>{try{if(typeof L=="string")return L.length?JSON.parse(L):null;{const ce=new TextDecoder().decode(L);return ce.length?JSON.parse(ce):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof L=="string"?L:new TextDecoder().decode(L),arrayBuffer:async()=>L instanceof ArrayBuffer?L:new TextEncoder().encode(L).buffer,blob:async()=>L instanceof ArrayBuffer?If(L,P):new Blob([L],{type:P}),formData:async()=>{const V=new FormData;if(P==="multipart/form-data"&&typeof L=="string")try{const ce=JSON.parse(L);ce.fields&&Object.entries(ce.fields).forEach(([gs,Et])=>{V.append(gs,Et)}),ce.files&&Ue.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return V},body:e!=null&&e.stream?Of(async V=>{if(L instanceof ArrayBuffer)V.enqueue(new Uint8Array(L));else{const ce=new TextEncoder;V.enqueue(ce.encode(L))}V.close()}):Ca(typeof L=="string"?L:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};_.unsubscribe(),Cf().then(()=>m(Ce))});v=_.unsubscribe;const N=e!=null&&e.fos?s.fosSocket:s.socket;if(!N)throw Error(`No web socket transport available: ${e}`);N==null||N.send(g)})};exports.BASE_URL="kos:";exports.kosFetch=Pf;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const Lf=p.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class kf{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){Lf.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}const Ja=()=>({isMock:!1,URL:exports.BASE_URL}),bs=p.createLogger({name:"kos-service-request"}),Ln="errUnknown";async function ws(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((d,u)=>String(d).replace(`{${u}}`,r==null?void 0:r.path[u]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(d=>`${d}=${r.query[d]}`).join("&"):"",a=`${Ja().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;bs.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));try{const d=await exports.kosFetch(a,c);return d.status<200||d.status>=400?[`${d.statusText||Ln}`,null]:[null,(await d.json()).data]}catch(d){if(d instanceof DOMException){if(d.name==="TimeoutError")return bs.error(`Request timed out: ${a}`),["Request timed out",null];if(d.name==="AbortError")return bs.debug(`Request aborted: ${a}`),["Request aborted",null]}return bs.error(`Unexpected error during fetch: ${d}`),[d instanceof Error?d.message:Ln,null]}}function Oo(){return{get:(t,e,s)=>ws(t,"get",s,e),post:(t,e,s,r)=>ws(t,"post",r,e,s),put:(t,e,s,r)=>ws(t,"put",r,e,s),delete:(t,e,s,r)=>ws(t,"delete",r,e,s)}}class ec{constructor(){l(this,"middlewares",[])}use(e){this.middlewares.push(e)}async execute(e){let s=0;const r=async()=>{s++,s<this.middlewares.length&&await this.middlewares[s](e,r)};await this.middlewares[s](e,r)}}const Ff=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},yt=t=>({type:t,build:(e,s)=>I.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=I.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),Nf=t=>{I.getInstance().modelManager.registerModel(t)},Uf=(t,e)=>{I.getInstance().modelManager.registerCompanionModel(t,e)},tc=Symbol("KosObservableData");class sc{constructor(){l(this,"map");l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var o;return this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:()=>Array.from(this.map.keys())});this.map=M.observable.map(new Map)}setValue(e,s){this.map.set(e,s)}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}sc.prototype[tc]=!0;function jf(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const Ae=t=>{const e=jf(sc,t);return new e(t)},kn="/kos/ui/internal/heartbeat/",Bf=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${kn}${t}`,callback:()=>{a=performance.now()}}),d=r??3e3,u=window.setInterval(()=>{let v=performance.now()-a;v=v/1e3,v>d/1e3&&i.abort()},d),h=o??2e3,g=window.setInterval(()=>{Fa({msg:{},options:{topic:`${kn}${t}`,destinationAddress:e}})},h),m=()=>{window.clearInterval(g),window.clearInterval(u),c()},y=()=>{m(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:m}},rc=(...t)=>e=>t.reduce((s,r)=>r(s),e),Kf={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Hf(t,e){let s=1;const r={...Kf,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(p.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(d=>setTimeout(d,a)),s++;else throw c}throw new Error("All attempts failed")}const zf=p.createLogger({name:"kos-service-request"}),oe=t=>({isMock:!1,URL:exports.BASE_URL}),Gf=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g})=>{const m={method:"DELETE"};t&&(m.destinationAddress=t),o&&(m.tracker=o),bt(m,{ordered:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g});try{const y=await s(n||`${e}/${r}`,m);if(!y.ok)throw Error(`There was a problem deleting the model; returned status ${y.status}`);return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while deleting model");if(y.name==="AbortError")throw new B("Request was cancelled while deleting model")}throw y}},bt=(t,{ordered:e,studio:s,fos:r,destinationAddress:o,bridge:n,timeout:i,signal:a})=>(i&&(t.timeout=i),a&&(t.signal=a),e&&(t.ordered=e),s&&(t.studio=s),r&&(t.fos=r),n&&(t.bridge=n),(o||o==="")&&(t.destinationAddress=o),t),Vf=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,signal:d,destinationAddress:u})=>{const h={method:"GET"};t&&(h.destinationAddress=t),bt(h,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,signal:d,destinationAddress:u});const g=r||e;try{const m=await s(g,h);if(!m.ok){let v;try{v=await m.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${m.status}`,v??void 0)}return await m.json()??void 0}catch(m){if(m instanceof DOMException){if(m.name==="TimeoutError")throw new B("Request timed out while retrieving models");if(m.name==="AbortError")throw new B("Request was cancelled while retrieving models")}throw m}},Yf=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:d,signal:u,destinationAddress:h})=>{const g={method:"GET"};t&&(g.destinationAddress=t),c&&(g.tracker=c),bt(g,{timeout:d,ordered:o,studio:n,fos:i,bridge:a,signal:u,destinationAddress:h});const m=r||e;zf.debug(`resolvedUrl: ${m}`);try{const y=await s(m,g);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while retrieving model");if(y.name==="AbortError")throw new B("Request was cancelled while retrieving model")}throw y}},qf=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:d,signal:u,destinationAddress:h})=>{const g={method:"GET"};t&&(g.destinationAddress=t),bt(g,{timeout:d,ordered:n,studio:i,fos:a,bridge:c,signal:u,destinationAddress:h});const m=r||`${e}/${o}`;try{const y=await s(m,g);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem retrieving the model; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while retrieving model by ID");if(y.name==="AbortError")throw new B("Request was cancelled while retrieving model by ID")}throw y}};class B extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Fn=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:d,timeout:u,signal:h,destinationAddress:g})=>{const m={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(m.destinationAddress=t),i&&(m.tracker=i),bt(m,{timeout:u,ordered:n,studio:a,fos:c,bridge:d,signal:h,destinationAddress:g});try{const y=await s(o||e,m);if(!y.ok){let E;try{E=await y.json()}catch{}throw new B(`There was a problem sending the POST data; returned status ${y.status}`,E??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new B("Request timed out while adding model");if(y.name==="AbortError")throw new B("Request was cancelled while adding model")}throw y}},Nn=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:d,bridge:u,timeout:h,signal:g,destinationAddress:m})=>{const y={method:t};o&&(y.body=JSON.stringify(o)),e&&(y.destinationAddress=e),bt(y,{timeout:h,ordered:a,studio:c,fos:d,bridge:u,signal:g,destinationAddress:m});try{const v=await r(i||`${s}/${n}`,y);if(!v.ok){let _;try{_=await v.json()}catch{}throw new B(`There was a problem modifying the model; returned status ${v.status}`,_??void 0)}return await v.json()??void 0}catch(v){if(v instanceof DOMException){if(v.name==="TimeoutError")throw new B("Request timed out while modifying model");if(v.name==="AbortError")throw new B("Request was cancelled while modifying model")}throw v}},se={build:({destinationAddress:t="",basePath:e,getAllPath:s,getOnePath:r,deleteModelPath:o,addModelPath:n,modifyModelPath:i,mock:a=!1})=>{const c=a?fetch:exports.kosFetch;return{getAll:Vf(t,s||e,c),getModelById:qf(t,r||e,c),getOne:Yf(t,r||e,c),addModel:Fn(t,n||e,c),deleteModel:Gf(t,o||e,c),modifyModel:Nn("POST",t,i||e,c),putModel:Nn("PUT",t,i||e,c),postModel:Fn(t,n||e,c)}}},Wf=pt(),oc=()=>`kos-${Wf}`,Qf=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(oc()),$o=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=O(t,i=>{$.debug(`recieved response for refId ${t}: ${i}`),o(),clearTimeout(n);try{const a=i!=null&&i.body?JSON.parse(i.body):{};s(a)}catch{const a=(i==null?void 0:i.body)||{};s(a)}}),n=setTimeout(()=>{o(),r(Error(`Request with ID ${t} timed out. Cancelling.`))},e)}),Zf=async(t,e,s)=>{const r=$o(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)},Xf=async({topic:t,msg:e,requestId:s})=>{const r=s??pt(),o=$o(r);j(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},le=new Map;class nc{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){X(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=ve(this._parent))==null?void 0:e.model}get companionModels(){const e=ve(this._id);return e!=null&&e.model?Ya(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||!le.has(n.id)?!1:(i=le.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=le.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=le.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 z={createContext:(t,e)=>{const s=le.get(t)??new nc(t);if(e){if(!le.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return le.set(t,s),s},getContext:t=>le.get(t),deleteContext:t=>{le.delete(t)},setParentContext:(t,e)=>{var s;if(!le.has(e))throw new Error(`Parent context ${e} does not exist`);(s=le.get(t))==null||s.setParent(e)},rootContext:()=>le.get("root")};z.createContext("root");const Jf=t=>z.getContext(t.id);function eg(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class Do{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=Ae(),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(eg(n,i))p.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=e.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){M.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,e,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,e,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function tg(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>M.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const Tt=p.createLogger({name:"kos-container-model"});class Te{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?S.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const o=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=M.observable.map(o),this.idx=Ae(),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 Do({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&&z.setParentContext(e.id,this._parentId),s||this.increment();const r=this._disposerMap.get(e.id);r&&(r(),this._disposerMap.delete(e.id));const o=Object.entries(this._optionsMap||{}),n=Object.values(this._optionsMap||{}),i=new Map(o.map(([u,h])=>[h,u])),a=u=>{var g,m;n.includes(u.name)&&((g=this.index.get(i.get(u.name)))==null||g.refresh());const h=o.filter(([,y])=>typeof y=="function");for(const[y]of h)(m=this.index.get(y))==null||m.refresh()},c=tg(e,a,n.filter(u=>typeof u=="string")),d=M.observe(e,a);this._disposerMap.set(e.id||"",()=>[d,...c].forEach(u=>u()))}removeModel(e,s){this._data.delete(e),s||this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),this.increment()}getModel(e){return this._data.get(e)}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(Tt.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):(Tt.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Tt.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async clear(){this._data.forEach(e=>{const s=e.id;He(e).then(()=>{Tt.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>Tt.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}const Lr=p.createLogger({name:"kos-data-container"});class Co{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"idx");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=Ae(),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new Do({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??[]:(Lr.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):(Lr.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return Lr.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 sg{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"childRegistration");l(this,"model");this.type=e,this.model=s,this.childRegistration=r}get factory(){return te.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return he(this.type)}}class rg{constructor({type:e,model:s,childRegistration:r}){l(this,"type");l(this,"model");l(this,"childRegistration");this.type=e,this.model=s,this.childRegistration=r}get factory(){return te.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return he(this.type)}}class ic{constructor(){l(this,"_token");M.makeAutoObservable(this),O("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class ac{constructor(){l(this,"routes",[]);l(this,"openApiRoutes",[])}use(e,s,...r){this.routes.push({method:e,path:s,middlewares:r});const o=this.extractOpenApiParams(s);this.openApiRoutes.push({method:e,path:s,parameters:o})}remove(e,s){const r=this.routes.length;return this.routes=this.routes.filter(o=>!(o.method===e&&o.path===s)),this.openApiRoutes=this.openApiRoutes.filter(o=>!(o.method===e&&o.path===s)),r-this.routes.length}removeAllForPath(e){const s=this.routes.length;return this.routes=this.routes.filter(r=>r.path!==e),this.openApiRoutes=this.openApiRoutes.filter(r=>r.path!==e),s-this.routes.length}getRoutes(){return this.routes.map(e=>({method:e.method,path:e.path}))}async handle(e,s){var a;const{path:r,query:o,params:n}=this.extractPathParams(e.path),i={...e,params:n,query:o};for(const c of this.routes){const d=this.matchRoute(c.path,r);if(c.method===e.method&&d){i.params=d;let u=0;const h=async()=>{if(u<c.middlewares.length){const g=c.middlewares[u++];await g(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 cc=p.createLogger({name:"intent-service"}),og=t=>{po(`/kos/intent/${t.type}`)?j(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):cc.info(`No subscribers for intent ${t.type}. Intent not sent.`)},ng=async t=>new Promise(e=>{const{type:s,options:r}=t;if(po(`/kos/intent/${t.type}`)){const o=pt(),{unsubscribe:n}=O(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);j(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else cc.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),_e=p.createLogger({name:"app-startup-service"});async function lc(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return _e.warn("No app IDs provided to waitForAppsToStart"),!0;_e.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await bo(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>cp),[d,u]=await c.get("/api/kos/apps/started");return d?(_e.error("Error fetching started apps:",d),[]):u}catch(c){_e.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(d=>{const u=c.find(h=>h.appId===d);return!(!u||!u.started||o&&!u.postStarted)}),timeout:s}),a=t.filter(c=>{const d=i.find(u=>u.appId===c);return!!(!d||!d.started||o&&!d.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(_e.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return _e.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(_e.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function ig(t,e={}){return lc([t],e)}async function ag(t,e=!1){const s={};try{const r=await exports.kosFetch("kos:///api/kos/apps/started");if(!r.ok)return t.forEach(i=>s[i]=!1),s;const o=await r.json(),n=(o==null?void 0:o.data)??[];t.forEach(i=>{const a=n.find(c=>c.appId===i);s[i]=(a==null?void 0:a.started)===!0&&(!e||(a==null?void 0:a.postStarted)===!0)})}catch(r){_e.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function cg(){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 _e.error("Failed to fetch started apps:",t),[]}}const Wr=M.when,Ro=M.computed,X=M.runInAction,G=M.autorun,dc=M.reaction,Ao=M.observable,xo="Not Assigned",lg="kos.trouble.added",dg="kos.trouble.removed";var me=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t))(me||{}),Ht=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Ht||{});const uc=p.createLogger({name:"config-bean-service",group:"Services"}),Po=exports.BASE_URL,hc=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:ug,getOne:hg}=se.build({destinationAddress:"",basePath:`${Po}/kos/config/`}),fc=async(t,e,s="/api/kos/config")=>(uc.debug(`sending modify request for ConfigBean: ${t}`),ug({model:e,urlOverride:`${Po}${s}/${t}`})),gc=async(t,e="/api/kos/config")=>(uc.debug(`sending get request for ConfigBean: ${t}`),await hg({urlOverride:`${Po}${e}/details/${t}/15`})),Lo=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",pr=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 mc(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])?mc(t[r],o,s):s[o]=t[r]}return s}const yc=(t,e)=>{const s=t.details[0].bean||pc(t.details[0].scopes),r=mc(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},bc=(t,e)=>{M.runInAction(()=>{t.changes.forEach(s=>{const r=s.attr;let o=s.currentValue,n=s.previousValue;typeof o=="string"&&Lo(o)&&(o=o.toLowerCase()=="true",n=(n==null?void 0:n.toLowerCase())=="true"),typeof o=="string"&&pr(o)&&(o=Number(o),n=Number(n)),e.props[r]=o,e.prevProps[r]=n})})},wc=t=>Object.fromEntries(t.props.entries),fg=t=>e=>s=>t.build(e,s);var gg=Object.defineProperty,pg=Object.getOwnPropertyDescriptor,vc=(t,e,s,r)=>{for(var o=r>1?void 0:r?pg(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&&gg(e,s,o),o};function mg(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const ko="config-bean-model",vs=p.getLogger(ko),yg=Ge("path");let Ns=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=fc,getConfigBean:r=gc}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Ae(),this.prevProps=Ae()}get values(){return this.props.values}async ready(){vs.debug(`readying config bean ${this.path}`),vs.debug(`complete readying config bean ${this.path}`)}async load(){vs.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;yc(e,this),vs.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=mg(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=wc(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){bc(t,this)}};vc([U({topic:`/kos/config/${yg}`,websocket:!0})],Ns.prototype,"handleConfigBeanUpdated",1);Ns=vc([R(ko)],Ns);const Yt=new we({class:Ns,type:ko}),mr=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Yt.type,id:`${Yt.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:H.INIT,lazy:e}},{URL:Mc}=oe(),{getOne:bg,getAll:wg}=se.build({basePath:`${Mc}/api/kos/regions/info`}),Ec=async()=>await bg({}),Tc=async()=>await wg({urlOverride:`${Mc}/api/kos/regions`}),vg=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Ec,getRegions:Tc},Symbol.toStringTag,{value:"Module"}));var ie=(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))(ie||{});const _c={s:["time",1,0,0],second:["time",1,0,0],m:["time",1/60,0,0],minute:["time",1/60,0,0],h:["time",1/3600,0,0],hour:["time",1/3600,0,0],day:["time",1/86400,0,0],week:["time",1/604800,0,0],month:["time",1/2628e3,0,0],year:["time",1/31536e3,0,0],default:["time",1/.001,0,0],ms:["time",1/.001,0,0],millisecond:["time",1/.001,0,0],microsecond:["time",1/1e-6,0,0],nanosecond:["time",1/1e-9,0,0],picosecond:["time",1/1e-12,0,0]};function Mg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return o[n.name]=i,n.alias&&(o[n.alias]=i),o},{..._c});return{...t,...r}}function Eg(t,e){const s=e.id,r=e.units.reduce((o,n)=>{const i=o[n.measure]||{},a=i[s]||{};i[s]=a;const c=[n.measure,n.scale,n.offset,n.decimals,n.alias,s];return a[n.name]=c,Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,n.alias&&(o[n.alias]=i),o},{time:{[s]:{..._c}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function Tg(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 _g=Object.defineProperty,Ig=Object.getOwnPropertyDescriptor,Fo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ig(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&_g(e,s,o),o};const Cs="region-info-model",_t=p.createLogger({name:"region-info-model"});let qt=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[ie.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[ie.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[ie.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[ie.family]!==s[ie.family])throw new Error(`Cannot convert between units of different families: ${e[ie.family]} and ${s[ie.family]}`);const r=e[ie.offset],o=e[ie.scale],n=s[ie.scale],i=s[ie.offset],a=s[ie.decimals];return((t-r)/(o/n)+i).toFixed(a)}convertByUnitName(t,e,s){const r=this.unitSystemMap[e],o=this.unitSystemMap[s];if(!r||!o)throw new Error(`No unit found with name: ${e} or ${s}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return this.convertByUnit(t,r,o)}convert(t,e,s){var a,c;if(e.unit&&s.unit)return this.convertByUnitName(t,e.unit,s.unit);const r=e.unit||"",o=s.unit||"";let n=this.unitSystemMap[r],i=this.unitSystemMap[o];if(!i&&s.measure&&s.system){const d=this.measureMap[s.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=d[s.system])==null?void 0:a.default,i||_t.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const d=this.measureMap[e.measure];if(!d)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=d[e.system])==null?void 0:c.default,n||_t.info("Could not find default unit for measure",e.measure)}return!n||!i?(_t.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){_t.debug("initializing region info")}async load(){_t.debug("loading region info");const t=await Tc();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 Ec();e&&(this.unitSystems=e.data.unitSystems.reduce((s,r)=>{const o={id:r.id,name:r.id};return s[r.id]=o,s},this.unitSystems),this.unitSystemMap=e.data.unitSystems.reduce(Mg,{}),this.measureMap=e.data.unitSystems.reduce(Eg,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(Tg,{}),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))}};Fo([mr({path:"kos:service:region:settings"})],qt.prototype,"regionSource",2);Fo([mr({path:"kos:service:region"})],qt.prototype,"region",2);qt=Fo([R(Cs)],qt);const ee={registration:{[Cs]:{class:qt,singleton:!0}},type:Cs,factory:te.Singleton.create(Cs)},Us=({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},No=(t,e,s)=>{const{model:r}=ve(ee.type);if(!r)throw new Error("RegionInfo model not found");if(!Fs(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=Us({source:e}),i=Us({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Un(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 Sg=(t,e,s,r)=>{const o=No(t,e,s),n=Us({source:e}),{model:i}=ve(ee.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},d=Us({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),u=i.getDefaultUnitForMeasure(a,d.system),h=i.getDefaultUnitDecimalPlaces(a,d.system),g={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:u||n.unit||"",display:Un(o,u||n.unit||"",{...g,mode:"long"}),shortDisplay:Un(o,u||n.unit||"",{...g,mode:"short"})}};function jn({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 Bn({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 Qe=(t,e)=>s=>!t||!e?s:pr(s)?No(Number(s),t,e):s,Og=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return jn(t.options).map(Qe(s,r));if(t.options.type==="rangeInterval")return Bn(t.options).map(Qe(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(Qe(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return jn(t.options.unitSystems[e]).map(Qe(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Bn(t.options.unitSystems[e]).map(Qe(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(Qe(s,r))}}return[]},$g=(t,e)=>{if(!((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options)))return t.options.type==="unitSystemRangeCount"&&e?{type:"rangeCount",...t.options.unitSystems[e]}:t.options.type==="unitSystemRangeInterval"&&e?{type:"rangeInterval",...t.options.unitSystems[e]}:t.options.type==="unitSystemList"&&e?{type:"list",...t.options.unitSystems[e]}:t.options.type==="unitSystemKeypad"&&e?{type:"keypad",...t.options.unitSystems[e]}:t.options};var Dg=Object.defineProperty,Cg=Object.getOwnPropertyDescriptor,Uo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cg(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&&Dg(e,s,o),o};function Rg(t){return(t==null?void 0:t.type)==="enum"}function Ag(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 xg(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return Re.format(r,e)}const Rs="config-bean-prop-model",Ze=p.createLogger({name:"config-bean-prop-model"}),Pg=Ge("path"),Lg=Ge("serviceBasePath");let Wt=class{constructor(t,e){l(this,"id");l(this,"path");l(this,"attribute");l(this,"converter");l(this,"formatter");l(this,"optionsExpander");l(this,"serviceBasePath");l(this,"regionInfo");l(this,"bean");this.id=t,this.path=e.path,this.attribute=e.attribute,this.converter=e.converter,this.formatter=e.formatter,this.serviceBasePath=e.serviceBasePath,this.optionsExpander=e.optionsExpander}getDefaultUnitDecimalPlaces(t,e,s){if(!t)throw new Error("measure is required");if(!e)throw new Error("unitSystem is required");return hc(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?Ag(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=Rg(r)?r.values:Og(r,s,e==null?void 0:e.from,e==null?void 0:e.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,o=(t==null?void 0:t.system)||e,n=t==null?void 0:t.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),o=this.convertUnit(e.to,t,s);return{backend:r,display:o}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let d=String(t);return d=c.formatToParts(Number(t))[0].value,Number(d)}}catch(c){Ze.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,o)}return e||""}async activate(){Ze.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 xg(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){Ze.error(`error formatting value ${t}`,e)}return String(t)}get unit(){const t=this.getConverter();if(!isNaN(this.value)){const e=this.getFormatterOptions(t);if(e){const r=e.formatToParts(Number(this.value)).find(o=>o.type==="unit");return(r==null?void 0:r.value)??this.getDefaultUnit(t)}}return this.getDefaultUnit(t)}get displayOptions(){var o;const t=this.bean.getSchemaForProperty(this.attribute),e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=((o=s==null?void 0:s.to)==null?void 0:o.system)??e;return $g(t,r)}getMeasureFromFormat(){const t=this.schemaFormat;return t?this.regionInfo.getUnitMeasure(t):""}getConverterFromFormat(){const t=this.getMeasureFromFormat();if(t){const e=this.regionInfo.selectedUnitSystem;return{unit:this.schemaFormat||this.regionInfo.getDefaultUnitForMeasure(t,e),measure:t}}return{}}getDefaultUnit(t){var r,o;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure;return s?((r=t==null?void 0:t.to)==null?void 0:r.unit)||this.getDefaultUnitForMeasure(s,((o=t==null?void 0:t.to)==null?void 0:o.system)||e):this.getConverterFromFormat().unit}getFormatterOptions(t){var n,i,a;const e=this.regionInfo.defaultUnitSystem,s=t==null?void 0:t.measure,r=new Intl.NumberFormat().resolvedOptions().locale;let o=null;if(s||this.formatter){const c=s?{style:"unit",unit:this.getDefaultUnit(t)}:null,d=this.formatter||c;if(d){let u=typeof d=="function"?d(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):d;s&&(u={unit:this.getDefaultUnit(t),...u},u.style==="unit"&&(u.maximumFractionDigits=u.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...u})}catch(h){Ze.error(`error creating formatter ${u}. Returning the raw value`,h)}}else Ze.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,d,u,h,g,m;const{unit:t,measure:e}=this.getConverterFromFormat();if(this.schemaFormat==="drt")return;const s=t==="drt"?"second":t;if(this.converter){const y=(r=this.converter)==null?void 0:r.measure,v=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=y||v||E||e,N=((d=(c=this.converter)==null?void 0:c.to)==null?void 0:d.unit)||this.regionInfo.getDefaultUnitForMeasure(_,((h=(u=this.converter)==null?void 0:u.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),x=((m=(g=this.converter)==null?void 0:g.to)==null?void 0:m.system)??this.regionInfo.getUnitSystem(N),D=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:D,...this.converter.from},to:{...this.converter.to,unit:N,system:x},measure:_}}if(s&&e){const y=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),v=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(y);return{measure:e,to:{unit:v===E?s:y}}}}async updateProperty(t){Ze.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)}};Uo([mt({modelType:ee.type})],Wt.prototype,"regionInfo",2);Uo([mr({path:Pg,serviceBasePath:Lg})],Wt.prototype,"bean",2);Wt=Uo([R(Rs)],Wt);const Ve={registration:{[Rs]:{class:Wt,singleton:!1}},type:Rs,factory:te.Factory.create(Rs)};function kg(t){const{path:e,attribute:s,converter:r,formatter:o,lazy:n,optionsExpander:i,serviceBasePath:a}=t,c=r;return c&&(typeof c!="function"&&typeof c.from=="string"&&(c.from={unit:c.from}),typeof c!="function"&&typeof c.to=="string"&&(c.to={unit:c.to})),(d,u)=>{d[F]=d[F]||{},d[F][u]={modelType:Ve.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:H.INIT,lazy:n}}}class Fg{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=Ao.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=G(()=>{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){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=G(()=>{var r,o;(e.endState||e.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw p.error(e),e}}}const Ic="future-model",wt=yt(Ic),br=p.createLogger({name:"future-service",group:"Services"}),{isMock:Ng,URL:cs}=oe();var xe=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(xe||{});const{getAll:Ug,modifyModel:jg,addModel:Bg,deleteModel:Kg,postModel:Hg}=se.build({destinationAddress:"",basePath:`${cs}/api/future`,mock:Ng}),zg=async()=>await Ug({}),Sc=async(t,e="/api/kos/future")=>(br.info(`sending delete request for Future: ${t}`),await Kg({id:t,urlOverride:`${cs}${e}/${t}`})),Oc=async(t,e="/api/kos/future")=>(br.info("sending add request for Future"),await Bg({model:t,urlOverride:`${cs}${e}`})),Gg=async(t,e,s="/api/kos/future")=>(br.info(`sending modify request for Future: ${t}`),jg({model:e,id:t,urlOverride:`${cs}${s}/${t}`})),$c=async(t,e="/api/kos/future")=>(br.info(`sending cancel request for Future: ${t}`),Hg({urlOverride:`${cs}${e}/${t}/cancel`,ordered:!0,model:{}})),jo=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}),Bo=(t,e)=>{p.debug(`future dto ${t.id} end state ${t.endState}`),p.debug(`future model ${e.id} end state ${e.endState}`),e.endState?p.debug(`future model ${e.id} is already complete`):(p.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=jo(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]})})}))},Dc=t=>e=>s=>t.build(String(e),s),Ko=t=>e=>rc(jo,Dc(t)(e.tracker||e.id))(e);var Vg=Object.defineProperty,Yg=Object.getOwnPropertyDescriptor,Cc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Yg(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&&Vg(e,s,o),o};const kr=p.getLogger(wt.type);let js=class{constructor(t,e,s){l(this,"logger");l(this,"_cancelFuture");l(this,"futureId");Object.assign(this,e),this.logger=s.logger,this.id=t,this.futureId=e.id,this.namespace=e.namespace||"kos",this._cancelFuture=$c,Wr(()=>this.status===xe.Success||this.status===xe.Fail,()=>{kr.info(`Future ${this.id} has completed with status ${this.status}`),He(this)})}async load(){kr.debug(`loading Future ${this.id}`)}unload(){kr.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await Wr(()=>this.futureId!==xo),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[d,u]of Object.entries(e))if(Math.abs(t)>=u){s=d,r=Math.round(t/u);break}const n=new Intl.RelativeTimeFormat("en",{numeric:"auto"}).formatToParts(r,s);return n.length===3?`${((a=n[1])==null?void 0:a.value)??0} ${((c=n[2])==null?void 0:c.value)??""}`:"0 seconds"}handleFutureUpdated(t){this.logger.debug(`Future ${this.id} updated. future: ${t.id} endState: ${t.endState} progress: ${t.progress} remainingTimeMs: ${t.remainingTimeMs}`),Bo(t,this)}};Cc([U({topic:`kos.future/${xs}`})],js.prototype,"handleFutureUpdated",1);js=Cc([R(wt.type)],js);const Rc=js,Ac=Oo();var qg=Object.defineProperty,Wg=Object.getOwnPropertyDescriptor,xc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Wg(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&&qg(e,s,o),o};const Pc="browser-router-model",Qg="kos.http.request",Zg="kos.http.response";let Bs=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new ac}get id(){return this._id}async handleRequest(t,e){const s=e.headers["src-addr"],r=e.headers["dst-addr"],o=e.headers.url,n=e.headers.method,i=e.headers["request-id"],a={id:i,method:n,path:o,body:t};let c=200;const d={send:u=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(u),Na({msg:u,options:{responseId:i,destinationAddress:s,type:Zg,sourceAddress:r,status:c}})},status:function(u){return c=u,this}};if(a.path==="/openapi.json"){d.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,d)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};xc([U({topic:Qg})],Bs.prototype,"handleRequest",1);Bs=xc([R(Pc)],Bs);const Ho=new Ee({class:Bs,type:Pc}),Lc="future-container-model",Pe=yt(Lc),kc=t=>Ko(wt)(t),Xg=t=>{const e=kc(t);return Pe.build(Pe.type,{}).addFutureModel(e),e},Jg=t=>Pe.build(Pe.type,{}).getFuture(String(t)),ze={buildFutureModel:kc,initiateFuture:Xg,getFuture:Jg};var ep=Object.defineProperty,tp=Object.getOwnPropertyDescriptor,zo=(t,e,s,r)=>{for(var o=r>1?void 0:r?tp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ep(e,s,o),o};const Ms=p.getLogger(Pe.type);let Qt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_deleteFuture");l(this,"_addFuture");l(this,"_futures");l(this,"createModel");l(this,"deleteModel");const{deleteFuture:r=Sc,addFuture:o=Oc}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new Te,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){Ms.error("error deleting a Future"),Ms.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Ko(wt)(s);return this.addFutureModel(r),r}}catch(e){throw Ms.error("error creating a Future"),Ms.error(e),e}}handleFutureUpdated(t,e){const s=ze.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),j(r,e.body,e.headers)}};zo([be],Qt.prototype,"_futures",2);zo([U({topic:"kos.future"})],Qt.prototype,"handleFutureUpdated",1);Qt=zo([R(Pe.type)],Qt);const Fc=Qt,{URL:ls}=oe(),{getOne:sp,postModel:rp,deleteModel:Nc}=se.build({basePath:`${ls}/api/keyVal`}),Qr=p.createLogger({name:"key-value-service",group:"Services"}),Uc=async(t,e)=>{await Nc({urlOverride:`${ls}/api/keyVal/${t}/${e}`,id:e})},jc=async(t,e,s)=>{const r=await rp({urlOverride:`${ls}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw Qr.error("Failed to update studio-state data",r),new Error(`Failed to update studio-state data for namespace ${t}`);return r.data},Bc=async(t="studio")=>{Qr.debug("sending GET for studio-state");const e=await sp({urlOverride:`${ls}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw Qr.error("Failed to retrieve studio-state data",e),new Error(`Failed to retrieve studio-state data for namespace ${t}`);return e.data},op=async t=>{await Nc({urlOverride:`${ls}/api/keyVal/${t}}`,id:""})},np=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Uc,deleteKeyValueNamespace:op,getKeyValue:Bc,updateKeyValue:jc},Symbol.toStringTag,{value:"Module"}));var ip=Object.defineProperty,ap=Object.getOwnPropertyDescriptor,Go=(t,e,s,r)=>{for(var o=r>1?void 0:r?ap(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ip(e,s,o),o};const Kc="key-value-model";let Zt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"namespace");l(this,"data");this.id=t,this.logger=s.logger,this.data=Ae(),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 jc(this.namespace,t,e),this.data[t]=e):(await Uc(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await Bc(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)}};Go([U({topic:"/keyVal/set"})],Zt.prototype,"handleStateUpdate",1);Go([U({topic:"/keyVal/remove"})],Zt.prototype,"handleStateDelete",1);Zt=Go([R(Kc)],Zt);const Vo=new we({class:Zt,type:Kc}),De=Oo(),cp=Object.freeze(Object.defineProperty({__proto__:null,default:De},Symbol.toStringTag,{value:"Module"})),lp=p.createLogger({name:"kos-log-manager-service",group:"Services"}),dp="/api/kos/logs/overrides",Hc=async()=>(lp.debug("sending GET for kos-log-manager"),await De.get(dp)),up=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:Hc},Symbol.toStringTag,{value:"Module"}));var hp=Object.defineProperty,fp=Object.getOwnPropertyDescriptor,wr=(t,e,s,r)=>{for(var o=r>1?void 0:r?fp(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&&hp(e,s,o),o};const zc="kos-log-manager-model",gp="/kos/logs/override/add/*",pp="/kos/logs/override/remove/*",mp=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 it=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new Co}updateModel(t){}resolveLoggers(){const t=p.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:mp(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=p.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=p.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=p.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await Hc();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)})}};wr([na("/api/kos/ui/loggers")],it.prototype,"getAllLoggers",1);wr([U({topic:gp,websocket:!0,wildcardName:"nodeType"})],it.prototype,"handleOverrideAdded",1);wr([U({topic:pp,websocket:!0,wildcardName:"nodeType"})],it.prototype,"handleOverrideRemoved",1);it=wr([R(zc)],it);const Gc=new Ee({class:it,type:zc}),{URL:ds}=oe(),{postModel:Yo,getOne:yp}=se.build({basePath:`${ds}/api/kos-time`});p.createLogger({name:"kos-time-service",group:"Services"});const Vc=async t=>{const e=await Yo({model:t,urlOverride:`${ds}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Yc=async t=>{const e=await Yo({model:t,urlOverride:`${ds}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},qc=async t=>{const e=await Yo({model:{},urlOverride:`${ds}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},Wc=async()=>{const t=await yp({urlOverride:`${ds}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},bp=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Wc,setDate:Yc,setTime:Vc,setTimezone:qc},Symbol.toStringTag,{value:"Module"}));var wp=Object.defineProperty,vp=Object.getOwnPropertyDescriptor,vr=(t,e,s,r)=>{for(var o=r>1?void 0:r?vp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&wp(e,s,o),o};const St="kos-time-model",Mp="/kos/time/time",Ep="/kos/time/day",Tp="/kos/time/timezone";let at=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"timezone");this.id=t,this.logger=s.logger,this.timezone=""}async updateSystemTime(t){await Vc(t)}async updateSystemDate(t){await Yc(t)}async updateSystemTimezone(t){await qc(t)}handleTimeChange(){j(Ht.TIME_CHANGE,{})}handleDayChange(){j(Ht.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),j(Ht.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await Wc();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};vr([U({topic:Mp,websocket:!0})],at.prototype,"handleTimeChange",1);vr([U({topic:Ep,websocket:!0})],at.prototype,"handleDayChange",1);vr([U({topic:Tp,websocket:!0})],at.prototype,"handleTimeZoneChange",1);at=vr([R(St)],at);const Ks={registration:{[St]:{class:at,singleton:!0}},type:St,predicate:he(St),factory:te.Singleton.create(St)};var _p=Object.defineProperty,Ip=Object.getOwnPropertyDescriptor,Qc=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ip(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&_p(e,s,o),o};const Zc="log-block-container-model";let Hs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({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}`)}};Qc([be],Hs.prototype,"_models",2);Hs=Qc([R(Zc)],Hs);const Sp=p.createLogger({name:"log-stream-container-service",group:"Services"}),Xc=()=>{var r;const t=ue(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return p.error(`getKosConnectionId: ${s}`),s},vt=Xc(),Op="/api/kos/logs/node/{nodeId}/streams",Jc=async()=>(Sp.debug("sending GET for log-stream-container"),await De.get(Op,{path:{nodeId:"primary"}},{destinationAddress:vt})),el=async(t,e="primary")=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:vt})},tl=async t=>{await De.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:vt})},$p=async()=>{await De.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:vt})},sl=async t=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:vt}),rl=async(t,e)=>await De.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:vt}),Dp=Object.freeze(Object.defineProperty({__proto__:null,createOverride:$p,getKosConnectionId:Xc,getLogStreamBlock:rl,getLogStreamBlocks:sl,getLogStreams:Jc,subscribeToLogStream:el,unsubscribeFromLogStream:tl},Symbol.toStringTag,{value:"Module"}));var Cp=Object.getOwnPropertyDescriptor,Rp=(t,e,s,r)=>{for(var o=r>1?void 0:r?Cp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ol="log-block-model";let Zr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await rl(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}`)}};Zr=Rp([R(ol)],Zr);const Xt=new we({class:Zr,type:ol}),Mr=new we({class:Hs,type:Zc});Mr.addRelatedModel(Xt);var Ap=Object.defineProperty,xp=Object.getOwnPropertyDescriptor,nl=(t,e,s,r)=>{for(var o=r>1?void 0:r?xp(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ap(e,s,o),o};const il="log-stream-model";let zs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"_blocks");l(this,"name");l(this,"currentBlockId");l(this,"isResetting");l(this,"generatorInstance");l(this,"shouldStop",!1);this.id=t,this.logger=s.logger,this.currentBlockId="",this.name=e.name,this.nodeId=e.nodeId,this.isResetting=!0,this._blocks=Mr.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=Xt.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=Xt.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 el(this.name)}async unsubscribe(){await tl(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 sl(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=dc(()=>{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()}}};nl([be],zs.prototype,"_blocks",2);zs=nl([R(il)],zs);const zt=new we({class:zs,type:il});var Pp=Object.defineProperty,Lp=Object.getOwnPropertyDescriptor,Ye=(t,e,s,r)=>{for(var o=r>1?void 0:r?Lp(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&&Pp(e,s,o),o};const al="log-stream-container-model",kp="/kos/logs/subscription/addBlock/*",Fp="/kos/logs/subscription/updateBlock/*",Np="/kos/logs/subscription/removeBlock/*",Up="/kos/logs/subscription/lines/*",cl="/kos/logs/streams/add/*";let Se=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"selectedStream");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Te({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: ${cl}`);const e=t.stream,s=zt.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=zt.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 Jc();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=zt.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};Ye([be],Se.prototype,"_models",2);Ye([U({topic:[cl],websocket:!0})],Se.prototype,"handleStreamAdded",1);Ye([U({topic:[kp],websocket:!0})],Se.prototype,"handleAddBlock",1);Ye([U({topic:[Np],websocket:!0})],Se.prototype,"handleRemoveBlock",1);Ye([U({topic:[Fp],websocket:!0})],Se.prototype,"handleUpdateBlock",1);Ye([U({topic:[Up],websocket:!0})],Se.prototype,"handleLogLine",1);Se=Ye([R(al)],Se);const us=new Ee({class:Se,type:al});us.addRelatedModel(zt);us.addRelatedModel(Mr);us.addRelatedModel(Xt);const jp=t=>t.rank!==void 0,Bp=t=>t.visibleRole!==void 0,Kp=t=>t.color!==void 0,Hp=t=>{const e=t.info;return jp(e)?e.rank:0},zp=t=>{const e=t.info;return Kp(e)?e.color:"orange"},Gp=t=>{const e=t.info;return Bp(e)?e.visibleRole:"TECHNICIAN"},{URL:qo}=oe(),{getAll:Vp,postModel:ll}=se.build({basePath:`${qo}/api/kos/troubles`}),dl=async()=>await Vp({}),ul=async(t,e)=>{try{const s=await ll({model:{},urlOverride:`${qo}/api/kos/troubles/resolve/${t}`,tracker:e});return s!=null&&s.data&&ze.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:xe.Fail,tracker:e,reason:"Failed to resolve trouble"};return ze.initiateFuture(r),r}},Yp=async(t,e)=>{try{const s=await ll({model:t,urlOverride:`${qo}/api/kos/troubles/resolve/`,tracker:e});return s!=null&&s.data&&ze.initiateFuture(s.data),s.data}catch{const r={id:e||"",endState:xe.Fail,tracker:e,reason:"Failed to resolve troubles"};return ze.initiateFuture(r),r}},qp=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Yp,getTroubles:dl,resolveTrouble:ul},Symbol.toStringTag,{value:"Module"})),Gs="troubleDataMapper",Es=new Map;is(Gs,{register:(t,e)=>{var s;Es.has(t)||Es.set(t,[]),(s=Es.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Es.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:p.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const hs="troubleMapper",Ts=new Map;is(hs,{register:(t,e)=>{var s;Ts.has(t)||Ts.set(t,[]),(s=Ts.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=Ts.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(p.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});S[hs].register("nozzle",async t=>[t.data.nozzlePath]);S[hs].register("path",async t=>[t.data.path]);const Wp=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>S[hs].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},hl=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>S[Gs].execute(i,t)),r=S[Gs].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 Qp{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class Zp{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class Xe{static getHandler(e){switch(e){case"ResolvableTrouble":return new Qp;case"BlockPumpTrouble":return new Zp;default:return}}}var Xp=Object.defineProperty,Jp=Object.getOwnPropertyDescriptor,fl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Jp(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&&Xp(e,s,o),o};const Ot="trouble-model";function _s(t){return typeof t.shouldDefer=="boolean"}let Vs=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:d,createTime:u,role:h,color:g,...m},y){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=y.logger,this.type=c,this._troubleId=o,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=g,this.tags=s,this.info=r,this.group=d,this.createTime=u,this.clientData=n,this.data={},Object.assign(this.data,m),this.futureHandler=new yr(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=Xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Xe.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=Xe.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Xe.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=Xe.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=Xe.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 hl(this)}get deferredCompanion(){const t=Yr(this.id,e=>_s(e));if(t&&_s(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Yr(this.id,e=>_s(e));return t&&_s(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 ul(this._troubleId,t)}};fl([hn()],Vs.prototype,"resolve",1);Vs=fl([R(Ot)],Vs);const Jt={registration:{[Ot]:{class:Vs,singleton:!1}},type:Ot,predicate:he(Ot),factory:te.Factory.create(Ot)};var em=Object.defineProperty,tm=Object.getOwnPropertyDescriptor,Er=(t,e,s,r)=>{for(var o=r>1?void 0:r?tm(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&em(e,s,o),o};const Kn=p.createLogger({name:"trouble-container-model"});function Hn(t){return S.propertyMapper.hasMapper(me.TroubleRank)?S.propertyMapper.executeMapper(me.TroubleRank,t):Hp(t)}function zn(t){return(S.propertyMapper.hasMapper(me.TroubleColor)?S.propertyMapper.executeMapper(me.TroubleColor,t):zp(t)).toLowerCase()}function Gn(t){return(S.propertyMapper.hasMapper(me.TroubleRole)?S.propertyMapper.executeMapper(me.TroubleRole,t):Gp(t)).toLowerCase()}const sm="trouble-container-model";class de{}l(de,"INDEX_TROUBLES_BY_IFACE","byIface"),l(de,"INDEX_TROUBLES_BY_TYPE","byType"),l(de,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(de,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(de,"SORT_KEY_RANK","rank"),l(de,"TROUBLES_DEFERRED","true");let ct=class{constructor(t){l(this,"id");l(this,"troubles");this.id=t,this.troubles=new Te({indexMap:{[de.INDEX_TROUBLES_BY_IFACE]:Wp,[de.INDEX_TROUBLES_BY_TYPE]:"type",[de.INDEX_TROUBLES_BY_GROUP]:"group",[de.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:de.SORT_KEY_RANK,parentId:t})}async load(){Kn.debug("loading trouble container");const t=await dl();try{t==null||t.data.forEach(e=>{const s={...e,rank:Hn(e),color:zn(e),role:Gn(e),id:String(e.id)},r=Jt.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw Kn.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&He(s)}handleTroubleAdded(t){const e={...t,rank:Hn(t),color:zn(t),role:Gn(t),id:String(t.id)};if(e.role==="NONE")return;const s=Jt.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};Er([be],ct.prototype,"troubles",2);Er([U({topic:"/kos/trouble/remove",websocket:!0,lifecycle:H.INIT})],ct.prototype,"handleTroubleRemoved",1);Er([U({topic:"/kos/trouble/add",websocket:!0})],ct.prototype,"handleTroubleAdded",1);ct=Er([R(sm)],ct);const Is="trouble-container-model",lt={registration:{[Is]:{class:ct,singleton:!0}},type:Is,predicate:he(Is),factory:te.Singleton.create(Is)},{URL:gl}=oe(),{getAll:rm}=se.build({basePath:`${gl}/api/kos/ota`}),Vn=p.createLogger({name:"ota-service",group:"Services"}),om=async()=>{Vn.debug("sending GET request to /api/kos/ota/artifacts");const t=await rm({urlOverride:`${gl}/api/kos/ota/artifacts`});return Vn.debug("getArtifacts - response:",t),t==null?void 0:t.data};var nm=Object.defineProperty,im=Object.getOwnPropertyDescriptor,Tr=(t,e,s,r)=>{for(var o=r>1?void 0:r?im(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&&nm(e,s,o),o};const pl="ota-model",am=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Fr=t=>{const e=t.artifactInfo,s=am(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 dt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new Co);l(this,"troubleContainer");this.id=t,this.logger=s.logger}get downloadInProgressTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTADownloadInProgressTrouble"))==null?void 0:e[0]}get updatePendingTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAUpdatePendingTrouble"))==null?void 0:e[0]}get pausedDueToErrorsTrouble(){var e;return(e=this.troubleContainer.troubles.getIndexByKey("byType","OTAPausedDueToErrorsTrouble"))==null?void 0:e[0]}get updates(){return this.data}get status(){return this.pausedDueToErrorsTrouble?"error":this.downloadInProgressTrouble?"downloading":this.updatePendingTrouble?"pending":"idle"}installAndReboot(){var t;this.updatePendingTrouble||this.logger.error("installAndReboot - OTAUpdatePendingTrouble not present"),this.logger.debug("installAndReboot - resolve OTAUpdatePendingTrouble"),(t=this.updatePendingTrouble)==null||t.resolve()}async init(){this.logger.debug(`initializing ota ${this.id}`)}async load(){this.logger.debug(`loading ota ${this.id}`);try{const t=await om();t&&t.forEach(e=>{const s=Fr(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=Fr(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=Fr(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};Tr([mt({modelType:lt.type})],dt.prototype,"troubleContainer",2);Tr([U({topic:"/kos/ota/artifacts/all",websocket:!0})],dt.prototype,"handleAllArtifacts",1);Tr([U({topic:"/kos/ota/artifacts/changed",websocket:!0})],dt.prototype,"handleChangedArtifacts",1);dt=Tr([R(pl)],dt);const Ys=new Ee({class:dt,type:pl});function cm(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 Nr=p.createLogger({name:"software-info-service",group:"Services"}),Wo=async t=>{Nr.debug("sending GET for software-info");const[e,s]=await Ac.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Nr.debug("Request was aborted"),new B("Request was aborted")):(Nr.error("Failed to fetch software-info",e),new B("Failed to fetch software-info"));return s},lm=cm(Wo),dm=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Wo,getSoftwareInfosWithCancel:lm},Symbol.toStringTag,{value:"Module"}));var um=Object.getOwnPropertyDescriptor,hm=(t,e,s,r)=>{for(var o=r>1?void 0:r?um(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const $t="software-info-model";let Xr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodes");this.id=t,this.logger=s.logger,this.nodes=[]}async init(){this.logger.debug(`initializing software-info ${this.id}`)}groupBy(t,e){return t.reduce((s,r)=>(s[r[e]]=[...s[r[e]]||[],r],s),{})}async load(){this.logger.debug(`loading software-info ${this.id}`);try{const t=await Wo(),e=(t==null?void 0:t.nodes)||{};X(()=>{const r=Object.keys(e).map(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 B&&this.logger.error("Failed to fetch software-info",t)}}};Xr=hm([R($t)],Xr);const qs={registration:{[$t]:{class:Xr,singleton:!1}},type:$t,predicate:he($t),factory:te.Factory.create($t)},{URL:ml}=oe(),{getOne:fm}=se.build({basePath:`${ml}/api/kos/state`}),gm=p.createLogger({name:"state-bean-service",group:"Services"}),yl=async({path:t})=>(gm.debug("sending GET for state-bean"),await fm({urlOverride:`${ml}/api/kos/state/${t}`})),pm=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:yl},Symbol.toStringTag,{value:"Module"}));var mm=Object.defineProperty,ym=Object.getOwnPropertyDescriptor,bl=(t,e,s,r)=>{for(var o=r>1?void 0:r?ym(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&mm(e,s,o),o};const Dt="state-bean-model",bm=Ge("path");let Ws=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"props");l(this,"logger");this.id=t,this.logger=s.logger,this.props=Ao.map(new Map),zr(e,this)}updateModel(t){zr(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&Lo(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&pr(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 yl({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};bl([U({topic:`/kos/state/${bm}`,websocket:!0})],Ws.prototype,"handleConfigBeanUpdated",1);Ws=bl([R(Dt)],Ws);const es={registration:{[Dt]:{class:Ws,singleton:!1}},type:Dt,predicate:he(Dt),factory:te.Factory.create(Dt)};var wm=Object.defineProperty,vm=Object.getOwnPropertyDescriptor,wl=(t,e,s,r)=>{for(var o=r>1?void 0:r?vm(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&&wm(e,s,o),o};const Ct="state-prop-model",Yn=Ge("path");let Qs=class{constructor(t,e,s){l(this,"id");l(this,"path");l(this,"attribute");l(this,"logger");l(this,"stateBean");this.id=t,this.logger=s.logger,this.path=e.path,this.attribute=e.attribute}get value(){return this.stateBean.props.get(this.attribute)}async init(){this.logger.debug(`initializing state-prop ${this.id}`)}async load(){this.logger.debug(`loading state-prop ${this.id}`)}toString(){var t;return((t=this.value)==null?void 0:t.toString())??""}};wl([mt({modelType:es.type,id:`state-bean-${Yn}`,options:{path:Yn}})],Qs.prototype,"stateBean",2);Qs=wl([R(Ct)],Qs);const Qo={registration:{[Ct]:{class:Qs,singleton:!1}},type:Ct,predicate:he(Ct),factory:te.Factory.create(Ct)},{URL:Mm}=oe(),{getAll:Em}=se.build({basePath:`${Mm}/api/state-prop`}),Tm=p.createLogger({name:"state-prop-service",group:"Services"}),_m=async()=>(Tm.debug("sending GET for state-prop"),await Em({})),Im=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:_m},Symbol.toStringTag,{value:"Module"})),{URL:Zo}=oe(),{getOne:vl}=se.build({basePath:`${Zo}/api/translation`}),Gt=p.createLogger({name:"translation-service",group:"Services"}),Sm=()=>{const t=window.location.origin,e=ue();return(e==null?void 0:e.host)||t},Ml=async(t,e)=>{Gt.debug("sending GET for translation");const s=e??Sm();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Gt.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Gt.error("Error fetching translations",r),r}},Om=async()=>{Gt.debug("getting localization descriptor");const t=await vl({urlOverride:`${Zo}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get tool localization descriptor ${t==null?void 0:t.status}`);return t.data},El=t=>async()=>{Gt.debug("getting kos localization descriptor");const e=await vl({urlOverride:`${Zo}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get tool localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},Tl="langResolver";var $m=Object.getOwnPropertyDescriptor,Dm=(t,e,s,r)=>{for(var o=r>1?void 0:r?$m(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Rt="translation-model";function Cm(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 _l(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null){const n=_l(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function Il(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]=Il(t[r],e[r]):s[r]=e[r]);return s}const Jr=(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)?Jr(r,e):r},Ss=(t,e,s)=>{const r=/{{(.*?)}}/g,n=Jr(t,e).replace(r,(a,c)=>Object.prototype.hasOwnProperty.call(s||{},c.trim())?s==null?void 0:s[c.trim()]:a);return Jr(n,e)},qn=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let eo=class{constructor(t,e,s){l(this,"id");l(this,"namespace");l(this,"descriptor");l(this,"defaultLocale");l(this,"currentLocale");l(this,"bundleResolver");l(this,"data");l(this,"logger");l(this,"resolver");l(this,"disposer");l(this,"context");l(this,"rootUrl");this.id=t,this.defaultLocale=e.defaultLocale||"en",this.currentLocale=e.currentLocale||"en",this.namespace=e.namespace,this.descriptor=e.descriptor,this.rootUrl=e.rootUrl,this.data={},this.resolver=e.resolver||s.kosContext.get(Tl),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=z.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return Ml(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);X(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=Il(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=_l(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=qn(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}=Cm(e),{namespace:n,key:i}=qn(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Ss(d,this.data,o)):Ss(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[a];return Array.isArray(c)?c.map(d=>Ss(d,this.data,o)):Ss(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()})}};eo=Dm([fr(),R(Rt)],eo);const Zs={registration:{[Rt]:{class:eo,singleton:!1}},type:Rt,predicate:he(Rt),factory:te.Factory.create(Rt)};var Rm=Object.defineProperty,Am=Object.getOwnPropertyDescriptor,Sl=(t,e,s,r)=>{for(var o=r>1?void 0:r?Am(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&&Rm(e,s,o),o};const At="translation-container-model",xm=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function Pm(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error(`namespace ${t} not found in descriptor`);const r=s.basePath,o=s.locales[e].file;return xm([r,o])}let Xs=class{constructor(t,e,s){l(this,"id");l(this,"lang");l(this,"rootUrl");l(this,"descriptor");l(this,"_defaultNamespace");l(this,"resolver");l(this,"logger");l(this,"descriptorUrl");l(this,"namespaces",[]);l(this,"_models");this.id=t,this.lang=e.lang||"en",this.descriptor=e.descriptor,this._defaultNamespace=e.defaultNamespace,this.descriptorUrl=e.descriptorUrl,this.rootUrl=e.rootUrl,this.resolver=e.resolver||Pm.bind(this),s.kosContext.set(Tl,this.resolver),this.logger=s.logger,this._models=new Te({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel(`translation-${this._defaultNamespace}`):void 0}getModel(t){return this.logger.debug(`getting model ${t}`),this._models.getModel(`translation-${t}`)}get models(){return this._models}get data(){return this._models.data}async reload(){this._models.clear(),await za(this);for(const t of this.namespaces){const e=this.resolveNamespace(t);await ae(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=Zs.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=Zs.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}`)}};Sl([be],Xs.prototype,"_models",2);Xs=Sl([R(At)],Xs);const Oe={registration:{[At]:{class:Xs,singleton:!0}},type:At,predicate:he(At),factory:te.Singleton.create(At)},Lm={set(t,e){const s=z.getContext(Oe.type);s&&s.set(t,e)},get(t){const e=z.getContext(Oe.type);return e==null?void 0:e.get(t)}},Ol={async init(t){const e=Oe.factory(t);return await ae(e),{translations:e}}};function km(t){return t.troubles!==void 0&&t.troubles instanceof Array&&t.troublesByType!==void 0&&typeof t.troublesByType=="object"}const Fm=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},$l="kos-ws-event",Xo=yt($l);var Nm=Object.defineProperty,Um=Object.getOwnPropertyDescriptor,Jo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Um(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Nm(e,s,o),o};const jm=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){p.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const d=this._topicMap.get(i)||0;a=`${a}-${d+1}`,this._topicMap.set(i,d+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:jm({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),p.debug(`logged ${this.events.size} events`)}}};Jo([U({topic:[ns.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Jo([U({topic:[ns.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Jo([R(Xo.type)],exports.WsEventModel);const Wn=ue(),Bm=Wn.debug==="true"||Wn.debug===!0,Km="/api/system/canvas",Dl=async(t,e)=>{const s=e||Km,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:Bm?"false":"true"},body:t})},Hm=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Dl},Symbol.toStringTag,{value:"Module"}));function Qn(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var zm=Object.defineProperty,Gm=Object.getOwnPropertyDescriptor,Cl=(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&&zm(e,s,o),o};const Rl="canvas-renderer-model";function Ur(t){return typeof t.onDone=="function"}let Js=class{constructor(t,e,s){l(this,"id");l(this,"router");l(this,"logger");l(this,"_renderer",null);l(this,"_clearOnComplete");l(this,"isStreaming",!1);l(this,"renderLoopId",null);l(this,"sendIntervalId",null);l(this,"timeoutId",null);l(this,"apiPath");l(this,"endpointName");l(this,"width",50);l(this,"height",30);l(this,"fps",10);l(this,"durationMs",null);l(this,"_onFrame",null);this.id=t,this.logger=s.logger,this.width=e.width??50,this.height=e.height??30,this.fps=e.fps??10,this.durationMs=e.durationMs??null,this.apiPath=e.apiPath??"/api/system/canvas",this.endpointName=e.endpoint}set onFrame(t){this._onFrame=t}set renderer(t){var e,s;this._renderer&&(this.stopStreaming(),(s=(e=this._renderer).dispose)==null||s.call(e)),this._renderer=t,this.isStreaming&&this.startStreaming()}setClearOnComplete(t){this._clearOnComplete=t}sendDataFrame(t,e){Dl(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=Qn(t);this.sendDataFrame(e,this.apiPath),(s=this._onFrame)==null||s.call(this,e)}stopStreaming(t=!0){var e,s;this.logger.debug(`stopStreaming called with clearCanvas=${t}`),this.isStreaming=!1,this.renderLoopId&&cancelAnimationFrame(this.renderLoopId),this.sendIntervalId&&clearInterval(this.sendIntervalId),this.timeoutId&&clearTimeout(this.timeoutId),(s=(e=this._renderer)==null?void 0:e.pause)==null||s.call(e),t&&(this.logger.debug("Clearing canvas..."),this.clearCanvas())}clearCanvas(){var s;const t=this.width>0?this.width:50,e=this.height>0?this.height:30;if(t>0&&e>0){const r=t*e*4,o=new Uint8ClampedArray(r);for(let i=3;i<r;i+=4)o[i]=255;const n=Qn(o);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 Ur(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=Ur(this._renderer);Ur(this._renderer)&&this._renderer.onDone(()=>{var c,d,u;this.logger.debug(`Renderer completed for ${this.id}`),j("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((u=(d=this._renderer)==null?void 0:d.isOneShot)==null?void 0:u.call(d))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,d;const a=(d=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:d.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(t,e)=>{this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`),this.stopStreaming(),e.send({status:"OK"})}),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/start`,async(t,e)=>{this.startStreaming(),e.send({status:"OK"})})}};Cl([mt({modelType:Ho.type})],Js.prototype,"router",2);Js=Cl([R(Rl)],Js);const en=new we({class:Js,type:Rl});class Al{constructor({src:e}){l(this,"video");l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);l(this,"doneCallback",null);this.video=document.createElement("video"),this.video.src=e,this.video.crossOrigin="anonymous",this.video.muted=!0,this.video.loop=!1,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");this.ctx=s,this.handleEnded=this.handleEnded.bind(this),this.video.addEventListener("ended",this.handleEnded)}handleEnded(){this.doneCallback&&this.doneCallback()}reset(){this.video.pause(),this.video.currentTime=0,this.lastUpdate=performance.now()}play(){this.video.play().catch(console.warn)}pause(){this.video.pause()}renderFrame(e,s){this.canvas.width=e,this.canvas.height=s,this.video.readyState>=2&&this.ctx.drawImage(this.video,0,0,e,s)}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}onDone(e){this.doneCallback=e}dispose(){this.video.pause(),this.video.removeAttribute("src"),this.video.load(),this.video.remove(),this.video.removeEventListener("ended",this.handleEnded),this.doneCallback=null}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}}class Vm{constructor(){l(this,"canvas");l(this,"gl");l(this,"lastWidth",0);l(this,"lastHeight",0);l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl");if(!e)throw new Error("WebGL not supported");this.gl=e}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e=this.lastWidth,s=this.lastHeight){const r=new Uint8Array(e*s*4);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,r);const o=new Uint8ClampedArray(r.length);for(let n=0;n<s;n++){const i=n*e*4,a=(s-1-n)*e*4;o.set(r.subarray(i,i+e*4),a)}return o}}class Ym extends Vm{constructor({speedPx:s=1}={}){super();l(this,"program");l(this,"posBuffer");l(this,"aPosition");l(this,"uMinHue");l(this,"uMaxHue");l(this,"uHueOffset");l(this,"uGridHeight");l(this,"minHue",0);l(this,"maxHue",80);l(this,"hueOffset",0);l(this,"speedPx",1);this.speedPx=s;const r=this.gl,o=`
|
|
78
78
|
attribute vec2 a_position;
|
|
79
79
|
void main() {
|
|
80
80
|
gl_Position = vec4(a_position, 0, 1);
|