@kosdev-code/kos-ui-sdk 0.1.0-dev.5798 → 0.1.0-dev.5800
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 +8 -8
- package/index.cjs.map +1 -1
- package/index.js +1902 -1903
- package/index.js.map +1 -1
- package/kos-models.json +1 -1
- package/package.json +3 -3
package/index.cjs
CHANGED
|
@@ -104,10 +104,10 @@ cmd:${s}
|
|
|
104
104
|
${c}topics:${e}
|
|
105
105
|
`:`${c}type:kos.broker.${s}
|
|
106
106
|
|
|
107
|
-
["${e}"]`;if(r?(f=this.fosSocket)==null?void 0:f.connectionEstablished:(p=this.socket)==null?void 0:p.connectionEstablished){const v=r?this.fosSocket:this.socket;(y=v==null?void 0:v.socket)==null||y.send(u)}else{at.debug("no connection adding to offline messages");const v=r?this.fosSocket:this.socket;v==null||v.addOfflineMessage(u)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n,explicitDestination:i}){const{unsubscribe:a,count:c}=C(e,s);return at.debug(`Topic ${e} currently has ${c} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n,i),()=>{const{count:u}=a();at.debug(`Topic ${e} currently has ${u} subscribers`),u===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n,i)}}async whenReady(){const e=this;return this.webSocketSupported?(await E.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(Lt,"_instance");class Zm{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);l(this,"baselineDependencies",new Map);l(this,"registeredTopics",new Set);l(this,"onceTopics",new Set);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[Z])||{},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.onceTopics.has(c)){this.log.debug(`Skipping once topic (already fired): ${c}`);return}if(this.registeredTopics.has(c)){this.log.debug(`Skipping duplicate subscription for ${c}`);return}if(this.registeredTopics.add(c),i.once&&this.onceTopics.add(c),this.log.debug(`Resolved topic: ${n} → ${c}`),i.requiresBaseline&&(this.baselineDependencies.set(c,i.requiresBaseline),this.log.debug(`Registered baseline dependency for ${c}: ${i.requiresBaseline.path}`)),i.flow)this.subscribeWithFlowControl(i,c,a);else{const u=this.createHandler(c,i);this.subscribe(i,c,u,a===I.ACTIVATE)}})}deactivate(){var s;this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const r of this.activatableDisposers)try{r()}catch(o){this.log.error("Error during subscription disposal",o)}this.activatableDisposers=[];const e=((s=this.modelData)==null?void 0:s[Z])||{};for(const[r,o]of Object.entries(e))if(o.lifecycle===I.ACTIVATE){const n=this.resolvePropKey(r);this.registeredTopics.delete(n)}}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=[],this.registeredTopics.clear()}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=Lt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n,explicitDestination:e.explicitDestination});o?this.activatableDisposers.push(i):this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=C(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{try{const o=this.extractWildcardCapture(e,r,s),n=this.isBaselineReady(e);if(!this.model.isReady()||!n){n?this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`):this.log.warn(`Baseline not ready for ${e}. Queuing message.`);const i=()=>{const a=sn(r,s.skipParse),c=s.transform(a);if(s.condition(c,this.modelData,r))return this.callHandlerWithWildcard(s,c,o,r)};this.offlineQueue.enqueue(i,e,r)}else{const i=sn(r,s.skipParse),a=s.transform(i);if(s.condition(a,this.modelData,r))return this.callHandlerWithWildcard(s,a,o,r)}}catch(o){this.log.error(`Error handling subscription for ${e}`,o)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!dl(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return ul(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 qm(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===I.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;Lt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a,explicitDestination:e.explicitDestination}),i=fa(s)}else i=fa(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,e,r)}}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}getResponseStore(){return this.modelData.serviceResponses}isBaselineReady(e){const s=this.baselineDependencies.get(e);if(!s)return!0;const r=this.getResponseStore();if(!r)return this.log.warn(`ServiceResponseStore not found for baseline check on topic: ${e}`),!1;const n=`${(s.method||"get").toUpperCase()}:${s.path}`;return r.has(n)}flushQueueForBaseline(e){const s=this.baselineDependencies.get(e);if(!s){this.log.debug(`No baseline dependency for topic: ${e}`);return}const r=this.getResponseStore();if(!r){this.log.warn("ServiceResponseStore not found, falling back to standard flush"),this.offlineQueue.flush();return}const o=s.method||"get",n=r.getTemporalMetadataByPath(s.path,o);if(!n){this.log.warn(`Baseline temporal metadata not found for ${s.path}, falling back to standard flush`),this.offlineQueue.flush();return}const i=s.replayStrategy||pt.AFTER_REQUEST;this.log.info(`Flushing queue with strategy ${i} for topic: ${e}`),this.log.debug(`Baseline timing - requested: ${n.requestedAt}, received: ${n.receivedAt}`),this.offlineQueue.flushWithStrategy(i,n.requestedAt,n.receivedAt)}}function $t(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 Jm(t){return!!(t!=null&&t[Be])&&Object.keys(t[Be]).length>0}function ey(t){return!!(t!=null&&t[Z])&&Object.keys(t[Z]).length>0}function ty(t){return!!(t!=null&&t[Ke])&&t[Ke].length>0}function sy(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[gt])&&Object.keys(e[gt]).length>0}function ry(t){return t.retention===ie.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function oy(t,e){return t.has(e)}function ny(t){return!t.expiresAt||Date.now()<t.expiresAt}function ma(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class iy{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:ie.SINGLE},o=Date.now(),n=Date.now()){if(this.shouldExtendTTL(e,r))return this.extendExistingTTL(e,r.ttl),!1;const i=this.createCachedResponse(s,e,r,o,n);return this.storeResponse(e,i,r),!0}get(e){const s=this.responses.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.delete(e);return}return s.data}}getByPath(e,s="get"){return this.get(this.makeKey(e,s))}has(e){return this.get(e)!==void 0}delete(e){this.responses.delete(e),this.retentionPolicies.delete(e);const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}clearPath(e){Array.from(this.responses.keys()).filter(r=>this.extractPath(r)===e).forEach(r=>this.delete(r))}clear(){this.cleanupTimers.forEach(e=>clearTimeout(e)),this.responses.clear(),this.retentionPolicies.clear(),this.cleanupTimers.clear()}get size(){return this.responses.size}shouldCleanupAfterHandler(e){const s=this.retentionPolicies.get(e);return(s==null?void 0:s.retention)===ie.IMMEDIATE}shouldExtendTTL(e,s){if(!ry(s)||!oy(this.responses,e))return!1;const r=this.responses.get(e);return ny(r)}extendExistingTTL(e,s){const r=this.responses.get(e);r.expiresAt=Date.now()+s,this.resetCleanupTimer(e,s)}resetCleanupTimer(e,s){this.clearTimerIfExists(e),ma(e,s,this.cleanupTimers,r=>this.delete(r))}clearTimerIfExists(e){const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}createCachedResponse(e,s,r,o,n){return{data:e,timestamp:n,requestedAt:o,receivedAt:n,path:this.extractPath(s),method:this.extractMethod(s),expiresAt:this.calculateExpiresAt(r)}}calculateExpiresAt(e){return e.retention===ie.TTL&&e.ttl?Date.now()+e.ttl:void 0}storeResponse(e,s,r){this.responses.set(e,s),this.retentionPolicies.set(e,r),this.applyRetentionPolicy(e,r)}applyRetentionPolicy(e,s){switch(s.retention){case ie.IMMEDIATE:break;case ie.TTL:s.ttl&&ma(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case ie.SINGLE:break;case ie.PERMANENT:case ie.MANUAL:break}}makeKey(e,s){return`${s.toUpperCase()}:${e}`}extractPath(e){return e.split(":",2)[1]||e}extractMethod(e){return e.split(":",2)[0]||"get"}getTemporalMetadata(e){const s=this.responses.get(e);if(s)return{requestedAt:s.requestedAt,receivedAt:s.receivedAt}}getTemporalMetadataByPath(e,s="get"){return this.getTemporalMetadata(this.makeKey(e,s))}cleanup(){const e=Date.now();Array.from(this.responses.entries()).filter(([r,o])=>o.expiresAt&&e>o.expiresAt).map(([r])=>r).forEach(r=>this.delete(r))}}class ay{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=Hn.create({modelId:s,modelTypeName:r}),i=new lm(e,$t(n,"fsm")),a=new dm($t(n,"offline-queue")),c=new tm(e),u=new em(e),d=new iy;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(Jm(o)&&(h.effectManager=new sm(r,s,o,$t(n,"effect"))),ey(o)){const f=$t(n,"subscription");h.subscriptionManager=new Zm(e,o,s,a,f),h.onlineLifecycleManager=new hm(e,$t(n,"online"))}return ty(o)&&(h.httpRouteManager=new Yn(o,$t(n,"http-routes"))),sy(o)&&(h.serviceRequestManager=new Km(o,d)),h}}const N=A.getLogger("kos-model"),cy="kos.extension.model.loader";class ql{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,"_isLoadExecuting");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"serviceResponses");l(this,"serviceRequestManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this._isLoadExecuting=!1,this.modelData=r,this._status=w.CREATED,this._activeStatus=w.INACTIVE,this._onlineStatus=w.OFFLINE;const o=ay.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,this.serviceResponses=o.serviceResponseStore,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),o.serviceRequestManager&&(this.serviceRequestManager=o.serviceRequestManager),E.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,serviceRequestManager:!1,serviceResponses:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Zg(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;N.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=Q.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw N.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r,o;N.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ls(this,I.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(I.ACTIVATE));const n=Q.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),this.initializeStateMachineForLifecycle(I.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(I.ACTIVATE),this.createLifecycleCompanions(I.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(n){throw N.debug(`Model ${this.modelId} failed to activate`),n}}async whenLoaded(){await Ko([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{N.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await Ko([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{N.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Ko([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===w.READY,onMatch:()=>{N.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,o;if(this.fsm.current===w.READY){N.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{N.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ls(this,I.READY),await Sl(this,Vn.READY,I.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(I.READY));const n=Q.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.ready)==null?void 0:r.call(s,n)),this.offlineQueue.flush(),this.initializeStateMachineForLifecycle(I.READY),(o=this.subscriptionManager)==null||o.registerAll(I.READY),this.createLifecycleCompanions(I.READY),N.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};H(ml(this.modelTypeName,this.modelId),i),H(yl(this.modelTypeName),i)}catch(n){throw N.error(n),Error(n)}}async load(){var o,n,i,a,c,u;const e=this[et];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===w.LOADED){N.debug(`Model ${s} with id ${r} already loaded`);return}if(this._isLoadExecuting){N.debug(`Model ${s} with id ${r} is currently executing load`);return}this._isLoadExecuting=!0;try{N.debug(`Loading model ${s} with id ${r}`),await ls(this,I.LOAD);const d=Q.getContext(r),h=`${cy}.${s}`,f=await T.loader.executeLoader(h,{});f&&(N.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(I.LOAD)),await((i=(n=this.modelData)==null?void 0:n.load)==null?void 0:i.call(n,d)),te(()=>{this.loaded=!0}),N.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(I.LOAD),(a=this.subscriptionManager)==null||a.registerAll(I.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(I.LOAD)}catch(d){throw N.error(`Model ${r} failed to load`,d),d}finally{this._isLoadExecuting=!1}}async unload(){var e,s,r,o,n,i,a;N.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const c=this.getChildren().map(d=>{var h;return(h=d.unload)==null?void 0:h.call(d)}).filter(d=>!!d);await Promise.allSettled(c);const u=Q.getContext(this.modelId);if(await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,u)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),this.modelData){const d=this.modelData;if(d._fsmInitialized=!1,d._fsmConfig){const h=((o=d._fsmOptions)==null?void 0:o.stateProperty)||"currentState";d[h]=void 0}d.stateHistory&&(d.stateHistory=[])}N.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(n=this.effectManager)==null||n.disposeAll(),(i=this.subscriptionManager)==null||i.disposeAll(),(a=this.httpRouteManager)==null||a.dispose()}catch(c){throw N.debug(`Model ${this.modelId} failed to unload`),c}}async init(){var n,i,a,c;const e=this[et];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=Q.getContext(s);N.debug(`Initializing model ${r} with id ${s}`),await ls(this,I.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(I.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,o)),this.initialized=!0,N.debug(`Model ${r} with id ${s} initialized`),(c=this.onlineLifecycleManager)==null||c.register(),this.initializeStateMachineForLifecycle(I.INIT),this.registerSubscribers(I.INIT),this.createLifecycleCompanions(I.INIT)}catch(u){throw N.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;N.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&Bc(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;N.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=Q.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(I.ONLINE)}async offline(){var s,r,o;N.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=Q.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 Ho=g.createLogger({name:"kos-model-instantiator"});class ly{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new zg(e,s,this.createModelInstance.bind(this))}createModelInstance(e,s,r={}){var a;const o=this.registry.models[e];if(!o){const c=`No model registered for type ${e}`;throw Ho.error(c,{modelType:e,requestedId:s,providedOptions:r,availableModelTypes:Object.keys(this.registry.models)}),Pt(new Error(c),{modelType:e,modelId:s,operation:"model instantiation - registry lookup",options:r,metadata:{availableModelTypes:Object.keys(this.registry.models)}})}const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Ho.debug(`Creating model instance: ${e} [${n}]`);const c=r&&Object.keys(r).length>0,u=o.class||o.create;if(((a=u==null?void 0:u.prototype)==null?void 0:a[Qs])===!0&&!c){const h=new Error(`Model ${e} requires options but none were provided`);throw ua(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Pt(h,{modelType:e,modelId:n,operation:"model instantiation - options validation",options:r,metadata:{requiresOptions:!0,hasOptions:!1}})}try{const h=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),f=new ql({modelTypeName:e,id:n,modelData:h});this.cache.addModel(f),this._createCompanionModels(f,r)}catch(h){throw ua(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Pt(h,{modelType:e,modelId:n,operation:"model instantiation",options:r})}}const i=this.cache.getModelById(n);if(!i)throw Ho.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}createCompanionModels(e,s,r){this.companionInstantiator.createCompanionModels(e,s,r)}_createCompanionModels(e,s){this.createCompanionModels(e,s)}}let uy=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 Jt(e)}};const zl=10,ya=g.createLogger({name:"kos-model-manager"});class Vl{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Kg,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 uy(e),r.cache=new Hg(e.preloadModels),r.instantiator=new ly(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(ya.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=>(ya.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 Jt(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(L.RESET,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),pl.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),zl)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}createLifecycleCompanions(e,s,r){this.instantiator.createCompanionModels(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var wr=(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))(wr||{}),ut=(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))(ut||{});const dy=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),E.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),E.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,n=>A.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(()=>{E.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=>A.debug(n.machine.current)),online:s}},W=g.createLogger({name:"kos-core"}),hy=()=>{const t=de(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},fy=()=>{const t=window.location.protocol,e=de(),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://")},py=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=de(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},gy=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=de(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},my=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?g.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):g.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)}}},ba=t=>typeof t.reload=="function",yy=t=>typeof t.unload=="function";var Gl=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(Gl||{});class S{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=wr.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,E.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(Te.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(ut.GO_ONLINE)}),C(Te.DISCONNECTED,async()=>{this.fsmService.service.send(ut.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0,this.fsmService.service.send(ut.RELOAD)}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(Te.RELOAD,()=>{W.warn("WebSocket requested reload"),this.fsmService.service.send(ut.RELOAD)}),C("/studio/project/reload",()=>{W.warn("Project requested reload"),this.fsmService.service.send(ut.RELOAD)});const s=Lt.getInstance(),r=py(),o=gy(),n=fy();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=hy()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=dy(this),this.fsmService.service.send(ut.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){W.info("reload already in progress");return}this._reloading=!0,W.warn("reloading KOS Core"),W.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)ba(c.modelData)&&(W.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),W.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&ba(c.modelData)&&(W.warn(`reloading model ${c.modelId}`),(i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{E.runInAction(()=>{W.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){W.debug("KOS Core going online"),await this._transport.whenReady(),W.debug("KOS Transport Ready. Calling online() for models"),H("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){W.debug("KOS Core going offline"),H("/kosCore/offline","/kosCore/offline")}async unload(){var o;W.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,W.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)yy(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-e;setTimeout(()=>{E.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await E.when(()=>this.status===wr.READY)}async ready(){W.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}=my(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw W.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);W.debug("leaving kos-core ready() ")}get isReady(){return this.status===wr.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){W.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,W.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){W.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,W.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(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{T.dataMapper.registerDataMapper(u,p)}):T.dataMapper.registerDataMapper(u,d))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&T.propertyMapper.registerPropertyMapper(u,d)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&T.loader.registerLoader(u,d)}),R.model.getAll().forEach(([,u])=>{e.models={...e.models,...u.registration}}),e.models={...e.models,...R.model.getLegacyModels()},R.companion.getAll().forEach(([u,d])=>{e.companionModels={...e.companionModels},e.companionModels[u]=e.companionModels[u]||[];for(const h of d){let f;if(typeof h=="string"){const p=e.models[h];if(p!=null&&p.class){const y=p.class.prototype[et];f=y==null?void 0:y.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),R.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=Vl.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(S,"_instance");const by=g.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Yl{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=S.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){by.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}class vy extends Yl{constructor(s){super();l(this,"targetId");l(this,"currentPath",[]);l(this,"foundPath",null);this.targetId=s}visit(s){var o;if(this.visitedModels.has(s.modelId))return;this.currentPath.push(s.modelId),this.visitedModels.add(s.modelId),!!this.visitModel(s.modelData)||(o=s.getChildren)==null||o.call(s).forEach(n=>{var i;this.foundPath||(i=n.accept)==null||i.call(n,this)}),this.foundPath||this.currentPath.pop()}visitModel(s){return s.id===this.targetId?(this.foundPath=this.currentPath.slice(0,-1),!0):!1}getAncestorPath(){return this.foundPath??[]}wasFound(){return this.foundPath!==null}}function wy(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,o)})})}function Ey(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const Qn=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},Wl=t=>t,Xn=t=>t,My=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=Wl,idMapper:o=Xn})=>n=>{const i=n.map(o),c=Qn(i,t.data).map(r).filter(Boolean);t.removeAll(c);const u=i.map(d=>{const h=t.getModel(d.id);return h&&s?s(d,h):e(d)}).filter(Boolean);t.addAll(u)},_y=({container:t,onAddItem:e,onRemoveItem:s=Wl,idMapper:r=Xn})=>o=>{const n=o.map(r);Qn(n,t.models).forEach(s),n.forEach(e)},Ty=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=Xn})=>o=>{const n=o.map(r);Qn(n,t).forEach(s),n.forEach(e)},Sy=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},va=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),wa=[{amount:60,name:"seconds"},{amount:60,name:"minutes"},{amount:24,name:"hours"},{amount:7,name:"days"},{amount:4.34524,name:"weeks"},{amount:12,name:"months"},{amount:Number.POSITIVE_INFINITY,name:"years"}];function Ql(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=wa.length;s++){const r=wa[s];if(Math.abs(e)<r.amount)return va.format(Math.round(e),r.name);e/=r.amount}return va.format(Math.round(e),"years")}const Zn=t=>t%4===0&&t%100!==0||t%400===0,Jn=(t,e)=>[31,Zn(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Xl=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,Jn(s.getFullYear(),s.getMonth()))),s},Zl=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},Ft="en-US",Jl={short:{year:"numeric",month:"2-digit",day:"2-digit"},medium:{year:"numeric",month:"short",day:"2-digit"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}},eu={short:{hour:"2-digit",minute:"2-digit",hour12:!0},medium:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0},long:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZoneName:"short"},full:{hour:"2-digit",minute:"2-digit",hour12:!0,timeZoneName:"long"}},tu=(t,{dateStyle:e="short",locales:s=Ft}={dateStyle:"short",locales:Ft})=>{const r=e==="short"?Jl.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},su=(t,{locales:e=Ft,timeStyle:s="short"}={locales:Ft,timeStyle:"short"})=>{const r=eu[s];return new Intl.DateTimeFormat(e,r).format(t)},ru=(t,{dateStyle:e="short",locales:s=Ft,timeStyle:r="short"}={dateStyle:"short",locales:Ft,timeStyle:"short"})=>{const o={...e&&Jl[e],...r&&eu[r]};return new Intl.DateTimeFormat(s,o).format(t)},$y=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Zl,addMonthsToDate:Xl,formatDate:tu,formatDateSince:Ql,formatDateTime:ru,formatTime:su,getDaysInMonth:Jn,isLeapYear:Zn},Symbol.toStringTag,{value:"Module"})),ou="featureFlagResolver",cr=new Map;Zt(ou,{register:(t,e)=>{var s;cr.has(t)||cr.set(t,[]),(s=cr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=cr.get(t);if(!s)return[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(g.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return iu.updateFlags(i),Object.keys(i)}});const Oy="kos.loader.featureFlag";class nu{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new nu;const iu=window.KosFeatureFlags,au=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,o=n=>{const i=(n+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},cu=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return au(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},lu=(t,e)=>getComputedStyle(t).getPropertyValue(e),Iy=(t,e)=>cu(lu(t,e)),Cy=(t,e)=>{const s={...t};return s.id&&delete s.id,s},on=(t,e,s=Cy)=>{const r=s(t,e);E.runInAction(()=>{Object.assign(e,r)})};class uu{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 Dy=async(t,e)=>{const s=new uu;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},Jt=t=>({type:t,build:(e,s)=>S.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=S.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),xy=t=>{S.getInstance().modelManager.registerModel(t)},Ay=(t,e)=>{S.getInstance().modelManager.registerCompanionModel(t,e)},Ea="/kos/ui/internal/heartbeat/",Ry=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=S.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${Ea}${t}`,callback:()=>{a=performance.now()}}),u=r??3e3,d=window.setInterval(()=>{let v=performance.now()-a;v=v/1e3,v>u/1e3&&i.abort()},u),h=o??2e3,f=window.setInterval(()=>{Nl({msg:{},options:{topic:`${Ea}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},y=()=>{p(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:p}},du=(...t)=>e=>t.reduce((s,r)=>r(s),e),Py={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function ky(t,e){let s=1;const r={...Py,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(g.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw c}throw new Error("All attempts failed")}const Ly=g.createLogger({name:"kos-service-request"}),fe=t=>({isMock:!1,URL:exports.BASE_URL}),Fy=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f})=>{const p={method:"DELETE"};t&&(p.destinationAddress=t),o&&(p.tracker=o),es(p,{ordered:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f});try{const y=await s(n||`${e}/${r}`,p);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 z("Request timed out while deleting model");if(y.name==="AbortError")throw new z("Request was cancelled while deleting model")}throw y}},es=(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),Ny=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,signal:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),es(h,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,signal:u,destinationAddress:d});const f=r||e;try{const p=await s(f,h);if(!p.ok){let v;try{v=await p.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${p.status}`,v??void 0)}return await p.json()??void 0}catch(p){if(p instanceof DOMException){if(p.name==="TimeoutError")throw new z("Request timed out while retrieving models");if(p.name==="AbortError")throw new z("Request was cancelled while retrieving models")}throw p}},Uy=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:u,signal:d,destinationAddress:h})=>{const f={method:"GET"};t&&(f.destinationAddress=t),c&&(f.tracker=c),es(f,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,signal:d,destinationAddress:h});const p=r||e;Ly.debug(`resolvedUrl: ${p}`);try{const y=await s(p,f);if(!y.ok){let M;try{M=await y.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${y.status}`,M??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new z("Request timed out while retrieving model");if(y.name==="AbortError")throw new z("Request was cancelled while retrieving model")}throw y}},jy=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:u,signal:d,destinationAddress:h})=>{const f={method:"GET"};t&&(f.destinationAddress=t),es(f,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,signal:d,destinationAddress:h});const p=r||`${e}/${o}`;try{const y=await s(p,f);if(!y.ok){let M;try{M=await y.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${y.status}`,M??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new z("Request timed out while retrieving model by ID");if(y.name==="AbortError")throw new z("Request was cancelled while retrieving model by ID")}throw y}};class z extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Ma=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f})=>{const p={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(p.destinationAddress=t),i&&(p.tracker=i),es(p,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,signal:h,destinationAddress:f});try{const y=await s(o||e,p);if(!y.ok){let M;try{M=await y.json()}catch{}throw new z(`There was a problem sending the POST data; returned status ${y.status}`,M??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new z("Request timed out while adding model");if(y.name==="AbortError")throw new z("Request was cancelled while adding model")}throw y}},_a=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,signal:f,destinationAddress:p})=>{const y={method:t};o&&(y.body=JSON.stringify(o)),e&&(y.destinationAddress=e),es(y,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,signal:f,destinationAddress:p});try{const v=await r(i||`${s}/${n}`,y);if(!v.ok){let $;try{$=await v.json()}catch{}throw new z(`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 z("Request timed out while modifying model");if(v.name==="AbortError")throw new z("Request was cancelled while modifying model")}throw v}},ce={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:Ny(t,s||e,c),getModelById:jy(t,r||e,c),getOne:Uy(t,r||e,c),addModel:Ma(t,n||e,c),deleteModel:Fy(t,o||e,c),modifyModel:_a("POST",t,i||e,c),putModel:_a("PUT",t,i||e,c),postModel:Ma(t,n||e,c)}}};function By(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function Ky(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function Hy(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function qy(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function zy(t){const e=t.serviceResponses;e&&e.clear()}const Vy=wt(),hu=()=>`kos-${Vy}`,Gy=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(hu()),ei=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=C(t,i=>{A.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)}),Yy=async(t,e,s)=>{const r=ei(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)},Wy=async({topic:t,msg:e,requestId:s})=>{const r=s??wt(),o=ei(r);H(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},be=new Map;class fu{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new E.ObservableMap({}),this._parent="",E.makeAutoObservable(this)}setParent(e){te(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=ke(this._parent))==null?void 0:e.model}get companionModels(){const e=ke(this._id);return e!=null&&e.model?nl(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||!be.has(n.id)?!1:(i=be.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=be.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=be.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 Q={createContext:(t,e)=>{const s=be.get(t)??new fu(t);if(e){if(!be.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return be.set(t,s),s},getContext:t=>be.get(t),deleteContext:t=>{be.delete(t)},setParentContext:(t,e)=>{var s;if(!be.has(e))throw new Error(`Parent context ${e} does not exist`);(s=be.get(t))==null||s.setParent(e)},rootContext:()=>be.get("root")};Q.createContext("root");const Qy=t=>Q.getContext(t.id),ct=g.createLogger({name:"kos-data-container"});class ti{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");l(this,"_maxCapacity");l(this,"_evictionStrategy");l(this,"_evictionBatchSize");l(this,"_insertionOrder",[]);l(this,"_accessTimes");l(this,"_customEvictionFilter");this._data=E.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=E.observable.map(s),this.idx=Pe(),this._maxCapacity=e==null?void 0:e.maxCapacity,this._evictionStrategy=(e==null?void 0:e.evictionStrategy)||"fifo",this._evictionBatchSize=(e==null?void 0:e.evictionBatchSize)??Math.max(10,Math.ceil(((e==null?void 0:e.maxCapacity)??100)*.1)),this._customEvictionFilter=e==null?void 0:e.customEvictionFilter,this._evictionStrategy==="lru"&&this._maxCapacity&&(this._accessTimes=E.observable.map(new Map)),E.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new qn({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){E.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){E.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(){E.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=this._ensureObservable(e);this._cleanupExistingDisposer(e.id),this._persistData(r),this._trackDataMetadata(r),this._enforceCapacityLimits(),this._configureDataMonitoring(r),s||this.increment()}_ensureObservable(e){return E.isObservable(e)?e:E.observable.object(e)}_cleanupExistingDisposer(e){if(!e)return;const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}_persistData(e){this._data.set(e.id||"",e)}_trackDataMetadata(e){this._maxCapacity&&(this._insertionOrder.push(e.id||""),this._accessTimes&&this._accessTimes.set(e.id||"",Date.now()))}_enforceCapacityLimits(){this._maxCapacity&&this._data.size>this._maxCapacity&&this._evictModels()}_configureDataMonitoring(e){const s=E.observe(e,r=>{Object.values(this._optionsMap||{}).includes(r.name)&&this.increment()});this._disposerMap.set(e.id||"",s)}removeModel(e){this._data.delete(e);const s=this._insertionOrder.indexOf(e);s!==-1&&this._insertionOrder.splice(s,1),this._accessTimes&&this._accessTimes.delete(e),this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){const s=E.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){const s=this._data.get(e);return s&&this._accessTimes&&this._accessTimes.set(e,Date.now()),s}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(ct.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):(ct.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return ct.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}_evictModels(){if(!this._maxCapacity)return;const e=this._data.size-this._maxCapacity;if(e<=0)return;const s=Math.min(this._evictionBatchSize,e);this._logDataCapacityWarning(s);const r=this._selectDataForEviction(s);this._removeEvictedData(r),this._logDataEvictionComplete(r.length)}_logDataCapacityWarning(e){ct.info(`Data container capacity exceeded (${this._data.size}/${this._maxCapacity}). Evicting ${e} items using ${this._evictionStrategy} strategy. This may indicate missing cleanup handlers or data inconsistency.`)}_selectDataForEviction(e){switch(this._evictionStrategy){case"fifo":return this._selectFifoData(e);case"lru":return this._selectLruData(e);case"custom":return this._selectCustomData(e);default:return this._selectFifoData(e)}}_selectFifoData(e){const s=[];for(let r=0;r<e&&this._insertionOrder.length>0;r++){const o=this._insertionOrder.shift();o&&this._data.has(o)&&s.push(o)}return s}_selectLruData(e){const s=[];return this._accessTimes&&Array.from(this._accessTimes.entries()).sort((o,n)=>o[1]-n[1]).slice(0,e).forEach(([o])=>{this._data.has(o)&&s.push(o)}),s}_selectCustomData(e){return this._customEvictionFilter?this._customEvictionFilter(this.data).slice(0,e).map(r=>r.id):(ct.error("Custom eviction strategy specified but no customEvictionFilter provided. Falling back to FIFO."),this._selectFifoData(e))}_removeEvictedData(e){e.forEach(s=>{var o;const r=this._data.get(s);ct.info(`Evicting data item: ${s}`,{itemId:s,itemType:r?(o=r.constructor)==null?void 0:o.name:"unknown",strategy:this._evictionStrategy}),this.removeModel(s)})}_logDataEvictionComplete(e){ct.info(`Evicted ${e} data items. Current size: ${this._data.size}/${this._maxCapacity}`)}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 Xy{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 he.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return Ie(this.type)}}class Zy{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 he.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return Ie(this.type)}}class pu{constructor(){l(this,"_token");E.makeAutoObservable(this),C("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class gu{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 u=this.matchRoute(c.path,r);if(c.method===e.method&&u){i.params=u;let d=0;const h=async()=>{if(d<c.middlewares.length){const f=c.middlewares[d++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),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 mu=g.createLogger({name:"intent-service"}),Jy=t=>{On(`/kos/intent/${t.type}`)?H(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):mu.info(`No subscribers for intent ${t.type}. Intent not sent.`)},eb=async t=>new Promise(e=>{const{type:s,options:r}=t;if(On(`/kos/intent/${t.type}`)){const o=wt(),{unsubscribe:n}=C(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);H(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else mu.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),je=g.createLogger({name:"app-startup-service"});async function yu(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return je.warn("No app IDs provided to waitForAppsToStart"),!0;je.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await Dn(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>Wn),[u,d]=await c.get("/api/kos/apps/started");return u?(je.error("Error fetching started apps:",u),[]):d}catch(c){je.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(u=>{const d=c.find(h=>h.appId===u);return!(!d||!d.started||o&&!d.postStarted)}),timeout:s}),a=t.filter(c=>{const u=i.find(d=>d.appId===c);return!!(!u||!u.started||o&&!u.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(je.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return je.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(je.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function tb(t,e={}){return yu([t],e)}async function sb(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){je.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function rb(){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 je.error("Failed to fetch started apps:",t),[]}}const nn=E.when,si=E.computed,te=E.runInAction,X=E.autorun,bu=E.reaction,ri=E.observable,oi="Not Assigned",ob="kos.trouble.added",nb="kos.trouble.removed";var se=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t.RegionServicePath="kos.region.service_path.mapper",t.ConfigServicePath="kos.config.service_path.mapper",t))(se||{}),Is=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Is||{});const vu=g.createLogger({name:"config-bean-service",group:"Services"}),ni=exports.BASE_URL,wu=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:ib,getOne:ab}=ce.build({destinationAddress:"",basePath:`${ni}/kos/config/`}),Eu=async(t,e,s="/api/kos/config")=>(vu.debug(`sending modify request for ConfigBean: ${t}`),ib({model:e,urlOverride:`${ni}${s}/${t}`})),Mu=async(t,e="/api/kos/config")=>(vu.debug(`sending get request for ConfigBean: ${t}`),await ab({urlOverride:`${ni}${e}/details/${t}/15`})),ii=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",go=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function _u(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Tu(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])?Tu(t[r],o,s):s[o]=t[r]}return s}const Su=(t,e)=>{const s=t.details[0].bean||_u(t.details[0].scopes),r=Tu(s);E.runInAction(()=>{const o={...r};e.props.setValues(o)})},$u=(t,e)=>{E.runInAction(()=>{const s=t.changes.reduce((n,i)=>(n[i.attr]=i,n),{}),r=t.scopedChanges.reduce((n,i)=>{const a=n[i.attr];return a&&(n[i.attr]={...a,currentValue:i.currentValue??a.currentValue,previousValue:i.previousValue??a.previousValue}),n},s);Object.values(r).forEach(n=>{const i=n.attr;let a=n.currentValue,c=n.previousValue;typeof a=="string"&&ii(a)&&(a=a.toLowerCase()=="true",c=(c==null?void 0:c.toLowerCase())=="true"),typeof a=="string"&&go(a)&&(a=Number(a),c=Number(c)),e.props[i]=a,e.prevProps[i]=c})})},Ou=t=>Object.fromEntries(t.props.entries),cb=t=>e=>s=>t.build(e,s);var lb=Object.defineProperty,ub=Object.getOwnPropertyDescriptor,Iu=(t,e,s,r)=>{for(var o=r>1?void 0:r?ub(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&&lb(e,s,o),o};function db(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const ai="config-bean-model",lr=g.getLogger(ai),hb=vt("path");function fb(t){return T.propertyMapper.hasMapper(se.ConfigServicePath)?T.propertyMapper.executeMapper(se.ConfigServicePath,t):"/api/kos/config"}let Dr=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath||fb(this);const{modifyConfigBean:s=Eu,getConfigBean:r=Mu}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Pe(),this.prevProps=Pe()}get values(){return this.props.values}async ready(){lr.debug(`readying config bean ${this.path}`),lr.debug(`complete readying config bean ${this.path}`)}async load(){lr.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;Su(e,this),lr.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;te(()=>{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=db(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=Ou(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){$u(t,this)}};Iu([B({topic:`/kos/config/${hb}`,websocket:!0})],Dr.prototype,"handleConfigBeanUpdated",1);Dr=Iu([D(ai)],Dr);const Rs=new Ee({class:Dr,type:ai}),mo=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Rs.type,id:`${Rs.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:I.INIT,lazy:e}},{URL:ci}=fe(),{getOne:pb,getAll:gb}=ce.build({basePath:`${ci}/api/kos/regions/info`}),Cu=async t=>{try{return await pb({urlOverride:`${ci}${t}/info`})}catch{return}},Du=async t=>{try{return await gb({urlOverride:`${ci}${t}`})}catch{return}},mb=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Cu,getRegions:Du},Symbol.toStringTag,{value:"Module"}));var ge=(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))(ge||{});const xu={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 yb(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},{...xu});return{...t,...r}}function bb(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,n.alias&&(a[n.alias]=c),Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,o},{time:{[s]:{...xu}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function vb(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 wb=Object.defineProperty,Eb=Object.getOwnPropertyDescriptor,li=(t,e,s,r)=>{for(var o=r>1?void 0:r?Eb(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&&wb(e,s,o),o};const Er="region-info-model",cs=g.createLogger({name:"region-info-model"});function Mb(t){return T.propertyMapper.hasMapper(se.RegionServicePath)?T.propertyMapper.executeMapper(se.RegionServicePath,t):"/api/kos/regions"}let Ps=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"serviceBasePath");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.serviceBasePath=Mb(this),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[ge.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[ge.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[ge.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[ge.family]!==s[ge.family])throw new Error(`Cannot convert between units of different families: ${e[ge.family]} and ${s[ge.family]}`);const r=e[ge.offset],o=e[ge.scale],n=s[ge.scale],i=s[ge.offset],a=s[ge.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 u=this.measureMap[s.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=u[s.system])==null?void 0:a.default,i||cs.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const u=this.measureMap[e.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=u[e.system])==null?void 0:c.default,n||cs.info("Could not find default unit for measure",e.measure)}return!n||!i?(cs.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){cs.debug("initializing region info")}async load(){cs.debug("loading region info");const t=await Du(this.serviceBasePath);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 Cu(this.serviceBasePath);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(yb,{}),this.measureMap=e.data.unitSystems.reduce(bb,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(vb,{}),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))}};li([mo({path:"kos:service:region:settings"})],Ps.prototype,"regionSource",2);li([mo({path:"kos:service:region"})],Ps.prototype,"region",2);Ps=li([D(Er)],Ps);const ae={registration:{[Er]:{class:Ps,singleton:!0}},type:Er,factory:he.Singleton.create(Er)},xr=({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},ui=(t,e,s)=>{const{model:r}=ke(ae.type);if(!r)throw new Error("RegionInfo model not found");if(!Ir(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=xr({source:e}),i=xr({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Ta(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 _b=(t,e,s,r)=>{const o=ui(t,e,s),n=xr({source:e}),{model:i}=ke(ae.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=xr({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),d=i.getDefaultUnitForMeasure(a,u.system),h=i.getDefaultUnitDecimalPlaces(a,u.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:d||n.unit||"",display:Ta(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:Ta(o,d||n.unit||"",{...f,mode:"short"})}};function Sa({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 $a({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 Ot=(t,e)=>s=>!t||!e?s:go(s)?ui(Number(s),t,e):s,Tb=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Sa(t.options).map(Ot(s,r));if(t.options.type==="rangeInterval")return $a(t.options).map(Ot(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(Ot(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Sa(t.options.unitSystems[e]).map(Ot(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return $a(t.options.unitSystems[e]).map(Ot(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(Ot(s,r))}}return[]},Sb=(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 $b=Object.defineProperty,Ob=Object.getOwnPropertyDescriptor,di=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ob(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&&$b(e,s,o),o};function Ib(t){return(t==null?void 0:t.type)==="enum"}function Cb(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 Db(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return Xe.format(r,e)}const Mr="config-bean-prop-model",It=g.createLogger({name:"config-bean-prop-model"}),xb=vt("path"),Ab=vt("serviceBasePath");let ks=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 wu(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?Cb(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=Ib(r)?r.values:Tb(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,i;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 a=this.getDefaultUnitDecimalPlaces(r,((n=s==null?void 0:s.to)==null?void 0:n.system)||e,(i=s==null?void 0:s.to)==null?void 0:i.unit);try{const u=this.getFormatterOptions(s);if(u){let d=String(t);return d=u.formatToParts(Number(t))[0].value,Number(d)}}catch(u){It.info(`error formatting value ${t}`,u)}return Number(t).toFixed(a)}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(){It.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 Db(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){It.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 Sb(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,u=this.formatter||c;if(u){let d=typeof u=="function"?u(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):u;s&&(d={unit:this.getDefaultUnit(t),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...d})}catch(h){It.error(`error creating formatter ${d}. Returning the raw value`,h)}}else It.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,u,d,h,f,p,y,v;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const M=(r=this.converter)==null?void 0:r.measure,$=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,U=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,x=(u=(c=this.converter)==null?void 0:c.to)!=null&&u.unit?this.regionInfo.getUnitMeasure(this.converter.to.unit):void 0,O=M||$||U||x||e,P=((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.unit)||this.regionInfo.getDefaultUnitForMeasure(O,((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.defaultUnitSystem),V=((v=(y=this.converter)==null?void 0:y.to)==null?void 0:v.system)??this.regionInfo.getUnitSystem(P),ee=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:ee,...this.converter.from},to:{...this.converter.to,unit:P,system:V},measure:O}}if(s&&e){const M=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),$=this.regionInfo.getUnitSystem(s),U=this.regionInfo.getUnitSystem(M);return{measure:e,to:{unit:$===U?s:M}}}}async updateProperty(t){It.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)}};di([Xt({modelType:ae.type})],ks.prototype,"regionInfo",2);di([mo({path:xb,serviceBasePath:Ab})],ks.prototype,"bean",2);ks=di([D(Mr)],ks);const Et={registration:{[Mr]:{class:ks,singleton:!1}},type:Mr,factory:he.Factory.create(Mr)};function Rb(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})),(u,d)=>{u[F]=u[F]||{},u[F][d]={modelType:Et.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:I.INIT,lazy:n}}}const hi=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}),fi=(t,e)=>{g.debug(`future dto ${t.id} end state ${t.endState}`),g.debug(`future model ${e.id} end state ${e.endState}`),e.endState?g.debug(`future model ${e.id} is already complete`):(g.debug(`updating future model ${e.id}`),E.runInAction(()=>{const s=hi(t);te(()=>{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]})})}))},Au=t=>e=>s=>t.build(String(e),s),pi=t=>e=>du(hi,Au(t)(e.tracker||e.id))(e),yo=g.createLogger({name:"future-service",group:"Services"}),{isMock:Pb,URL:Zs}=fe();var tt=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(tt||{});const{getAll:kb,modifyModel:Lb,addModel:Fb,deleteModel:Nb,postModel:Ub}=ce.build({destinationAddress:"",basePath:`${Zs}/api/future`,mock:Pb}),jb=async()=>await kb({}),Ru=async(t,e="/api/kos/future")=>(yo.info(`sending delete request for Future: ${t}`),await Nb({id:t,urlOverride:`${Zs}${e}/${t}`})),Pu=async(t,e="/api/kos/future")=>(yo.info("sending add request for Future"),await Fb({model:t,urlOverride:`${Zs}${e}`})),Bb=async(t,e,s="/api/kos/future")=>(yo.info(`sending modify request for Future: ${t}`),Lb({model:e,id:t,urlOverride:`${Zs}${s}/${t}`})),ku=async(t,e="/api/kos/future")=>(yo.info(`sending cancel request for Future: ${t}`),Ub({urlOverride:`${Zs}${e}/${t}/cancel`,ordered:!0,model:{}})),Lu=De();var Kb=Object.defineProperty,Hb=Object.getOwnPropertyDescriptor,Fu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Hb(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&&Kb(e,s,o),o};const Nu="browser-router-model",qb="kos.http.request",zb="kos.http.response";let Ar=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new gu}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 u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),Ul({msg:d,options:{responseId:i,destinationAddress:s,type:zb,sourceAddress:r,status:c}})},status:function(d){return c=d,this}};if(a.path==="/openapi.json"){u.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,u)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};Fu([B({topic:qb})],Ar.prototype,"handleRequest",1);Ar=Fu([D(Nu)],Ar);const gi=new Ce({class:Ar,type:Nu}),Uu="future-model",ts=Jt(Uu);var Vb=Object.defineProperty,Gb=Object.getOwnPropertyDescriptor,ju=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gb(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Vb(e,s,o),o};const qo=g.getLogger(ts.type);let Rr=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=ku,nn(()=>this.status===tt.Success||this.status===tt.Fail,()=>{qo.info(`Future ${this.id} has completed with status ${this.status}`),Re(this)})}async load(){qo.debug(`loading Future ${this.id}`)}unload(){qo.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await nn(()=>this.futureId!==oi),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[u,d]of Object.entries(e))if(Math.abs(t)>=d){s=u,r=Math.round(t/d);break}const 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}`),fi(t,this)}};ju([B({topic:`kos.future/${Tr}`})],Rr.prototype,"handleFutureUpdated",1);Rr=ju([D(ts.type)],Rr);const Bu=Rr,Ku="future-container-model",st=Jt(Ku),Hu=t=>pi(ts)(t),Yb=t=>{const e=Hu(t);return st.build(st.type,{}).addFutureModel(e),e},Wb=t=>st.build(st.type,{}).getFuture(String(t)),mt={buildFutureModel:Hu,initiateFuture:Yb,getFuture:Wb};var Qb=Object.defineProperty,Xb=Object.getOwnPropertyDescriptor,mi=(t,e,s,r)=>{for(var o=r>1?void 0:r?Xb(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Qb(e,s,o),o};const ur=g.getLogger(st.type);let Ls=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=Ru,addFuture:o=Pu}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new Fe,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){ur.error("error deleting a Future"),ur.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=pi(ts)(s);return this.addFutureModel(r),r}}catch(e){throw ur.error("error creating a Future"),ur.error(e),e}}handleFutureUpdated(t,e){const s=mt.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),H(r,e.body,e.headers)}};mi([Oe],Ls.prototype,"_futures",2);mi([B({topic:"kos.future"})],Ls.prototype,"handleFutureUpdated",1);Ls=mi([D(st.type)],Ls);const qu=Ls,{URL:Js}=fe(),{getOne:Zb,postModel:Jb,deleteModel:zu}=ce.build({basePath:`${Js}/api/keyVal`}),an=g.createLogger({name:"key-value-service",group:"Services"}),Vu=async(t,e)=>{await zu({urlOverride:`${Js}/api/keyVal/${t}/${e}`,id:e})},Gu=async(t,e,s)=>{const r=await Jb({urlOverride:`${Js}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw an.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},Yu=async(t="studio")=>{an.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await Zb({urlOverride:`${Js}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw an.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},ev=async t=>{await zu({urlOverride:`${Js}/api/keyVal/${t}`,id:""})},tv=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Vu,deleteKeyValueNamespace:ev,getKeyValue:Yu,updateKeyValue:Gu},Symbol.toStringTag,{value:"Module"}));var sv=Object.defineProperty,rv=Object.getOwnPropertyDescriptor,yi=(t,e,s,r)=>{for(var o=r>1?void 0:r?rv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&sv(e,s,o),o};const Wu="key-value-model";let Fs=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=Pe(),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 Gu(this.namespace,t,e),this.data[t]=e):(await Vu(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await Yu(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)}};yi([B({topic:"/keyVal/set"})],Fs.prototype,"handleStateUpdate",1);yi([B({topic:"/keyVal/remove"})],Fs.prototype,"handleStateDelete",1);Fs=yi([D(Wu)],Fs);const bi=new Ee({class:Fs,type:Wu});var ve="INUMBER",ss="IOP1",rs="IOP2",os="IOP3",He="IVAR",yt="IVARNAME",Nt="IFUNCALL",bo="IFUNDEF",ue="IEXPR",vi="IEXPREVAL",Mt="IMEMBER",vo="IENDSTATEMENT",Ut="IARRAY";function k(t,e){this.type=t,this.value=e??0}k.prototype.toString=function(){switch(this.type){case ve:case ss:case rs:case os:case He:case yt:case vo:return this.value;case Nt:return"CALL "+this.value;case bo:return"DEF "+this.value;case Ut:return"ARRAY "+this.value;case Mt:return"."+this.value;default:return"Invalid Instruction"}};function wo(t){return new k(ss,t)}function We(t){return new k(rs,t)}function Qu(t){return new k(os,t)}function cn(t,e,s,r,o){for(var n=[],i=[],a,c,u,d,h=0;h<t.length;h++){var f=t[h],p=f.type;if(p===ve||p===yt)Array.isArray(f.value)?n.push.apply(n,cn(f.value.map(function(y){return new k(ve,y)}).concat(new k(Ut,f.value.length)),e,s,r,o)):n.push(f);else if(p===He&&o.hasOwnProperty(f.value))f=new k(ve,o[f.value]),n.push(f);else if(p===rs&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new k(ve,d(a.value,c.value)),n.push(f);else if(p===os&&n.length>2)u=n.pop(),c=n.pop(),a=n.pop(),f.value==="?"?n.push(a.value?c.value:u.value):(d=r[f.value],f=new k(ve,d(a.value,c.value,u.value)),n.push(f));else if(p===ss&&n.length>0)a=n.pop(),d=e[f.value],f=new k(ve,d(a.value)),n.push(f);else if(p===ue){for(;n.length>0;)i.push(n.shift());i.push(new k(ue,cn(f.value,e,s,r,o)))}else if(p===Mt&&n.length>0)a=n.pop(),n.push(new k(ve,a.value[f.value]));else{for(;n.length>0;)i.push(n.shift());i.push(f)}}for(;n.length>0;)i.push(n.shift());return i}function Xu(t,e,s){for(var r=[],o=0;o<t.length;o++){var n=t[o],i=n.type;if(i===He&&n.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===ss?u=wo(c.value):c.type===rs?u=We(c.value):c.type===os?u=Qu(c.value):u=new k(c.type,c.value),r.push(u)}else i===ue?r.push(new k(ue,Xu(n.value,e,s))):r.push(n)}return r}function ht(t,e,s){var r=[],o,n,i,a,c,u;if(wi(t))return Ue(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===ve||p===yt)r.push(f.value);else if(p===rs)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!ht(n,e,s):!1):f.value==="or"?r.push(o?!0:!!ht(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,ht(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(Ue(o,s),Ue(n,s))));else if(p===os)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(ht(o?n:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(Ue(o,s),Ue(n,s),Ue(i,s))));else if(p===He)if(f.value in e.functions)r.push(e.functions[f.value]);else if(f.value in e.unaryOps&&e.parser.isOperatorEnabled(f.value))r.push(e.unaryOps[f.value]);else{var y=s[f.value];if(y!==void 0)r.push(y);else throw new Error("undefined variable: "+f.value)}else if(p===ss)o=r.pop(),a=e.unaryOps[f.value],r.push(a(Ue(o,s)));else if(p===Nt){for(u=f.value,c=[];u-- >0;)c.unshift(Ue(r.pop(),s));if(a=r.pop(),a.apply&&a.call)r.push(a.apply(void 0,c));else throw new Error(a+" is not a function")}else if(p===bo)r.push(function(){for(var v=r.pop(),M=[],$=f.value;$-- >0;)M.unshift(r.pop());var U=r.pop(),x=function(){for(var O=Object.assign({},s),P=0,V=M.length;P<V;P++)O[M[P]]=arguments[P];return ht(v,e,O)};return Object.defineProperty(x,"name",{value:U,writable:!1}),s[U]=x,x}());else if(p===ue)r.push(ov(f,e));else if(p===vi)r.push(f);else if(p===Mt)o=r.pop(),r.push(o[f.value]);else if(p===vo)r.pop();else if(p===Ut){for(u=f.value,c=[];u-- >0;)c.unshift(r.pop());r.push(c)}else throw new Error("invalid Expression")}if(r.length>1)throw new Error("invalid Expression (parity)");return r[0]===0?0:Ue(r[0],s)}function ov(t,e,s){return wi(t)?t:{type:vi,value:function(r){return ht(t.value,e,r)}}}function wi(t){return t&&t.type===vi}function Ue(t,e){return wi(t)?t.value(e):t}function Ei(t,e){for(var s=[],r,o,n,i,a,c,u=0;u<t.length;u++){var d=t[u],h=d.type;if(h===ve)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Oa).join(", ")+"]"):s.push(Oa(d.value));else if(h===rs)o=s.pop(),r=s.pop(),i=d.value,e?i==="^"?s.push("Math.pow("+r+", "+o+")"):i==="and"?s.push("(!!"+r+" && !!"+o+")"):i==="or"?s.push("(!!"+r+" || !!"+o+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+o+")))"):i==="=="?s.push("("+r+" === "+o+")"):i==="!="?s.push("("+r+" !== "+o+")"):i==="["?s.push(r+"[("+o+") | 0]"):s.push("("+r+" "+i+" "+o+")"):i==="["?s.push(r+"["+o+"]"):s.push("("+r+" "+i+" "+o+")");else if(h===os)if(n=s.pop(),o=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+o+" : "+n+")");else throw new Error("invalid Expression");else if(h===He||h===yt)s.push(d.value);else if(h===ss)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):e?i==="not"?s.push("(!"+r+")"):i==="!"?s.push("fac("+r+")"):s.push(i+"("+r+")"):i==="!"?s.push("("+r+"!)"):s.push("("+i+" "+r+")");else if(h===Nt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===bo){for(o=s.pop(),c=d.value,a=[];c-- >0;)a.unshift(s.pop());r=s.pop(),e?s.push("("+r+" = function("+a.join(", ")+") { return "+o+" })"):s.push("("+r+"("+a.join(", ")+") = "+o+")")}else if(h===Mt)r=s.pop(),s.push(r+"."+d.value);else if(h===Ut){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ue)s.push("("+Ei(d.value,e)+")");else if(h!==vo)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Oa(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function At(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function Mi(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===He||i.type===yt?!r&&!At(e,i.value)?e.push(i.value):(o!==null&&(At(e,o)||e.push(o)),o=i.value):i.type===Mt&&r&&o!==null?o+="."+i.value:i.type===ue?Mi(i.value,e,s):o!==null&&(At(e,o)||e.push(o),o=null)}o!==null&&!At(e,o)&&e.push(o)}function Se(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}Se.prototype.simplify=function(t){return t=t||{},new Se(cn(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};Se.prototype.substitute=function(t,e){return e instanceof Se||(e=this.parser.parse(String(e))),new Se(Xu(this.tokens,t,e),this.parser)};Se.prototype.evaluate=function(t){return t=t||{},ht(this.tokens,this,t)};Se.prototype.toString=function(){return Ei(this.tokens,!1)};Se.prototype.symbols=function(t){t=t||{};var e=[];return Mi(this.tokens,e,t),e};Se.prototype.variables=function(t){t=t||{};var e=[];Mi(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};Se.prototype.toJSFunction=function(t,e){var s=this,r=new Function(t,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+Ei(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var Ns="TEOF",j="TOP",Eo="TNUMBER",Zu="TSTRING",qe="TPAREN",jt="TBRACKET",Mo="TCOMMA",_i="TNAME",Ti="TSEMICOLON";function Ju(t,e,s){this.type=t,this.value=e,this.index=s}Ju.prototype.toString=function(){return this.type+": "+this.value};function Y(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}Y.prototype.newToken=function(t,e,s){return new Ju(t,e,s??this.pos)};Y.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};Y.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};Y.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(Ns,"EOF");if(this.isWhitespace()||this.isComment())return this.next();if(this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName())return this.current;this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')};Y.prototype.isString=function(){var t=!1,e=this.pos,s=this.expression.charAt(e);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,e+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(e+1,r);this.current=this.newToken(Zu,this.unescape(o),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};Y.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(qe,t),this.pos++,!0):!1};Y.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(jt,t),this.pos++,!0):!1};Y.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(Mo,","),this.pos++,!0):!1};Y.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(Ti,";"),this.pos++,!0):!1};Y.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(r in this.consts)return this.current=this.newToken(Eo,this.consts[r]),this.pos+=r.length,!0}return!1};Y.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(j,r),this.pos+=r.length,!0}return!1};Y.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(t,e);return this.current=this.newToken(_i,o),this.pos+=o.length,!0}return!1};Y.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
|
|
108
|
-
`||e==="\r")&&(t=!0,this.pos++,!(this.pos>=this.expression.length));)e=this.expression.charAt(this.pos);return t};var
|
|
109
|
-
`;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var o=t.substring(e+1,e+5);
|
|
110
|
-
`,s+1);while(s>=0&&s<this.pos);return{line:t,column:e}};Y.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)};function q(t,e,s){this.parser=t,this.tokens=e,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}q.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};q.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?At(e,t.value):typeof e=="function"?e(t):t.value===e};q.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};q.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};q.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};q.prototype.expect=function(t,e){if(!this.accept(t,e)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(e||t))}};q.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.accept(_i)||this.accept(j,s))t.push(new k(He,this.current.value));else if(this.accept(Eo))t.push(new k(ve,this.current.value));else if(this.accept(Zu))t.push(new k(ve,this.current.value));else if(this.accept(qe,"("))this.parseExpression(t),this.expect(qe,")");else if(this.accept(jt,"["))if(this.accept(jt,"]"))t.push(new k(Ut,0));else{var r=this.parseArrayList(t);t.push(new k(Ut,r))}else throw new Error("unexpected "+this.nextToken)};q.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};q.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};q.prototype.parseUntilEndStatement=function(t,e){return this.accept(Ti)?(this.nextToken&&this.nextToken.type!==Ns&&!(this.nextToken.type===qe&&this.nextToken.value===")")&&e.push(new k(vo)),this.nextToken.type!==Ns&&this.parseExpression(e),t.push(new k(ue,e)),!0):!1};q.prototype.parseArrayList=function(t){for(var e=0;!this.accept(jt,"]");)for(this.parseExpression(t),++e;this.accept(Mo);)this.parseExpression(t),++e;return e};q.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(j,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===Nt){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var o=0,n=e.value+1;o<n;o++){var i=r-o;t[i].type===He&&(t[i]=new k(yt,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new k(ue,s)),t.push(new k(bo,e.value));continue}if(e.type!==He&&e.type!==Mt)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new k(yt,e.value)),t.push(new k(ue,s)),t.push(We("="))}};q.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(j,"?");){var e=[],s=[];this.parseConditionalExpression(e),this.expect(j,":"),this.parseConditionalExpression(s),t.push(new k(ue,e)),t.push(new k(ue,s)),t.push(Qu("?"))}};q.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(j,"or");){var e=[];this.parseAndExpression(e),t.push(new k(ue,e)),t.push(We("or"))}};q.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(j,"and");){var e=[];this.parseComparison(e),t.push(new k(ue,e)),t.push(We("and"))}};var iv=["==","!=","<","<=",">=",">","in"];q.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,iv);){var e=this.current;this.parseAddSub(t),t.push(We(e.value))}};var av=["+","-","||"];q.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(j,av);){var e=this.current;this.parseTerm(t),t.push(We(e.value))}};var cv=["*","/","%"];q.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,cv);){var e=this.current;this.parseFactor(t),t.push(We(e.value))}};q.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.save(),this.accept(j,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===qe&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===Ti||this.nextToken.type===Mo||this.nextToken.type===Ns||this.nextToken.type===qe&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(wo(r.value))}else this.parseExponential(t)};q.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(j,"^");)this.parseFactor(t),t.push(We("^"))};q.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(j,"!");)t.push(wo("!"))};q.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.accept(j,s)){var r=this.current;this.parseAtom(t),t.push(wo(r.value))}else for(this.parseMemberExpression(t);this.accept(qe,"(");)if(this.accept(qe,")"))t.push(new k(Nt,0));else{var o=this.parseArgumentList(t);t.push(new k(Nt,o))}};q.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(qe,")");)for(this.parseExpression(t),++e;this.accept(Mo);)this.parseExpression(t),++e;return e};q.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(j,".")||this.accept(jt,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(_i),t.push(new k(Mt,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(jt,"]"),t.push(We("["))}else throw new Error("unexpected symbol: "+e.value)}};function lv(t,e){return Number(t)+Number(e)}function uv(t,e){return t-e}function dv(t,e){return t*e}function hv(t,e){return t/e}function fv(t,e){return t%e}function pv(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function gv(t,e){return t===e}function mv(t,e){return t!==e}function yv(t,e){return t>e}function bv(t,e){return t<e}function vv(t,e){return t>=e}function wv(t,e){return t<=e}function Ev(t,e){return!!(t&&e)}function Mv(t,e){return!!(t||e)}function _v(t,e){return At(e,t)}function Tv(t){return(Math.exp(t)-Math.exp(-t))/2}function Sv(t){return(Math.exp(t)+Math.exp(-t))/2}function $v(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function Ov(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function Iv(t){return Math.log(t+Math.sqrt(t*t-1))}function Cv(t){return Math.log((1+t)/(1-t))/2}function Ia(t){return Math.log(t)*Math.LOG10E}function Dv(t){return-t}function xv(t){return!t}function Av(t){return t<0?Math.ceil(t):Math.floor(t)}function Rv(t){return Math.random()*(t||1)}function Ca(t){return Si(t+1)}function Pv(t){return isFinite(t)&&t===Math.round(t)}var kv=4.7421875,zo=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function Si(t){var e,s;if(Pv(t)){if(t<=0)return isFinite(t)?1/0:NaN;if(t>171)return 1/0;for(var r=t-2,o=t-1;r>1;)o*=r,r--;return o===0&&(o=1),o}if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*Si(1-t));if(t>=171.35)return 1/0;if(t>85){var n=t*t,i=n*t,a=i*t,c=a*t;return Math.sqrt(2*Math.PI/t)*Math.pow(t/Math.E,t)*(1+1/(12*t)+1/(288*n)-139/(51840*i)-571/(2488320*a)+163879/(209018880*c)+5246819/(75246796800*c*t))}--t,s=zo[0];for(var u=1;u<zo.length;++u)s+=zo[u]/(t+u);return e=t+kv+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function Lv(t){return Array.isArray(t)?t.length:String(t).length}function Da(){for(var t=0,e=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),o;e<r?(o=e/r,t=t*o*o+1,e=r):r>0?(o=r/e,t+=o*o):t+=r}return e===1/0?1/0:e*Math.sqrt(t)}function xa(t,e,s){return t?e:s}function Fv(t,e){return typeof e>"u"||+e==0?Math.round(t):(t=+t,e=-+e,isNaN(t)||!(typeof e=="number"&&e%1===0)?NaN:(t=t.toString().split("e"),t=Math.round(+(t[0]+"e"+(t[1]?+t[1]-e:-e))),t=t.toString().split("e"),+(t[0]+"e"+(t[1]?+t[1]+e:e))))}function Nv(t,e,s){return s&&(s[t]=e),e}function Uv(t,e){return t[e|0]}function jv(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function Bv(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function Kv(t,e){if(typeof t!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(e))throw new Error("Second argument to map is not an array");return e.map(function(s,r){return t(s,r)})}function Hv(t,e,s){if(typeof t!="function")throw new Error("First argument to fold is not a function");if(!Array.isArray(s))throw new Error("Second argument to fold is not an array");return s.reduce(function(r,o,n){return t(r,o,n)},e)}function qv(t,e){if(typeof t!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(e))throw new Error("Second argument to filter is not an array");return e.filter(function(s,r){return t(s,r)})}function zv(t,e){if(!(Array.isArray(e)||typeof e=="string"))throw new Error("Second argument to indexOf is not a string or array");return e.indexOf(t)}function Vv(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function Gv(t){return(t>0)-(t<0)||+t}var Aa=1/3;function Yv(t){return t<0?-Math.pow(-t,Aa):Math.pow(t,Aa)}function Wv(t){return Math.exp(t)-1}function Qv(t){return Math.log(1+t)}function Xv(t){return Math.log(t)/Math.LN2}function _t(t){this.options=t||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||Tv,cosh:Math.cosh||Sv,tanh:Math.tanh||$v,asinh:Math.asinh||Ov,acosh:Math.acosh||Iv,atanh:Math.atanh||Cv,sqrt:Math.sqrt,cbrt:Math.cbrt||Yv,log:Math.log,log2:Math.log2||Xv,ln:Math.log,lg:Math.log10||Ia,log10:Math.log10||Ia,expm1:Math.expm1||Wv,log1p:Math.log1p||Qv,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||Av,"-":Dv,"+":Number,exp:Math.exp,not:xv,length:Lv,"!":Ca,sign:Math.sign||Gv},this.binaryOps={"+":lv,"-":uv,"*":dv,"/":hv,"%":fv,"^":Math.pow,"||":pv,"==":gv,"!=":mv,">":yv,"<":bv,">=":vv,"<=":wv,and:Ev,or:Mv,in:_v,"=":Nv,"[":Uv},this.ternaryOps={"?":xa},this.functions={random:Rv,fac:Ca,min:Bv,max:jv,hypot:Math.hypot||Da,pyt:Math.hypot||Da,pow:Math.pow,atan2:Math.atan2,if:xa,gamma:Si,roundTo:Fv,map:Kv,fold:Hv,filter:qv,indexOf:zv,join:Vv},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}_t.prototype.parse=function(t){var e=[],s=new q(this,new Y(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect(Ns,"EOF"),new Se(e,this)};_t.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var ed=new _t;_t.parse=function(t){return ed.parse(t)};_t.evaluate=function(t,e){return ed.parse(t).evaluate(e)};var Ra={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"remainder","^":"power","!":"factorial","<":"comparison",">":"comparison","<=":"comparison",">=":"comparison","==":"comparison","!=":"comparison","||":"concatenate",and:"logical",or:"logical",not:"logical","?":"conditional",":":"conditional","=":"assignment","[":"array","()=":"fndef"};function Zv(t){return Ra.hasOwnProperty(t)?Ra[t]:t}_t.prototype.isOperatorEnabled=function(t){var e=Zv(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var Jv=Object.defineProperty,ew=Object.getOwnPropertyDescriptor,tw=(t,e,s)=>e in t?Jv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,sw=(t,e,s,r)=>{for(var o=r>1?void 0:r?ew(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},rw=(t,e,s)=>(tw(t,e+"",s),s);const ow="kos-expression-evaluator-model";class nw{constructor(e,s,r,o){l(this,"name");l(this,"expression");l(this,"expr");l(this,"getContextData",null);l(this,"_lastResult",{value:void 0});this.name=e,this.expression=s,this.expr=r,this.getContextData=o,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(e){this._lastResult=e}evaluate(e){try{return{value:this.expr.evaluate(e),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let Pr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"parser");l(this,"_data");l(this,"_expressions",new Map);l(this,"_results");l(this,"_contextRevision",0);this.id=t,this.logger=s.logger,this._data=Pe(),this._results=Pe(),this.parser=new _t,this.parser.functions.exists=r=>r!=null,this.parser.functions.isEmpty=r=>r==null?!0:typeof r=="string"||Array.isArray(r)?r.length===0:typeof r=="object"?Object.keys(r).length===0:!1}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(t){this._data.setValues(t),te(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(t,e){this._data[t]=e}updateNestedValue(t,e){const s=t.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${t}" - cannot be empty`);return}let o=this._data;for(const n of s)(o[n]===void 0||o[n]===null)&&(o[n]={}),o=o[n];o[r]=e,this.logger.debug(`Updated nested context value "${t}" to:`,e)}addModelToContext(t,e){this._data[t]=e}addExpression(t,e){try{const s=this.parser.parse(e),r=new nw(t,e,s,()=>this.data);this._expressions.set(t,r),this.evaluateExpression(t),this.logger.debug(`Added expression "${t}": ${e}`)}catch(s){throw this.logger.error(`Failed to parse expression "${t}"`,s),s}}removeExpression(t){const e=this._expressions.delete(t);return e?(delete this._results[t],this.logger.debug(`Removed expression "${t}"`)):this.logger.warn(`Attempted to remove non-existent expression "${t}". Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpression(t){const e=this._expressions.get(t);return e||this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpressionValue(t){const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return e.result}getCachedExpressionValue(t){const e=this._expressions.get(t);if(e)return e.result}get expressions(){return Array.from(this._expressions.values())}get expressionNames(){return Array.from(this._expressions.keys())}get results(){return this.evaluateAllExpressions(),this._results}evaluateAllExpressions(){Array.from(this._expressions.keys()).forEach(e=>{this._expressions.get(e)&&this.evaluateExpression(e)})}evaluateExpression(t){this.logger.debug(`Evaluating expression: ${String(t)}`);const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${String(t)}" not found`);return}const s=e.evaluate(this.data);this.logger.debug(`Expression "${String(t)}" evaluated to:`,s);const r=e.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(t)}" result changed from`,r,"to",s),e.updateResult(s),this.updateResult(t,s))}updateResult(t,e){this.logger.debug(`ExpressionEvaluator.updateResult called for "${t}":`,e),te(()=>{this._results[t]=e})}createExpression(t){const e=wt();return this.addExpression(e,t),e}};rw(Pr,"Registration");Pr=sw([D({modelTypeId:ow,singleton:!1})],Pr);const td=Pr.Registration,iw=g.createLogger({name:"kos-log-manager-service",group:"Services"}),aw="/api/kos/logs/overrides",sd=async()=>(iw.debug("sending GET for kos-log-manager"),await Ne.get(aw)),cw=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:sd},Symbol.toStringTag,{value:"Module"}));var lw=Object.defineProperty,uw=Object.getOwnPropertyDescriptor,_o=(t,e,s,r)=>{for(var o=r>1?void 0:r?uw(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&&lw(e,s,o),o};const rd="kos-log-manager-model",dw="/kos/logs/override/add/*",hw="/kos/logs/override/remove/*",fw=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 Bt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new ti}updateModel(t){}resolveLoggers(){const t=g.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:fw(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=g.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=g.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=g.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=g.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 sd();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)})}};_o([Hc("/api/kos/ui/loggers")],Bt.prototype,"getAllLoggers",1);_o([B({topic:dw,websocket:!0,wildcardName:"nodeType"})],Bt.prototype,"handleOverrideAdded",1);_o([B({topic:hw,websocket:!0,wildcardName:"nodeType"})],Bt.prototype,"handleOverrideRemoved",1);Bt=_o([D(rd)],Bt);const od=new Ce({class:Bt,type:rd}),{URL:er}=fe(),{postModel:$i,getOne:pw}=ce.build({basePath:`${er}/api/kos-time`});g.createLogger({name:"kos-time-service",group:"Services"});const nd=async t=>{const e=await $i({model:t,urlOverride:`${er}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},id=async t=>{const e=await $i({model:t,urlOverride:`${er}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},ad=async t=>{const e=await $i({model:{},urlOverride:`${er}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},cd=async()=>{const t=await pw({urlOverride:`${er}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},gw=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:cd,setDate:id,setTime:nd,setTimezone:ad},Symbol.toStringTag,{value:"Module"}));var mw=Object.defineProperty,yw=Object.getOwnPropertyDescriptor,To=(t,e,s,r)=>{for(var o=r>1?void 0:r?yw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&mw(e,s,o),o};const us="kos-time-model",bw="/kos/time/time",vw="/kos/time/day",ww="/kos/time/timezone";let Kt=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 nd(t)}async updateSystemDate(t){await id(t)}async updateSystemTimezone(t){await ad(t)}handleTimeChange(){H(Is.TIME_CHANGE,{})}handleDayChange(){H(Is.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),H(Is.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await cd();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};To([B({topic:bw,websocket:!0})],Kt.prototype,"handleTimeChange",1);To([B({topic:vw,websocket:!0})],Kt.prototype,"handleDayChange",1);To([B({topic:ww,websocket:!0})],Kt.prototype,"handleTimeZoneChange",1);Kt=To([D(us)],Kt);const kr={registration:{[us]:{class:Kt,singleton:!0}},type:us,predicate:Ie(us),factory:he.Singleton.create(us)};var Ew=Object.defineProperty,Mw=Object.getOwnPropertyDescriptor,ld=(t,e,s,r)=>{for(var o=r>1?void 0:r?Mw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ew(e,s,o),o};const ud="log-block-container-model";let Lr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Fe({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}`)}};ld([Oe],Lr.prototype,"_models",2);Lr=ld([D(ud)],Lr);const _w=g.createLogger({name:"log-stream-container-service",group:"Services"}),dd=()=>{var r;const t=de(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return g.error(`getKosConnectionId: ${s}`),s},ns=dd(),Tw="/api/kos/logs/node/{nodeId}/streams",hd=async()=>(_w.debug("sending GET for log-stream-container"),await Ne.get(Tw,{path:{nodeId:"primary"}},{destinationAddress:ns})),fd=async(t,e="primary")=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:ns})},pd=async t=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:ns})},Sw=async()=>{await Ne.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:ns})},gd=async t=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:ns}),md=async(t,e)=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:ns}),$w=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Sw,getKosConnectionId:dd,getLogStreamBlock:md,getLogStreamBlocks:gd,getLogStreams:hd,subscribeToLogStream:fd,unsubscribeFromLogStream:pd},Symbol.toStringTag,{value:"Module"}));var Ow=Object.getOwnPropertyDescriptor,Iw=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ow(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const yd="log-block-model";let ln=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await md(this.stream,this.blockNum);if(t){this.logger.error(`Failed to get log block ${this.blockNum}`);return}e&&this.addLines(e.lines,!0)}updateModel(t){this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount}addLines(t,e){const s=e?[]:this.lines;this.lines=[...s,...t],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};ln=Iw([D(yd)],ln);const Us=new Ee({class:ln,type:yd}),So=new Ee({class:Lr,type:ud});So.addRelatedModel(Us);var Cw=Object.defineProperty,Dw=Object.getOwnPropertyDescriptor,bd=(t,e,s,r)=>{for(var o=r>1?void 0:r?Dw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Cw(e,s,o),o};const vd="log-stream-model";let Fr=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=So.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=Us.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=Us.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 fd(this.name)}async unsubscribe(){await pd(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 gd(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=bu(()=>{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()}}};bd([Oe],Fr.prototype,"_blocks",2);Fr=bd([D(vd)],Fr);const Cs=new Ee({class:Fr,type:vd});var xw=Object.defineProperty,Aw=Object.getOwnPropertyDescriptor,Tt=(t,e,s,r)=>{for(var o=r>1?void 0:r?Aw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&xw(e,s,o),o};const wd="log-stream-container-model",Rw="/kos/logs/subscription/addBlock/*",Pw="/kos/logs/subscription/updateBlock/*",kw="/kos/logs/subscription/removeBlock/*",Lw="/kos/logs/subscription/lines/*",Ed="/kos/logs/streams/add/*";let ze=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 Fe({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: ${Ed}`);const e=t.stream,s=Cs.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=Cs.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 hd();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=Cs.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};Tt([Oe],ze.prototype,"_models",2);Tt([B({topic:[Ed],websocket:!0})],ze.prototype,"handleStreamAdded",1);Tt([B({topic:[Rw],websocket:!0})],ze.prototype,"handleAddBlock",1);Tt([B({topic:[kw],websocket:!0})],ze.prototype,"handleRemoveBlock",1);Tt([B({topic:[Pw],websocket:!0})],ze.prototype,"handleUpdateBlock",1);Tt([B({topic:[Lw],websocket:!0})],ze.prototype,"handleLogLine",1);ze=Tt([D(wd)],ze);const tr=new Ce({class:ze,type:wd});tr.addRelatedModel(Cs);tr.addRelatedModel(So);tr.addRelatedModel(Us);const Fw=t=>(t==null?void 0:t.rank)!==void 0,Nw=t=>(t==null?void 0:t.visibleRole)!==void 0,Uw=t=>(t==null?void 0:t.color)!==void 0,jw=t=>{const e=t.info??{};return Fw(e)?e.rank:0},Bw=t=>{const e=t.info??{};return Uw(e)?e.color:"orange"},Kw=t=>{const e=t.info??{};return Nw(e)?e.visibleRole:"TECHNICIAN"},{URL:$o}=fe(),{getAll:Hw,postModel:Md}=ce.build({basePath:`${$o}/api/kos/troubles`}),Ds=g.createLogger({name:"trouble-services"}),_d=()=>{var r,o;const t=de(),e=t==null?void 0:t.connId;Ds.debug(`connId from query params: ${e}`),Ds.debug(`window.kosBridge: ${window!=null&&window.kosBridge?"available":"not available"} - ${(r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId")}`);const s=e||((o=window==null?void 0:window.kosBridge)==null?void 0:o.call(window,"connId"));return Ds.info(`getKosConnectionId: ${s}`),s},js=_d();Ds.info(`Destination address for trouble services: ${js}`);const Td=async t=>{const e=t.includes("/kos/troubles");return Ds.info(`Fetching troubles from ${t} with destination address: ${e?js:"N/A (not a kos troubles path)"}`),await Hw({urlOverride:`${$o}${t}`,destinationAddress:e?js:void 0})},Sd=async(t,e="/api/kos/troubles",s)=>{try{const r=e.includes("/kos/troubles"),o=await Md({model:{},urlOverride:`${$o}${e}/resolve/${t}`,destinationAddress:r?js:void 0,tracker:s});return o!=null&&o.data&&mt.initiateFuture(o.data),o.data}catch{const o={id:s||"",endState:tt.Fail,tracker:s,reason:"Failed to resolve trouble"};return mt.initiateFuture(o),o}},$d=async(t,e="/api/kos/troubles",s)=>{try{const r=await Md({model:t,urlOverride:`${$o}${e}/resolve/`,destinationAddress:js,tracker:s});return r!=null&&r.data&&mt.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:tt.Fail,tracker:s,reason:"Failed to resolve troubles"};return mt.initiateFuture(o),o}},qw=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:$d,getKosConnectionId:_d,getTroubles:Td,resolveTrouble:Sd},Symbol.toStringTag,{value:"Module"})),Nr="troubleDataMapper",dr=new Map;Zt(Nr,{register:(t,e)=>{var s;dr.has(t)||dr.set(t,[]),(s=dr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=dr.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}:g.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const sr="troubleMapper",hr=new Map;Zt(sr,{register:(t,e)=>{var s;hr.has(t)||hr.set(t,[]),(s=hr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=hr.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(g.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});T[sr].register("nozzle",async t=>[t.data.nozzlePath]);T[sr].register("path",async t=>[t.data.path]);const zw=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>T[sr].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},Od=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>T[Nr].execute(i,t)),r=T[Nr].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 Vw{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class Gw{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class Ct{static getHandler(e){switch(e){case"ResolvableTrouble":return new Vw;case"BlockPumpTrouble":return new Gw;default:return}}}var Yw=Object.defineProperty,Ww=Object.getOwnPropertyDescriptor,Id=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ww(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&&Yw(e,s,o),o};const ds="trouble-model";function fr(t){return typeof t.shouldDefer=="boolean"}let Ur=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:u,createTime:d,role:h,color:f,servicePath:p,rawJson:y,...v},M){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"servicePath");l(this,"group");l(this,"createTime");l(this,"rawJson");l(this,"_mapped",{});this.id=t,this.logger=M.logger,this.type=c,this._troubleId=o,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=f,this.tags=s,this.info=r,this.group=u,this.rawJson=y,this.servicePath=p??"/api/kos/troubles",this.createTime=d,this.clientData=n,this.data={},Object.assign(this.data,v),this.futureHandler=new po(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=Ct.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Ct.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=Ct.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Ct.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=Ct.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=Ct.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 Od(this)}get deferredCompanion(){const t=Jo(this.id,e=>fr(e));if(t&&fr(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Jo(this.id,e=>fr(e));return t&&fr(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 Sd(this._troubleId,this.servicePath,t)}};Id([Do()],Ur.prototype,"resolve",1);Ur=Id([D(ds)],Ur);const Bs={registration:{[ds]:{class:Ur,singleton:!1}},type:ds,predicate:Ie(ds),factory:he.Factory.create(ds)};var Cd=Object.defineProperty,Qw=Object.getOwnPropertyDescriptor,Xw=(t,e,s)=>e in t?Cd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Oo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Qw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Cd(e,s,o),o},Zw=(t,e,s)=>(Xw(t,e+"",s),s);function Pa(t){return T.propertyMapper.hasMapper(se.TroubleRank)?T.propertyMapper.executeMapper(se.TroubleRank,t):jw(t)}function ka(t){return(T.propertyMapper.hasMapper(se.TroubleColor)?T.propertyMapper.executeMapper(se.TroubleColor,t):Bw(t)).toLowerCase()}function La(t){return(T.propertyMapper.hasMapper(se.TroubleRole)?T.propertyMapper.executeMapper(se.TroubleRole,t):Kw(t)).toLowerCase()}const Jw="trouble-container-model";class we{}l(we,"INDEX_TROUBLES_BY_IFACE","byIface"),l(we,"INDEX_TROUBLES_BY_TYPE","byType"),l(we,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(we,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(we,"SORT_KEY_RANK","rank"),l(we,"TROUBLES_DEFERRED","true");let bt=class{constructor(t,e){l(this,"id");l(this,"servicePath","/api/kos/troubles");this.id=t,this.servicePath=e.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");try{const t=await Td(this.servicePath);t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:Pa(e),color:ka(e),role:La(e),id:String(e.id),rawJson:e},r=Bs.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(t){throw this.logger.error(t),t}}async resolveAll(t){const e=this.troubles.data.filter(s=>s.resolvable).map(s=>s.rawId);return await $d(e,this.servicePath,t)}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&Re(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:Pa(t),color:ka(t),role:La(t),id:String(t.id),rawJson:t};if(e.role==="NONE")return;const s=Bs.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};Zw(bt,"Registration");Oo([Do()],bt.prototype,"resolveAll",1);Oo([B({topic:"/kos/trouble/remove",websocket:!0,lifecycle:I.INIT})],bt.prototype,"handleTroubleRemoved",1);Oo([B({topic:"/kos/trouble/add",websocket:!0})],bt.prototype,"handleTroubleAdded",1);bt=Oo([D({modelTypeId:Jw,singleton:!0}),Qt(),Kc(),uo({containerProperty:"troubles",containerOptions:{indexMap:{[we.INDEX_TROUBLES_BY_IFACE]:zw,[we.INDEX_TROUBLES_BY_TYPE]:"type",[we.INDEX_TROUBLES_BY_GROUP]:"group",[we.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:we.SORT_KEY_RANK}})],bt);const Ht=bt.Registration,{URL:Dd}=fe(),{getAll:eE}=ce.build({basePath:`${Dd}/api/kos/ota`}),Fa=g.createLogger({name:"ota-service",group:"Services"}),tE=async()=>{Fa.debug("sending GET request to /api/kos/ota/artifacts");const t=await eE({urlOverride:`${Dd}/api/kos/ota/artifacts`});return Fa.debug("getArtifacts - response:",t),t==null?void 0:t.data};var sE=Object.defineProperty,rE=Object.getOwnPropertyDescriptor,Io=(t,e,s,r)=>{for(var o=r>1?void 0:r?rE(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&&sE(e,s,o),o};const xd="ota-model",oE=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Vo=t=>{const e=t.artifactInfo,s=oE(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 qt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new ti);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 tE();t&&t.forEach(e=>{const s=Vo(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=Vo(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=Vo(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};Io([Xt({modelType:Ht.type})],qt.prototype,"troubleContainer",2);Io([B({topic:"/kos/ota/artifacts/all",websocket:!0})],qt.prototype,"handleAllArtifacts",1);Io([B({topic:"/kos/ota/artifacts/changed",websocket:!0})],qt.prototype,"handleChangedArtifacts",1);qt=Io([D(xd)],qt);const jr=new Ce({class:qt,type:xd});function nE(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 Oi=()=>{var r;const t=de(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return g.info(`getKosConnectionId: ${s}`),s},Go=g.createLogger({name:"software-info-service",group:"Services"}),iE=Oi(),Ii=async t=>{Go.debug("sending GET for software-info");const[e,s]=await Lu.get("/api/kos/manifest/info",void 0,{signal:t,destinationAddress:iE});if(!s)throw t!=null&&t.aborted?(Go.debug("Request was aborted"),new z("Request was aborted")):(Go.error("Failed to fetch software-info",e),new z("Failed to fetch software-info"));return s},aE=nE(Ii),cE=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:Ii,getSoftwareInfosWithCancel:aE},Symbol.toStringTag,{value:"Module"}));var lE=Object.getOwnPropertyDescriptor,uE=(t,e,s,r)=>{for(var o=r>1?void 0:r?lE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const hs="software-info-model";let un=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 Ii(),e=(t==null?void 0:t.nodes)||{};te(()=>{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 z&&this.logger.error("Failed to fetch software-info",t)}}};un=uE([D(hs)],un);const Br={registration:{[hs]:{class:un,singleton:!1}},type:hs,predicate:Ie(hs),factory:he.Factory.create(hs)},{URL:Ad}=fe(),{getOne:dE}=ce.build({basePath:`${Ad}/api/kos/state`}),hE=g.createLogger({name:"state-bean-service",group:"Services"}),Rd=async({path:t})=>(hE.debug("sending GET for state-bean"),await dE({urlOverride:`${Ad}/api/kos/state/${t}`})),fE=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Rd},Symbol.toStringTag,{value:"Module"}));var pE=Object.defineProperty,gE=Object.getOwnPropertyDescriptor,Pd=(t,e,s,r)=>{for(var o=r>1?void 0:r?gE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&pE(e,s,o),o};const fs="state-bean-model",mE=vt("path");let Kr=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=ri.map(new Map),on(e,this)}updateModel(t){on(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&ii(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&go(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 Rd({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};Pd([B({topic:`/kos/state/${mE}`,websocket:!0})],Kr.prototype,"handleConfigBeanUpdated",1);Kr=Pd([D(fs)],Kr);const Ks={registration:{[fs]:{class:Kr,singleton:!1}},type:fs,predicate:Ie(fs),factory:he.Factory.create(fs)};var yE=Object.defineProperty,bE=Object.getOwnPropertyDescriptor,kd=(t,e,s,r)=>{for(var o=r>1?void 0:r?bE(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&&yE(e,s,o),o};const ps="state-prop-model",Na=vt("path");let Hr=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())??""}};kd([Xt({modelType:Ks.type,id:`state-bean-${Na}`,options:{path:Na}})],Hr.prototype,"stateBean",2);Hr=kd([D(ps)],Hr);const Ci={registration:{[ps]:{class:Hr,singleton:!1}},type:ps,predicate:Ie(ps),factory:he.Factory.create(ps)},{URL:vE}=fe(),{getAll:wE}=ce.build({basePath:`${vE}/api/state-prop`}),EE=g.createLogger({name:"state-prop-service",group:"Services"}),ME=async()=>(EE.debug("sending GET for state-prop"),await wE({})),_E=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:ME},Symbol.toStringTag,{value:"Module"})),{URL:Di}=fe(),{getOne:Ld}=ce.build({basePath:`${Di}/api/translation`}),xs=g.createLogger({name:"translation-service",group:"Services"}),TE=()=>{const t=window.location.origin,e=de();return(e==null?void 0:e.host)||t},Fd=async(t,e)=>{xs.debug(`Loading translations from: ${t}`);const s=e??TE();try{const r=await fetch(`${s}${t}`);return r.status!==200?(xs.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw xs.error("Error fetching translations",r),r}},SE=async()=>{xs.debug("Getting system localization descriptor");const t=await Ld({urlOverride:`${Di}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get localization descriptor ${t==null?void 0:t.status}`);return t.data},Nd=t=>async()=>{xs.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await Ld({urlOverride:`${Di}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},Ud="langResolver";var $E=Object.getOwnPropertyDescriptor,OE=(t,e,s,r)=>{for(var o=r>1?void 0:r?$E(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const gs="translation-model";function IE(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 jd(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])){const n=jd(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function Bd(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]=Bd(t[r],e[r]):s[r]=e[r]);return s}const dn=(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)?dn(r,e):r},pr=(t,e,s)=>{const r=/{{(.*?)}}/g,n=dn(t,e).replace(r,(a,c)=>{const u=c.trim();if(Object.prototype.hasOwnProperty.call(s||{},u))return s==null?void 0:s[u];if(u.includes(".")){const d=u.split(".");let h=s;for(const f of d)if(h&&typeof h=="object"&&Object.prototype.hasOwnProperty.call(h,f))h=h[f];else return a;return h}return a});return dn(n,e)},Ua=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let hn=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(Ud),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=Q.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return Fd(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);te(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=Bd(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=jd(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=Ua(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}=IE(e),{namespace:n,key:i}=Ua(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):s??i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>pr(u,this.data,o)):pr(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[i];return Array.isArray(c)?c.map(u=>pr(u,this.data,o)):pr(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=E.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};hn=OE([lo(),D(gs)],hn);const qr={registration:{[gs]:{class:hn,singleton:!1}},type:gs,predicate:Ie(gs),factory:he.Factory.create(gs)};var CE=Object.defineProperty,DE=Object.getOwnPropertyDescriptor,Kd=(t,e,s,r)=>{for(var o=r>1?void 0:r?DE(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&&CE(e,s,o),o};const ms="translation-container-model",xE=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function AE(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 xE([r,o])}let zr=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||AE.bind(this),s.kosContext.set(Ud,this.resolver),this.logger=s.logger,this._models=new Fe({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(t){return this.logger.debug("getting model "+t),this._models.getModel("translation-"+t)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const t of this.namespaces){const e=this.resolveNamespace(t);await ye(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=qr.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)||te(()=>{this.namespaces.push(t)}),n}else{this.logger.warn("namespace "+t+" not found in descriptor");const r=qr.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)}};Kd([Oe],zr.prototype,"_models",2);zr=Kd([D(ms)],zr);const Ve={registration:{[ms]:{class:zr,singleton:!0}},type:ms,predicate:Ie(ms),factory:he.Singleton.create(ms)},RE={set(t,e){const s=Q.getContext(Ve.type);s&&s.set(t,e)},get(t){const e=Q.getContext(Ve.type);return e==null?void 0:e.get(t)}},Hd={async init(t){const e=Ve.factory(t);return await ye(e),{translations:e}}};function PE(t){return(t==null?void 0:t.troubles)!==void 0&&(t==null?void 0:t.troubles)instanceof Array&&(t==null?void 0:t.troublesByType)!==void 0&&typeof(t==null?void 0:t.troublesByType)=="object"}const qd="kos-ws-event",xi=Jt(qd);var kE=Object.defineProperty,LE=Object.getOwnPropertyDescriptor,Ai=(t,e,s,r)=>{for(var o=r>1?void 0:r?LE(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&&kE(e,s,o),o};const FE=({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=E.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){g.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:FE({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),g.debug(`logged ${this.events.size} events`)}}};Ai([B({topic:[Ws.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Ai([B({topic:[Ws.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Ai([D(xi.type)],exports.WsEventModel);const ja=de(),NE=ja.debug==="true"||ja.debug===!0,UE="/api/system/canvas",zd=async(t,e)=>{const s=e||UE,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:NE?"false":"true"},body:t})},jE=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:zd},Symbol.toStringTag,{value:"Module"}));function Ba(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var BE=Object.defineProperty,KE=Object.getOwnPropertyDescriptor,Vd=(t,e,s,r)=>{for(var o=r>1?void 0:r?KE(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&&BE(e,s,o),o};const Gd="canvas-renderer-model";function Yo(t){return typeof t.onDone=="function"}let Vr=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){zd(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=Ba(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=Ba(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 Yo(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=Yo(this._renderer);Yo(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),H("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((d=(u=this._renderer)==null?void 0:u.isOneShot)==null?void 0:d.call(u))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,u;const a=(u=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:u.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(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"})})}};Vd([Xt({modelType:gi.type})],Vr.prototype,"router",2);Vr=Vd([D(Gd)],Vr);const Ri=new Ee({class:Vr,type:Gd});class Yd{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 HE{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 qE extends HE{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=`
|
|
107
|
+
["${e}"]`;if(r?(f=this.fosSocket)==null?void 0:f.connectionEstablished:(p=this.socket)==null?void 0:p.connectionEstablished){const v=r?this.fosSocket:this.socket;(y=v==null?void 0:v.socket)==null||y.send(u)}else{at.debug("no connection adding to offline messages");const v=r?this.fosSocket:this.socket;v==null||v.addOfflineMessage(u)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n,explicitDestination:i}){const{unsubscribe:a,count:c}=C(e,s);return at.debug(`Topic ${e} currently has ${c} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n,i),()=>{const{count:u}=a();at.debug(`Topic ${e} currently has ${u} subscribers`),u===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n,i)}}async whenReady(){const e=this;return this.webSocketSupported?(await E.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(Lt,"_instance");class Zm{constructor(e,s,r,o,n){l(this,"disposers",[]);l(this,"activatableDisposers",[]);l(this,"flowControllers",new Map);l(this,"baselineDependencies",new Map);l(this,"registeredTopics",new Set);l(this,"onceTopics",new Set);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[Z])||{},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.onceTopics.has(c)){this.log.debug(`Skipping once topic (already fired): ${c}`);return}if(this.registeredTopics.has(c)){this.log.debug(`Skipping duplicate subscription for ${c}`);return}if(this.registeredTopics.add(c),i.once&&this.onceTopics.add(c),this.log.debug(`Resolved topic: ${n} → ${c}`),i.requiresBaseline&&(this.baselineDependencies.set(c,i.requiresBaseline),this.log.debug(`Registered baseline dependency for ${c}: ${i.requiresBaseline.path}`)),i.flow)this.subscribeWithFlowControl(i,c,a);else{const u=this.createHandler(c,i);this.subscribe(i,c,u,a===I.ACTIVATE)}})}deactivate(){var s;this.log.debug(`Deactivating subscriptions for ${this.modelId}`);for(const r of this.activatableDisposers)try{r()}catch(o){this.log.error("Error during subscription disposal",o)}this.activatableDisposers=[];const e=((s=this.modelData)==null?void 0:s[Z])||{};for(const[r,o]of Object.entries(e))if(o.lifecycle===I.ACTIVATE){const n=this.resolvePropKey(r);this.registeredTopics.delete(n)}}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=[],this.registeredTopics.clear()}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=Lt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n,explicitDestination:e.explicitDestination});o?this.activatableDisposers.push(i):this.disposers.push(i)}else{this.log.debug(`Subscribing to EventBus topic: ${s}`);const{unsubscribe:i}=C(s,r);o?this.activatableDisposers.push(i):this.disposers.push(i)}}createHandler(e,s){return async r=>{try{const o=this.extractWildcardCapture(e,r,s),n=this.isBaselineReady(e);if(!this.model.isReady()||!n){n?this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`):this.log.warn(`Baseline not ready for ${e}. Queuing message.`);const i=()=>{const a=sn(r,s.skipParse),c=s.transform(a);if(s.condition(c,this.modelData,r))return this.callHandlerWithWildcard(s,c,o,r)};this.offlineQueue.enqueue(i,e,r)}else{const i=sn(r,s.skipParse),a=s.transform(i);if(s.condition(a,this.modelData,r))return this.callHandlerWithWildcard(s,a,o,r)}}catch(o){this.log.error(`Error handling subscription for ${e}`,o)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!dl(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return ul(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 qm(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===I.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;Lt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a,explicitDestination:e.explicitDestination}),i=fa(s)}else i=fa(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,e,r)}}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}getResponseStore(){return this.modelData.serviceResponses}isBaselineReady(e){const s=this.baselineDependencies.get(e);if(!s)return!0;const r=this.getResponseStore();if(!r)return this.log.warn(`ServiceResponseStore not found for baseline check on topic: ${e}`),!1;const n=`${(s.method||"get").toUpperCase()}:${s.path}`;return r.has(n)}flushQueueForBaseline(e){const s=this.baselineDependencies.get(e);if(!s){this.log.debug(`No baseline dependency for topic: ${e}`);return}const r=this.getResponseStore();if(!r){this.log.warn("ServiceResponseStore not found, falling back to standard flush"),this.offlineQueue.flush();return}const o=s.method||"get",n=r.getTemporalMetadataByPath(s.path,o);if(!n){this.log.warn(`Baseline temporal metadata not found for ${s.path}, falling back to standard flush`),this.offlineQueue.flush();return}const i=s.replayStrategy||pt.AFTER_REQUEST;this.log.info(`Flushing queue with strategy ${i} for topic: ${e}`),this.log.debug(`Baseline timing - requested: ${n.requestedAt}, received: ${n.receivedAt}`),this.offlineQueue.flushWithStrategy(i,n.requestedAt,n.receivedAt)}}function $t(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 Jm(t){return!!(t!=null&&t[Be])&&Object.keys(t[Be]).length>0}function ey(t){return!!(t!=null&&t[Z])&&Object.keys(t[Z]).length>0}function ty(t){return!!(t!=null&&t[Ke])&&t[Ke].length>0}function sy(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[gt])&&Object.keys(e[gt]).length>0}function ry(t){return t.retention===ie.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function oy(t,e){return t.has(e)}function ny(t){return!t.expiresAt||Date.now()<t.expiresAt}function ma(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class iy{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:ie.SINGLE},o=Date.now(),n=Date.now()){if(this.shouldExtendTTL(e,r))return this.extendExistingTTL(e,r.ttl),!1;const i=this.createCachedResponse(s,e,r,o,n);return this.storeResponse(e,i,r),!0}get(e){const s=this.responses.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.delete(e);return}return s.data}}getByPath(e,s="get"){return this.get(this.makeKey(e,s))}has(e){return this.get(e)!==void 0}delete(e){this.responses.delete(e),this.retentionPolicies.delete(e);const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}clearPath(e){Array.from(this.responses.keys()).filter(r=>this.extractPath(r)===e).forEach(r=>this.delete(r))}clear(){this.cleanupTimers.forEach(e=>clearTimeout(e)),this.responses.clear(),this.retentionPolicies.clear(),this.cleanupTimers.clear()}get size(){return this.responses.size}shouldCleanupAfterHandler(e){const s=this.retentionPolicies.get(e);return(s==null?void 0:s.retention)===ie.IMMEDIATE}shouldExtendTTL(e,s){if(!ry(s)||!oy(this.responses,e))return!1;const r=this.responses.get(e);return ny(r)}extendExistingTTL(e,s){const r=this.responses.get(e);r.expiresAt=Date.now()+s,this.resetCleanupTimer(e,s)}resetCleanupTimer(e,s){this.clearTimerIfExists(e),ma(e,s,this.cleanupTimers,r=>this.delete(r))}clearTimerIfExists(e){const s=this.cleanupTimers.get(e);s&&(clearTimeout(s),this.cleanupTimers.delete(e))}createCachedResponse(e,s,r,o,n){return{data:e,timestamp:n,requestedAt:o,receivedAt:n,path:this.extractPath(s),method:this.extractMethod(s),expiresAt:this.calculateExpiresAt(r)}}calculateExpiresAt(e){return e.retention===ie.TTL&&e.ttl?Date.now()+e.ttl:void 0}storeResponse(e,s,r){this.responses.set(e,s),this.retentionPolicies.set(e,r),this.applyRetentionPolicy(e,r)}applyRetentionPolicy(e,s){switch(s.retention){case ie.IMMEDIATE:break;case ie.TTL:s.ttl&&ma(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case ie.SINGLE:break;case ie.PERMANENT:case ie.MANUAL:break}}makeKey(e,s){return`${s.toUpperCase()}:${e}`}extractPath(e){return e.split(":",2)[1]||e}extractMethod(e){return e.split(":",2)[0]||"get"}getTemporalMetadata(e){const s=this.responses.get(e);if(s)return{requestedAt:s.requestedAt,receivedAt:s.receivedAt}}getTemporalMetadataByPath(e,s="get"){return this.getTemporalMetadata(this.makeKey(e,s))}cleanup(){const e=Date.now();Array.from(this.responses.entries()).filter(([r,o])=>o.expiresAt&&e>o.expiresAt).map(([r])=>r).forEach(r=>this.delete(r))}}class ay{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=Hn.create({modelId:s,modelTypeName:r}),i=new lm(e,$t(n,"fsm")),a=new dm($t(n,"offline-queue")),c=new tm(e),u=new em(e),d=new iy;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(Jm(o)&&(h.effectManager=new sm(r,s,o,$t(n,"effect"))),ey(o)){const f=$t(n,"subscription");h.subscriptionManager=new Zm(e,o,s,a,f),h.onlineLifecycleManager=new hm(e,$t(n,"online"))}return ty(o)&&(h.httpRouteManager=new Yn(o,$t(n,"http-routes"))),sy(o)&&(h.serviceRequestManager=new Km(o,d)),h}}const N=A.getLogger("kos-model"),cy="kos.extension.model.loader";class ql{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,"_isLoadExecuting");l(this,"offlineQueue");l(this,"subscriptionManager");l(this,"effectManager");l(this,"httpRouteManager");l(this,"onlineLifecycleManager");l(this,"serviceResponses");l(this,"serviceRequestManager");l(this,"companionManager");l(this,"childResolver");l(this,"fsm");this._id=typeof s<"u"?`${s}`:e,this.modelTypeName=e,this.initialized=!1,this.loaded=!1,this._isLoadExecuting=!1,this.modelData=r,this._status=w.CREATED,this._activeStatus=w.INACTIVE,this._onlineStatus=w.OFFLINE;const o=ay.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,this.serviceResponses=o.serviceResponseStore,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),o.serviceRequestManager&&(this.serviceRequestManager=o.serviceRequestManager),E.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,serviceRequestManager:!1,serviceResponses:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Zg(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;N.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=Q.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw N.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r,o;N.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ls(this,I.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(I.ACTIVATE));const n=Q.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),this.initializeStateMachineForLifecycle(I.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(I.ACTIVATE),this.createLifecycleCompanions(I.ACTIVATE),N.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(n){throw N.debug(`Model ${this.modelId} failed to activate`),n}}async whenLoaded(){await Ko([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{N.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await Ko([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{N.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Ko([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===w.READY,onMatch:()=>{N.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,o;if(this.fsm.current===w.READY){N.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{N.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ls(this,I.READY),await Sl(this,Vn.READY,I.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(I.READY));const n=Q.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.ready)==null?void 0:r.call(s,n)),this.offlineQueue.flush(),this.initializeStateMachineForLifecycle(I.READY),(o=this.subscriptionManager)==null||o.registerAll(I.READY),this.createLifecycleCompanions(I.READY),N.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};H(ml(this.modelTypeName,this.modelId),i),H(yl(this.modelTypeName),i)}catch(n){throw N.error(n),Error(n)}}async load(){var o,n,i,a,c,u;const e=this[et];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===w.LOADED){N.debug(`Model ${s} with id ${r} already loaded`);return}if(this._isLoadExecuting){N.debug(`Model ${s} with id ${r} is currently executing load`);return}this._isLoadExecuting=!0;try{N.debug(`Loading model ${s} with id ${r}`),await ls(this,I.LOAD);const d=Q.getContext(r),h=`${cy}.${s}`,f=await T.loader.executeLoader(h,{});f&&(N.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(I.LOAD)),await((i=(n=this.modelData)==null?void 0:n.load)==null?void 0:i.call(n,d)),te(()=>{this.loaded=!0}),N.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(I.LOAD),(a=this.subscriptionManager)==null||a.registerAll(I.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(I.LOAD)}catch(d){throw N.error(`Model ${r} failed to load`,d),d}finally{this._isLoadExecuting=!1}}async unload(){var e,s,r,o,n,i,a;N.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);try{const c=this.getChildren().map(d=>{var h;return(h=d.unload)==null?void 0:h.call(d)}).filter(d=>!!d);await Promise.allSettled(c);const u=Q.getContext(this.modelId);if(await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,u)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),this.modelData){const d=this.modelData;if(d._fsmInitialized=!1,d._fsmConfig){const h=((o=d._fsmOptions)==null?void 0:o.stateProperty)||"currentState";d[h]=void 0}d.stateHistory&&(d.stateHistory=[])}N.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(n=this.effectManager)==null||n.disposeAll(),(i=this.subscriptionManager)==null||i.disposeAll(),(a=this.httpRouteManager)==null||a.dispose()}catch(c){throw N.debug(`Model ${this.modelId} failed to unload`),c}}async init(){var n,i,a,c;const e=this[et];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=Q.getContext(s);N.debug(`Initializing model ${r} with id ${s}`),await ls(this,I.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(I.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,o)),this.initialized=!0,N.debug(`Model ${r} with id ${s} initialized`),(c=this.onlineLifecycleManager)==null||c.register(),this.initializeStateMachineForLifecycle(I.INIT),this.registerSubscribers(I.INIT),this.createLifecycleCompanions(I.INIT)}catch(u){throw N.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;N.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&Bc(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;N.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=Q.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(I.ONLINE)}async offline(){var s,r,o;N.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=Q.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 Ho=g.createLogger({name:"kos-model-instantiator"});class ly{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new zg(e,s,this.createModelInstance.bind(this))}createModelInstance(e,s,r={}){var a;const o=this.registry.models[e];if(!o){const c=`No model registered for type ${e}`;throw Ho.error(c,{modelType:e,requestedId:s,providedOptions:r,availableModelTypes:Object.keys(this.registry.models)}),Pt(new Error(c),{modelType:e,modelId:s,operation:"model instantiation - registry lookup",options:r,metadata:{availableModelTypes:Object.keys(this.registry.models)}})}const n=o.singleton?e:s;if(this.cache.restoreFromDeleteCache(n),!this.cache.hasModel(n)){Ho.debug(`Creating model instance: ${e} [${n}]`);const c=r&&Object.keys(r).length>0,u=o.class||o.create;if(((a=u==null?void 0:u.prototype)==null?void 0:a[Qs])===!0&&!c){const h=new Error(`Model ${e} requires options but none were provided`);throw ua(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Pt(h,{modelType:e,modelId:n,operation:"model instantiation - options validation",options:r,metadata:{requiresOptions:!0,hasOptions:!1}})}try{const h=o.create?o.create({modelTypeId:e,id:n,options:r}):new o.class(n,r),f=new ql({modelTypeName:e,id:n,modelData:h});this.cache.addModel(f),this._createCompanionModels(f,r)}catch(h){throw ua(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Pt(h,{modelType:e,modelId:n,operation:"model instantiation",options:r})}}const i=this.cache.getModelById(n);if(!i)throw Ho.error(`Model ${e} [${n}] not found in cache`),new Error(`Model ${e} [${n}] not found in cache`);return{model:i,data:i.modelData}}createCompanionModels(e,s,r){this.companionInstantiator.createCompanionModels(e,s,r)}_createCompanionModels(e,s){this.createCompanionModels(e,s)}}let uy=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 Jt(e)}};const zl=10,ya=g.createLogger({name:"kos-model-manager"});class Vl{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new Kg,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 uy(e),r.cache=new Hg(e.preloadModels),r.instantiator=new ly(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(ya.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=>(ya.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 Jt(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(L.RESET,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),pl.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),zl)))}async destroyModel(e){var s;e!=null&&e.modelId&&this.dependencies.canDestroy(e.modelId)&&(await((s=e.unload)==null?void 0:s.call(e)),this.removeModel(e))}createModelInstance(e,s,r={}){return this.instantiator.createModelInstance(e,s,r)}createLifecycleCompanions(e,s,r){this.instantiator.createCompanionModels(e,s,r)}registerCompanionModel(e,s){this._registry.registerCompanionModel(e,s)}registerModel(e){this._registry.registerModel(e)}}var wr=(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))(wr||{}),ut=(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))(ut||{});const dy=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),E.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),E.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,n=>A.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(()=>{E.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=>A.debug(n.machine.current)),online:s}},W=g.createLogger({name:"kos-core"}),hy=()=>{const t=de(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},fy=()=>{const t=window.location.protocol,e=de(),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://")},py=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=de(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},gy=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=de(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},my=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?g.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):g.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)}}},ba=t=>typeof t.reload=="function",yy=t=>typeof t.unload=="function";var Gl=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(Gl||{});class S{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=wr.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,E.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(Te.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(ut.GO_ONLINE)}),C(Te.DISCONNECTED,async()=>{this.fsmService.service.send(ut.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0,this.fsmService.service.send(ut.RELOAD)}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(Te.RELOAD,()=>{W.warn("WebSocket requested reload"),this.fsmService.service.send(ut.RELOAD)}),C("/studio/project/reload",()=>{W.warn("Project requested reload"),this.fsmService.service.send(ut.RELOAD)});const s=Lt.getInstance(),r=py(),o=gy(),n=fy();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=hy()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=dy(this),this.fsmService.service.send(ut.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){W.info("reload already in progress");return}this._reloading=!0,W.warn("reloading KOS Core"),W.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)ba(c.modelData)&&(W.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),W.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&ba(c.modelData)&&(W.warn(`reloading model ${c.modelId}`),(i=c.unload)==null||i.call(c),await c.modelData.reload(),(a=c.registerSubscribers)==null||a.call(c));const r=Date.now()-e;setTimeout(()=>{E.runInAction(()=>{W.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){W.debug("KOS Core going online"),await this._transport.whenReady(),W.debug("KOS Transport Ready. Calling online() for models"),H("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){W.debug("KOS Core going offline"),H("/kosCore/offline","/kosCore/offline")}async unload(){var o;W.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,W.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)yy(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-e;setTimeout(()=>{E.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await E.when(()=>this.status===wr.READY)}async ready(){W.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}=my(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw W.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);W.debug("leaving kos-core ready() ")}get isReady(){return this.status===wr.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){W.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,W.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){W.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,W.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(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{T.dataMapper.registerDataMapper(u,p)}):T.dataMapper.registerDataMapper(u,d))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&T.propertyMapper.registerPropertyMapper(u,d)}),(c=e.extensions)!=null&&c.contextLoader&&Object.keys(e.extensions.contextLoader).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.contextLoader)==null?void 0:f[u];d&&T.loader.registerLoader(u,d)}),R.model.getAll().forEach(([,u])=>{e.models={...e.models,...u.registration}}),e.models={...e.models,...R.model.getLegacyModels()},R.companion.getAll().forEach(([u,d])=>{e.companionModels={...e.companionModels},e.companionModels[u]=e.companionModels[u]||[];for(const h of d){let f;if(typeof h=="string"){const p=e.models[h];if(p!=null&&p.class){const y=p.class.prototype[et];f=y==null?void 0:y.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),R.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=Vl.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(S,"_instance");const by=g.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Yl{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=S.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){by.info(`model ${e.modelId} already visited`);return}const s=!!this.visitModel(e.modelData,this);this.visitedModels.add(e.modelId),!s&&((r=e.getChildren)==null||r.call(e).forEach(o=>{var n;(n=o.accept)==null||n.call(o,this)}))}}class vy extends Yl{constructor(s){super();l(this,"targetId");l(this,"currentPath",[]);l(this,"foundPath",null);this.targetId=s}visit(s){var o;if(this.visitedModels.has(s.modelId))return;this.currentPath.push(s.modelId),this.visitedModels.add(s.modelId),!!this.visitModel(s.modelData)||(o=s.getChildren)==null||o.call(s).forEach(n=>{var i;this.foundPath||(i=n.accept)==null||i.call(n,this)}),this.foundPath||this.currentPath.pop()}visitModel(s){return s.id===this.targetId?(this.foundPath=this.currentPath.slice(0,-1),!0):!1}getAncestorPath(){return this.foundPath??[]}wasFound(){return this.foundPath!==null}}function wy(t,e){e.forEach(s=>{Object.getOwnPropertyNames(s.prototype).forEach(r=>{const o=Object.getOwnPropertyDescriptor(s.prototype,r);Object.defineProperty(t.prototype,r,o)})})}function Ey(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const Qn=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},Wl=t=>t,Xn=t=>t,My=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=Wl,idMapper:o=Xn})=>n=>{const i=n.map(o),c=Qn(i,t.data).map(r).filter(Boolean);t.removeAll(c);const u=i.map(d=>{const h=t.getModel(d.id);return h&&s?s(d,h):e(d)}).filter(Boolean);t.addAll(u)},_y=({container:t,onAddItem:e,onRemoveItem:s=Wl,idMapper:r=Xn})=>o=>{const n=o.map(r);Qn(n,t.models).forEach(s),n.forEach(e)},Ty=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=Xn})=>o=>{const n=o.map(r);Qn(n,t).forEach(s),n.forEach(e)},Sy=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},va=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),wa=[{amount:60,name:"seconds"},{amount:60,name:"minutes"},{amount:24,name:"hours"},{amount:7,name:"days"},{amount:4.34524,name:"weeks"},{amount:12,name:"months"},{amount:Number.POSITIVE_INFINITY,name:"years"}];function Ql(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=wa.length;s++){const r=wa[s];if(Math.abs(e)<r.amount)return va.format(Math.round(e),r.name);e/=r.amount}return va.format(Math.round(e),"years")}const Zn=t=>t%4===0&&t%100!==0||t%400===0,Jn=(t,e)=>[31,Zn(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Xl=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,Jn(s.getFullYear(),s.getMonth()))),s},Zl=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},Ft="en-US",Jl={short:{year:"numeric",month:"2-digit",day:"2-digit"},medium:{year:"numeric",month:"short",day:"2-digit"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}},eu={short:{hour:"2-digit",minute:"2-digit",hour12:!0},medium:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0},long:{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZoneName:"short"},full:{hour:"2-digit",minute:"2-digit",hour12:!0,timeZoneName:"long"}},tu=(t,{dateStyle:e="short",locales:s=Ft}={dateStyle:"short",locales:Ft})=>{const r=e==="short"?Jl.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},su=(t,{locales:e=Ft,timeStyle:s="short"}={locales:Ft,timeStyle:"short"})=>{const r=eu[s];return new Intl.DateTimeFormat(e,r).format(t)},ru=(t,{dateStyle:e="short",locales:s=Ft,timeStyle:r="short"}={dateStyle:"short",locales:Ft,timeStyle:"short"})=>{const o={...e&&Jl[e],...r&&eu[r]};return new Intl.DateTimeFormat(s,o).format(t)},$y=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Zl,addMonthsToDate:Xl,formatDate:tu,formatDateSince:Ql,formatDateTime:ru,formatTime:su,getDaysInMonth:Jn,isLeapYear:Zn},Symbol.toStringTag,{value:"Module"})),ou="featureFlagResolver",cr=new Map;Zt(ou,{register:(t,e)=>{var s;cr.has(t)||cr.set(t,[]),(s=cr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=cr.get(t);if(!s)return[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(g.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return iu.updateFlags(i),Object.keys(i)}});const Oy="kos.loader.featureFlag";class nu{constructor(e={}){l(this,"flags",{});this.flags=e}isFeatureEnabled(e){return!!this.flags[e]}enableFeature(e){this.flags[e]=!0}disableFeature(e){this.flags[e]=!1}toggleFeature(e){this.flags[e]=!this.flags[e]}updateFlags(e){this.flags={...this.flags,...e}}}window.KosFeatureFlags=window.KosFeatureFlags??new nu;const iu=window.KosFeatureFlags,au=(t,e,s)=>{s/=100;const r=e*Math.min(s,1-s)/100,o=n=>{const i=(n+t/30)%12,a=s-r*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${o(0)}${o(8)}${o(4)}`},cu=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return au(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},lu=(t,e)=>getComputedStyle(t).getPropertyValue(e),Iy=(t,e)=>cu(lu(t,e)),Cy=(t,e)=>{const s={...t};return s.id&&delete s.id,s},on=(t,e,s=Cy)=>{const r=s(t,e);E.runInAction(()=>{Object.assign(e,r)})};class uu{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 Dy=async(t,e)=>{const s=new uu;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},Jt=t=>({type:t,build:(e,s)=>S.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=S.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),xy=t=>{S.getInstance().modelManager.registerModel(t)},Ay=(t,e)=>{S.getInstance().modelManager.registerCompanionModel(t,e)},Ea="/kos/ui/internal/heartbeat/",Ry=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=S.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${Ea}${t}`,callback:()=>{a=performance.now()}}),u=r??3e3,d=window.setInterval(()=>{let v=performance.now()-a;v=v/1e3,v>u/1e3&&i.abort()},u),h=o??2e3,f=window.setInterval(()=>{Nl({msg:{},options:{topic:`${Ea}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},y=()=>{p(),s&&s(),i.signal.removeEventListener("abort",y)};return i.signal.addEventListener("abort",y),{cleanUpHeartbeat:p}},du=(...t)=>e=>t.reduce((s,r)=>r(s),e),Py={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function ky(t,e){let s=1;const r={...Py,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(g.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw c}throw new Error("All attempts failed")}const Ly=g.createLogger({name:"kos-service-request"}),fe=t=>({isMock:!1,URL:exports.BASE_URL}),Fy=(t,e,s)=>async({id:r,tracker:o,urlOverride:n,ordered:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f})=>{const p={method:"DELETE"};t&&(p.destinationAddress=t),o&&(p.tracker=o),es(p,{ordered:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f});try{const y=await s(n||`${e}/${r}`,p);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 z("Request timed out while deleting model");if(y.name==="AbortError")throw new z("Request was cancelled while deleting model")}throw y}},es=(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),Ny=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,timeout:c,signal:u,destinationAddress:d})=>{const h={method:"GET"};t&&(h.destinationAddress=t),es(h,{timeout:c,ordered:o,studio:n,fos:i,bridge:a,signal:u,destinationAddress:d});const f=r||e;try{const p=await s(f,h);if(!p.ok){let v;try{v=await p.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${p.status}`,v??void 0)}return await p.json()??void 0}catch(p){if(p instanceof DOMException){if(p.name==="TimeoutError")throw new z("Request timed out while retrieving models");if(p.name==="AbortError")throw new z("Request was cancelled while retrieving models")}throw p}},Uy=(t,e,s)=>async({urlOverride:r,ordered:o,studio:n,fos:i,bridge:a,tracker:c,timeout:u,signal:d,destinationAddress:h})=>{const f={method:"GET"};t&&(f.destinationAddress=t),c&&(f.tracker=c),es(f,{timeout:u,ordered:o,studio:n,fos:i,bridge:a,signal:d,destinationAddress:h});const p=r||e;Ly.debug(`resolvedUrl: ${p}`);try{const y=await s(p,f);if(!y.ok){let M;try{M=await y.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${y.status}`,M??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new z("Request timed out while retrieving model");if(y.name==="AbortError")throw new z("Request was cancelled while retrieving model")}throw y}},jy=(t,e,s)=>async({urlOverride:r,id:o,ordered:n,studio:i,fos:a,bridge:c,timeout:u,signal:d,destinationAddress:h})=>{const f={method:"GET"};t&&(f.destinationAddress=t),es(f,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,signal:d,destinationAddress:h});const p=r||`${e}/${o}`;try{const y=await s(p,f);if(!y.ok){let M;try{M=await y.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${y.status}`,M??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new z("Request timed out while retrieving model by ID");if(y.name==="AbortError")throw new z("Request was cancelled while retrieving model by ID")}throw y}};class z extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const Ma=(t,e,s)=>async({model:r,urlOverride:o,ordered:n,tracker:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f})=>{const p={method:"POST",body:typeof r=="string"?r:JSON.stringify(r)};t&&(p.destinationAddress=t),i&&(p.tracker=i),es(p,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,signal:h,destinationAddress:f});try{const y=await s(o||e,p);if(!y.ok){let M;try{M=await y.json()}catch{}throw new z(`There was a problem sending the POST data; returned status ${y.status}`,M??void 0)}return await y.json()??void 0}catch(y){if(y instanceof DOMException){if(y.name==="TimeoutError")throw new z("Request timed out while adding model");if(y.name==="AbortError")throw new z("Request was cancelled while adding model")}throw y}},_a=(t="POST",e,s,r)=>async({model:o,id:n,urlOverride:i,ordered:a,studio:c,fos:u,bridge:d,timeout:h,signal:f,destinationAddress:p})=>{const y={method:t};o&&(y.body=JSON.stringify(o)),e&&(y.destinationAddress=e),es(y,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,signal:f,destinationAddress:p});try{const v=await r(i||`${s}/${n}`,y);if(!v.ok){let $;try{$=await v.json()}catch{}throw new z(`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 z("Request timed out while modifying model");if(v.name==="AbortError")throw new z("Request was cancelled while modifying model")}throw v}},ce={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:Ny(t,s||e,c),getModelById:jy(t,r||e,c),getOne:Uy(t,r||e,c),addModel:Ma(t,n||e,c),deleteModel:Fy(t,o||e,c),modifyModel:_a("POST",t,i||e,c),putModel:_a("PUT",t,i||e,c),postModel:Ma(t,n||e,c)}}};function By(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function Ky(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function Hy(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function qy(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function zy(t){const e=t.serviceResponses;e&&e.clear()}const Vy=wt(),hu=()=>`kos-${Vy}`,Gy=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(hu()),ei=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=C(t,i=>{A.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)}),Yy=async(t,e,s)=>{const r=ei(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)},Wy=async({topic:t,msg:e,requestId:s})=>{const r=s??wt(),o=ei(r);H(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},be=new Map;class fu{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new E.ObservableMap({}),this._parent="",E.makeAutoObservable(this)}setParent(e){te(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=ke(this._parent))==null?void 0:e.model}get companionModels(){const e=ke(this._id);return e!=null&&e.model?nl(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||!be.has(n.id)?!1:(i=be.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=be.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=be.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 Q={createContext:(t,e)=>{const s=be.get(t)??new fu(t);if(e){if(!be.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return be.set(t,s),s},getContext:t=>be.get(t),deleteContext:t=>{be.delete(t)},setParentContext:(t,e)=>{var s;if(!be.has(e))throw new Error(`Parent context ${e} does not exist`);(s=be.get(t))==null||s.setParent(e)},rootContext:()=>be.get("root")};Q.createContext("root");const Qy=t=>Q.getContext(t.id),ct=g.createLogger({name:"kos-data-container"});class ti{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");l(this,"_maxCapacity");l(this,"_evictionStrategy");l(this,"_evictionBatchSize");l(this,"_insertionOrder",[]);l(this,"_accessTimes");l(this,"_customEvictionFilter");this._data=E.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=E.observable.map(s),this.idx=Pe(),this._maxCapacity=e==null?void 0:e.maxCapacity,this._evictionStrategy=(e==null?void 0:e.evictionStrategy)||"fifo",this._evictionBatchSize=(e==null?void 0:e.evictionBatchSize)??Math.max(10,Math.ceil(((e==null?void 0:e.maxCapacity)??100)*.1)),this._customEvictionFilter=e==null?void 0:e.customEvictionFilter,this._evictionStrategy==="lru"&&this._maxCapacity&&(this._accessTimes=E.observable.map(new Map)),E.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new qn({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){E.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){E.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(){E.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=this._ensureObservable(e);this._cleanupExistingDisposer(e.id),this._persistData(r),this._trackDataMetadata(r),this._enforceCapacityLimits(),this._configureDataMonitoring(r),s||this.increment()}_ensureObservable(e){return E.isObservable(e)?e:E.observable.object(e)}_cleanupExistingDisposer(e){if(!e)return;const s=this._disposerMap.get(e);s&&(s(),this._disposerMap.delete(e))}_persistData(e){this._data.set(e.id||"",e)}_trackDataMetadata(e){this._maxCapacity&&(this._insertionOrder.push(e.id||""),this._accessTimes&&this._accessTimes.set(e.id||"",Date.now()))}_enforceCapacityLimits(){this._maxCapacity&&this._data.size>this._maxCapacity&&this._evictModels()}_configureDataMonitoring(e){const s=E.observe(e,r=>{Object.values(this._optionsMap||{}).includes(r.name)&&this.increment()});this._disposerMap.set(e.id||"",s)}removeModel(e){this._data.delete(e);const s=this._insertionOrder.indexOf(e);s!==-1&&this._insertionOrder.splice(s,1),this._accessTimes&&this._accessTimes.delete(e),this.increment();const r=this._disposerMap.get(e);r&&(r(),this._disposerMap.delete(e))}updateModel(e){const s=E.observable.object(e);this._data.set(s.id||"",s),this.increment()}getModel(e){const s=this._data.get(e);return s&&this._accessTimes&&this._accessTimes.set(e,Date.now()),s}getIndexKeys(e){return this.index.has(e)?this.index.get(e).keys??[]:(ct.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):(ct.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return ct.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}_evictModels(){if(!this._maxCapacity)return;const e=this._data.size-this._maxCapacity;if(e<=0)return;const s=Math.min(this._evictionBatchSize,e);this._logDataCapacityWarning(s);const r=this._selectDataForEviction(s);this._removeEvictedData(r),this._logDataEvictionComplete(r.length)}_logDataCapacityWarning(e){ct.info(`Data container capacity exceeded (${this._data.size}/${this._maxCapacity}). Evicting ${e} items using ${this._evictionStrategy} strategy. This may indicate missing cleanup handlers or data inconsistency.`)}_selectDataForEviction(e){switch(this._evictionStrategy){case"fifo":return this._selectFifoData(e);case"lru":return this._selectLruData(e);case"custom":return this._selectCustomData(e);default:return this._selectFifoData(e)}}_selectFifoData(e){const s=[];for(let r=0;r<e&&this._insertionOrder.length>0;r++){const o=this._insertionOrder.shift();o&&this._data.has(o)&&s.push(o)}return s}_selectLruData(e){const s=[];return this._accessTimes&&Array.from(this._accessTimes.entries()).sort((o,n)=>o[1]-n[1]).slice(0,e).forEach(([o])=>{this._data.has(o)&&s.push(o)}),s}_selectCustomData(e){return this._customEvictionFilter?this._customEvictionFilter(this.data).slice(0,e).map(r=>r.id):(ct.error("Custom eviction strategy specified but no customEvictionFilter provided. Falling back to FIFO."),this._selectFifoData(e))}_removeEvictedData(e){e.forEach(s=>{var o;const r=this._data.get(s);ct.info(`Evicting data item: ${s}`,{itemId:s,itemType:r?(o=r.constructor)==null?void 0:o.name:"unknown",strategy:this._evictionStrategy}),this.removeModel(s)})}_logDataEvictionComplete(e){ct.info(`Evicted ${e} data items. Current size: ${this._data.size}/${this._maxCapacity}`)}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 Xy{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 he.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return Ie(this.type)}}class Zy{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 he.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return Ie(this.type)}}class pu{constructor(){l(this,"_token");E.makeAutoObservable(this),C("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class gu{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 u=this.matchRoute(c.path,r);if(c.method===e.method&&u){i.params=u;let d=0;const h=async()=>{if(d<c.middlewares.length){const f=c.middlewares[d++];await f(i,s,h)}};await h();return}}(a=s.status)==null||a.call(s,404).send({error:"Route not found"})}extractOpenApiParams(e){return e.split("/").filter(s=>s.startsWith(":")).map(s=>({name:s.slice(1),in:"path",required:!0,schema:{type:"string"}}))}generateOpenApiSpec(){const e={};for(const s of this.openApiRoutes)e[s.path]||(e[s.path]={}),e[s.path][s.method.toLowerCase()]={summary:s.description||`Handles ${s.method} ${s.path}`,parameters:s.parameters||[],responses:{200:{description:"Successful response"}}};return{openapi:"3.0.0",info:{title:"Kos Router API",version:"1.0.0",description:"Dynamically generated OpenAPI documentation"},paths:e}}extractPathParams(e){const[s,r]=e.split("?"),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 mu=g.createLogger({name:"intent-service"}),Jy=t=>{On(`/kos/intent/${t.type}`)?H(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):mu.info(`No subscribers for intent ${t.type}. Intent not sent.`)},eb=async t=>new Promise(e=>{const{type:s,options:r}=t;if(On(`/kos/intent/${t.type}`)){const o=wt(),{unsubscribe:n}=C(o,a=>{clearTimeout(i),n(),a&&(a.headers=a.headers||{},a.headers["kos.intent.type"]=s,a.headers.responseId=o),e([null,{body:a==null?void 0:a.body,payload:a}])}),i=setTimeout(()=>{n(),e([`Intent ${s} timed out after 1 second`,null]),console.warn(`Intent ${s} timed out after 1 second`)},1e3);H(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else mu.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),je=g.createLogger({name:"app-startup-service"});async function yu(t,e={}){const{timeout:s=3e4,throwOnTimeout:r=!0,requirePostStarted:o=!1}=e;if(t.length===0)return je.warn("No app IDs provided to waitForAppsToStart"),!0;je.debug(`Waiting for apps to start: ${t.join(", ")}`);try{const n=t.map(c=>`/kos/app/started/${c}`),i=await Dn(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>Wn),[u,d]=await c.get("/api/kos/apps/started");return u?(je.error("Error fetching started apps:",u),[]):d}catch(c){je.error("Failed to fetch app startup status:",c)}return[]},shouldUseFetchedState:c=>t.every(u=>{const d=c.find(h=>h.appId===u);return!(!d||!d.started||o&&!d.postStarted)}),timeout:s}),a=t.filter(c=>{const u=i.find(d=>d.appId===c);return!!(!u||!u.started||o&&!u.postStarted)});if(a.length>0){const c=`Apps not started: ${a.join(", ")}`;if(je.error(c),r)throw new Error(`App startup timeout: ${c}`);return!1}return je.info(`All apps started successfully: ${t.join(", ")}`),!0}catch(n){const i=`Failed to wait for apps to start: ${t.join(", ")}`;if(je.error(i,n),r)throw new Error(`${i} - ${n instanceof Error?n.message:String(n)}`);return!1}}async function tb(t,e={}){return yu([t],e)}async function sb(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){je.error("Failed to check app startup status:",r),t.forEach(o=>s[o]=!1)}return s}async function rb(){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 je.error("Failed to fetch started apps:",t),[]}}const nn=E.when,si=E.computed,te=E.runInAction,X=E.autorun,bu=E.reaction,ri=E.observable,oi="Not Assigned",ob="kos.trouble.added",nb="kos.trouble.removed";var se=(t=>(t.TroubleRank="kos.trouble.rank.mapper",t.TroubleColor="kos.trouble.color.mapper",t.TroubleRole="kos.trouble.role.mapper",t.RegionServicePath="kos.region.service_path.mapper",t.ConfigServicePath="kos.config.service_path.mapper",t))(se||{}),Is=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))(Is||{});const vu=g.createLogger({name:"config-bean-service",group:"Services"}),ni=exports.BASE_URL,wu=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:ib,getOne:ab}=ce.build({destinationAddress:"",basePath:`${ni}/kos/config/`}),Eu=async(t,e,s="/api/kos/config")=>(vu.debug(`sending modify request for ConfigBean: ${t}`),ib({model:e,urlOverride:`${ni}${s}/${t}`})),Mu=async(t,e="/api/kos/config")=>(vu.debug(`sending get request for ConfigBean: ${t}`),await ab({urlOverride:`${ni}${e}/details/${t}/15`})),ii=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",go=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function _u(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Tu(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])?Tu(t[r],o,s):s[o]=t[r]}return s}const Su=(t,e)=>{const s=t.details[0].bean||_u(t.details[0].scopes),r=Tu(s);E.runInAction(()=>{const o={...r};e.props.setValues(o)})},$u=(t,e)=>{E.runInAction(()=>{const s=t.changes.reduce((n,i)=>(n[i.attr]=i,n),{}),r=t.scopedChanges.reduce((n,i)=>{const a=n[i.attr];return a&&(n[i.attr]={...a,currentValue:i.currentValue??a.currentValue,previousValue:i.previousValue??a.previousValue}),n},s);Object.values(r).forEach(n=>{const i=n.attr;let a=n.currentValue,c=n.previousValue;typeof a=="string"&&ii(a)&&(a=a.toLowerCase()=="true",c=(c==null?void 0:c.toLowerCase())=="true"),typeof a=="string"&&go(a)&&(a=Number(a),c=Number(c)),e.props[i]=a,e.prevProps[i]=c})})},Ou=t=>Object.fromEntries(t.props.entries),cb=t=>e=>s=>t.build(e,s);var lb=Object.defineProperty,ub=Object.getOwnPropertyDescriptor,Iu=(t,e,s,r)=>{for(var o=r>1?void 0:r?ub(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&&lb(e,s,o),o};function db(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const ai="config-bean-model",lr=g.getLogger(ai),hb=vt("path");function fb(t){return T.propertyMapper.hasMapper(se.ConfigServicePath)?T.propertyMapper.executeMapper(se.ConfigServicePath,t):"/api/kos/config"}let Dr=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath||fb(this);const{modifyConfigBean:s=Eu,getConfigBean:r=Mu}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Pe(),this.prevProps=Pe()}get values(){return this.props.values}async ready(){lr.debug(`readying config bean ${this.path}`),lr.debug(`complete readying config bean ${this.path}`)}async load(){lr.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;Su(e,this),lr.debug(this.values);const s=t==null?void 0:t.data.details[0].schema;te(()=>{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=db(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=Ou(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){$u(t,this)}};Iu([B({topic:`/kos/config/${hb}`,websocket:!0})],Dr.prototype,"handleConfigBeanUpdated",1);Dr=Iu([D(ai)],Dr);const Rs=new Ee({class:Dr,type:ai}),mo=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Rs.type,id:`${Rs.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:I.INIT,lazy:e}},{URL:ci}=fe(),{getOne:pb,getAll:gb}=ce.build({basePath:`${ci}/api/kos/regions/info`}),Cu=async t=>{try{return await pb({urlOverride:`${ci}${t}/info`})}catch{return}},Du=async t=>{try{return await gb({urlOverride:`${ci}${t}`})}catch{return}},mb=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Cu,getRegions:Du},Symbol.toStringTag,{value:"Module"}));var ge=(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))(ge||{});const xu={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 yb(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},{...xu});return{...t,...r}}function bb(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,n.alias&&(a[n.alias]=c),Object.hasOwn(n,"default")&&Object.defineProperty(a,"default",{value:c,writable:!0,enumerable:!0,configurable:!0}),o[n.measure]=i,o},{time:{[s]:{...xu}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function vb(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 wb=Object.defineProperty,Eb=Object.getOwnPropertyDescriptor,li=(t,e,s,r)=>{for(var o=r>1?void 0:r?Eb(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&&wb(e,s,o),o};const Er="region-info-model",cs=g.createLogger({name:"region-info-model"});function Mb(t){return T.propertyMapper.hasMapper(se.RegionServicePath)?T.propertyMapper.executeMapper(se.RegionServicePath,t):"/api/kos/regions"}let Ps=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"serviceBasePath");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.serviceBasePath=Mb(this),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[ge.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[ge.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[ge.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[ge.family]!==s[ge.family])throw new Error(`Cannot convert between units of different families: ${e[ge.family]} and ${s[ge.family]}`);const r=e[ge.offset],o=e[ge.scale],n=s[ge.scale],i=s[ge.offset],a=s[ge.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 u=this.measureMap[s.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);i=(a=u[s.system])==null?void 0:a.default,i||cs.info("Could not find default unit for measure",s.measure)}if(!n&&e.measure&&e.system){const u=this.measureMap[e.measure];if(!u)throw Error(`Could not find measure ${s.measure}. Measure should be one of ${Object.keys(this.measureMap).join(", ")}`);n=(c=u[e.system])==null?void 0:c.default,n||cs.info("Could not find default unit for measure",e.measure)}return!n||!i?(cs.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){cs.debug("initializing region info")}async load(){cs.debug("loading region info");const t=await Du(this.serviceBasePath);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 Cu(this.serviceBasePath);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(yb,{}),this.measureMap=e.data.unitSystems.reduce(bb,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(vb,{}),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))}};li([mo({path:"kos:service:region:settings"})],Ps.prototype,"regionSource",2);li([mo({path:"kos:service:region"})],Ps.prototype,"region",2);Ps=li([D(Er)],Ps);const ae={registration:{[Er]:{class:Ps,singleton:!0}},type:Er,factory:he.Singleton.create(Er)},xr=({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},ui=(t,e,s)=>{const{model:r}=ke(ae.type);if(!r)throw new Error("RegionInfo model not found");if(!Ir(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=xr({source:e}),i=xr({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function Ta(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 _b=(t,e,s,r)=>{const o=ui(t,e,s),n=xr({source:e}),{model:i}=ke(ae.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=xr({source:s||c,defaultMeasure:i.getUnitMeasure(n.unit||"")}),d=i.getDefaultUnitForMeasure(a,u.system),h=i.getDefaultUnitDecimalPlaces(a,u.system),f={...r,minDecimals:(r==null?void 0:r.minDecimals)??h,maxDecimals:(r==null?void 0:r.maxDecimals)??h};return{value:o,unit:d||n.unit||"",display:Ta(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:Ta(o,d||n.unit||"",{...f,mode:"short"})}};function Sa({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 $a({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 Ot=(t,e)=>s=>!t||!e?s:go(s)?ui(Number(s),t,e):s,Tb=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return Sa(t.options).map(Ot(s,r));if(t.options.type==="rangeInterval")return $a(t.options).map(Ot(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map(Ot(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Sa(t.options.unitSystems[e]).map(Ot(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return $a(t.options.unitSystems[e]).map(Ot(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map(Ot(s,r))}}return[]},Sb=(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 $b=Object.defineProperty,Ob=Object.getOwnPropertyDescriptor,di=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ob(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&&$b(e,s,o),o};function Ib(t){return(t==null?void 0:t.type)==="enum"}function Cb(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 Db(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return Xe.format(r,e)}const Mr="config-bean-prop-model",It=g.createLogger({name:"config-bean-prop-model"}),xb=vt("path"),Ab=vt("serviceBasePath");let ks=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 wu(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?Cb(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=Ib(r)?r.values:Tb(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,i;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 a=this.getDefaultUnitDecimalPlaces(r,((n=s==null?void 0:s.to)==null?void 0:n.system)||e,(i=s==null?void 0:s.to)==null?void 0:i.unit);try{const u=this.getFormatterOptions(s);if(u){let d=String(t);return d=u.formatToParts(Number(t))[0].value,Number(d)}}catch(u){It.info(`error formatting value ${t}`,u)}return Number(t).toFixed(a)}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(){It.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 Db(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){It.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 Sb(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,u=this.formatter||c;if(u){let d=typeof u=="function"?u(((n=t==null?void 0:t.to)==null?void 0:n.system)||e):u;s&&(d={unit:this.getDefaultUnit(t),...d},d.style==="unit"&&(d.maximumFractionDigits=d.maximumFractionDigits??this.getDefaultUnitDecimalPlaces(s,((i=t==null?void 0:t.to)==null?void 0:i.system)||e,(a=t==null?void 0:t.to)==null?void 0:a.unit)));try{o=new Intl.NumberFormat(r,{...d})}catch(h){It.error(`error creating formatter ${d}. Returning the raw value`,h)}}else It.debug(`no formatter found for config bean prop ${this.id}. Returning the raw value`)}return o}getConverter(){var r,o,n,i,a,c,u,d,h,f,p,y,v;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const M=(r=this.converter)==null?void 0:r.measure,$=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,U=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,x=(u=(c=this.converter)==null?void 0:c.to)!=null&&u.unit?this.regionInfo.getUnitMeasure(this.converter.to.unit):void 0,O=M||$||U||x||e,P=((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.unit)||this.regionInfo.getDefaultUnitForMeasure(O,((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.defaultUnitSystem),V=((v=(y=this.converter)==null?void 0:y.to)==null?void 0:v.system)??this.regionInfo.getUnitSystem(P),ee=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:ee,...this.converter.from},to:{...this.converter.to,unit:P,system:V},measure:O}}if(s&&e){const M=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),$=this.regionInfo.getUnitSystem(s),U=this.regionInfo.getUnitSystem(M);return{measure:e,to:{unit:$===U?s:M}}}}async updateProperty(t){It.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)}};di([Xt({modelType:ae.type})],ks.prototype,"regionInfo",2);di([mo({path:xb,serviceBasePath:Ab})],ks.prototype,"bean",2);ks=di([D(Mr)],ks);const Et={registration:{[Mr]:{class:ks,singleton:!1}},type:Mr,factory:he.Factory.create(Mr)};function Rb(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})),(u,d)=>{u[F]=u[F]||{},u[F][d]={modelType:Et.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:I.INIT,lazy:n}}}const hi=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}),fi=(t,e)=>{g.debug(`future dto ${t.id} end state ${t.endState}`),g.debug(`future model ${e.id} end state ${e.endState}`),e.endState?g.debug(`future model ${e.id} is already complete`):(g.debug(`updating future model ${e.id}`),E.runInAction(()=>{const s=hi(t);te(()=>{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]})})}))},Au=t=>e=>s=>t.build(String(e),s),pi=t=>e=>du(hi,Au(t)(e.tracker||e.id))(e),yo=g.createLogger({name:"future-service",group:"Services"}),{isMock:Pb,URL:Zs}=fe();var tt=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(tt||{});const{getAll:kb,modifyModel:Lb,addModel:Fb,deleteModel:Nb,postModel:Ub}=ce.build({destinationAddress:"",basePath:`${Zs}/api/future`,mock:Pb}),jb=async()=>await kb({}),Ru=async(t,e="/api/kos/future")=>(yo.info(`sending delete request for Future: ${t}`),await Nb({id:t,urlOverride:`${Zs}${e}/${t}`})),Pu=async(t,e="/api/kos/future")=>(yo.info("sending add request for Future"),await Fb({model:t,urlOverride:`${Zs}${e}`})),Bb=async(t,e,s="/api/kos/future")=>(yo.info(`sending modify request for Future: ${t}`),Lb({model:e,id:t,urlOverride:`${Zs}${s}/${t}`})),ku=async(t,e="/api/kos/future")=>(yo.info(`sending cancel request for Future: ${t}`),Ub({urlOverride:`${Zs}${e}/${t}/cancel`,ordered:!0,model:{}})),Lu="future-model",ts=Jt(Lu),Fu="future-container-model",st=Jt(Fu),Nu=t=>pi(ts)(t),Kb=t=>{const e=Nu(t);return st.build(st.type,{}).addFutureModel(e),e},Hb=t=>st.build(st.type,{}).getFuture(String(t)),mt={buildFutureModel:Nu,initiateFuture:Kb,getFuture:Hb},qb=t=>!t||!t.data;function gi(t,e,s={}){const{alias:r,namespace:o,abortController:n=!1,trackerPolicy:i="id"}=s;return async function(...a){const c=wt();g.debug(`Calling future service ${e} with tracker ${c}`);let u,d;n&&(u=new AbortController);const h=mt.initiateFuture({tracker:c,id:oi});o&&(h.namespace=o),g.debug(`waiting for future ${h.id} to be ready`),await ye(h),g.debug(`future ${h.id} is ready`),te(()=>{g.debug(`Adding future ${h.id} to futureHandler`),this.futureHandler.addFuture(h,r)}),n&&u&&(d=X(()=>{(h.status==="CANCELLED"||h.endState===tt.Canceled)&&(g.debug(`Future ${h.id} cancelled, aborting request`),u==null||u.abort())}),u.signal.addEventListener("abort",async()=>{if(h.status!=="CANCELLED"&&h.endState!==tt.Canceled&&!h.endState){g.debug(`AbortController aborted, cancelling future ${h.id}`);try{await h.cancelFuture()}catch(p){g.error(`Failed to cancel future ${h.id}:`,p)}}},{once:!0}));const f=()=>{d&&(d(),d=void 0)};try{const p=[...a];if(n&&u){const M=p[p.length-1];M&&typeof M=="object"&&"aborted"in M?p[p.length-1]=u.signal:p.push(u.signal)}if(i==="context"){const M=p[p.length-1];if(Kn(M))M.$tracker=c;else{const $={[ho]:!0,$tracker:c};p.push($)}}else p.push(c);const y=await t.apply(this,p);g.debug(`received future response for ${c}`,y);const v=qb(y)?y:y==null?void 0:y.data;return v?(v.progress=1,g.debug("mapping future response to future model"),h.endState?g.debug(`future ${h.id} has already completed. Not updating the model`):fi(v,h)):this.futureHandler.removeFuture(r),f(),v}catch(p){if(f(),n&&(u!=null&&u.signal.aborted)){const y=new Error("Operation cancelled");throw g.debug(`Operation ${e} was cancelled`),y}throw g.error(p),p}}}Zt(tl,{register:()=>{},execute:()=>gi});function bo(t={}){const{alias:e}=t;return(s,r,o)=>{s[Es]=s[Es]||{},e&&(s[Ts]=s[Ts]||new Map,s[Ts].set(r,e));const n=o.value,i=gi(n,r,t);s[Es][r]={handler:i}}}const{URL:Uu}=fe(),{getOne:zb}=ce.build({basePath:`${Uu}/api/kos/state`}),Vb=g.createLogger({name:"state-bean-service",group:"Services"}),ju=async({path:t})=>(Vb.debug("sending GET for state-bean"),await zb({urlOverride:`${Uu}/api/kos/state/${t}`})),Gb=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:ju},Symbol.toStringTag,{value:"Module"}));var Yb=Object.defineProperty,Wb=Object.getOwnPropertyDescriptor,Bu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Wb(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&&Yb(e,s,o),o};const us="state-bean-model",Qb=vt("path");let Ar=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=ri.map(new Map),on(e,this)}updateModel(t){on(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&ii(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&go(r)&&(r=Number(r)),this.props.set(e,r)})}async init(){this.logger.debug(`initializing state-bean ${this.id}`)}updateProps(t){Object.entries(t).forEach(([e,s])=>{this.props.set(e,s)})}async load(){this.logger.debug(`loading state-bean ${this.id}`);const t=await ju({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};Bu([B({topic:`/kos/state/${Qb}`,websocket:!0})],Ar.prototype,"handleConfigBeanUpdated",1);Ar=Bu([D(us)],Ar);const Ls={registration:{[us]:{class:Ar,singleton:!1}},type:us,predicate:Ie(us),factory:he.Factory.create(us)},Xb=({path:t})=>(e,s)=>{e[F]=e[F]||{},e[F][s]={modelType:Ls.type,id:`${Ls.type}-${t}`,options:{path:t},lifecycle:I.INIT}};var Zb=Object.defineProperty,Jb=Object.getOwnPropertyDescriptor,Ku=(t,e,s,r)=>{for(var o=r>1?void 0:r?Jb(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Zb(e,s,o),o};const ds="state-prop-model",Oa=vt("path");let Rr=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())??""}};Ku([Xt({modelType:Ls.type,id:`state-bean-${Oa}`,options:{path:Oa}})],Rr.prototype,"stateBean",2);Rr=Ku([D(ds)],Rr);const mi={registration:{[ds]:{class:Rr,singleton:!1}},type:ds,predicate:Ie(ds),factory:he.Factory.create(ds)},{URL:ev}=fe(),{getAll:tv}=ce.build({basePath:`${ev}/api/state-prop`}),sv=g.createLogger({name:"state-prop-service",group:"Services"}),rv=async()=>(sv.debug("sending GET for state-prop"),await tv({})),ov=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:rv},Symbol.toStringTag,{value:"Module"}));function nv(t){const{path:e,attribute:s}=t;return(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:mi.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:I.INIT}}}var iv=Object.defineProperty,av=Object.getOwnPropertyDescriptor,Hu=(t,e,s,r)=>{for(var o=r>1?void 0:r?av(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&iv(e,s,o),o};const qu="browser-router-model",cv="kos.http.request",lv="kos.http.response";let Pr=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new gu}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 u={send:d=>{this.logger.debug(`sending response to ${r}`),this.logger.debug(d),Ul({msg:d,options:{responseId:i,destinationAddress:s,type:lv,sourceAddress:r,status:c}})},status:function(d){return c=d,this}};if(a.path==="/openapi.json"){u.send(this.router.generateOpenApiSpec());return}await this.router.handle(a,u)}use(t,e,...s){this.router.use(t,e,...s)}remove(t,e){return this.router.remove(t,e)}removeAllForPath(t){return this.router.removeAllForPath(t)}getRoutes(){return this.router.getRoutes()}async init(){this.logger.debug(`initializing browser-router ${this.id}`)}async load(){this.logger.debug(`loading browser-router ${this.id}`)}};Hu([B({topic:cv})],Pr.prototype,"handleRequest",1);Pr=Hu([D(qu)],Pr);const yi=new Ce({class:Pr,type:qu});var uv=Object.defineProperty,dv=Object.getOwnPropertyDescriptor,zu=(t,e,s,r)=>{for(var o=r>1?void 0:r?dv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&uv(e,s,o),o};const qo=g.getLogger(ts.type);let kr=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=ku,nn(()=>this.status===tt.Success||this.status===tt.Fail,()=>{qo.info(`Future ${this.id} has completed with status ${this.status}`),Re(this)})}async load(){qo.debug(`loading Future ${this.id}`)}unload(){qo.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await nn(()=>this.futureId!==oi),await this._cancelFuture(this.futureId,t)}get status(){return this.endState?this.endState:this.progress>-1?"IN_PROGRESS":"NOT_ACTIVE"}get timeRemaining(){var a,c;const t=this.remainingTimeMs||-1;if(t<0)return"";const e={year:1e3*60*60*24*365,month:1e3*60*60*24*30,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60,second:1e3};let s="second",r=0;for(const[u,d]of Object.entries(e))if(Math.abs(t)>=d){s=u,r=Math.round(t/d);break}const 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}`),fi(t,this)}};zu([B({topic:`kos.future/${Tr}`})],kr.prototype,"handleFutureUpdated",1);kr=zu([D(ts.type)],kr);const Vu=kr;var hv=Object.defineProperty,fv=Object.getOwnPropertyDescriptor,bi=(t,e,s,r)=>{for(var o=r>1?void 0:r?fv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&hv(e,s,o),o};const ur=g.getLogger(st.type);let Fs=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=Ru,addFuture:o=Pu}=e;this.logger=s.logger,this._deleteFuture=r,this._addFuture=o,this.id=t,this._futures=new Fe,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){ur.error("error deleting a Future"),ur.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=pi(ts)(s);return this.addFutureModel(r),r}}catch(e){throw ur.error("error creating a Future"),ur.error(e),e}}handleFutureUpdated(t,e){const s=mt.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),H(r,e.body,e.headers)}};bi([Oe],Fs.prototype,"_futures",2);bi([B({topic:"kos.future"})],Fs.prototype,"handleFutureUpdated",1);Fs=bi([D(st.type)],Fs);const Gu=Fs,{URL:Js}=fe(),{getOne:pv,postModel:gv,deleteModel:Yu}=ce.build({basePath:`${Js}/api/keyVal`}),an=g.createLogger({name:"key-value-service",group:"Services"}),Wu=async(t,e)=>{await Yu({urlOverride:`${Js}/api/keyVal/${t}/${e}`,id:e})},Qu=async(t,e,s)=>{const r=await gv({urlOverride:`${Js}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw an.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},Xu=async(t="studio")=>{an.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await pv({urlOverride:`${Js}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw an.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},mv=async t=>{await Yu({urlOverride:`${Js}/api/keyVal/${t}`,id:""})},yv=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Wu,deleteKeyValueNamespace:mv,getKeyValue:Xu,updateKeyValue:Qu},Symbol.toStringTag,{value:"Module"}));var bv=Object.defineProperty,vv=Object.getOwnPropertyDescriptor,vi=(t,e,s,r)=>{for(var o=r>1?void 0:r?vv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&bv(e,s,o),o};const Zu="key-value-model";let Ns=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=Pe(),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 Qu(this.namespace,t,e),this.data[t]=e):(await Wu(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await Xu(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)}};vi([B({topic:"/keyVal/set"})],Ns.prototype,"handleStateUpdate",1);vi([B({topic:"/keyVal/remove"})],Ns.prototype,"handleStateDelete",1);Ns=vi([D(Zu)],Ns);const wi=new Ee({class:Ns,type:Zu});var ve="INUMBER",ss="IOP1",rs="IOP2",os="IOP3",He="IVAR",yt="IVARNAME",Nt="IFUNCALL",vo="IFUNDEF",ue="IEXPR",Ei="IEXPREVAL",Mt="IMEMBER",wo="IENDSTATEMENT",Ut="IARRAY";function k(t,e){this.type=t,this.value=e??0}k.prototype.toString=function(){switch(this.type){case ve:case ss:case rs:case os:case He:case yt:case wo:return this.value;case Nt:return"CALL "+this.value;case vo:return"DEF "+this.value;case Ut:return"ARRAY "+this.value;case Mt:return"."+this.value;default:return"Invalid Instruction"}};function Eo(t){return new k(ss,t)}function We(t){return new k(rs,t)}function Ju(t){return new k(os,t)}function cn(t,e,s,r,o){for(var n=[],i=[],a,c,u,d,h=0;h<t.length;h++){var f=t[h],p=f.type;if(p===ve||p===yt)Array.isArray(f.value)?n.push.apply(n,cn(f.value.map(function(y){return new k(ve,y)}).concat(new k(Ut,f.value.length)),e,s,r,o)):n.push(f);else if(p===He&&o.hasOwnProperty(f.value))f=new k(ve,o[f.value]),n.push(f);else if(p===rs&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new k(ve,d(a.value,c.value)),n.push(f);else if(p===os&&n.length>2)u=n.pop(),c=n.pop(),a=n.pop(),f.value==="?"?n.push(a.value?c.value:u.value):(d=r[f.value],f=new k(ve,d(a.value,c.value,u.value)),n.push(f));else if(p===ss&&n.length>0)a=n.pop(),d=e[f.value],f=new k(ve,d(a.value)),n.push(f);else if(p===ue){for(;n.length>0;)i.push(n.shift());i.push(new k(ue,cn(f.value,e,s,r,o)))}else if(p===Mt&&n.length>0)a=n.pop(),n.push(new k(ve,a.value[f.value]));else{for(;n.length>0;)i.push(n.shift());i.push(f)}}for(;n.length>0;)i.push(n.shift());return i}function ed(t,e,s){for(var r=[],o=0;o<t.length;o++){var n=t[o],i=n.type;if(i===He&&n.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===ss?u=Eo(c.value):c.type===rs?u=We(c.value):c.type===os?u=Ju(c.value):u=new k(c.type,c.value),r.push(u)}else i===ue?r.push(new k(ue,ed(n.value,e,s))):r.push(n)}return r}function ht(t,e,s){var r=[],o,n,i,a,c,u;if(Mi(t))return Ue(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===ve||p===yt)r.push(f.value);else if(p===rs)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!ht(n,e,s):!1):f.value==="or"?r.push(o?!0:!!ht(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,ht(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(Ue(o,s),Ue(n,s))));else if(p===os)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(ht(o?n:i,e,s)):(a=e.ternaryOps[f.value],r.push(a(Ue(o,s),Ue(n,s),Ue(i,s))));else if(p===He)if(f.value in e.functions)r.push(e.functions[f.value]);else if(f.value in e.unaryOps&&e.parser.isOperatorEnabled(f.value))r.push(e.unaryOps[f.value]);else{var y=s[f.value];if(y!==void 0)r.push(y);else throw new Error("undefined variable: "+f.value)}else if(p===ss)o=r.pop(),a=e.unaryOps[f.value],r.push(a(Ue(o,s)));else if(p===Nt){for(u=f.value,c=[];u-- >0;)c.unshift(Ue(r.pop(),s));if(a=r.pop(),a.apply&&a.call)r.push(a.apply(void 0,c));else throw new Error(a+" is not a function")}else if(p===vo)r.push(function(){for(var v=r.pop(),M=[],$=f.value;$-- >0;)M.unshift(r.pop());var U=r.pop(),x=function(){for(var O=Object.assign({},s),P=0,V=M.length;P<V;P++)O[M[P]]=arguments[P];return ht(v,e,O)};return Object.defineProperty(x,"name",{value:U,writable:!1}),s[U]=x,x}());else if(p===ue)r.push(wv(f,e));else if(p===Ei)r.push(f);else if(p===Mt)o=r.pop(),r.push(o[f.value]);else if(p===wo)r.pop();else if(p===Ut){for(u=f.value,c=[];u-- >0;)c.unshift(r.pop());r.push(c)}else throw new Error("invalid Expression")}if(r.length>1)throw new Error("invalid Expression (parity)");return r[0]===0?0:Ue(r[0],s)}function wv(t,e,s){return Mi(t)?t:{type:Ei,value:function(r){return ht(t.value,e,r)}}}function Mi(t){return t&&t.type===Ei}function Ue(t,e){return Mi(t)?t.value(e):t}function _i(t,e){for(var s=[],r,o,n,i,a,c,u=0;u<t.length;u++){var d=t[u],h=d.type;if(h===ve)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(Ia).join(", ")+"]"):s.push(Ia(d.value));else if(h===rs)o=s.pop(),r=s.pop(),i=d.value,e?i==="^"?s.push("Math.pow("+r+", "+o+")"):i==="and"?s.push("(!!"+r+" && !!"+o+")"):i==="or"?s.push("(!!"+r+" || !!"+o+")"):i==="||"?s.push("(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }(("+r+"),("+o+")))"):i==="=="?s.push("("+r+" === "+o+")"):i==="!="?s.push("("+r+" !== "+o+")"):i==="["?s.push(r+"[("+o+") | 0]"):s.push("("+r+" "+i+" "+o+")"):i==="["?s.push(r+"["+o+"]"):s.push("("+r+" "+i+" "+o+")");else if(h===os)if(n=s.pop(),o=s.pop(),r=s.pop(),i=d.value,i==="?")s.push("("+r+" ? "+o+" : "+n+")");else throw new Error("invalid Expression");else if(h===He||h===yt)s.push(d.value);else if(h===ss)r=s.pop(),i=d.value,i==="-"||i==="+"?s.push("("+i+r+")"):e?i==="not"?s.push("(!"+r+")"):i==="!"?s.push("fac("+r+")"):s.push(i+"("+r+")"):i==="!"?s.push("("+r+"!)"):s.push("("+i+" "+r+")");else if(h===Nt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===vo){for(o=s.pop(),c=d.value,a=[];c-- >0;)a.unshift(s.pop());r=s.pop(),e?s.push("("+r+" = function("+a.join(", ")+") { return "+o+" })"):s.push("("+r+"("+a.join(", ")+") = "+o+")")}else if(h===Mt)r=s.pop(),s.push(r+"."+d.value);else if(h===Ut){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ue)s.push("("+_i(d.value,e)+")");else if(h!==wo)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function Ia(t){return typeof t=="string"?JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"):t}function At(t,e){for(var s=0;s<t.length;s++)if(t[s]===e)return!0;return!1}function Ti(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===He||i.type===yt?!r&&!At(e,i.value)?e.push(i.value):(o!==null&&(At(e,o)||e.push(o)),o=i.value):i.type===Mt&&r&&o!==null?o+="."+i.value:i.type===ue?Ti(i.value,e,s):o!==null&&(At(e,o)||e.push(o),o=null)}o!==null&&!At(e,o)&&e.push(o)}function Se(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}Se.prototype.simplify=function(t){return t=t||{},new Se(cn(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};Se.prototype.substitute=function(t,e){return e instanceof Se||(e=this.parser.parse(String(e))),new Se(ed(this.tokens,t,e),this.parser)};Se.prototype.evaluate=function(t){return t=t||{},ht(this.tokens,this,t)};Se.prototype.toString=function(){return _i(this.tokens,!1)};Se.prototype.symbols=function(t){t=t||{};var e=[];return Ti(this.tokens,e,t),e};Se.prototype.variables=function(t){t=t||{};var e=[];Ti(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};Se.prototype.toJSFunction=function(t,e){var s=this,r=new Function(t,"with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return "+_i(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var Us="TEOF",j="TOP",Mo="TNUMBER",td="TSTRING",qe="TPAREN",jt="TBRACKET",_o="TCOMMA",Si="TNAME",$i="TSEMICOLON";function sd(t,e,s){this.type=t,this.value=e,this.index=s}sd.prototype.toString=function(){return this.type+": "+this.value};function Y(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}Y.prototype.newToken=function(t,e,s){return new sd(t,e,s??this.pos)};Y.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};Y.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};Y.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(Us,"EOF");if(this.isWhitespace()||this.isComment())return this.next();if(this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName())return this.current;this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')};Y.prototype.isString=function(){var t=!1,e=this.pos,s=this.expression.charAt(e);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,e+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(e+1,r);this.current=this.newToken(td,this.unescape(o),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};Y.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(qe,t),this.pos++,!0):!1};Y.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(jt,t),this.pos++,!0):!1};Y.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(_o,","),this.pos++,!0):!1};Y.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken($i,";"),this.pos++,!0):!1};Y.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(r in this.consts)return this.current=this.newToken(Mo,this.consts[r]),this.pos+=r.length,!0}return!1};Y.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(j,r),this.pos+=r.length,!0}return!1};Y.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(t,e);return this.current=this.newToken(Si,o),this.pos+=o.length,!0}return!1};Y.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
|
|
108
|
+
`||e==="\r")&&(t=!0,this.pos++,!(this.pos>=this.expression.length));)e=this.expression.charAt(this.pos);return t};var Ev=/^[0-9a-f]{4}$/i;Y.prototype.unescape=function(t){var e=t.indexOf("\\");if(e<0)return t;for(var s=t.substring(0,e);e>=0;){var r=t.charAt(++e);switch(r){case"'":s+="'";break;case'"':s+='"';break;case"\\":s+="\\";break;case"/":s+="/";break;case"b":s+="\b";break;case"f":s+="\f";break;case"n":s+=`
|
|
109
|
+
`;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var o=t.substring(e+1,e+5);Ev.test(o)||this.parseError("Illegal escape sequence: \\u"+o),s+=String.fromCharCode(parseInt(o,16)),e+=4;break;default:throw this.parseError('Illegal escape sequence: "\\'+r+'"')}++e;var n=t.indexOf("\\",e);s+=t.substring(e,n<0?t.length:n),e=n}return s};Y.prototype.isComment=function(){var t=this.expression.charAt(this.pos);return t==="/"&&this.expression.charAt(this.pos+1)==="*"?(this.pos=this.expression.indexOf("*/",this.pos)+2,this.pos===1&&(this.pos=this.expression.length),!0):!1};Y.prototype.isRadixInteger=function(){var t=this.pos;if(t>=this.expression.length-2||this.expression.charAt(t)!=="0")return!1;++t;var e,s;if(this.expression.charAt(t)==="x")e=16,s=/^[0-9a-f]$/i,++t;else if(this.expression.charAt(t)==="b")e=2,s=/^[01]$/i,++t;else return!1;for(var r=!1,o=t;t<this.expression.length;){var n=this.expression.charAt(t);if(s.test(n))t++,r=!0;else break}return r&&(this.current=this.newToken(Mo,parseInt(this.expression.substring(o,t),e)),this.pos=t),r};Y.prototype.isNumber=function(){for(var t=!1,e=this.pos,s=e,r=e,o=!1,n=!1,i;e<this.expression.length&&(i=this.expression.charAt(e),i>="0"&&i<="9"||!o&&i===".");)i==="."?o=!0:n=!0,e++,t=n;if(t&&(r=e),i==="e"||i==="E"){e++;for(var a=!0,c=!1;e<this.expression.length;){if(i=this.expression.charAt(e),a&&(i==="+"||i==="-"))a=!1;else if(i>="0"&&i<="9")c=!0,a=!1;else break;e++}c||(e=r)}return t?(this.current=this.newToken(Mo,parseFloat(this.expression.substring(s,e))),this.pos=e):this.pos=r,t};Y.prototype.isOperator=function(){var t=this.pos,e=this.expression.charAt(this.pos);if(e==="+"||e==="-"||e==="*"||e==="/"||e==="%"||e==="^"||e==="?"||e===":"||e===".")this.current=this.newToken(j,e);else if(e==="∙"||e==="•")this.current=this.newToken(j,"*");else if(e===">")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,">="),this.pos++):this.current=this.newToken(j,">");else if(e==="<")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"<="),this.pos++):this.current=this.newToken(j,"<");else if(e==="|")if(this.expression.charAt(this.pos+1)==="|")this.current=this.newToken(j,"||"),this.pos++;else return!1;else if(e==="=")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"=="),this.pos++):this.current=this.newToken(j,e);else if(e==="!")this.expression.charAt(this.pos+1)==="="?(this.current=this.newToken(j,"!="),this.pos++):this.current=this.newToken(j,e);else return!1;return this.pos++,this.isOperatorEnabled(this.current.value)?!0:(this.pos=t,!1)};Y.prototype.isOperatorEnabled=function(t){return this.parser.isOperatorEnabled(t)};Y.prototype.getCoordinates=function(){var t=0,e,s=-1;do t++,e=this.pos-s,s=this.expression.indexOf(`
|
|
110
|
+
`,s+1);while(s>=0&&s<this.pos);return{line:t,column:e}};Y.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)};function q(t,e,s){this.parser=t,this.tokens=e,this.current=null,this.nextToken=null,this.next(),this.savedCurrent=null,this.savedNextToken=null,this.allowMemberAccess=s.allowMemberAccess!==!1}q.prototype.next=function(){return this.current=this.nextToken,this.nextToken=this.tokens.next()};q.prototype.tokenMatches=function(t,e){return typeof e>"u"?!0:Array.isArray(e)?At(e,t.value):typeof e=="function"?e(t):t.value===e};q.prototype.save=function(){this.savedCurrent=this.current,this.savedNextToken=this.nextToken,this.tokens.save()};q.prototype.restore=function(){this.tokens.restore(),this.current=this.savedCurrent,this.nextToken=this.savedNextToken};q.prototype.accept=function(t,e){return this.nextToken.type===t&&this.tokenMatches(this.nextToken,e)?(this.next(),!0):!1};q.prototype.expect=function(t,e){if(!this.accept(t,e)){var s=this.tokens.getCoordinates();throw new Error("parse error ["+s.line+":"+s.column+"]: Expected "+(e||t))}};q.prototype.parseAtom=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.accept(Si)||this.accept(j,s))t.push(new k(He,this.current.value));else if(this.accept(Mo))t.push(new k(ve,this.current.value));else if(this.accept(td))t.push(new k(ve,this.current.value));else if(this.accept(qe,"("))this.parseExpression(t),this.expect(qe,")");else if(this.accept(jt,"["))if(this.accept(jt,"]"))t.push(new k(Ut,0));else{var r=this.parseArrayList(t);t.push(new k(Ut,r))}else throw new Error("unexpected "+this.nextToken)};q.prototype.parseExpression=function(t){var e=[];this.parseUntilEndStatement(t,e)||(this.parseVariableAssignmentExpression(e),!this.parseUntilEndStatement(t,e)&&this.pushExpression(t,e))};q.prototype.pushExpression=function(t,e){for(var s=0,r=e.length;s<r;s++)t.push(e[s])};q.prototype.parseUntilEndStatement=function(t,e){return this.accept($i)?(this.nextToken&&this.nextToken.type!==Us&&!(this.nextToken.type===qe&&this.nextToken.value===")")&&e.push(new k(wo)),this.nextToken.type!==Us&&this.parseExpression(e),t.push(new k(ue,e)),!0):!1};q.prototype.parseArrayList=function(t){for(var e=0;!this.accept(jt,"]");)for(this.parseExpression(t),++e;this.accept(_o);)this.parseExpression(t),++e;return e};q.prototype.parseVariableAssignmentExpression=function(t){for(this.parseConditionalExpression(t);this.accept(j,"=");){var e=t.pop(),s=[],r=t.length-1;if(e.type===Nt){if(!this.tokens.isOperatorEnabled("()="))throw new Error("function definition is not permitted");for(var o=0,n=e.value+1;o<n;o++){var i=r-o;t[i].type===He&&(t[i]=new k(yt,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new k(ue,s)),t.push(new k(vo,e.value));continue}if(e.type!==He&&e.type!==Mt)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new k(yt,e.value)),t.push(new k(ue,s)),t.push(We("="))}};q.prototype.parseConditionalExpression=function(t){for(this.parseOrExpression(t);this.accept(j,"?");){var e=[],s=[];this.parseConditionalExpression(e),this.expect(j,":"),this.parseConditionalExpression(s),t.push(new k(ue,e)),t.push(new k(ue,s)),t.push(Ju("?"))}};q.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(j,"or");){var e=[];this.parseAndExpression(e),t.push(new k(ue,e)),t.push(We("or"))}};q.prototype.parseAndExpression=function(t){for(this.parseComparison(t);this.accept(j,"and");){var e=[];this.parseComparison(e),t.push(new k(ue,e)),t.push(We("and"))}};var Mv=["==","!=","<","<=",">=",">","in"];q.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,Mv);){var e=this.current;this.parseAddSub(t),t.push(We(e.value))}};var _v=["+","-","||"];q.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(j,_v);){var e=this.current;this.parseTerm(t),t.push(We(e.value))}};var Tv=["*","/","%"];q.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,Tv);){var e=this.current;this.parseFactor(t),t.push(We(e.value))}};q.prototype.parseFactor=function(t){var e=this.tokens.unaryOps;function s(o){return o.value in e}if(this.save(),this.accept(j,s)){if(this.current.value!=="-"&&this.current.value!=="+"){if(this.nextToken.type===qe&&this.nextToken.value==="("){this.restore(),this.parseExponential(t);return}else if(this.nextToken.type===$i||this.nextToken.type===_o||this.nextToken.type===Us||this.nextToken.type===qe&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(Eo(r.value))}else this.parseExponential(t)};q.prototype.parseExponential=function(t){for(this.parsePostfixExpression(t);this.accept(j,"^");)this.parseFactor(t),t.push(We("^"))};q.prototype.parsePostfixExpression=function(t){for(this.parseFunctionCall(t);this.accept(j,"!");)t.push(Eo("!"))};q.prototype.parseFunctionCall=function(t){var e=this.tokens.unaryOps;function s(n){return n.value in e}if(this.accept(j,s)){var r=this.current;this.parseAtom(t),t.push(Eo(r.value))}else for(this.parseMemberExpression(t);this.accept(qe,"(");)if(this.accept(qe,")"))t.push(new k(Nt,0));else{var o=this.parseArgumentList(t);t.push(new k(Nt,o))}};q.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(qe,")");)for(this.parseExpression(t),++e;this.accept(_o);)this.parseExpression(t),++e;return e};q.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(j,".")||this.accept(jt,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(Si),t.push(new k(Mt,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(jt,"]"),t.push(We("["))}else throw new Error("unexpected symbol: "+e.value)}};function Sv(t,e){return Number(t)+Number(e)}function $v(t,e){return t-e}function Ov(t,e){return t*e}function Iv(t,e){return t/e}function Cv(t,e){return t%e}function Dv(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function xv(t,e){return t===e}function Av(t,e){return t!==e}function Rv(t,e){return t>e}function Pv(t,e){return t<e}function kv(t,e){return t>=e}function Lv(t,e){return t<=e}function Fv(t,e){return!!(t&&e)}function Nv(t,e){return!!(t||e)}function Uv(t,e){return At(e,t)}function jv(t){return(Math.exp(t)-Math.exp(-t))/2}function Bv(t){return(Math.exp(t)+Math.exp(-t))/2}function Kv(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function Hv(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function qv(t){return Math.log(t+Math.sqrt(t*t-1))}function zv(t){return Math.log((1+t)/(1-t))/2}function Ca(t){return Math.log(t)*Math.LOG10E}function Vv(t){return-t}function Gv(t){return!t}function Yv(t){return t<0?Math.ceil(t):Math.floor(t)}function Wv(t){return Math.random()*(t||1)}function Da(t){return Oi(t+1)}function Qv(t){return isFinite(t)&&t===Math.round(t)}var Xv=4.7421875,zo=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];function Oi(t){var e,s;if(Qv(t)){if(t<=0)return isFinite(t)?1/0:NaN;if(t>171)return 1/0;for(var r=t-2,o=t-1;r>1;)o*=r,r--;return o===0&&(o=1),o}if(t<.5)return Math.PI/(Math.sin(Math.PI*t)*Oi(1-t));if(t>=171.35)return 1/0;if(t>85){var n=t*t,i=n*t,a=i*t,c=a*t;return Math.sqrt(2*Math.PI/t)*Math.pow(t/Math.E,t)*(1+1/(12*t)+1/(288*n)-139/(51840*i)-571/(2488320*a)+163879/(209018880*c)+5246819/(75246796800*c*t))}--t,s=zo[0];for(var u=1;u<zo.length;++u)s+=zo[u]/(t+u);return e=t+Xv+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function Zv(t){return Array.isArray(t)?t.length:String(t).length}function xa(){for(var t=0,e=0,s=0;s<arguments.length;s++){var r=Math.abs(arguments[s]),o;e<r?(o=e/r,t=t*o*o+1,e=r):r>0?(o=r/e,t+=o*o):t+=r}return e===1/0?1/0:e*Math.sqrt(t)}function Aa(t,e,s){return t?e:s}function Jv(t,e){return typeof e>"u"||+e==0?Math.round(t):(t=+t,e=-+e,isNaN(t)||!(typeof e=="number"&&e%1===0)?NaN:(t=t.toString().split("e"),t=Math.round(+(t[0]+"e"+(t[1]?+t[1]-e:-e))),t=t.toString().split("e"),+(t[0]+"e"+(t[1]?+t[1]+e:e))))}function ew(t,e,s){return s&&(s[t]=e),e}function tw(t,e){return t[e|0]}function sw(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function rw(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function ow(t,e){if(typeof t!="function")throw new Error("First argument to map is not a function");if(!Array.isArray(e))throw new Error("Second argument to map is not an array");return e.map(function(s,r){return t(s,r)})}function nw(t,e,s){if(typeof t!="function")throw new Error("First argument to fold is not a function");if(!Array.isArray(s))throw new Error("Second argument to fold is not an array");return s.reduce(function(r,o,n){return t(r,o,n)},e)}function iw(t,e){if(typeof t!="function")throw new Error("First argument to filter is not a function");if(!Array.isArray(e))throw new Error("Second argument to filter is not an array");return e.filter(function(s,r){return t(s,r)})}function aw(t,e){if(!(Array.isArray(e)||typeof e=="string"))throw new Error("Second argument to indexOf is not a string or array");return e.indexOf(t)}function cw(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function lw(t){return(t>0)-(t<0)||+t}var Ra=1/3;function uw(t){return t<0?-Math.pow(-t,Ra):Math.pow(t,Ra)}function dw(t){return Math.exp(t)-1}function hw(t){return Math.log(1+t)}function fw(t){return Math.log(t)/Math.LN2}function _t(t){this.options=t||{},this.unaryOps={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh||jv,cosh:Math.cosh||Bv,tanh:Math.tanh||Kv,asinh:Math.asinh||Hv,acosh:Math.acosh||qv,atanh:Math.atanh||zv,sqrt:Math.sqrt,cbrt:Math.cbrt||uw,log:Math.log,log2:Math.log2||fw,ln:Math.log,lg:Math.log10||Ca,log10:Math.log10||Ca,expm1:Math.expm1||dw,log1p:Math.log1p||hw,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||Yv,"-":Vv,"+":Number,exp:Math.exp,not:Gv,length:Zv,"!":Da,sign:Math.sign||lw},this.binaryOps={"+":Sv,"-":$v,"*":Ov,"/":Iv,"%":Cv,"^":Math.pow,"||":Dv,"==":xv,"!=":Av,">":Rv,"<":Pv,">=":kv,"<=":Lv,and:Fv,or:Nv,in:Uv,"=":ew,"[":tw},this.ternaryOps={"?":Aa},this.functions={random:Wv,fac:Da,min:rw,max:sw,hypot:Math.hypot||xa,pyt:Math.hypot||xa,pow:Math.pow,atan2:Math.atan2,if:Aa,gamma:Oi,roundTo:Jv,map:ow,fold:nw,filter:iw,indexOf:aw,join:cw},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}_t.prototype.parse=function(t){var e=[],s=new q(this,new Y(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect(Us,"EOF"),new Se(e,this)};_t.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var rd=new _t;_t.parse=function(t){return rd.parse(t)};_t.evaluate=function(t,e){return rd.parse(t).evaluate(e)};var Pa={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"remainder","^":"power","!":"factorial","<":"comparison",">":"comparison","<=":"comparison",">=":"comparison","==":"comparison","!=":"comparison","||":"concatenate",and:"logical",or:"logical",not:"logical","?":"conditional",":":"conditional","=":"assignment","[":"array","()=":"fndef"};function pw(t){return Pa.hasOwnProperty(t)?Pa[t]:t}_t.prototype.isOperatorEnabled=function(t){var e=pw(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var gw=Object.defineProperty,mw=Object.getOwnPropertyDescriptor,yw=(t,e,s)=>e in t?gw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,bw=(t,e,s,r)=>{for(var o=r>1?void 0:r?mw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},vw=(t,e,s)=>(yw(t,e+"",s),s);const ww="kos-expression-evaluator-model";class Ew{constructor(e,s,r,o){l(this,"name");l(this,"expression");l(this,"expr");l(this,"getContextData",null);l(this,"_lastResult",{value:void 0});this.name=e,this.expression=s,this.expr=r,this.getContextData=o,this._lastResult={value:void 0,error:void 0}}get result(){return this._lastResult}updateResult(e){this._lastResult=e}evaluate(e){try{return{value:this.expr.evaluate(e),error:void 0}}catch(s){return{value:void 0,error:s instanceof Error?s.message:String(s)}}}}let Lr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"parser");l(this,"_data");l(this,"_expressions",new Map);l(this,"_results");l(this,"_contextRevision",0);this.id=t,this.logger=s.logger,this._data=Pe(),this._results=Pe(),this.parser=new _t,this.parser.functions.exists=r=>r!=null,this.parser.functions.isEmpty=r=>r==null?!0:typeof r=="string"||Array.isArray(r)?r.length===0:typeof r=="object"?Object.keys(r).length===0:!1}get data(){return this._data}get contextRevision(){return this._contextRevision}setContextData(t){this._data.setValues(t),te(()=>{this._contextRevision++,this.logger.debug("Context revision incremented to:",this._contextRevision)})}updateContextValue(t,e){this._data[t]=e}updateNestedValue(t,e){const s=t.split("."),r=s.pop();if(!r){this.logger.error(`Invalid path "${t}" - cannot be empty`);return}let o=this._data;for(const n of s)(o[n]===void 0||o[n]===null)&&(o[n]={}),o=o[n];o[r]=e,this.logger.debug(`Updated nested context value "${t}" to:`,e)}addModelToContext(t,e){this._data[t]=e}addExpression(t,e){try{const s=this.parser.parse(e),r=new Ew(t,e,s,()=>this.data);this._expressions.set(t,r),this.evaluateExpression(t),this.logger.debug(`Added expression "${t}": ${e}`)}catch(s){throw this.logger.error(`Failed to parse expression "${t}"`,s),s}}removeExpression(t){const e=this._expressions.delete(t);return e?(delete this._results[t],this.logger.debug(`Removed expression "${t}"`)):this.logger.warn(`Attempted to remove non-existent expression "${t}". Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpression(t){const e=this._expressions.get(t);return e||this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`),e}getExpressionValue(t){const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${t}" not found. Available expressions: [${this.expressionNames.join(", ")}]`);return}return e.result}getCachedExpressionValue(t){const e=this._expressions.get(t);if(e)return e.result}get expressions(){return Array.from(this._expressions.values())}get expressionNames(){return Array.from(this._expressions.keys())}get results(){return this.evaluateAllExpressions(),this._results}evaluateAllExpressions(){Array.from(this._expressions.keys()).forEach(e=>{this._expressions.get(e)&&this.evaluateExpression(e)})}evaluateExpression(t){this.logger.debug(`Evaluating expression: ${String(t)}`);const e=this._expressions.get(t);if(!e){this.logger.warn(`Expression "${String(t)}" not found`);return}const s=e.evaluate(this.data);this.logger.debug(`Expression "${String(t)}" evaluated to:`,s);const r=e.result;(s.value!==r.value||s.error!==r.error)&&(this.logger.debug(`Expression "${String(t)}" result changed from`,r,"to",s),e.updateResult(s),this.updateResult(t,s))}updateResult(t,e){this.logger.debug(`ExpressionEvaluator.updateResult called for "${t}":`,e),te(()=>{this._results[t]=e})}createExpression(t){const e=wt();return this.addExpression(e,t),e}};vw(Lr,"Registration");Lr=bw([D({modelTypeId:ww,singleton:!1})],Lr);const od=Lr.Registration,Mw=g.createLogger({name:"kos-log-manager-service",group:"Services"}),_w="/api/kos/logs/overrides",nd=async()=>(Mw.debug("sending GET for kos-log-manager"),await Ne.get(_w)),Tw=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:nd},Symbol.toStringTag,{value:"Module"}));var Sw=Object.defineProperty,$w=Object.getOwnPropertyDescriptor,To=(t,e,s,r)=>{for(var o=r>1?void 0:r?$w(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Sw(e,s,o),o};const id="kos-log-manager-model",Ow="/kos/logs/override/add/*",Iw="/kos/logs/override/remove/*",Cw=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 Bt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new ti}updateModel(t){}resolveLoggers(){const t=g.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:Cw(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=g.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=g.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=g.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=g.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 nd();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)})}};To([Hc("/api/kos/ui/loggers")],Bt.prototype,"getAllLoggers",1);To([B({topic:Ow,websocket:!0,wildcardName:"nodeType"})],Bt.prototype,"handleOverrideAdded",1);To([B({topic:Iw,websocket:!0,wildcardName:"nodeType"})],Bt.prototype,"handleOverrideRemoved",1);Bt=To([D(id)],Bt);const ad=new Ce({class:Bt,type:id}),{URL:er}=fe(),{postModel:Ii,getOne:Dw}=ce.build({basePath:`${er}/api/kos-time`});g.createLogger({name:"kos-time-service",group:"Services"});const cd=async t=>{const e=await Ii({model:t,urlOverride:`${er}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},ld=async t=>{const e=await Ii({model:t,urlOverride:`${er}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},ud=async t=>{const e=await Ii({model:{},urlOverride:`${er}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},dd=async()=>{const t=await Dw({urlOverride:`${er}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},xw=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:dd,setDate:ld,setTime:cd,setTimezone:ud},Symbol.toStringTag,{value:"Module"}));var Aw=Object.defineProperty,Rw=Object.getOwnPropertyDescriptor,So=(t,e,s,r)=>{for(var o=r>1?void 0:r?Rw(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&&Aw(e,s,o),o};const hs="kos-time-model",Pw="/kos/time/time",kw="/kos/time/day",Lw="/kos/time/timezone";let Kt=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 cd(t)}async updateSystemDate(t){await ld(t)}async updateSystemTimezone(t){await ud(t)}handleTimeChange(){H(Is.TIME_CHANGE,{})}handleDayChange(){H(Is.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),H(Is.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await dd();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};So([B({topic:Pw,websocket:!0})],Kt.prototype,"handleTimeChange",1);So([B({topic:kw,websocket:!0})],Kt.prototype,"handleDayChange",1);So([B({topic:Lw,websocket:!0})],Kt.prototype,"handleTimeZoneChange",1);Kt=So([D(hs)],Kt);const Fr={registration:{[hs]:{class:Kt,singleton:!0}},type:hs,predicate:Ie(hs),factory:he.Singleton.create(hs)};var Fw=Object.defineProperty,Nw=Object.getOwnPropertyDescriptor,hd=(t,e,s,r)=>{for(var o=r>1?void 0:r?Nw(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&&Fw(e,s,o),o};const fd="log-block-container-model";let Nr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Fe({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}`)}};hd([Oe],Nr.prototype,"_models",2);Nr=hd([D(fd)],Nr);const Uw=g.createLogger({name:"log-stream-container-service",group:"Services"}),pd=()=>{var r;const t=de(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return g.error(`getKosConnectionId: ${s}`),s},ns=pd(),jw="/api/kos/logs/node/{nodeId}/streams",gd=async()=>(Uw.debug("sending GET for log-stream-container"),await Ne.get(jw,{path:{nodeId:"primary"}},{destinationAddress:ns})),md=async(t,e="primary")=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:ns})},yd=async t=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:ns})},Bw=async()=>{await Ne.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:ns})},bd=async t=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:ns}),vd=async(t,e)=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:ns}),Kw=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Bw,getKosConnectionId:pd,getLogStreamBlock:vd,getLogStreamBlocks:bd,getLogStreams:gd,subscribeToLogStream:md,unsubscribeFromLogStream:yd},Symbol.toStringTag,{value:"Module"}));var Hw=Object.getOwnPropertyDescriptor,qw=(t,e,s,r)=>{for(var o=r>1?void 0:r?Hw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const wd="log-block-model";let ln=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"nodeId");l(this,"stream");l(this,"blockNum");l(this,"startLineNum");l(this,"endLineNum");l(this,"startTime");l(this,"endTime");l(this,"lineCount");l(this,"lines");l(this,"inc");this.id=t,this.logger=s.logger,this.nodeId=e.nodeId,this.stream=e.stream,this.blockNum=e.blockNum,this.startLineNum=e.startLineNum,this.endLineNum=e.endLineNum,this.startTime=e.startTime,this.endTime=e.endTime,this.lineCount=e.lineCount,this.lines=[],this.inc=0}async syncLines(){const[t,e]=await vd(this.stream,this.blockNum);if(t){this.logger.error(`Failed to get log block ${this.blockNum}`);return}e&&this.addLines(e.lines,!0)}updateModel(t){this.startLineNum=t.startLineNum,this.endLineNum=t.endLineNum,this.startTime=t.startTime,this.endTime=t.endTime,this.lineCount=t.lineCount}addLines(t,e){const s=e?[]:this.lines;this.lines=[...s,...t],this.inc+=1}async init(){this.logger.debug(`initializing log-block ${this.id}`)}async load(){this.logger.debug(`loading log-block ${this.id}`)}};ln=qw([D(wd)],ln);const js=new Ee({class:ln,type:wd}),$o=new Ee({class:Nr,type:fd});$o.addRelatedModel(js);var zw=Object.defineProperty,Vw=Object.getOwnPropertyDescriptor,Ed=(t,e,s,r)=>{for(var o=r>1?void 0:r?Vw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&zw(e,s,o),o};const Md="log-stream-model";let Ur=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=$o.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=js.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=js.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 md(this.name)}async unsubscribe(){await yd(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 bd(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=bu(()=>{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()}}};Ed([Oe],Ur.prototype,"_blocks",2);Ur=Ed([D(Md)],Ur);const Cs=new Ee({class:Ur,type:Md});var Gw=Object.defineProperty,Yw=Object.getOwnPropertyDescriptor,Tt=(t,e,s,r)=>{for(var o=r>1?void 0:r?Yw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Gw(e,s,o),o};const _d="log-stream-container-model",Ww="/kos/logs/subscription/addBlock/*",Qw="/kos/logs/subscription/updateBlock/*",Xw="/kos/logs/subscription/removeBlock/*",Zw="/kos/logs/subscription/lines/*",Td="/kos/logs/streams/add/*";let ze=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 Fe({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: ${Td}`);const e=t.stream,s=Cs.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=Cs.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 gd();if(t){this.logger.error(`Error loading log-streams: ${t}`);return}e&&e.forEach(s=>{const r=Cs.instance(s).options({name:s,nodeId:"primary"}).build();this.addModel(r)})}};Tt([Oe],ze.prototype,"_models",2);Tt([B({topic:[Td],websocket:!0})],ze.prototype,"handleStreamAdded",1);Tt([B({topic:[Ww],websocket:!0})],ze.prototype,"handleAddBlock",1);Tt([B({topic:[Xw],websocket:!0})],ze.prototype,"handleRemoveBlock",1);Tt([B({topic:[Qw],websocket:!0})],ze.prototype,"handleUpdateBlock",1);Tt([B({topic:[Zw],websocket:!0})],ze.prototype,"handleLogLine",1);ze=Tt([D(_d)],ze);const tr=new Ce({class:ze,type:_d});tr.addRelatedModel(Cs);tr.addRelatedModel($o);tr.addRelatedModel(js);const Jw=t=>(t==null?void 0:t.rank)!==void 0,eE=t=>(t==null?void 0:t.visibleRole)!==void 0,tE=t=>(t==null?void 0:t.color)!==void 0,sE=t=>{const e=t.info??{};return Jw(e)?e.rank:0},rE=t=>{const e=t.info??{};return tE(e)?e.color:"orange"},oE=t=>{const e=t.info??{};return eE(e)?e.visibleRole:"TECHNICIAN"},{URL:Oo}=fe(),{getAll:nE,postModel:Sd}=ce.build({basePath:`${Oo}/api/kos/troubles`}),Ds=g.createLogger({name:"trouble-services"}),$d=()=>{var r,o;const t=de(),e=t==null?void 0:t.connId;Ds.debug(`connId from query params: ${e}`),Ds.debug(`window.kosBridge: ${window!=null&&window.kosBridge?"available":"not available"} - ${(r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId")}`);const s=e||((o=window==null?void 0:window.kosBridge)==null?void 0:o.call(window,"connId"));return Ds.info(`getKosConnectionId: ${s}`),s},Bs=$d();Ds.info(`Destination address for trouble services: ${Bs}`);const Od=async t=>{const e=t.includes("/kos/troubles");return Ds.info(`Fetching troubles from ${t} with destination address: ${e?Bs:"N/A (not a kos troubles path)"}`),await nE({urlOverride:`${Oo}${t}`,destinationAddress:e?Bs:void 0})},Id=async(t,e="/api/kos/troubles",s)=>{try{const r=e.includes("/kos/troubles"),o=await Sd({model:{},urlOverride:`${Oo}${e}/resolve/${t}`,destinationAddress:r?Bs:void 0,tracker:s});return o!=null&&o.data&&mt.initiateFuture(o.data),o.data}catch{const o={id:s||"",endState:tt.Fail,tracker:s,reason:"Failed to resolve trouble"};return mt.initiateFuture(o),o}},Cd=async(t,e="/api/kos/troubles",s)=>{try{const r=await Sd({model:t,urlOverride:`${Oo}${e}/resolve/`,destinationAddress:Bs,tracker:s});return r!=null&&r.data&&mt.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:tt.Fail,tracker:s,reason:"Failed to resolve troubles"};return mt.initiateFuture(o),o}},iE=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Cd,getKosConnectionId:$d,getTroubles:Od,resolveTrouble:Id},Symbol.toStringTag,{value:"Module"})),jr="troubleDataMapper",dr=new Map;Zt(jr,{register:(t,e)=>{var s;dr.has(t)||dr.set(t,[]),(s=dr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=dr.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}:g.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const sr="troubleMapper",hr=new Map;Zt(sr,{register:(t,e)=>{var s;hr.has(t)||hr.set(t,[]),(s=hr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=hr.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(g.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});T[sr].register("nozzle",async t=>[t.data.nozzlePath]);T[sr].register("path",async t=>[t.data.path]);const aE=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>T[sr].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},Dd=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>T[jr].execute(i,t)),r=T[jr].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 cE{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class lE{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class Ct{static getHandler(e){switch(e){case"ResolvableTrouble":return new cE;case"BlockPumpTrouble":return new lE;default:return}}}var uE=Object.defineProperty,dE=Object.getOwnPropertyDescriptor,xd=(t,e,s,r)=>{for(var o=r>1?void 0:r?dE(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&&uE(e,s,o),o};const fs="trouble-model";function fr(t){return typeof t.shouldDefer=="boolean"}let Br=class{constructor(t,{resolvable:e,tags:s,info:r,id:o,clientData:n,rank:i,ifaces:a,type:c,group:u,createTime:d,role:h,color:f,servicePath:p,rawJson:y,...v},M){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"servicePath");l(this,"group");l(this,"createTime");l(this,"rawJson");l(this,"_mapped",{});this.id=t,this.logger=M.logger,this.type=c,this._troubleId=o,this._resolvable=!!e,this.ifaces=a,this.rank=i,this.role=h,this.color=f,this.tags=s,this.info=r,this.group=u,this.rawJson=y,this.servicePath=p??"/api/kos/troubles",this.createTime=d,this.clientData=n,this.data={},Object.assign(this.data,v),this.futureHandler=new po(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=Ct.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Ct.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=Ct.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:Ct.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=Ct.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=Ct.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 Dd(this)}get deferredCompanion(){const t=Jo(this.id,e=>fr(e));if(t&&fr(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Jo(this.id,e=>fr(e));return t&&fr(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 Id(this._troubleId,this.servicePath,t)}};xd([bo()],Br.prototype,"resolve",1);Br=xd([D(fs)],Br);const Ks={registration:{[fs]:{class:Br,singleton:!1}},type:fs,predicate:Ie(fs),factory:he.Factory.create(fs)};var Ad=Object.defineProperty,hE=Object.getOwnPropertyDescriptor,fE=(t,e,s)=>e in t?Ad(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Io=(t,e,s,r)=>{for(var o=r>1?void 0:r?hE(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&&Ad(e,s,o),o},pE=(t,e,s)=>(fE(t,e+"",s),s);function ka(t){return T.propertyMapper.hasMapper(se.TroubleRank)?T.propertyMapper.executeMapper(se.TroubleRank,t):sE(t)}function La(t){return(T.propertyMapper.hasMapper(se.TroubleColor)?T.propertyMapper.executeMapper(se.TroubleColor,t):rE(t)).toLowerCase()}function Fa(t){return(T.propertyMapper.hasMapper(se.TroubleRole)?T.propertyMapper.executeMapper(se.TroubleRole,t):oE(t)).toLowerCase()}const gE="trouble-container-model";class we{}l(we,"INDEX_TROUBLES_BY_IFACE","byIface"),l(we,"INDEX_TROUBLES_BY_TYPE","byType"),l(we,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(we,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(we,"SORT_KEY_RANK","rank"),l(we,"TROUBLES_DEFERRED","true");let bt=class{constructor(t,e){l(this,"id");l(this,"servicePath","/api/kos/troubles");this.id=t,this.servicePath=e.servicePath??this.servicePath}async load(){this.logger.debug("loading trouble container");try{const t=await Od(this.servicePath);t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:ka(e),color:La(e),role:Fa(e),id:String(e.id),rawJson:e},r=Ks.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(t){throw this.logger.error(t),t}}async resolveAll(t){const e=this.troubles.data.filter(s=>s.resolvable).map(s=>s.rawId);return await Cd(e,this.servicePath,t)}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&Re(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:ka(t),color:La(t),role:Fa(t),id:String(t.id),rawJson:t};if(e.role==="NONE")return;const s=Ks.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};pE(bt,"Registration");Io([bo()],bt.prototype,"resolveAll",1);Io([B({topic:"/kos/trouble/remove",websocket:!0,lifecycle:I.INIT})],bt.prototype,"handleTroubleRemoved",1);Io([B({topic:"/kos/trouble/add",websocket:!0})],bt.prototype,"handleTroubleAdded",1);bt=Io([D({modelTypeId:gE,singleton:!0}),Qt(),Kc(),uo({containerProperty:"troubles",containerOptions:{indexMap:{[we.INDEX_TROUBLES_BY_IFACE]:aE,[we.INDEX_TROUBLES_BY_TYPE]:"type",[we.INDEX_TROUBLES_BY_GROUP]:"group",[we.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:we.SORT_KEY_RANK}})],bt);const Ht=bt.Registration,{URL:Rd}=fe(),{getAll:mE}=ce.build({basePath:`${Rd}/api/kos/ota`}),Na=g.createLogger({name:"ota-service",group:"Services"}),yE=async()=>{Na.debug("sending GET request to /api/kos/ota/artifacts");const t=await mE({urlOverride:`${Rd}/api/kos/ota/artifacts`});return Na.debug("getArtifacts - response:",t),t==null?void 0:t.data};var bE=Object.defineProperty,vE=Object.getOwnPropertyDescriptor,Co=(t,e,s,r)=>{for(var o=r>1?void 0:r?vE(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&&bE(e,s,o),o};const Pd="ota-model",wE=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},Vo=t=>{const e=t.artifactInfo,s=wE(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 qt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new ti);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 yE();t&&t.forEach(e=>{const s=Vo(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=Vo(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=Vo(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};Co([Xt({modelType:Ht.type})],qt.prototype,"troubleContainer",2);Co([B({topic:"/kos/ota/artifacts/all",websocket:!0})],qt.prototype,"handleAllArtifacts",1);Co([B({topic:"/kos/ota/artifacts/changed",websocket:!0})],qt.prototype,"handleChangedArtifacts",1);qt=Co([D(Pd)],qt);const Kr=new Ce({class:qt,type:Pd}),kd=De(),Ua=de(),EE=Ua.debug==="true"||Ua.debug===!0,ME="/api/system/canvas",Ld=async(t,e)=>{const s=e||ME,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:EE?"false":"true"},body:t})},_E=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Ld},Symbol.toStringTag,{value:"Module"}));function ja(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var TE=Object.defineProperty,SE=Object.getOwnPropertyDescriptor,Fd=(t,e,s,r)=>{for(var o=r>1?void 0:r?SE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&TE(e,s,o),o};const Nd="canvas-renderer-model";function Go(t){return typeof t.onDone=="function"}let Hr=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){Ld(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=ja(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=ja(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 Go(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=Go(this._renderer);Go(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),H("/canvas/renderer/completed",{endpoint:this.endpointName,rendererId:this.id,rendererType:(c=this._renderer)==null?void 0:c.constructor.name,timestamp:Date.now()});let a=!0;this._clearOnComplete!==void 0?a=this._clearOnComplete:a=!(((d=(u=this._renderer)==null?void 0:u.isOneShot)==null?void 0:d.call(u))??!1),this.stopStreaming(a)}),this._renderer.renderFrame(this.width,this.height);const n=(r=(s=this._renderer).readPixels)==null?void 0:r.call(s,this.width,this.height);if(n&&this._onFrame&&this.handleFrame(n),this.isOneShotDone()){requestAnimationFrame(()=>{this.stopStreaming(!1)});return}const i=()=>{var a;(a=this._renderer)==null||a.renderFrame(this.width,this.height),this.renderLoopId=requestAnimationFrame(i)};this.renderLoopId=requestAnimationFrame(i),this.sendIntervalId=setInterval(()=>{var c,u;const a=(u=(c=this._renderer)==null?void 0:c.readPixels)==null?void 0:u.call(c,this.width,this.height);a&&this._onFrame&&(this.handleFrame(a),this.checkStreaming())},1e3/this.fps),!o&&this.durationMs!=null&&(this.timeoutId=setTimeout(()=>{this.stopStreaming()},this.durationMs))}}async init(){this.logger.debug(`initializing canvas-renderer ${this.id}`)}async load(){this.logger.debug(`loading canvas-renderer ${this.id}`),this.router.use("POST",`/api/ui/canvas/${this.endpointName}/stop`,async(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"})})}};Fd([Xt({modelType:yi.type})],Hr.prototype,"router",2);Hr=Fd([D(Nd)],Hr);const Ci=new Ee({class:Hr,type:Nd});class Ud{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 $E{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 OE extends $E{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=`
|
|
111
111
|
attribute vec2 a_position;
|
|
112
112
|
void main() {
|
|
113
113
|
gl_Position = vec4(a_position, 0, 1);
|
|
@@ -141,8 +141,8 @@ ${c}topics:${e}
|
|
|
141
141
|
vec3 rgb = hslToRgb(hue, 1.0, 0.5);
|
|
142
142
|
gl_FragColor = vec4(rgb, 1.0);
|
|
143
143
|
}
|
|
144
|
-
`,i=this.compileShader(r.VERTEX_SHADER,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class St{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("2d");if(!e)throw new Error("2D canvas not supported");this.ctx=e}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}}function Pi(t){class e extends t{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(o){this.doneCallback=o}signalDoneIfNeeded(){var o;this.oneShotDone||((o=this.doneCallback)==null||o.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return e}const zE=Pi(St);class VE extends zE{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();l(this,"offset",0);l(this,"speed");l(this,"colors");l(this,"direction");l(this,"loop");this.colors=s,this.direction=r,this.speed=o,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,r){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const o=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(o,0,n,0),a=1/(this.colors.length-1);this.colors.forEach((c,u)=>{i.addColorStop(u*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const GE=Pi(St);class Wd extends GE{constructor({src:s}){super();l(this,"img");l(this,"loaded",!1);this.img=new Image,this.img.src=s,this.img.crossOrigin="anonymous",this.img.onload=()=>{this.loaded=!0}}reset(){this.resetOneShot()}renderFrame(s,r){!this.loaded||this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.drawImage(this.img,0,0,s,r),this.signalDoneIfNeeded())}}class YE extends Yd{constructor(s){super(s);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"startTime");l(this,"endTime");l(this,"completionCallback",null);this.loopConfig=s.loop??!1,this.startTime=s.startTime??0,this.endTime=s.endTime??null,this.video.removeEventListener("ended",this.handleEnded),this.video.addEventListener("ended",this.handleVideoEnd.bind(this)),this.startTime>0&&(this.video.currentTime=this.startTime),this.endTime!==null&&this.video.addEventListener("timeupdate",this.handleTimeUpdate.bind(this))}handleTimeUpdate(){this.endTime!==null&&this.video.currentTime>=this.endTime&&this.handleVideoEnd()}handleVideoEnd(){this.loopConfig===!0?(this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):(this.video.pause(),this.completionCallback&&this.completionCallback())}reset(){super.reset(),this.currentLoopCount=0,this.video.currentTime=this.startTime}onDone(s){this.completionCallback=s}isOneShot(){return this.loopConfig===!1||this.loopConfig===1}dispose(){this.video.removeEventListener("ended",this.handleVideoEnd),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.completionCallback=null,super.dispose()}}function WE(t){const e=t.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(e))throw new Error(`Invalid hex color: ${t}`);let s,r,o;return e.length===3?(s=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),o=parseInt(e[2]+e[2],16)):(s=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),o=parseInt(e.substring(4,6),16)),{r:s,g:r,b:o}}function Qd(t){return typeof t=="string"?WE(t):t}function Gr(t){const e=Qd(t);return`rgb(${e.r},${e.g},${e.b})`}class QE extends St{constructor(s={}){super();l(this,"columns",[]);l(this,"fallChance");l(this,"speed");l(this,"baseColor");l(this,"trailColors");this.speed=s.speed??1,this.fallChance=s.fallChance??.7,s.baseColor?this.baseColor=Qd(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let o=0;o<=5;o++){const n=1-o/5*.6;r.push({r:Math.floor(this.baseColor.r*n),g:Math.floor(this.baseColor.g*n),b:Math.floor(this.baseColor.b*n)})}return r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const c=this.columns[a];let u=0,d=0,h=0;if(i===c)u=this.baseColor.r,d=this.baseColor.g,h=this.baseColor.b;else if(i<c&&i>c-this.trailColors.length){const p=c-i;if(p<this.trailColors.length){const y=this.trailColors[p];u=y.r,d=y.g,h=y.b}}const f=(i*s+a)*4;n[f]=u,n[f+1]=d,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(o,0,0)}}class XE{constructor(e,s){l(this,"baseRenderer");l(this,"overlayIcons",new Map);l(this,"overlayConfigs");l(this,"loadedIcons",new Set);l(this,"canvas");l(this,"ctx");l(this,"persistOverlaysOnComplete");l(this,"baseRendererCompleted",!1);l(this,"completionCallback",null);l(this,"hasSignaledCompletion",!1);this.baseRenderer=s(e.baseRenderer.type,e.baseRenderer.data),this.overlayConfigs=e.overlays,this.persistOverlaysOnComplete=e.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const e of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(e.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${e.src}`,r)},s.src=e.src,this.overlayIcons.set(e.src,s)}}calculateOverlayPosition(e,s,r){let o,n;if(typeof e.position=="string")switch(e.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-e.size)/2,n=0;break;case"top-right":o=s-e.size,n=0;break;case"center-left":o=0,n=(r-e.size)/2;break;case"center":o=(s-e.size)/2,n=(r-e.size)/2;break;case"center-right":o=s-e.size,n=(r-e.size)/2;break;case"bottom-left":o=0,n=r-e.size;break;case"bottom-center":o=(s-e.size)/2,n=r-e.size;break;case"bottom-right":o=s-e.size,n=r-e.size;break;default:o=0,n=0}else o=e.position.x,n=e.position.y;return e.offset&&(o+=e.offset.x||0,n+=e.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(e,s){if(this.canvas.width=e,this.canvas.height=s,this.ctx.clearRect(0,0,e,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(e,s);else{this.baseRenderer.renderFrame(e,s);const r=this.baseRenderer.readPixels(e,s);if(r&&r.length>0){const o=new ImageData(r,e,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(e,s)}}renderOverlays(e,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const o=this.overlayIcons.get(r.src);if(!o||!this.loadedIcons.has(r.src))continue;const n=this.calculateOverlayPosition(r,e,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(o,n.x,n.y,r.size,r.size),this.ctx.restore()}}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(e){this.completionCallback=e,this.hasSignaledCompletion&&e()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class Xd extends St{constructor(s){super();l(this,"img");l(this,"loaded",!1);l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"colorOverride");l(this,"originalSvgData",null);l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);this.img=new Image,this.img.crossOrigin="anonymous",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,this.colorOverride=s.colorOverride,this.colorOverride&&s.src.toLowerCase().includes(".svg")?this.loadAndProcessSvg(s.src):this.img.src=s.src,this.img.onload=()=>{this.loaded=!0},this.img.onerror=r=>{console.error("Failed to load image:",r)}}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(!this.loaded||this.completed)return;if(this.isPaused){this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.ctx.drawImage(this.img,0,0,s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":this.position+=d;break;case"right":this.position+=d;break;case"up":this.position+=d;break;case"down":this.position+=d;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(s,r,o,i)}drawScrollingImage(s,r,o,n){var h,f,p,y,v,M,$,U,x;const i=this.img.width/this.img.height;let a,c;((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((v=this.scrollConfig)==null?void 0:v.height)||r);let u,d;switch(o==="left"||o==="right"?(u=0,((M=this.scrollConfig)==null?void 0:M.offsetY)==="center"||(($=this.scrollConfig)==null?void 0:$.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((U=this.scrollConfig)==null?void 0:U.offsetX)==="center"||((x=this.scrollConfig)==null?void 0:x.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),o){case"left":{const O=s-this.position;if(O<s&&O>-a&&this.ctx.drawImage(this.img,O,d,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>n){const P=O+a+n;P<s&&this.ctx.drawImage(this.img,P,d,a,c)}break}case"right":{const O=-a+this.position;if(O>-a&&O<s&&this.ctx.drawImage(this.img,O,d,a,c),this.loopConfig&&this.pauseDuration===0&&O-n-a>-a){const P=O-a-n;P<s&&this.ctx.drawImage(this.img,P,d,a,c)}break}case"up":{const O=r-this.position;if(O>-c&&O<r&&this.ctx.drawImage(this.img,u,O,a,c),this.loopConfig&&this.pauseDuration===0&&O+c+n<r){const P=O+c+n;P>-c&&this.ctx.drawImage(this.img,u,P,a,c)}break}case"down":{const O=-c+this.position;if(O>-c&&O<r&&this.ctx.drawImage(this.img,u,O,a,c),this.loopConfig&&this.pauseDuration===0&&O-n-c>-c){const P=O-c-n;P<r&&this.ctx.drawImage(this.img,u,P,a,c)}break}}}checkScrollCompletion(s,r,o,n){var h,f,p,y,v;if(!this.isPlaying)return;const i=this.img.width/this.img.height;let a,c;switch(((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((v=this.scrollConfig)==null?void 0:v.height)||r),o){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let u=!1;const d=1;switch(o){case"left":u=s-this.position<-a-d;break;case"right":u=-a+this.position>s+d;break;case"up":u=r-this.position<-c-d;break;case"down":u=-c+this.position>r+d;break}u&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}async loadAndProcessSvg(s){try{const o=await(await fetch(s)).text();this.originalSvgData=o;const n=this.applySvgColorOverride(o),i=`data:image/svg+xml;base64,${btoa(n)}`;this.img.src=i}catch(r){console.error("Failed to load and process SVG:",r),this.img.src=s}}applySvgColorOverride(s){if(!this.colorOverride)return s;const r=Gr(this.colorOverride);return s.replace(/fill\s*=\s*["'][^"']*["']/gi,`fill="${r}"`).replace(/fill\s*:\s*[^;"]*/gi,`fill:${r}`).replace(/stroke\s*=\s*["'][^"']*["']/gi,`stroke="${r}"`).replace(/stroke\s*:\s*[^;"]*/gi,`stroke:${r}`)}dispose(){this.img.removeAttribute("src"),this.completionCallback=null,this.originalSvgData=null}}class ZE extends St{constructor(s){super();l(this,"text");l(this,"lines");l(this,"fontSize");l(this,"fontFamily");l(this,"lineHeight");l(this,"textColor");l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);l(this,"textWidth",0);l(this,"textHeight",0);l(this,"lineWidths",[]);l(this,"textMeasured",!1);this.text=s.text,this.lines=s.text.split(`
|
|
145
|
-
`),this.fontSize=s.fontSize??8,this.lineHeight=s.lineHeight??this.fontSize+2,this.fontFamily=s.fontFamily??"monospace, 'Lucida Console', 'Courier New', Courier",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,s.color?this.textColor=Gr(s.color):this.textColor="rgb(255,255,255)"}measureText(){if(this.textMeasured)return;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.lineWidths=[];let s=0;for(const r of this.lines){const n=this.ctx.measureText(r).width;this.lineWidths.push(n),s=Math.max(s,n)}this.textWidth=s,this.textHeight=this.lines.length*this.lineHeight,this.textMeasured=!0}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0,this.textMeasured=!1,this.lineWidths=[]}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(this.canvas.width=s,this.canvas.height=r,this.measureText(),this.completed)return;if(this.isPaused){this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.drawStaticText(s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":case"right":case"up":case"down":this.position+=d;break}}this.drawScrollingText(s,r,o,i),this.checkScrollCompletion(s,r,o)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const o=this.textHeight;let n=(r-o)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],c=this.lineWidths[i],u=(s-c)/2,d=n+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,o,n){var c,u,d,h;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";let i,a;o==="left"||o==="right"?(i=0,((c=this.scrollConfig)==null?void 0:c.offsetY)==="center"||((u=this.scrollConfig)==null?void 0:u.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((d=this.scrollConfig)==null?void 0:d.offsetX)==="center"||((h=this.scrollConfig)==null?void 0:h.offsetX)===void 0?(i=s/2,this.ctx.textAlign="center"):(i=this.scrollConfig.offsetX,this.ctx.textAlign="left"),a=0),this.drawMultiLineScrollText(o,s,r,n,i,a)}drawMultiLineScrollText(s,r,o,n,i,a){switch(s){case"left":{const c=r-this.position;if(c<r&&c>-this.textWidth&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&this.position>n){const u=c+this.textWidth+n;u<r&&this.drawTextBlock(u,a,"left")}break}case"right":{const c=-this.textWidth+this.position;if(c>-this.textWidth&&c<r&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textWidth>-this.textWidth){const u=c-this.textWidth-n;u<r&&this.drawTextBlock(u,a,"left")}break}case"up":{const c=o-this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c+this.textHeight+n<o){const u=c+this.textHeight+n;u>-this.textHeight&&this.drawTextBlock(i,u,"center")}break}case"down":{const c=-this.textHeight+this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textHeight>-this.textHeight){const u=c-this.textHeight-n;u<o&&this.drawTextBlock(i,u,"center")}break}}}drawTextBlock(s,r,o){for(let n=0;n<this.lines.length;n++){const i=this.lines[n],a=this.lineWidths[n];let c;o==="center"?c=s-a/2:c=s;const u=r+n*this.lineHeight;this.ctx.fillText(i,c,u)}}checkScrollCompletion(s,r,o){if(!this.isPlaying)return;let n=!1;const i=1;switch(o){case"left":n=s-this.position<-this.textWidth-i;break;case"right":n=-this.textWidth+this.position>s+i;break;case"up":n=r-this.position<-this.textHeight-i;break;case"down":n=-this.textHeight+this.position>r+i;break}n&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}dispose(){this.completionCallback=null}}class JE{constructor(e){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=e.patterns,this.loopConfig=e.loop??!1,this.transitionDuration=e.transitionDuration??0,this.patternOverrides=e.patternOverrides??{},this.patternStore=e.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var n,i,a,c;const e=this.patterns[this.currentPatternIndex],s=this.patternStore.get(e);if(!s){console.warn(`Pattern "${e}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[e]??{},o={...s.data,...r};try{this.currentRenderer=Yr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(c=(a=this.currentRenderer).play)==null||c.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(u){console.error(`Failed to create renderer for pattern "${e}":`,u),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const eM=Pi(St);class tM extends eM{constructor(s={r:0,g:0,b:0}){super();l(this,"color");let r;s.color!==void 0?r=s.color:s.r!==void 0&&s.g!==void 0&&s.b!==void 0?r={r:s.r,g:s.g,b:s.b}:r={r:0,g:0,b:0},this.color=Gr(r)}setColor(s){this.color=Gr(s),this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,r){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,r),this.signalDoneIfNeeded())}}class sM extends St{constructor({minHue:s=0,maxHue:r=360,speed:o=1}={}){super();l(this,"offset",0);l(this,"minHue");l(this,"maxHue");l(this,"speed");this.minHue=s,this.maxHue=r,this.speed=o}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,r,o){let n,i,a;if(r===0)n=i=a=o;else{const c=(h,f,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?h+(f-h)*6*p:p<.5?f:p<.6666666666666666?h+(f-h)*(.6666666666666666-p)*6:h),u=o<.5?o*(1+r):o+r-o*r,d=2*o-u;n=c(d,u,s+1/3),i=c(d,u,s),a=c(d,u,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let c=0;c<s;c++){const u=(c+this.offset)%s/s,d=this.minHue/360+u*((this.maxHue-this.minHue)/360),[h,f,p]=this.hslToRgb(d,1,.5);n[i++]=h,n[i++]=f,n[i++]=p,n[i++]=255}this.ctx.putImageData(o,0,0)}}const Ka=new Map;Zt(oe,{register(t,e){Ka.set(t,e)},execute(t,e){const s=Ka.get(t);return s?new s(e):null}});T.canvas.registerRenderer("video",YE);T.canvas.registerRenderer("video-basic",Yd);T[oe].register("image-static",Wd);T[oe].register("image-scrolling",Xd);const rM=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new Xd(t):new Wd(t)}};T[oe].register("image",rM);T[oe].register("color",tM);T[oe].register("matrix",QE);T[oe].register("sweep",sM);T[oe].register("gradient",VE);T[oe].register("drop",qE);T[oe].register("sequence",JE);T[oe].register("text",ZE);const oM=class{constructor(t){const e=(s,r)=>{const o=Yr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new XE(t,e)}};T[oe].register("overlay",oM);const Yr=({mode:t,data:e})=>{const s=T[oe].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var nM=Object.defineProperty,iM=Object.getOwnPropertyDescriptor,is=(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 Zd="canvas-dispatcher-model";function aM(t){if(t=t.replace(/^#/,""),t.length===3&&(t=t.split("").map(s=>s+s).join("")),t.length!==6)return null;const e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:e&255}}let rt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new Fe}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=Ri.instance(t).options({apiPath:e.apiPath,width:e.width,height:e.height,fps:e.fps,durationMs:e.durationMs??null,endpoint:t}).build();return this._endpointRenderers.addModel(s),s}addContent(t,e){this._content.has(t)&&this.logger.warn(`Content "${t}" already exists. Overwriting.`),this._content.set(t,e)}addPattern(t,e){this._patterns.has(t)&&this.logger.warn(`Pattern "${t}" already exists. Overwriting.`),this._patterns.set(t,e)}async handlePatternsPost(t,e){var o,n;const s=t.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=e.status)==null||o.call(e,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(n=e.status)==null||n.call(e,200).send({status:"OK"})}async handlePatternApplication(t,e){var u,d,h;const s=t.params.pattern,r=t.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=e.status)==null||d.call(e,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=t.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=Yr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var u,d,h;const s=t.params.color,r=aM(s);if(!r){(u=e.status)==null||u.call(e,400).send({error:"Invalid color format"});return}const o=t.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(d=e.status)==null||d.call(e,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=Yr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleEndpointCreation(t,e){var r,o;const s=t.body;if(!s.apiPath||!s.id){(r=e.status)==null||r.call(e,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=e.status)==null||o.call(e,200).send({status:"OK"})}async load(t){var s;const e=t==null?void 0:t.get(zt.loader);e&&((s=e.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};is([Oe],rt.prototype,"_endpointRenderers",2);is([Xs("/api/ui/canvas/patterns")],rt.prototype,"handlePatternsPost",1);is([Xs("/api/ui/canvas/pattern/:endpoint/:pattern")],rt.prototype,"handlePatternApplication",1);is([Xs("/api/ui/canvas/color/:endpoint/:color")],rt.prototype,"handleColorApplication",1);is([Xs("/api/ui/canvas/endpoint")],rt.prototype,"handleEndpointCreation",1);rt=is([D(Zd)],rt);const zt=new Ce({class:rt,type:Zd}),{URL:ki}=fe(),{getOne:Jd}=ce.build({basePath:`${ki}/api/device`}),Wr=g.createLogger({name:"device-service",group:"Services"}),eh=async()=>{Wr.debug("sending GET for device serial number");try{const t=await Jd({urlOverride:`${ki}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof z)return Wr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},th=async()=>{Wr.debug("sending GET for device details");try{const t=await Jd({urlOverride:`${ki}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof z)return Wr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},cM=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:th,getSerialNumber:eh},Symbol.toStringTag,{value:"Module"}));var lM=Object.defineProperty,uM=Object.getOwnPropertyDescriptor,sh=(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&&lM(e,s,o),o};const rh="device-model",dM="/kos/criticalData/changed",hM="/kos/criticalData/available";let Qr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=t,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[t]=this.nodeId.split("-");return t}get nodeName(){const[,t]=this.nodeId.split("-");return t}updateModel(t){this._serialNumber=t.serialNumber??"unassigned",this._name=t.name??"unassigned",this._nodeId=t.nodeId??"unassigned"}async loadDeviceData(){const[t,e]=await th();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}if(e){const{name:s,nodeId:r}=e;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[t,e]=await eh();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}this.updateModel({serialNumber:e,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};sh([B({topic:[dM,hM],websocket:!0})],Qr.prototype,"handleCriticalDataChanged",1);Qr=sh([D(rh)],Qr);const Xr=new Ce({class:Qr,type:rh});var fM=Object.getOwnPropertyDescriptor,pM=(t,e,s,r)=>{for(var o=r>1?void 0:r?fM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const oh="network-interface-model";let fn=class{constructor(t,e,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=t,this.logger=s.logger,this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}updateModel(t){this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};fn=pM([D(oh)],fn);const Li=new Ee({class:fn,type:oh}),{URL:gM}=fe(),{getAll:mM}=ce.build({basePath:`${gM}/api/kos/network/interfaces`}),yM=Oi(),Ha=g.createLogger({name:"network-interface-service",group:"Services"}),nh=async()=>{Ha.debug("sending GET for copy-logs");try{const t=await mM({destinationAddress:yM});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof z)return Ha.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},bM=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:nh},Symbol.toStringTag,{value:"Module"}));var vM=Object.defineProperty,wM=Object.getOwnPropertyDescriptor,ih=(t,e,s,r)=>{for(var o=r>1?void 0:r?wM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&vM(e,s,o),o};const ah="network-interface-container-model";let Zr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Fe({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await nh();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=Li.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};ih([Oe],Zr.prototype,"_models",2);Zr=ih([D(ah)],Zr);const Hs=new Ce({class:Zr,type:ah});Hs.addRelatedModel(Li);const{URL:EM}=fe(),{getAll:MM}=ce.build({basePath:`${EM}/api/kos/storage/devices`}),qa=g.createLogger({name:"storage-device-service",group:"Services"}),ch=async()=>{qa.debug("sending GET for storage-device");const t=await MM({});return!(t!=null&&t.data)||t.status!==200?(qa.error("Failed to retrieve storage-device data",t),[]):t.data},_M=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:ch},Symbol.toStringTag,{value:"Module"}));var TM=Object.getOwnPropertyDescriptor,SM=(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=i(o)||o);return o};const lh="storage-device-model";let pn=class{constructor(t,e,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=t,this.logger=s.logger,this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}updateModel(t){this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};pn=SM([lo(),D(lh)],pn);const Jr=new Ee({class:pn,type:lh});var $M=Object.defineProperty,OM=Object.getOwnPropertyDescriptor,Fi=(t,e,s,r)=>{for(var o=r>1?void 0:r?OM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&$M(e,s,o),o};const uh="storage-device-container-model",IM="/kos/storage";let qs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Fe({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=Jr.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await ch()).forEach(e=>{if(e.deviceType!=="disk"){const s={...e,kosParentId:this.id},r=Jr.instance(e.id).options(s).build();this.addModel(r)}})}};Fi([Oe],qs.prototype,"_models",2);Fi([B({topic:IM,websocket:!0})],qs.prototype,"handleStorageAvailability",1);qs=Fi([D(uh)],qs);const Vt=new Ce({class:qs,type:uh});Vt.addRelatedModel(Jr);const{URL:Ni}=fe(),{getAll:CM,postModel:DM}=ce.build({basePath:`${Ni}/api/kos/update/available`}),za=g.createLogger({name:"usb-update-service",group:"Services"}),dh=async()=>{za.debug("sending GET for usb-update");const t=await CM({urlOverride:`${Ni}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(za.error("Failed to retrieve usb-update data",t),[]):t.data},hh=async(t,e,s)=>{const r=await DM({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${Ni}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},xM=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:dh,installUpdate:hh},Symbol.toStringTag,{value:"Module"}));var AM=Object.defineProperty,RM=Object.getOwnPropertyDescriptor,fh=(t,e,s,r)=>{for(var o=r>1?void 0:r?RM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&AM(e,s,o),o};const ph="usb-update-model";let eo=class{constructor(t,e,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=t,this.logger=s.logger,this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes,this.futureHandler=new po(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),hh(this.manifestId,this.deviceId,t)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};fh([Do()],eo.prototype,"install",1);eo=fh([D(ph)],eo);const Ui=new Ee({class:eo,type:ph});var PM=Object.defineProperty,kM=Object.getOwnPropertyDescriptor,Co=(t,e,s,r)=>{for(var o=r>1?void 0:r?kM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&PM(e,s,o),o};const gh="usb-update-container-model";let Gt=class{constructor(t,e,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Fe({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await dh();te(()=>{const e=t.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!e.includes(s.id)).forEach(s=>this.removeModel(s.id)),t.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=Ui.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(o)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var t;(t=this.disposer)==null||t.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};Co([Xt({modelType:Vt.type})],Gt.prototype,"storageService",2);Co([Oe],Gt.prototype,"_models",2);Co([Vc({dependencies:t=>[t.isUsbInserted]})],Gt.prototype,"usbInsertedEffect",1);Gt=Co([D(gh)],Gt);const zs=new Ce({class:Gt,type:gh});zs.addRelatedModel(Ui);const LM=()=>({...{[ts.type]:{class:Bu},[st.type]:{class:qu,singleton:!0},...ae.registration,...Et.registration,...Ht.registration,...qr.registration,...Ve.registration,[xi.type]:{class:exports.WsEventModel,singleton:!0},...Ks.registration,...Ci.registration,...kr.registration}}),ji=LM(),FM={models:ji,preloadModels:[]},NM=!0,mh=t=>()=>{const e=ji;return al(gn)(Bs).model(Ht).model(Vt).model(zs).model(Xr).model(jr).model(Rs).model(Br).model(bi).model(Hs).model(zt).model(Ri).model(td).model(gi,NM).model(tr).model(od),Object.keys(e).forEach(s=>{const r=e[s];il(gn)(s,r)}),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t)}},$e={};$e.core={models:mh($e)};$e.preload=R.model.preloadModel($e);$e.model=R.model.register($e);$e.companion=R.companion.register($e);$e.legacy=R.model.registerLegacyModel($e);const gn=$e;class UM{registerTroubleRankMapper(e,s){return T.propertyMapper.registerPropertyMapper(se.TroubleRank,e,s),this}registerTroubleRoleMapper(e,s){return T.propertyMapper.registerPropertyMapper(se.TroubleRole,e,s),this}registerTroubleColorMapper(e,s){return T.propertyMapper.registerPropertyMapper(se.TroubleColor,e,s),this}registerModelLoader(e,s,r){T.loader.registerLoader(e,s,r)}registerRegionServicePathMapper(e){return T.propertyMapper.registerPropertyMapper(se.RegionServicePath,e),this}registerCanvasPatternLoader(e,s){T.loader.registerLoader(zt.loader,e,s)}registerConfigServicePathMapper(e){return T.propertyMapper.registerPropertyMapper(se.ConfigServicePath,e),this}}const jM=async(t,e)=>{const s=bi.instance(t).options({}).build(),r=e?`${e}-`:"";return await ye(s),{getState:o=>s.data[`${r}${o}`],updateState:async(o,n)=>{await s.updateState(`${r}${o}`,n)},clean:async()=>{for(const o of s.data.keys)await s.updateState(`${r}${o}`,void 0)},unsubscribe:()=>{Re(s)}}},yh="kos:service:region",bh="regionId",BM=`${yh}-${bh}`,vh=async t=>{const e=Et.factory(BM)({path:yh,attribute:bh});await ye(e),e.updateProperty(t)};async function KM(){const{default:t}=await Promise.resolve().then(()=>Wn);return t}function HM(t){return Ye(t)}const Va=De(),qM=Object.freeze(Object.defineProperty({__proto__:null,api:Va,default:Va,kosServiceRequest:HM},Symbol.toStringTag,{value:"Module"}));function zM(t){return Ye(t)}const Ga=De(),VM=Object.freeze(Object.defineProperty({__proto__:null,api:Ga,default:Ga,kosServiceRequest:zM},Symbol.toStringTag,{value:"Module"}));function wh(t){return Ye(t)}const mn=De(),GM=Object.freeze(Object.defineProperty({__proto__:null,api:mn,default:mn,kosServiceRequest:wh},Symbol.toStringTag,{value:"Module"}));function YM(t){return Ye(t)}const Ya=De(),WM=Object.freeze(Object.defineProperty({__proto__:null,api:Ya,default:Ya,kosServiceRequest:YM},Symbol.toStringTag,{value:"Module"}));function QM(t){return Ye(t)}const Wa=De(),XM=Object.freeze(Object.defineProperty({__proto__:null,api:Wa,default:Wa,kosServiceRequest:QM},Symbol.toStringTag,{value:"Module"}));function ZM(t){return Ye(t)}const Qa=De(),JM=Object.freeze(Object.defineProperty({__proto__:null,api:Qa,default:Qa,kosServiceRequest:ZM},Symbol.toStringTag,{value:"Module"}));function e_(t){return Ye(t)}const Xa=De(),t_=Object.freeze(Object.defineProperty({__proto__:null,api:Xa,default:Xa,kosServiceRequest:e_},Symbol.toStringTag,{value:"Module"}));function s_(t){return Ye(t)}const Za=De(),r_=Object.freeze(Object.defineProperty({__proto__:null,api:Za,default:Za,kosServiceRequest:s_},Symbol.toStringTag,{value:"Module"})),Bi="/kos-timer-event",Ki="/kos-timer-event/tick",Hi="defaultTimerEnd",ys=g.createLogger({name:"timer-manager"}),o_=t=>t.updateProperty!==void 0;class Eh{constructor(e,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=e;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,o_(s)&&X(()=>{g.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:Hi}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){ys.debug(`Timer ${this.name} already started`);return}(this.state==="inactive"||this.state==="paused")&&(this.state="active",this.timer=setInterval(()=>this.updateTimer(),1e3))}pause(){this.timer&&(ys.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(e){this.timeout=e,this.restart()}addTimeoutAction(e){const s=e.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=e.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=e.action:this.timeoutActions.get(s).push(e)}removeTimeoutAction(e){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==e);o.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,o)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(e){this.timeoutActions.has(e)&&this.timeoutActions.get(e).forEach(s=>{var r;ys.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(ys.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){H(`${Ki}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){H(Bi,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const bs=new Map,Dt=(t,e)=>{const s=bs.get(t);if(!s){ys.error(`Timer ${t} not found`);return}e(s)},Mh={createRelativeTimer(t,e,s){const r=new Date,o=Math.round((e.getTime()-r.getTime())/1e3);return this.createTimer(t,o,s)},createTimer(t,e=60,s){if(bs.has(t))return bs.get(t);const r=new Eh(t,e,s);return bs.set(t,r),r},getTimer(t){return bs.get(t)},clearTimer(t){Dt(t,e=>e.pause())},restartTimer(t){Dt(t,e=>e.restart())},resetTimer(t){Dt(t,e=>e.reset())},addTimeoutAction(t,e){Dt(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){Dt(t,s=>s.removeTimeoutAction(e))},startTimer(t){Dt(t,e=>e.start())}},_h="kos:service:region:settings",Th="timeZone",n_=`${_h}-${Th}`,yn=async t=>{const e=Et.factory(n_)({path:_h,attribute:Th});await ye(e),e.updateProperty(t)},i_=t=>!t||!t.data;function qi(t,e,s={}){const{alias:r,namespace:o,abortController:n=!1,trackerPolicy:i="id"}=s;return async function(...a){const c=wt();g.debug(`Calling future service ${e} with tracker ${c}`);let u,d;n&&(u=new AbortController);const h=mt.initiateFuture({tracker:c,id:oi});o&&(h.namespace=o),g.debug(`waiting for future ${h.id} to be ready`),await ye(h),g.debug(`future ${h.id} is ready`),te(()=>{g.debug(`Adding future ${h.id} to futureHandler`),this.futureHandler.addFuture(h,r)}),n&&u&&(d=X(()=>{(h.status==="CANCELLED"||h.endState===tt.Canceled)&&(g.debug(`Future ${h.id} cancelled, aborting request`),u==null||u.abort())}),u.signal.addEventListener("abort",async()=>{if(h.status!=="CANCELLED"&&h.endState!==tt.Canceled&&!h.endState){g.debug(`AbortController aborted, cancelling future ${h.id}`);try{await h.cancelFuture()}catch(p){g.error(`Failed to cancel future ${h.id}:`,p)}}},{once:!0}));const f=()=>{d&&(d(),d=void 0)};try{const p=[...a];if(n&&u){const M=p[p.length-1];M&&typeof M=="object"&&"aborted"in M?p[p.length-1]=u.signal:p.push(u.signal)}if(i==="context"){const M=p[p.length-1];if(Kn(M))M.$tracker=c;else{const $={[ho]:!0,$tracker:c};p.push($)}}else p.push(c);const y=await t.apply(this,p);g.debug(`received future response for ${c}`,y);const v=i_(y)?y:y==null?void 0:y.data;return v?(v.progress=1,g.debug("mapping future response to future model"),h.endState?g.debug(`future ${h.id} has already completed. Not updating the model`):fi(v,h)):this.futureHandler.removeFuture(r),f(),v}catch(p){if(f(),n&&(u!=null&&u.signal.aborted)){const y=new Error("Operation cancelled");throw g.debug(`Operation ${e} was cancelled`),y}throw g.error(p),p}}}Zt(tl,{register:()=>{},execute:()=>qi});function Do(t={}){const{alias:e}=t;return(s,r,o)=>{s[Es]=s[Es]||{},e&&(s[Ts]=s[Ts]||new Map,s[Ts].set(r,e));const n=o.value,i=qi(n,r,t);s[Es][r]={handler:i}}}const a_=({path:t})=>(e,s)=>{e[F]=e[F]||{},e[F][s]={modelType:Ks.type,id:`${Ks.type}-${t}`,options:{path:t},lifecycle:I.INIT}};function c_(t){const{path:e,attribute:s}=t;return(r,o)=>{r[F]=r[F]||{},r[F][o]={modelType:Ci.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:I.INIT}}}const kt=g.createLogger({name:"services",group:"Services"}),l_=async(t,e)=>Sh(t,e,`${exports.BASE_URL}/api/server/login`),Sh=async(t,e,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:t,password:e})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},u_=async t=>$h(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),$h=async(t,e=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${e}?email=${t}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},d_=async(t,e)=>Oh(t,e,`${exports.BASE_URL}/api/server/resetPassword`),Oh=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{kt.debug(`resetting password with token ${t} and password ${e.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e})});if(kt.debug(`password reset returned status ${r.status}`),!r.ok){kt.error(`password reset failed with message ${r.statusText}`);const n=await r.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await r.json()},h_=async(t,e,s)=>Ih(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),Ih=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{kt.debug(`accepting invite with token ${t} and password ${e.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e,name:s})});if(kt.debug(`invitation accept returned status ${o.status}`),!o.ok){kt.error(`invite failed with message ${o.statusText}`);const i=await o.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await o.json()};function f_(t,e,s,r){const o=t instanceof Promise?{promise:t,abortController:e,cancelFuture:s,future:r}:t,{promise:n,abortController:i,cancelFuture:a,future:c}=o,u=n;let d=0,h="PENDING",f=!0;const p=new Set;let y;return c&&typeof c=="object"&&(y=E.autorun(()=>{const v=c.progress||0,M=c.status||"PENDING",$=!c.endState;(v!==d||M!==h||$!==f)&&(d=v,h=M,f=$,p.forEach(U=>{try{U(d,h)}catch(x){console.warn("Progress callback error:",x)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(v=>{try{v(d,h)}catch(M){console.warn("Progress callback error:",M)}})),y&&y(),p.clear()}),u.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",p.forEach(v=>{try{v(d,h)}catch(M){console.warn("Progress callback error:",M)}}),y&&y()},u.getController=()=>i,u.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(u,"progress",{get:()=>d,enumerable:!0}),Object.defineProperty(u,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(u,"isRunning",{get:()=>f,enumerable:!0}),u.onProgressUpdate=v=>(p.add(v),v(d,h),()=>p.delete(v)),u}var p_=Object.defineProperty,g_=Object.getOwnPropertyDescriptor,m_=(t,e,s)=>e in t?p_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,y_=(t,e,s,r)=>{for(var o=r>1?void 0:r?g_(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},b_=(t,e,s)=>(m_(t,e+"",s),s);const v_="gpio-pin-model";let to=class{constructor(t,e){l(this,"id");l(this,"pinNum");l(this,"chipNum");l(this,"name");l(this,"status");l(this,"connected");this.id=t,this.chipNum=e.chipNum,this.pinNum=e.pinNum,this.name=e.name,this.status="free",this.connected=e.connected??!1}updateModel(t){this.status=t.status??this.status,this.connected=t.connected??this.connected}async init(){this.logger.debug(`initializing gpio-pin ${this.id}`)}async load(){this.logger.debug(`loading gpio-pin ${this.id}`)}};b_(to,"Registration");to=y_([D({modelTypeId:v_,singleton:!1}),Qt()],to);const zi=to.Registration;var w_=Object.defineProperty,E_=Object.getOwnPropertyDescriptor,M_=(t,e,s)=>e in t?w_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,__=(t,e,s,r)=>{for(var o=r>1?void 0:r?E_(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},T_=(t,e,s)=>(M_(t,e+"",s),s);const S_="gpio-pin-container-model";let so=class{constructor(t,e){l(this,"id");this.id=t}updateModel(t){}getPin(t){const e=this.data[t];if(!e){this.logger.warn(`Pin number ${t} not found in container ${this.id}`);return}if(e.pinNum!==t){this.logger.warn(`Pin number mismatch for pin ${e.id} in container ${this.id}: expected ${t}, got ${e.pinNum}`);return}return this.data[t]}async init(){this.logger.debug(`initializing gpio-pin-container container ${this.id}`)}async load(){this.logger.debug(`loading gpio-pin-container container ${this.id}`)}};T_(so,"Registration");so=__([D({modelTypeId:S_,singleton:!1}),uo({containerOptions:{sortKey:"pinNum"}}),Qt()],so);const Vi=so.Registration;Vi.addRelatedModel(zi);var Ch=Object.defineProperty,$_=Object.getOwnPropertyDescriptor,O_=(t,e,s)=>e in t?Ch(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Dh=(t,e,s,r)=>{for(var o=r>1?void 0:r?$_(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&&Ch(e,s,o),o},I_=(t,e,s)=>(O_(t,e+"",s),s);const C_="gpio-chip-model";let Vs=class{constructor(t,e){l(this,"id");l(this,"num");l(this,"devName");l(this,"name");l(this,"pinCount");l(this,"pinNames");l(this,"_pins");this.id=t,this.num=e.num,this.devName=e.devName,this.name=e.name,this.pinCount=e.pinCount,this.pinNames=e.pinNames,this._pins=Vi.instance(`${this.id}-pins`).options({}).build()}get pinManager(){return this._pins}updateModel(t){}async handleGpioChipLoad(){}async init(){this.logger.debug(`initializing gpio-chip ${this.id}`)}async load(){this.logger.debug(`loading gpio-chip ${this.id}`)}};I_(Vs,"Registration");Dh([Oe],Vs.prototype,"_pins",2);Vs=Dh([D({modelTypeId:C_,singleton:!1}),Qt()],Vs);const ro=Vs.Registration;g.createLogger({name:"gpio-chip-container-service",group:"Services"});const xh="/api/kos/gpio/chips",D_="/api/kos/gpio/pins",Ah=wh,Rh=mn,x_=Object.freeze(Object.defineProperty({__proto__:null,GPIO_CHIP_PATH:xh,GPIO_PIN_PATH:D_,gpioApi:Rh,gpioServiceRequest:Ah},Symbol.toStringTag,{value:"Module"}));var Ph=Object.defineProperty,A_=Object.getOwnPropertyDescriptor,R_=(t,e,s)=>e in t?Ph(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,kh=(t,e,s,r)=>{for(var o=r>1?void 0:r?A_(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&&Ph(e,s,o),o},P_=(t,e,s)=>(R_(t,e+"",s),s);const k_="gpio-chip-container-model";let Gs=class{constructor(t,e){l(this,"id");l(this,"destinationAddress");this.id=t,this.destinationAddress=e.destinationAddress??""}updateModel(t){}async handleGpioChipInit(t,e){const[s,r]=await Rh.get("/api/kos/gpio/pins",void 0,{destinationAddress:this.destinationAddress});if(s){this.logger.error("Failed to fetch GPIO pins",s);return}Object.entries(e).forEach(([n,i])=>{i.forEach(a=>{var u;if(!a.num&&a.num!==0){this.logger.warn("Skipping GPIO chip with missing number",a);return}const c=ro.instance(`${ro.type}-${a.num}}`).options({num:a.num,devName:a.devName??"",name:a.name??"",pinCount:a.pinCount??0,pinNames:a.pinNames??[]}).build();(u=a.pinNames)==null||u.forEach((d,h)=>{const f=zi.instance(`${c.name}-${d}`).options({name:d,pinNum:h,chipNum:a.num}).build();c.pinManager.addModel(f)}),this.addModel(c)})});const o=["bound","pending","invalid","free"];for(const n of o)Object.entries(r).forEach(([i,a])=>{var c;(c=a==null?void 0:a[n])==null||c.forEach(u=>{const d=u.pinNum,h=u.chipNum;if(h===void 0||d===void 0){this.logger.warn("Skipping pin with missing chipNum or pinNum",u);return}const f=this.data[h];if(!f||f.num!==h){this.logger.warn(`No chip model found for chipNum ${h} when processing pin ${d}`);return}const p=f.pinManager.getPin(d);if(!p){this.logger.warn(`No pin model found for pinNum ${d} in chipNum ${h}`);return}p.updateModel({connected:u.connected,status:n})})})}async init(){this.logger.debug(`initializing gpio-chip-container container ${this.id}`)}async load(){this.logger.debug(`loading gpio-chip-container container ${this.id}`)}};P_(Gs,"Registration");kh([Ah({path:xh,method:"get",errorHandler:{strategy:"log",defaultValue:[]},lifecycle:I.INIT,requestOptions:t=>({destinationAddress:t.destinationAddress})})],Gs.prototype,"handleGpioChipInit",1);Gs=kh([D({modelTypeId:k_,singleton:!0}),uo({containerOptions:{sortKey:"num"}}),Qt()],Gs);const Lh=Gs.Registration;Lh.addRelatedModel(ro);const Ja=g.createLogger({name:"studio-properties-service",group:"Services"}),L_="/api/kos/studio/properties",Fh=async t=>{if(Ja.debug("sending GET for studio-properties"),!t)throw Ja.error("connectionId is undefined"),new Error("connectionId is undefined");return await Ne.get(L_,{},{destinationAddress:t,timeout:500})},F_=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Fh},Symbol.toStringTag,{value:"Module"}));var N_=Object.getOwnPropertyDescriptor,U_=(t,e,s,r)=>{for(var o=r>1?void 0:r?N_(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Nh="studio-properties-model",j_="/kos/studio/properties",ec={"kos.studio.tool.legacy":1};let bn=class{constructor(t,e,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=t,this.logger=s.logger,this.data=Pe(),this.connectionId=e.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var t;(t=this.unsubscribe)==null||t.call(this)}async initializePropertiesSession(){this.unsubscribe=Lt.getInstance().subscribeTopic({topic:j_,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await Fh(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(ec);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??ec),g.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return si(()=>this.get(t))}};bn=U_([D(Nh)],bn);const B_=new Ee({class:bn,type:Nh}),K_=dt.keyframes`
|
|
144
|
+
`,i=this.compileShader(r.VERTEX_SHADER,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class St{constructor(){l(this,"canvas");l(this,"ctx");l(this,"lastUpdate",0);this.canvas=document.createElement("canvas");const e=this.canvas.getContext("2d");if(!e)throw new Error("2D canvas not supported");this.ctx=e}dispose(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove()}shouldStep(e){const s=performance.now();return s-this.lastUpdate>=e?(this.lastUpdate=s,!0):!1}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}}function Di(t){class e extends t{constructor(){super(...arguments);l(this,"doneCallback",null);l(this,"oneShotDone",!1)}isOneShot(){return!0}onDone(o){this.doneCallback=o}signalDoneIfNeeded(){var o;this.oneShotDone||((o=this.doneCallback)==null||o.call(this),this.oneShotDone=!0)}resetOneShot(){this.doneCallback=null,this.oneShotDone=!1}get isOneShotDone(){return this.oneShotDone}}return e}const IE=Di(St);class CE extends IE{constructor({colors:s=["red","yellow","green"],direction:r="horizontal",speed:o=2,loop:n=!0}={}){super();l(this,"offset",0);l(this,"speed");l(this,"colors");l(this,"direction");l(this,"loop");this.colors=s,this.direction=r,this.speed=o,this.loop=n}reset(){this.offset=0,this.lastUpdate=performance.now(),this.loop||this.resetOneShot()}renderFrame(s,r){if(!this.loop&&this.isOneShotDone)return;this.loop&&this.shouldStep(50)&&(this.offset+=this.speed);const o=this.loop?-this.offset:0,n=this.loop?s*2-this.offset:s,i=this.ctx.createLinearGradient(o,0,n,0),a=1/(this.colors.length-1);this.colors.forEach((c,u)=>{i.addColorStop(u*a,c)}),this.ctx.fillStyle=i,this.ctx.fillRect(0,0,s,r),!this.loop&&!this.isOneShotDone&&this.signalDoneIfNeeded()}}const DE=Di(St);class jd extends DE{constructor({src:s}){super();l(this,"img");l(this,"loaded",!1);this.img=new Image,this.img.src=s,this.img.crossOrigin="anonymous",this.img.onload=()=>{this.loaded=!0}}reset(){this.resetOneShot()}renderFrame(s,r){!this.loaded||this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.drawImage(this.img,0,0,s,r),this.signalDoneIfNeeded())}}class xE extends Ud{constructor(s){super(s);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"startTime");l(this,"endTime");l(this,"completionCallback",null);this.loopConfig=s.loop??!1,this.startTime=s.startTime??0,this.endTime=s.endTime??null,this.video.removeEventListener("ended",this.handleEnded),this.video.addEventListener("ended",this.handleVideoEnd.bind(this)),this.startTime>0&&(this.video.currentTime=this.startTime),this.endTime!==null&&this.video.addEventListener("timeupdate",this.handleTimeUpdate.bind(this))}handleTimeUpdate(){this.endTime!==null&&this.video.currentTime>=this.endTime&&this.handleVideoEnd()}handleVideoEnd(){this.loopConfig===!0?(this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.video.currentTime=this.startTime,this.video.play().catch(console.warn)):(this.video.pause(),this.completionCallback&&this.completionCallback())}reset(){super.reset(),this.currentLoopCount=0,this.video.currentTime=this.startTime}onDone(s){this.completionCallback=s}isOneShot(){return this.loopConfig===!1||this.loopConfig===1}dispose(){this.video.removeEventListener("ended",this.handleVideoEnd),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.completionCallback=null,super.dispose()}}function AE(t){const e=t.replace("#","");if(!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(e))throw new Error(`Invalid hex color: ${t}`);let s,r,o;return e.length===3?(s=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),o=parseInt(e[2]+e[2],16)):(s=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),o=parseInt(e.substring(4,6),16)),{r:s,g:r,b:o}}function Bd(t){return typeof t=="string"?AE(t):t}function qr(t){const e=Bd(t);return`rgb(${e.r},${e.g},${e.b})`}class RE extends St{constructor(s={}){super();l(this,"columns",[]);l(this,"fallChance");l(this,"speed");l(this,"baseColor");l(this,"trailColors");this.speed=s.speed??1,this.fallChance=s.fallChance??.7,s.baseColor?this.baseColor=Bd(s.baseColor):this.baseColor={r:0,g:255,b:255},this.trailColors=this.calculateTrailColors()}calculateTrailColors(){const r=[];for(let o=0;o<=5;o++){const n=1-o/5*.6;r.push({r:Math.floor(this.baseColor.r*n),g:Math.floor(this.baseColor.g*n),b:Math.floor(this.baseColor.b*n)})}return r}reset(){this.columns=[],this.lastUpdate=performance.now()}renderFrame(s,r){this.columns.length!==s&&(this.columns=Array(s).fill(0).map(()=>Math.floor(Math.random()*r))),this.shouldStep(50)&&(this.columns=this.columns.map(i=>i>r+5?0:i+(Math.random()<this.fallChance?this.speed:0)));const o=this.ctx.createImageData(s,r),n=o.data;n.fill(0);for(let i=0;i<r;i++)for(let a=0;a<s;a++){const c=this.columns[a];let u=0,d=0,h=0;if(i===c)u=this.baseColor.r,d=this.baseColor.g,h=this.baseColor.b;else if(i<c&&i>c-this.trailColors.length){const p=c-i;if(p<this.trailColors.length){const y=this.trailColors[p];u=y.r,d=y.g,h=y.b}}const f=(i*s+a)*4;n[f]=u,n[f+1]=d,n[f+2]=h,n[f+3]=255}this.ctx.putImageData(o,0,0)}}class PE{constructor(e,s){l(this,"baseRenderer");l(this,"overlayIcons",new Map);l(this,"overlayConfigs");l(this,"loadedIcons",new Set);l(this,"canvas");l(this,"ctx");l(this,"persistOverlaysOnComplete");l(this,"baseRendererCompleted",!1);l(this,"completionCallback",null);l(this,"hasSignaledCompletion",!1);this.baseRenderer=s(e.baseRenderer.type,e.baseRenderer.data),this.overlayConfigs=e.overlays,this.persistOverlaysOnComplete=e.persistOverlaysOnComplete!==!1,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d");if(!r)throw new Error("2D canvas not supported");this.ctx=r,this.loadOverlayImages(),"onDone"in this.baseRenderer&&typeof this.baseRenderer.onDone=="function"&&this.baseRenderer.onDone(()=>{this.baseRendererCompleted=!0,!this.persistOverlaysOnComplete&&this.completionCallback&&this.completionCallback()})}async loadOverlayImages(){for(const e of this.overlayConfigs){const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{this.loadedIcons.add(e.src)},s.onerror=r=>{console.error(`Failed to load overlay image: ${e.src}`,r)},s.src=e.src,this.overlayIcons.set(e.src,s)}}calculateOverlayPosition(e,s,r){let o,n;if(typeof e.position=="string")switch(e.position){case"top-left":o=0,n=0;break;case"top-center":o=(s-e.size)/2,n=0;break;case"top-right":o=s-e.size,n=0;break;case"center-left":o=0,n=(r-e.size)/2;break;case"center":o=(s-e.size)/2,n=(r-e.size)/2;break;case"center-right":o=s-e.size,n=(r-e.size)/2;break;case"bottom-left":o=0,n=r-e.size;break;case"bottom-center":o=(s-e.size)/2,n=r-e.size;break;case"bottom-right":o=s-e.size,n=r-e.size;break;default:o=0,n=0}else o=e.position.x,n=e.position.y;return e.offset&&(o+=e.offset.x||0,n+=e.offset.y||0),{x:o,y:n}}reset(){this.baseRenderer.reset(),this.baseRendererCompleted=!1,this.hasSignaledCompletion=!1}renderFrame(e,s){if(this.canvas.width=e,this.canvas.height=s,this.ctx.clearRect(0,0,e,s),this.baseRendererCompleted&&this.persistOverlaysOnComplete)this.renderOverlays(e,s);else{this.baseRenderer.renderFrame(e,s);const r=this.baseRenderer.readPixels(e,s);if(r&&r.length>0){const o=new ImageData(r,e,s);this.ctx.putImageData(o,0,0)}this.renderOverlays(e,s)}}renderOverlays(e,s){for(const r of this.overlayConfigs){if(!r.persistent&&r.persistent!==void 0)continue;const o=this.overlayIcons.get(r.src);if(!o||!this.loadedIcons.has(r.src))continue;const n=this.calculateOverlayPosition(r,e,s);this.ctx.save(),r.opacity!==void 0&&(this.ctx.globalAlpha=Math.max(0,Math.min(1,r.opacity))),this.ctx.drawImage(o,n.x,n.y,r.size,r.size),this.ctx.restore()}}readPixels(e,s){return this.ctx.getImageData(0,0,e,s).data}play(){this.baseRenderer.play&&this.baseRenderer.play()}pause(){this.baseRenderer.pause&&this.baseRenderer.pause()}dispose(){this.overlayIcons.clear(),this.loadedIcons.clear(),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.remove(),this.baseRenderer.dispose&&this.baseRenderer.dispose()}onDone(e){this.completionCallback=e,this.hasSignaledCompletion&&e()}isOneShot(){return this.persistOverlaysOnComplete?!1:"isOneShot"in this.baseRenderer&&typeof this.baseRenderer.isOneShot=="function"?this.baseRenderer.isOneShot():!1}}class Kd extends St{constructor(s){super();l(this,"img");l(this,"loaded",!1);l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"colorOverride");l(this,"originalSvgData",null);l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);this.img=new Image,this.img.crossOrigin="anonymous",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,this.colorOverride=s.colorOverride,this.colorOverride&&s.src.toLowerCase().includes(".svg")?this.loadAndProcessSvg(s.src):this.img.src=s.src,this.img.onload=()=>{this.loaded=!0},this.img.onerror=r=>{console.error("Failed to load image:",r)}}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(!this.loaded||this.completed)return;if(this.isPaused){this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.canvas.width=s,this.canvas.height=r,this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.ctx.drawImage(this.img,0,0,s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":this.position+=d;break;case"right":this.position+=d;break;case"up":this.position+=d;break;case"down":this.position+=d;break}}this.drawScrollingImage(s,r,o,i),this.checkScrollCompletion(s,r,o,i)}drawScrollingImage(s,r,o,n){var h,f,p,y,v,M,$,U,x;const i=this.img.width/this.img.height;let a,c;((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((v=this.scrollConfig)==null?void 0:v.height)||r);let u,d;switch(o==="left"||o==="right"?(u=0,((M=this.scrollConfig)==null?void 0:M.offsetY)==="center"||(($=this.scrollConfig)==null?void 0:$.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((U=this.scrollConfig)==null?void 0:U.offsetX)==="center"||((x=this.scrollConfig)==null?void 0:x.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),o){case"left":{const O=s-this.position;if(O<s&&O>-a&&this.ctx.drawImage(this.img,O,d,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>n){const P=O+a+n;P<s&&this.ctx.drawImage(this.img,P,d,a,c)}break}case"right":{const O=-a+this.position;if(O>-a&&O<s&&this.ctx.drawImage(this.img,O,d,a,c),this.loopConfig&&this.pauseDuration===0&&O-n-a>-a){const P=O-a-n;P<s&&this.ctx.drawImage(this.img,P,d,a,c)}break}case"up":{const O=r-this.position;if(O>-c&&O<r&&this.ctx.drawImage(this.img,u,O,a,c),this.loopConfig&&this.pauseDuration===0&&O+c+n<r){const P=O+c+n;P>-c&&this.ctx.drawImage(this.img,u,P,a,c)}break}case"down":{const O=-c+this.position;if(O>-c&&O<r&&this.ctx.drawImage(this.img,u,O,a,c),this.loopConfig&&this.pauseDuration===0&&O-n-c>-c){const P=O-c-n;P<r&&this.ctx.drawImage(this.img,u,P,a,c)}break}}}checkScrollCompletion(s,r,o,n){var h,f,p,y,v;if(!this.isPlaying)return;const i=this.img.width/this.img.height;let a,c;switch(((h=this.scrollConfig)==null?void 0:h.maintainAspectRatio)!==!1?(f=this.scrollConfig)!=null&&f.height?(c=this.scrollConfig.height,a=c*i):(p=this.scrollConfig)!=null&&p.width?(a=this.scrollConfig.width,c=a/i):o==="left"||o==="right"?(c=r,a=c*i):(a=s,c=a/i):(a=((y=this.scrollConfig)==null?void 0:y.width)||s,c=((v=this.scrollConfig)==null?void 0:v.height)||r),o){case"left":case"right":this.loopConfig;break;case"up":case"down":this.loopConfig;break}let u=!1;const d=1;switch(o){case"left":u=s-this.position<-a-d;break;case"right":u=-a+this.position>s+d;break;case"up":u=r-this.position<-c-d;break;case"down":u=-c+this.position>r+d;break}u&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}async loadAndProcessSvg(s){try{const o=await(await fetch(s)).text();this.originalSvgData=o;const n=this.applySvgColorOverride(o),i=`data:image/svg+xml;base64,${btoa(n)}`;this.img.src=i}catch(r){console.error("Failed to load and process SVG:",r),this.img.src=s}}applySvgColorOverride(s){if(!this.colorOverride)return s;const r=qr(this.colorOverride);return s.replace(/fill\s*=\s*["'][^"']*["']/gi,`fill="${r}"`).replace(/fill\s*:\s*[^;"]*/gi,`fill:${r}`).replace(/stroke\s*=\s*["'][^"']*["']/gi,`stroke="${r}"`).replace(/stroke\s*:\s*[^;"]*/gi,`stroke:${r}`)}dispose(){this.img.removeAttribute("src"),this.completionCallback=null,this.originalSvgData=null}}class kE extends St{constructor(s){super();l(this,"text");l(this,"lines");l(this,"fontSize");l(this,"fontFamily");l(this,"lineHeight");l(this,"textColor");l(this,"scrollConfig");l(this,"loopConfig");l(this,"duration");l(this,"pauseDuration");l(this,"position",0);l(this,"startTime",0);l(this,"lastFrameTime",0);l(this,"currentLoopCount",0);l(this,"completionCallback",null);l(this,"isPlaying",!1);l(this,"completed",!1);l(this,"isPaused",!1);l(this,"pauseStartTime",0);l(this,"textWidth",0);l(this,"textHeight",0);l(this,"lineWidths",[]);l(this,"textMeasured",!1);this.text=s.text,this.lines=s.text.split(`
|
|
145
|
+
`),this.fontSize=s.fontSize??8,this.lineHeight=s.lineHeight??this.fontSize+2,this.fontFamily=s.fontFamily??"monospace, 'Lucida Console', 'Courier New', Courier",this.scrollConfig=s.scroll,this.loopConfig=s.loop??!1,this.duration=s.duration,this.pauseDuration=s.pauseBetweenLoops??0,s.color?this.textColor=qr(s.color):this.textColor="rgb(255,255,255)"}measureText(){if(this.textMeasured)return;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.lineWidths=[];let s=0;for(const r of this.lines){const n=this.ctx.measureText(r).width;this.lineWidths.push(n),s=Math.max(s,n)}this.textWidth=s,this.textHeight=this.lines.length*this.lineHeight,this.textMeasured=!0}reset(){this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime,this.currentLoopCount=0,this.completed=!1,this.isPlaying=!1,this.isPaused=!1,this.pauseStartTime=0,this.textMeasured=!1,this.lineWidths=[]}play(){this.isPlaying||(this.isPlaying=!0,this.startTime=performance.now(),this.lastFrameTime=this.startTime)}pause(){this.isPlaying=!1}renderFrame(s,r){var a;if(this.canvas.width=s,this.canvas.height=r,this.measureText(),this.completed)return;if(this.isPaused){this.ctx.clearRect(0,0,s,r),this.pauseDuration>0&&performance.now()-this.pauseStartTime>=this.pauseDuration&&(this.isPaused=!1,this.position=0,this.startTime=performance.now(),this.lastFrameTime=this.startTime);return}if(this.ctx.clearRect(0,0,s,r),!((a=this.scrollConfig)!=null&&a.enabled)){this.drawStaticText(s,r),this.duration&&this.isPlaying&&performance.now()-this.startTime>=this.duration&&this.handleCompletion();return}const o=this.scrollConfig.direction||"left",n=this.scrollConfig.speed||50,i=this.scrollConfig.gap||0;if(this.isPlaying){const c=performance.now(),u=(c-this.lastFrameTime)/1e3;this.lastFrameTime=c;const d=n*u;switch(o){case"left":case"right":case"up":case"down":this.position+=d;break}}this.drawScrollingText(s,r,o,i),this.checkScrollCompletion(s,r,o)}drawStaticText(s,r){this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";const o=this.textHeight;let n=(r-o)/2;for(let i=0;i<this.lines.length;i++){const a=this.lines[i],c=this.lineWidths[i],u=(s-c)/2,d=n+i*this.lineHeight;this.ctx.fillText(a,u,d)}}drawScrollingText(s,r,o,n){var c,u,d,h;this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.fillStyle=this.textColor,this.ctx.textBaseline="top";let i,a;o==="left"||o==="right"?(i=0,((c=this.scrollConfig)==null?void 0:c.offsetY)==="center"||((u=this.scrollConfig)==null?void 0:u.offsetY)===void 0?a=(r-this.textHeight)/2:a=this.scrollConfig.offsetY):(((d=this.scrollConfig)==null?void 0:d.offsetX)==="center"||((h=this.scrollConfig)==null?void 0:h.offsetX)===void 0?(i=s/2,this.ctx.textAlign="center"):(i=this.scrollConfig.offsetX,this.ctx.textAlign="left"),a=0),this.drawMultiLineScrollText(o,s,r,n,i,a)}drawMultiLineScrollText(s,r,o,n,i,a){switch(s){case"left":{const c=r-this.position;if(c<r&&c>-this.textWidth&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&this.position>n){const u=c+this.textWidth+n;u<r&&this.drawTextBlock(u,a,"left")}break}case"right":{const c=-this.textWidth+this.position;if(c>-this.textWidth&&c<r&&this.drawTextBlock(c,a,"left"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textWidth>-this.textWidth){const u=c-this.textWidth-n;u<r&&this.drawTextBlock(u,a,"left")}break}case"up":{const c=o-this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c+this.textHeight+n<o){const u=c+this.textHeight+n;u>-this.textHeight&&this.drawTextBlock(i,u,"center")}break}case"down":{const c=-this.textHeight+this.position;if(c>-this.textHeight&&c<o&&this.drawTextBlock(i,c,"center"),this.loopConfig&&this.pauseDuration===0&&c-n-this.textHeight>-this.textHeight){const u=c-this.textHeight-n;u<o&&this.drawTextBlock(i,u,"center")}break}}}drawTextBlock(s,r,o){for(let n=0;n<this.lines.length;n++){const i=this.lines[n],a=this.lineWidths[n];let c;o==="center"?c=s-a/2:c=s;const u=r+n*this.lineHeight;this.ctx.fillText(i,c,u)}}checkScrollCompletion(s,r,o){if(!this.isPlaying)return;let n=!1;const i=1;switch(o){case"left":n=s-this.position<-this.textWidth-i;break;case"right":n=-this.textWidth+this.position>s+i;break;case"up":n=r-this.position<-this.textHeight-i;break;case"down":n=-this.textHeight+this.position>r+i;break}n&&(this.loopConfig===!1||typeof this.loopConfig=="number"&&this.loopConfig===1?this.handleCompletion():typeof this.loopConfig=="number"&&this.loopConfig>1?(this.currentLoopCount++,this.currentLoopCount>=this.loopConfig?this.handleCompletion():this.startPauseOrNextLoop()):this.loopConfig===!0&&this.startPauseOrNextLoop())}startPauseOrNextLoop(){this.pauseDuration>0?(this.isPaused=!0,this.pauseStartTime=performance.now()):this.position=0}handleCompletion(){this.completed=!0,this.isPlaying=!1,this.completionCallback&&this.completionCallback()}onDone(s){this.completionCallback=s}isOneShot(){var s;return!((s=this.scrollConfig)!=null&&s.enabled)&&!this.loopConfig}dispose(){this.completionCallback=null}}class LE{constructor(e){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=e.patterns,this.loopConfig=e.loop??!1,this.transitionDuration=e.transitionDuration??0,this.patternOverrides=e.patternOverrides??{},this.patternStore=e.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var n,i,a,c;const e=this.patterns[this.currentPatternIndex],s=this.patternStore.get(e);if(!s){console.warn(`Pattern "${e}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[e]??{},o={...s.data,...r};try{this.currentRenderer=zr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(c=(a=this.currentRenderer).play)==null||c.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(u){console.error(`Failed to create renderer for pattern "${e}":`,u),this.moveToNextPattern()}}isDoneAware(e){return typeof(e==null?void 0:e.onDone)=="function"}handlePatternComplete(){this.transitionDuration>0?setTimeout(()=>{this.moveToNextPattern()},this.transitionDuration):this.moveToNextPattern()}moveToNextPattern(){this.currentPatternIndex++,this.currentPatternIndex>=this.patterns.length?this.loopConfig===!0?(this.currentPatternIndex=0,this.loadCurrentPattern()):typeof this.loopConfig=="number"&&this.currentLoopCount<this.loopConfig-1?(this.currentLoopCount++,this.currentPatternIndex=0,this.loadCurrentPattern()):this.completionCallback&&this.completionCallback():this.loadCurrentPattern()}reset(){this.currentPatternIndex=0,this.currentLoopCount=0,this.loadCurrentPattern()}play(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.play)==null||s.call(e)}pause(){var e,s;(s=(e=this.currentRenderer)==null?void 0:e.pause)==null||s.call(e)}renderFrame(e,s){this.width=e,this.height=s,this.canvas.width=e,this.canvas.height=s,this.currentRenderer&&this.currentRenderer.renderFrame(e,s)}readPixels(e,s){return this.currentRenderer?this.currentRenderer.readPixels(e,s):this.ctx.getImageData(0,0,e,s).data}onDone(e){this.completionCallback=e}isOneShot(){var e,s;return this.loopConfig===!1||this.loopConfig===1?this.patterns.length===1&&this.currentRenderer?((s=(e=this.currentRenderer).isOneShot)==null?void 0:s.call(e))??!1:!0:!1}dispose(){var e,s;this.currentRenderer&&((s=(e=this.currentRenderer).dispose)==null||s.call(e)),this.completionCallback=null}setPatternStore(e){this.patternStore=e,this.patterns.length>0&&this.loadCurrentPattern()}}const FE=Di(St);class NE extends FE{constructor(s={r:0,g:0,b:0}){super();l(this,"color");let r;s.color!==void 0?r=s.color:s.r!==void 0&&s.g!==void 0&&s.b!==void 0?r={r:s.r,g:s.g,b:s.b}:r={r:0,g:0,b:0},this.color=qr(r)}setColor(s){this.color=qr(s),this.resetOneShot()}reset(){this.resetOneShot()}renderFrame(s,r){this.isOneShotDone||(this.canvas.width=s,this.canvas.height=r,this.ctx.fillStyle=this.color,this.ctx.fillRect(0,0,s,r),this.signalDoneIfNeeded())}}class UE extends St{constructor({minHue:s=0,maxHue:r=360,speed:o=1}={}){super();l(this,"offset",0);l(this,"minHue");l(this,"maxHue");l(this,"speed");this.minHue=s,this.maxHue=r,this.speed=o}reset(){this.offset=0,this.lastUpdate=performance.now()}hslToRgb(s,r,o){let n,i,a;if(r===0)n=i=a=o;else{const c=(h,f,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?h+(f-h)*6*p:p<.5?f:p<.6666666666666666?h+(f-h)*(.6666666666666666-p)*6:h),u=o<.5?o*(1+r):o+r-o*r,d=2*o-u;n=c(d,u,s+1/3),i=c(d,u,s),a=c(d,u,s-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(a*255)]}renderFrame(s,r){this.shouldStep(50)&&(this.offset=(this.offset+this.speed)%s);const o=this.ctx.createImageData(s,r),n=o.data;let i=0;for(let a=0;a<r;a++)for(let c=0;c<s;c++){const u=(c+this.offset)%s/s,d=this.minHue/360+u*((this.maxHue-this.minHue)/360),[h,f,p]=this.hslToRgb(d,1,.5);n[i++]=h,n[i++]=f,n[i++]=p,n[i++]=255}this.ctx.putImageData(o,0,0)}}const Ba=new Map;Zt(oe,{register(t,e){Ba.set(t,e)},execute(t,e){const s=Ba.get(t);return s?new s(e):null}});T.canvas.registerRenderer("video",xE);T.canvas.registerRenderer("video-basic",Ud);T[oe].register("image-static",jd);T[oe].register("image-scrolling",Kd);const jE=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new Kd(t):new jd(t)}};T[oe].register("image",jE);T[oe].register("color",NE);T[oe].register("matrix",RE);T[oe].register("sweep",UE);T[oe].register("gradient",CE);T[oe].register("drop",OE);T[oe].register("sequence",LE);T[oe].register("text",kE);const BE=class{constructor(t){const e=(s,r)=>{const o=zr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new PE(t,e)}};T[oe].register("overlay",BE);const zr=({mode:t,data:e})=>{const s=T[oe].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var KE=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,is=(t,e,s,r)=>{for(var o=r>1?void 0:r?HE(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&&KE(e,s,o),o};const Hd="canvas-dispatcher-model";function qE(t){if(t=t.replace(/^#/,""),t.length===3&&(t=t.split("").map(s=>s+s).join("")),t.length!==6)return null;const e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:e&255}}let rt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_content",new Map);l(this,"_patterns",new Map);l(this,"_endpointRenderers");l(this,"pattern");l(this,"data");this.id=t,this.logger=s.logger,this._endpointRenderers=new Fe}addNamedEndpoint(t,e){this._endpointRenderers.getModel(t)&&this.logger.warn(`Endpoint "${t}" already exists. Overwriting.`);const s=Ci.instance(t).options({apiPath:e.apiPath,width:e.width,height:e.height,fps:e.fps,durationMs:e.durationMs??null,endpoint:t}).build();return this._endpointRenderers.addModel(s),s}addContent(t,e){this._content.has(t)&&this.logger.warn(`Content "${t}" already exists. Overwriting.`),this._content.set(t,e)}addPattern(t,e){this._patterns.has(t)&&this.logger.warn(`Pattern "${t}" already exists. Overwriting.`),this._patterns.set(t,e)}async handlePatternsPost(t,e){var o,n;const s=t.body,r=Array.isArray(s)?s:[s];if(r.some(i=>!i.id||!i.type||!i.data)){(o=e.status)==null||o.call(e,400).send({error:"Invalid pattern data"});return}for(const i of r)this._patterns.has(i.id)&&this.logger.warn(`Pattern "${i.id}" already exists. Overwriting.`),this.addPattern(i.id,i);(n=e.status)==null||n.call(e,200).send({status:"OK"})}async handlePatternApplication(t,e){var u,d,h;const s=t.params.pattern,r=t.params.endpoint,o=this._endpointRenderers.getModel(r);if(!o){(u=e.status)==null||u.call(e,404).send({error:`Endpoint "${r}" not found`});return}if(!this._patterns.has(s)){(d=e.status)==null||d.call(e,404).send({error:`Pattern "${s}" not found`});return}const n=this._patterns.get(s),i=n.type,a=t.body||{};this.data={...n.data,...a};const c=i==="sequence"?{...this.data,patternStore:this._patterns}:this.data;o.renderer=zr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var u,d,h;const s=t.params.color,r=qE(s);if(!r){(u=e.status)==null||u.call(e,400).send({error:"Invalid color format"});return}const o=t.params.endpoint,n=this._endpointRenderers.getModel(o);if(!n){(d=e.status)==null||d.call(e,404).send({error:`Endpoint "${o}" not found`});return}const{r:i,b:a,g:c}=r;n.renderer=zr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleEndpointCreation(t,e){var r,o;const s=t.body;if(!s.apiPath||!s.id){(r=e.status)==null||r.call(e,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=e.status)==null||o.call(e,200).send({status:"OK"})}async load(t){var s;const e=t==null?void 0:t.get(zt.loader);e&&((s=e.patterns)==null||s.forEach(r=>{if(!r.id||!r.type||!r.data){this.logger.warn(`Invalid pattern data: ${JSON.stringify(r)}`);return}this.addPattern(r.id,r)}))}};is([Oe],rt.prototype,"_endpointRenderers",2);is([Xs("/api/ui/canvas/patterns")],rt.prototype,"handlePatternsPost",1);is([Xs("/api/ui/canvas/pattern/:endpoint/:pattern")],rt.prototype,"handlePatternApplication",1);is([Xs("/api/ui/canvas/color/:endpoint/:color")],rt.prototype,"handleColorApplication",1);is([Xs("/api/ui/canvas/endpoint")],rt.prototype,"handleEndpointCreation",1);rt=is([D(Hd)],rt);const zt=new Ce({class:rt,type:Hd}),{URL:xi}=fe(),{getOne:qd}=ce.build({basePath:`${xi}/api/device`}),Vr=g.createLogger({name:"device-service",group:"Services"}),zd=async()=>{Vr.debug("sending GET for device serial number");try{const t=await qd({urlOverride:`${xi}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof z)return Vr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Vd=async()=>{Vr.debug("sending GET for device details");try{const t=await qd({urlOverride:`${xi}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof z)return Vr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},zE=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Vd,getSerialNumber:zd},Symbol.toStringTag,{value:"Module"}));var VE=Object.defineProperty,GE=Object.getOwnPropertyDescriptor,Gd=(t,e,s,r)=>{for(var o=r>1?void 0:r?GE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&VE(e,s,o),o};const Yd="device-model",YE="/kos/criticalData/changed",WE="/kos/criticalData/available";let Gr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_serialNumber");l(this,"_name");l(this,"_nodeId");this.id=t,this.logger=s.logger,this._serialNumber="unassigned",this._name="unassigned",this._nodeId="unassigned"}get serialNumber(){return this._serialNumber}get name(){return this._name}get nodeId(){return this._nodeId}get nodeType(){const[t]=this.nodeId.split("-");return t}get nodeName(){const[,t]=this.nodeId.split("-");return t}updateModel(t){this._serialNumber=t.serialNumber??"unassigned",this._name=t.name??"unassigned",this._nodeId=t.nodeId??"unassigned"}async loadDeviceData(){const[t,e]=await Vd();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}if(e){const{name:s,nodeId:r}=e;this.updateModel({name:s,nodeId:r,serialNumber:this.serialNumber})}}async loadSerialNumber(){const[t,e]=await zd();if(t){this.logger.error(`Error fetching device serial number: ${t}`);return}this.updateModel({serialNumber:e,name:this.name,nodeId:this.nodeId})}async handleCriticalDataChanged(){this.logger.debug(`Critical data changed for device ${this.id}`),await this.loadSerialNumber()}async init(){this.logger.debug(`initializing device ${this.id}`)}async load(){this.logger.debug(`loading device ${this.id}`),await this.loadDeviceData(),await this.loadSerialNumber()}};Gd([B({topic:[YE,WE],websocket:!0})],Gr.prototype,"handleCriticalDataChanged",1);Gr=Gd([D(Yd)],Gr);const Yr=new Ce({class:Gr,type:Yd});var QE=Object.getOwnPropertyDescriptor,XE=(t,e,s,r)=>{for(var o=r>1?void 0:r?QE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Wd="network-interface-model";let un=class{constructor(t,e,s){l(this,"id");l(this,"name");l(this,"type");l(this,"nmdevicestate");l(this,"hwaddress");l(this,"mtu");l(this,"configured");l(this,"wifi");l(this,"ethernet");l(this,"ip4settings");l(this,"category");l(this,"logger");this.id=t,this.logger=s.logger,this.name=e.name,this.type=e.type,this.nmdevicestate=e.nmdevicestate,this.hwaddress=e.hwaddress,this.mtu=e.mtu,this.configured=e.configured,this.wifi=e.wifi,this.ethernet=e.ethernet,this.ip4settings=e.ip4settings,this.category=e.category}updateModel(t){this.name=t.name,this.type=t.type,this.nmdevicestate=t.nmdevicestate,this.hwaddress=t.hwaddress,this.mtu=t.mtu,this.configured=t.configured,this.wifi=t.wifi,this.ethernet=t.ethernet,this.ip4settings=t.ip4settings,this.category=t.category}async init(){this.logger.debug(`initializing network-interface ${this.id}`)}async load(){this.logger.debug(`loading network-interface ${this.id}`)}};un=XE([D(Wd)],un);const Ai=new Ee({class:un,type:Wd}),Ri=()=>{var r;const t=de(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return g.info(`getKosConnectionId: ${s}`),s},{URL:ZE}=fe(),{getAll:JE}=ce.build({basePath:`${ZE}/api/kos/network/interfaces`}),eM=Ri(),Ka=g.createLogger({name:"network-interface-service",group:"Services"}),Qd=async()=>{Ka.debug("sending GET for copy-logs");try{const t=await JE({destinationAddress:eM});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof z)return Ka.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},tM=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Qd},Symbol.toStringTag,{value:"Module"}));var sM=Object.defineProperty,rM=Object.getOwnPropertyDescriptor,Xd=(t,e,s,r)=>{for(var o=r>1?void 0:r?rM(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&&sM(e,s,o),o};const Zd="network-interface-container-model";let Wr=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Fe({parentId:t,indexMap:{byCategory:"category"}})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing network-interface-container container ${this.id}`)}async refreshInterfaces(){this.logger.debug("refreshing interfaces");const[t,e]=await Qd();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=Ai.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Xd([Oe],Wr.prototype,"_models",2);Wr=Xd([D(Zd)],Wr);const Hs=new Ce({class:Wr,type:Zd});Hs.addRelatedModel(Ai);const{URL:oM}=fe(),{getAll:nM}=ce.build({basePath:`${oM}/api/kos/storage/devices`}),Ha=g.createLogger({name:"storage-device-service",group:"Services"}),Jd=async()=>{Ha.debug("sending GET for storage-device");const t=await nM({});return!(t!=null&&t.data)||t.status!==200?(Ha.error("Failed to retrieve storage-device data",t),[]):t.data},iM=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Jd},Symbol.toStringTag,{value:"Module"}));var aM=Object.getOwnPropertyDescriptor,cM=(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=i(o)||o);return o};const eh="storage-device-model";let dn=class{constructor(t,e,s){l(this,"id");l(this,"mountDir");l(this,"removed");l(this,"vendor");l(this,"runTimeMs");l(this,"model");l(this,"nodeId");l(this,"local");l(this,"label");l(this,"syspath");l(this,"logger");this.id=t,this.logger=s.logger,this.mountDir=e.mountDir,this.removed=e.removed,this.vendor=e.vendor,this.runTimeMs=e.runTimeMs,this.model=e.model,this.nodeId=e.nodeId,this.local=e.local,this.label=e.label,this.syspath=e.syspath}updateModel(t){this.mountDir=t.mountDir,this.removed=t.removed,this.vendor=t.vendor,this.runTimeMs=t.runTimeMs,this.model=t.model,this.nodeId=t.nodeId,this.local=t.local,this.label=t.label,this.syspath=t.syspath}async init(){this.logger.debug(`initializing storage-device ${this.id}`)}async load(){this.logger.debug(`loading storage-device ${this.id}`)}};dn=cM([lo(),D(eh)],dn);const Qr=new Ee({class:dn,type:eh});var lM=Object.defineProperty,uM=Object.getOwnPropertyDescriptor,Pi=(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&&lM(e,s,o),o};const th="storage-device-container-model",dM="/kos/storage";let qs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Fe({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}async init(){this.logger.debug(`initializing storage-device-container container ${this.id}`)}get isStorageInserted(){return this.data.length>0}get volumes(){return this.data}handleStorageAvailability(t){this._models.data.filter(s=>!t.find(r=>r.id===s.id)).forEach(s=>{this.removeModel(s.id)}),t.forEach(s=>{const r=this.getModel(s.id);if(r){const o={...s,kosParentId:this.id};r.updateModel(o)}else{const o={...s,kosParentId:this.id},n=Qr.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Jd()).forEach(e=>{if(e.deviceType!=="disk"){const s={...e,kosParentId:this.id},r=Qr.instance(e.id).options(s).build();this.addModel(r)}})}};Pi([Oe],qs.prototype,"_models",2);Pi([B({topic:dM,websocket:!0})],qs.prototype,"handleStorageAvailability",1);qs=Pi([D(th)],qs);const Vt=new Ce({class:qs,type:th});Vt.addRelatedModel(Qr);const{URL:ki}=fe(),{getAll:hM,postModel:fM}=ce.build({basePath:`${ki}/api/kos/update/available`}),qa=g.createLogger({name:"usb-update-service",group:"Services"}),sh=async()=>{qa.debug("sending GET for usb-update");const t=await hM({urlOverride:`${ki}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(qa.error("Failed to retrieve usb-update data",t),[]):t.data},rh=async(t,e,s)=>{const r=await fM({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${ki}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},pM=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:sh,installUpdate:rh},Symbol.toStringTag,{value:"Module"}));var gM=Object.defineProperty,mM=Object.getOwnPropertyDescriptor,oh=(t,e,s,r)=>{for(var o=r>1?void 0:r?mM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&gM(e,s,o),o};const nh="usb-update-model";let Xr=class{constructor(t,e,s){l(this,"id");l(this,"active");l(this,"blocked");l(this,"createTime");l(this,"deviceId");l(this,"manifestId");l(this,"notes");l(this,"futureHandler");l(this,"logger");this.id=t,this.logger=s.logger,this.active=e.active,this.blocked=e.blocked,this.createTime=e.createTime,this.deviceId=e.deviceId,this.manifestId=e.manifestId,this.notes=e.notes,this.futureHandler=new po(this)}updateModel(t){this.active=t.active,this.blocked=t.blocked,this.createTime=t.createTime,this.deviceId=t.deviceId,this.manifestId=t.manifestId,this.notes=t.notes}reset(){this.futureHandler.removeFuture()}get future(){return this.futureHandler.future}async install(t){if(!t)throw new Error("No tracker provided");return this.logger.info(`Installing update for manifest ${this.manifestId} from device ${this.deviceId}`),rh(this.manifestId,this.deviceId,t)}async init(){this.logger.debug(`initializing usb-update ${this.id}`)}async load(){this.logger.debug(`loading usb-update ${this.id}`)}};oh([bo()],Xr.prototype,"install",1);Xr=oh([D(nh)],Xr);const Li=new Ee({class:Xr,type:nh});var yM=Object.defineProperty,bM=Object.getOwnPropertyDescriptor,Do=(t,e,s,r)=>{for(var o=r>1?void 0:r?bM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&yM(e,s,o),o};const ih="usb-update-container-model";let Gt=class{constructor(t,e,s){l(this,"id");l(this,"disposer");l(this,"storageService");l(this,"_activeUpdate");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new Fe({parentId:t})}getModel(t){return this._models.getModel(t)}get models(){return this._models}get data(){return this._models.data}addModel(t){this._models.addModel(t)}removeModel(t){this._models.removeModel(t)}get activeUpdate(){return this._activeUpdate}reset(){this.clearActiveUpdate()}clearActiveUpdate(){this._activeUpdate=void 0}updateActiveUpdate(t){this._activeUpdate=t}get isUsbInserted(){return this.storageService.isStorageInserted}get hasAvailableUpdates(){return this._models.data.length>0}async syncAvailableUpdates(){const t=await sh();te(()=>{const e=t.map(s=>`${s.deviceId}-${s.manifestId}`);this._models.data.filter(s=>!e.includes(s.id)).forEach(s=>this.removeModel(s.id)),t.forEach(s=>{const r=`${s.deviceId}-${s.manifestId}`,o=Li.instance(r).forceUpdate.options({...s,createTime:new Date(s.createTime)}).build();this.addModel(o)}),this.data.length===1?this.updateActiveUpdate(this.data[0]):this.clearActiveUpdate()})}usbInsertedEffect(){this.isUsbInserted?this.syncAvailableUpdates():(this._models.clear(),this.clearActiveUpdate())}async init(){this.logger.debug(`initializing usb-update-container container ${this.id}`)}unload(){var t;(t=this.disposer)==null||t.call(this)}async activate(){this.logger.debug(`activating usb-update-container container ${this.id}`),await this.syncAvailableUpdates()}async load(){this.logger.debug(`loading usb-update-container container ${this.id}`)}};Do([Xt({modelType:Vt.type})],Gt.prototype,"storageService",2);Do([Oe],Gt.prototype,"_models",2);Do([Vc({dependencies:t=>[t.isUsbInserted]})],Gt.prototype,"usbInsertedEffect",1);Gt=Do([D(ih)],Gt);const zs=new Ce({class:Gt,type:ih});zs.addRelatedModel(Li);const{URL:Fi}=fe(),{getOne:ah}=ce.build({basePath:`${Fi}/api/translation`}),xs=g.createLogger({name:"translation-service",group:"Services"}),vM=()=>{const t=window.location.origin,e=de();return(e==null?void 0:e.host)||t},ch=async(t,e)=>{xs.debug(`Loading translations from: ${t}`);const s=e??vM();try{const r=await fetch(`${s}${t}`);return r.status!==200?(xs.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw xs.error("Error fetching translations",r),r}},wM=async()=>{xs.debug("Getting system localization descriptor");const t=await ah({urlOverride:`${Fi}/api/system/kos/localization`});if((t==null?void 0:t.status)!==200)throw new Error(`Failed to get localization descriptor ${t==null?void 0:t.status}`);return t.data},lh=t=>async()=>{xs.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await ah({urlOverride:`${Fi}/api/kos/localization/contexts`});if((e==null?void 0:e.status)!==200)throw new Error(`Failed to get KOS localization descriptor ${e==null?void 0:e.status}`);return e.data[t]},uh="langResolver";var EM=Object.getOwnPropertyDescriptor,MM=(t,e,s,r)=>{for(var o=r>1?void 0:r?EM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ps="translation-model";function _M(t){const e=typeof t=="string",s=e?!1:!!(t!=null&&t.data)&&typeof(t==null?void 0:t.data)!="string",r=e?t:t==null?void 0:t.defaultValue,o=e||t==null?void 0:t.context,n=e?void 0:s?t==null?void 0:t.data:t;return{isBasicOptions:e,defaultValue:r,context:o,data:n}}function dh(t,e=""){return Object.keys(t).reduce((s,r)=>{const o=e?`${e}.${r}`:r;if(typeof t[r]=="object"&&t[r]!==null&&!Array.isArray(t[r])){const n=dh(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function hh(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]=hh(t[r],e[r]):s[r]=e[r]);return s}const hn=(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)?hn(r,e):r},pr=(t,e,s)=>{const r=/{{(.*?)}}/g,n=hn(t,e).replace(r,(a,c)=>{const u=c.trim();if(Object.prototype.hasOwnProperty.call(s||{},u))return s==null?void 0:s[u];if(u.includes(".")){const d=u.split(".");let h=s;for(const f of d)if(h&&typeof h=="object"&&Object.prototype.hasOwnProperty.call(h,f))h=h[f];else return a;return h}return a});return hn(n,e)},za=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let fn=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(uh),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=Q.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return ch(o,this.rootUrl)}catch{return Promise.resolve({})}}),s=await Promise.allSettled(e);te(()=>{const r=s.reduce((o,n,i)=>(n.status==="fulfilled"?(this.logger.debug(`resolved ${t[i]}`,n.value),n.value&&(o=hh(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=dh(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=za(this.namespace,t);if(e!==this.namespace){const r=this.context.getModel(e);return r?r.exists(s):!1}return!!this.data[s]}resolveKey(t,e){if(!t)return this.logger.debug("key is empty"),"";const{defaultValue:s,context:r,data:o}=_M(e),{namespace:n,key:i}=za(this.namespace,t),a=`${i}_${r}`;if(n!==this.namespace){const c=this.context.getModel(n);return c?c.resolveKey(i,e):s??i}if(r&&this.data[a]){const c=this.data[a];return Array.isArray(c)?c.map(u=>pr(u,this.data,o)):pr(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[i];return Array.isArray(c)?c.map(u=>pr(u,this.data,o)):pr(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=E.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};fn=MM([lo(),D(ps)],fn);const Zr={registration:{[ps]:{class:fn,singleton:!1}},type:ps,predicate:Ie(ps),factory:he.Factory.create(ps)};var TM=Object.defineProperty,SM=Object.getOwnPropertyDescriptor,fh=(t,e,s,r)=>{for(var o=r>1?void 0:r?SM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&TM(e,s,o),o};const gs="translation-container-model",$M=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function OM(t,e){const s=this.descriptor.namespaces[t];if(!s)throw new Error("namespace "+t+" not found in descriptor");const r=s.basePath,o=s.locales[e].file;return $M([r,o])}let Jr=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||OM.bind(this),s.kosContext.set(uh,this.resolver),this.logger=s.logger,this._models=new Fe({parentId:t})}set currentLocale(t){this.lang=t,this.models.data.forEach(e=>{e.currentLocale=t})}get defaultNamespace(){return this._defaultNamespace?this.getModel("translation-"+this._defaultNamespace):void 0}getModel(t){return this.logger.debug("getting model "+t),this._models.getModel("translation-"+t)}get models(){return this._models}get data(){return this._models.data}async reload(){for(const t of this.namespaces){const e=this.resolveNamespace(t);await ye(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=Zr.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)||te(()=>{this.namespaces.push(t)}),n}else{this.logger.warn("namespace "+t+" not found in descriptor");const r=Zr.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)}};fh([Oe],Jr.prototype,"_models",2);Jr=fh([D(gs)],Jr);const Ve={registration:{[gs]:{class:Jr,singleton:!0}},type:gs,predicate:Ie(gs),factory:he.Singleton.create(gs)},IM={set(t,e){const s=Q.getContext(Ve.type);s&&s.set(t,e)},get(t){const e=Q.getContext(Ve.type);return e==null?void 0:e.get(t)}},ph={async init(t){const e=Ve.factory(t);return await ye(e),{translations:e}}},gh="kos-ws-event",Ni=Jt(gh);var CM=Object.defineProperty,DM=Object.getOwnPropertyDescriptor,Ui=(t,e,s,r)=>{for(var o=r>1?void 0:r?DM(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&&CM(e,s,o),o};const xM=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=E.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){g.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:xM({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),g.debug(`logged ${this.events.size} events`)}}};Ui([B({topic:[Ws.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);Ui([B({topic:[Ws.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=Ui([D(Ni.type)],exports.WsEventModel);const AM=()=>({...{[ts.type]:{class:Vu},[st.type]:{class:Gu,singleton:!0},...ae.registration,...Et.registration,...Ht.registration,...Zr.registration,...Ve.registration,[Ni.type]:{class:exports.WsEventModel,singleton:!0},...Ls.registration,...mi.registration,...Fr.registration}}),ji=AM(),RM={models:ji,preloadModels:[]},PM=!0,mh=t=>()=>{const e=ji;return al(pn)(Ks).model(Ht).model(Vt).model(zs).model(Yr).model(Kr).model(Rs).model(eo).model(wi).model(Hs).model(zt).model(Ci).model(od).model(yi,PM).model(tr).model(ad),Object.keys(e).forEach(s=>{const r=e[s];il(pn)(s,r)}),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t)}},$e={};$e.core={models:mh($e)};$e.preload=R.model.preloadModel($e);$e.model=R.model.register($e);$e.companion=R.companion.register($e);$e.legacy=R.model.registerLegacyModel($e);const pn=$e;class kM{registerTroubleRankMapper(e,s){return T.propertyMapper.registerPropertyMapper(se.TroubleRank,e,s),this}registerTroubleRoleMapper(e,s){return T.propertyMapper.registerPropertyMapper(se.TroubleRole,e,s),this}registerTroubleColorMapper(e,s){return T.propertyMapper.registerPropertyMapper(se.TroubleColor,e,s),this}registerModelLoader(e,s,r){T.loader.registerLoader(e,s,r)}registerRegionServicePathMapper(e){return T.propertyMapper.registerPropertyMapper(se.RegionServicePath,e),this}registerCanvasPatternLoader(e,s){T.loader.registerLoader(zt.loader,e,s)}registerConfigServicePathMapper(e){return T.propertyMapper.registerPropertyMapper(se.ConfigServicePath,e),this}}const LM=async(t,e)=>{const s=wi.instance(t).options({}).build(),r=e?`${e}-`:"";return await ye(s),{getState:o=>s.data[`${r}${o}`],updateState:async(o,n)=>{await s.updateState(`${r}${o}`,n)},clean:async()=>{for(const o of s.data.keys)await s.updateState(`${r}${o}`,void 0)},unsubscribe:()=>{Re(s)}}},yh="kos:service:region",bh="regionId",FM=`${yh}-${bh}`,vh=async t=>{const e=Et.factory(FM)({path:yh,attribute:bh});await ye(e),e.updateProperty(t)};async function NM(){const{default:t}=await Promise.resolve().then(()=>Wn);return t}function UM(t){return Ye(t)}const Va=De(),jM=Object.freeze(Object.defineProperty({__proto__:null,api:Va,default:Va,kosServiceRequest:UM},Symbol.toStringTag,{value:"Module"}));function BM(t){return Ye(t)}const Ga=De(),KM=Object.freeze(Object.defineProperty({__proto__:null,api:Ga,default:Ga,kosServiceRequest:BM},Symbol.toStringTag,{value:"Module"}));function wh(t){return Ye(t)}const gn=De(),HM=Object.freeze(Object.defineProperty({__proto__:null,api:gn,default:gn,kosServiceRequest:wh},Symbol.toStringTag,{value:"Module"}));function qM(t){return Ye(t)}const Ya=De(),zM=Object.freeze(Object.defineProperty({__proto__:null,api:Ya,default:Ya,kosServiceRequest:qM},Symbol.toStringTag,{value:"Module"}));function VM(t){return Ye(t)}const Wa=De(),GM=Object.freeze(Object.defineProperty({__proto__:null,api:Wa,default:Wa,kosServiceRequest:VM},Symbol.toStringTag,{value:"Module"}));function YM(t){return Ye(t)}const Qa=De(),WM=Object.freeze(Object.defineProperty({__proto__:null,api:Qa,default:Qa,kosServiceRequest:YM},Symbol.toStringTag,{value:"Module"}));function QM(t){return Ye(t)}const Xa=De(),XM=Object.freeze(Object.defineProperty({__proto__:null,api:Xa,default:Xa,kosServiceRequest:QM},Symbol.toStringTag,{value:"Module"}));function ZM(t){return Ye(t)}const Za=De(),JM=Object.freeze(Object.defineProperty({__proto__:null,api:Za,default:Za,kosServiceRequest:ZM},Symbol.toStringTag,{value:"Module"})),Bi="/kos-timer-event",Ki="/kos-timer-event/tick",Hi="defaultTimerEnd",ms=g.createLogger({name:"timer-manager"}),e_=t=>t.updateProperty!==void 0;class Eh{constructor(e,s,r){l(this,"name");l(this,"timeout");l(this,"timer");l(this,"state","inactive");l(this,"decrementValue",1);l(this,"remainingTime");l(this,"timeoutActions",new Map);this.name=e;const o=typeof s=="number"?s:s.value||60;this.timeout=o,this.state="inactive",this.remainingTime=o,e_(s)&&X(()=>{g.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:Hi}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){ms.debug(`Timer ${this.name} already started`);return}(this.state==="inactive"||this.state==="paused")&&(this.state="active",this.timer=setInterval(()=>this.updateTimer(),1e3))}pause(){this.timer&&(ms.debug(`Pausing timer ${this.name}`),this.state="paused",clearInterval(this.timer))}restart(){this.pause(),this.remainingTime=this.timeout,this.start()}reset(){this.pause(),this.remainingTime=this.timeout,this.state="inactive"}updateTimeout(e){this.timeout=e,this.restart()}addTimeoutAction(e){const s=e.remainingTime??0;this.timeoutActions.has(s)||this.timeoutActions.set(s,[]);const r=e.name,o=this.timeoutActions.get(s).find(n=>n.name===r);o?o.action=e.action:this.timeoutActions.get(s).push(e)}removeTimeoutAction(e){for(const[s,r]of this.timeoutActions.entries()){const o=r.filter(n=>n.name!==e);o.length===0?this.timeoutActions.delete(s):this.timeoutActions.set(s,o)}}updateTimer(){if(this.remainingTime=Math.round((this.remainingTime-this.decrementValue)*100)/100,this.remainingTime<=0){this.state==="active"&&this.executeActions(0),this.pause();return}this.state==="active"&&this.executeActions(this.remainingTime)}executeActions(e){this.timeoutActions.has(e)&&this.timeoutActions.get(e).forEach(s=>{var r;ms.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(ms.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){H(`${Ki}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){H(Bi,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const ys=new Map,Dt=(t,e)=>{const s=ys.get(t);if(!s){ms.error(`Timer ${t} not found`);return}e(s)},Mh={createRelativeTimer(t,e,s){const r=new Date,o=Math.round((e.getTime()-r.getTime())/1e3);return this.createTimer(t,o,s)},createTimer(t,e=60,s){if(ys.has(t))return ys.get(t);const r=new Eh(t,e,s);return ys.set(t,r),r},getTimer(t){return ys.get(t)},clearTimer(t){Dt(t,e=>e.pause())},restartTimer(t){Dt(t,e=>e.restart())},resetTimer(t){Dt(t,e=>e.reset())},addTimeoutAction(t,e){Dt(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){Dt(t,s=>s.removeTimeoutAction(e))},startTimer(t){Dt(t,e=>e.start())}},_h="kos:service:region:settings",Th="timeZone",t_=`${_h}-${Th}`,mn=async t=>{const e=Et.factory(t_)({path:_h,attribute:Th});await ye(e),e.updateProperty(t)};function s_(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 Yo=g.createLogger({name:"software-info-service",group:"Services"}),r_=Ri(),qi=async t=>{Yo.debug("sending GET for software-info");const[e,s]=await kd.get("/api/kos/manifest/info",void 0,{signal:t,destinationAddress:r_});if(!s)throw t!=null&&t.aborted?(Yo.debug("Request was aborted"),new z("Request was aborted")):(Yo.error("Failed to fetch software-info",e),new z("Failed to fetch software-info"));return s},o_=s_(qi),n_=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:qi,getSoftwareInfosWithCancel:o_},Symbol.toStringTag,{value:"Module"}));var i_=Object.getOwnPropertyDescriptor,a_=(t,e,s,r)=>{for(var o=r>1?void 0:r?i_(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const bs="software-info-model";let yn=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 qi(),e=(t==null?void 0:t.nodes)||{};te(()=>{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 z&&this.logger.error("Failed to fetch software-info",t)}}};yn=a_([D(bs)],yn);const eo={registration:{[bs]:{class:yn,singleton:!1}},type:bs,predicate:Ie(bs),factory:he.Factory.create(bs)};function c_(t){return(t==null?void 0:t.troubles)!==void 0&&(t==null?void 0:t.troubles)instanceof Array&&(t==null?void 0:t.troublesByType)!==void 0&&typeof(t==null?void 0:t.troublesByType)=="object"}const kt=g.createLogger({name:"services",group:"Services"}),l_=async(t,e)=>Sh(t,e,`${exports.BASE_URL}/api/server/login`),Sh=async(t,e,s=`${exports.BASE_URL}/api/login`)=>{const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({email:t,password:e})});if(!r.ok){const n=await r.json();throw Error(`${n==null?void 0:n.error}`)}return await r.json()},u_=async t=>$h(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),$h=async(t,e=`${exports.BASE_URL}/api/startPasswordReset`,s="server")=>{const r=await exports.kosFetch(`${e}?email=${t}`,{method:"POST",destinationAddress:s});if(!r.ok)throw Error(`There was a problem reseting config; returned status ${r.status}`);return await r.json()},d_=async(t,e)=>Oh(t,e,`${exports.BASE_URL}/api/server/resetPassword`),Oh=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{kt.debug(`resetting password with token ${t} and password ${e.replace(/./g,"*")}`);const r=await exports.kosFetch(`${s}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e})});if(kt.debug(`password reset returned status ${r.status}`),!r.ok){kt.error(`password reset failed with message ${r.statusText}`);const n=await r.json();throw Error(`${n==null?void 0:n.error}:There was a problem resetting the password.`)}return await r.json()},h_=async(t,e,s)=>Ih(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),Ih=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{kt.debug(`accepting invite with token ${t} and password ${e.replace(/./g,"*")}`);const o=await exports.kosFetch(`${r}`,{method:"POST",destinationAddress:"",body:JSON.stringify({token:t,password:e,name:s})});if(kt.debug(`invitation accept returned status ${o.status}`),!o.ok){kt.error(`invite failed with message ${o.statusText}`);const i=await o.json();throw Error(`${i==null?void 0:i.error}:There was a problem accepting the invite.`)}return await o.json()};function f_(t,e,s,r){const o=t instanceof Promise?{promise:t,abortController:e,cancelFuture:s,future:r}:t,{promise:n,abortController:i,cancelFuture:a,future:c}=o,u=n;let d=0,h="PENDING",f=!0;const p=new Set;let y;return c&&typeof c=="object"&&(y=E.autorun(()=>{const v=c.progress||0,M=c.status||"PENDING",$=!c.endState;(v!==d||M!==h||$!==f)&&(d=v,h=M,f=$,p.forEach(U=>{try{U(d,h)}catch(x){console.warn("Progress callback error:",x)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(v=>{try{v(d,h)}catch(M){console.warn("Progress callback error:",M)}})),y&&y(),p.clear()}),u.cancel=async()=>{i&&!i.signal.aborted&&i.abort(),a&&await a(),f=!1,h="CANCELLED",p.forEach(v=>{try{v(d,h)}catch(M){console.warn("Progress callback error:",M)}}),y&&y()},u.getController=()=>i,u.isCancelled=()=>(i==null?void 0:i.signal.aborted)??!1,Object.defineProperty(u,"progress",{get:()=>d,enumerable:!0}),Object.defineProperty(u,"status",{get:()=>h,enumerable:!0}),Object.defineProperty(u,"isRunning",{get:()=>f,enumerable:!0}),u.onProgressUpdate=v=>(p.add(v),v(d,h),()=>p.delete(v)),u}var p_=Object.defineProperty,g_=Object.getOwnPropertyDescriptor,m_=(t,e,s)=>e in t?p_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,y_=(t,e,s,r)=>{for(var o=r>1?void 0:r?g_(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},b_=(t,e,s)=>(m_(t,e+"",s),s);const v_="gpio-pin-model";let to=class{constructor(t,e){l(this,"id");l(this,"pinNum");l(this,"chipNum");l(this,"name");l(this,"status");l(this,"connected");this.id=t,this.chipNum=e.chipNum,this.pinNum=e.pinNum,this.name=e.name,this.status="free",this.connected=e.connected??!1}updateModel(t){this.status=t.status??this.status,this.connected=t.connected??this.connected}async init(){this.logger.debug(`initializing gpio-pin ${this.id}`)}async load(){this.logger.debug(`loading gpio-pin ${this.id}`)}};b_(to,"Registration");to=y_([D({modelTypeId:v_,singleton:!1}),Qt()],to);const zi=to.Registration;var w_=Object.defineProperty,E_=Object.getOwnPropertyDescriptor,M_=(t,e,s)=>e in t?w_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,__=(t,e,s,r)=>{for(var o=r>1?void 0:r?E_(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},T_=(t,e,s)=>(M_(t,e+"",s),s);const S_="gpio-pin-container-model";let so=class{constructor(t,e){l(this,"id");this.id=t}updateModel(t){}getPin(t){const e=this.data[t];if(!e){this.logger.warn(`Pin number ${t} not found in container ${this.id}`);return}if(e.pinNum!==t){this.logger.warn(`Pin number mismatch for pin ${e.id} in container ${this.id}: expected ${t}, got ${e.pinNum}`);return}return this.data[t]}async init(){this.logger.debug(`initializing gpio-pin-container container ${this.id}`)}async load(){this.logger.debug(`loading gpio-pin-container container ${this.id}`)}};T_(so,"Registration");so=__([D({modelTypeId:S_,singleton:!1}),uo({containerOptions:{sortKey:"pinNum"}}),Qt()],so);const Vi=so.Registration;Vi.addRelatedModel(zi);var Ch=Object.defineProperty,$_=Object.getOwnPropertyDescriptor,O_=(t,e,s)=>e in t?Ch(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Dh=(t,e,s,r)=>{for(var o=r>1?void 0:r?$_(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&&Ch(e,s,o),o},I_=(t,e,s)=>(O_(t,e+"",s),s);const C_="gpio-chip-model";let Vs=class{constructor(t,e){l(this,"id");l(this,"num");l(this,"devName");l(this,"name");l(this,"pinCount");l(this,"pinNames");l(this,"_pins");this.id=t,this.num=e.num,this.devName=e.devName,this.name=e.name,this.pinCount=e.pinCount,this.pinNames=e.pinNames,this._pins=Vi.instance(`${this.id}-pins`).options({}).build()}get pinManager(){return this._pins}updateModel(t){}async handleGpioChipLoad(){}async init(){this.logger.debug(`initializing gpio-chip ${this.id}`)}async load(){this.logger.debug(`loading gpio-chip ${this.id}`)}};I_(Vs,"Registration");Dh([Oe],Vs.prototype,"_pins",2);Vs=Dh([D({modelTypeId:C_,singleton:!1}),Qt()],Vs);const ro=Vs.Registration;g.createLogger({name:"gpio-chip-container-service",group:"Services"});const xh="/api/kos/gpio/chips",D_="/api/kos/gpio/pins",Ah=wh,Rh=gn,x_=Object.freeze(Object.defineProperty({__proto__:null,GPIO_CHIP_PATH:xh,GPIO_PIN_PATH:D_,gpioApi:Rh,gpioServiceRequest:Ah},Symbol.toStringTag,{value:"Module"}));var Ph=Object.defineProperty,A_=Object.getOwnPropertyDescriptor,R_=(t,e,s)=>e in t?Ph(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,kh=(t,e,s,r)=>{for(var o=r>1?void 0:r?A_(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&&Ph(e,s,o),o},P_=(t,e,s)=>(R_(t,e+"",s),s);const k_="gpio-chip-container-model";let Gs=class{constructor(t,e){l(this,"id");l(this,"destinationAddress");this.id=t,this.destinationAddress=e.destinationAddress??""}updateModel(t){}async handleGpioChipInit(t,e){const[s,r]=await Rh.get("/api/kos/gpio/pins",void 0,{destinationAddress:this.destinationAddress});if(s){this.logger.error("Failed to fetch GPIO pins",s);return}Object.entries(e).forEach(([n,i])=>{i.forEach(a=>{var u;if(!a.num&&a.num!==0){this.logger.warn("Skipping GPIO chip with missing number",a);return}const c=ro.instance(`${ro.type}-${a.num}}`).options({num:a.num,devName:a.devName??"",name:a.name??"",pinCount:a.pinCount??0,pinNames:a.pinNames??[]}).build();(u=a.pinNames)==null||u.forEach((d,h)=>{const f=zi.instance(`${c.name}-${d}`).options({name:d,pinNum:h,chipNum:a.num}).build();c.pinManager.addModel(f)}),this.addModel(c)})});const o=["bound","pending","invalid","free"];for(const n of o)Object.entries(r).forEach(([i,a])=>{var c;(c=a==null?void 0:a[n])==null||c.forEach(u=>{const d=u.pinNum,h=u.chipNum;if(h===void 0||d===void 0){this.logger.warn("Skipping pin with missing chipNum or pinNum",u);return}const f=this.data[h];if(!f||f.num!==h){this.logger.warn(`No chip model found for chipNum ${h} when processing pin ${d}`);return}const p=f.pinManager.getPin(d);if(!p){this.logger.warn(`No pin model found for pinNum ${d} in chipNum ${h}`);return}p.updateModel({connected:u.connected,status:n})})})}async init(){this.logger.debug(`initializing gpio-chip-container container ${this.id}`)}async load(){this.logger.debug(`loading gpio-chip-container container ${this.id}`)}};P_(Gs,"Registration");kh([Ah({path:xh,method:"get",errorHandler:{strategy:"log",defaultValue:[]},lifecycle:I.INIT,requestOptions:t=>({destinationAddress:t.destinationAddress})})],Gs.prototype,"handleGpioChipInit",1);Gs=kh([D({modelTypeId:k_,singleton:!0}),uo({containerOptions:{sortKey:"num"}}),Qt()],Gs);const Lh=Gs.Registration;Lh.addRelatedModel(ro);const Ja=g.createLogger({name:"studio-properties-service",group:"Services"}),L_="/api/kos/studio/properties",Fh=async t=>{if(Ja.debug("sending GET for studio-properties"),!t)throw Ja.error("connectionId is undefined"),new Error("connectionId is undefined");return await Ne.get(L_,{},{destinationAddress:t,timeout:500})},F_=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Fh},Symbol.toStringTag,{value:"Module"}));var N_=Object.getOwnPropertyDescriptor,U_=(t,e,s,r)=>{for(var o=r>1?void 0:r?N_(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Nh="studio-properties-model",j_="/kos/studio/properties",ec={"kos.studio.tool.legacy":1};let bn=class{constructor(t,e,s){l(this,"id");l(this,"connectionId");l(this,"unsubscribe",null);l(this,"logger");l(this,"data");this.id=t,this.logger=s.logger,this.data=Pe(),this.connectionId=e.connectionId}async init(){this.logger.debug(`initializing studio-properties ${this.id}`)}async load(){this.logger.debug(`loading studio-properties ${this.id}`)}async terminatePropertiesSession(){var t;(t=this.unsubscribe)==null||t.call(this)}async initializePropertiesSession(){this.unsubscribe=Lt.getInstance().subscribeTopic({topic:j_,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await Fh(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(ec);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??ec),g.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return si(()=>this.get(t))}};bn=U_([D(Nh)],bn);const B_=new Ee({class:bn,type:Nh}),K_=dt.keyframes`
|
|
146
146
|
0% {
|
|
147
147
|
left: -90px;
|
|
148
148
|
color: #eee;
|
|
@@ -212,7 +212,7 @@ ${c}topics:${e}
|
|
|
212
212
|
transform: translateX(100%) scaleX(0.5);
|
|
213
213
|
}
|
|
214
214
|
}
|
|
215
|
-
`;return _.jsxs("div",{css:o,children:[_.jsxs("div",{css:n,children:[_.jsx("div",{css:i,children:e}),_.jsx("div",{css:[a,t<0?c:""]})]}),_.jsx("div",{children:r})]})},Y_={setModel:()=>!1},xo=m.createContext(Y_),W_=()=>{const t=m.useContext(xo);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},Bh=({children:t})=>{const[e,s]=m.useState(),r=m.useCallback(o=>(s(o),!0),[s]);return _.jsx(xo.Provider,{value:{model:e,setModel:r},children:t})},Kh=g.createLogger({name:"kos-model-hierarchy-context"}),Q_={models:[],addModel:()=>{Kh.debug("Default implementation being used. Do Nothing.")}},Ao=m.createContext(Q_),X_=({children:t})=>{const[e,s]=m.useState([]),r=m.useCallback(o=>{e.includes(o)||(Kh.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[e]);return _.jsx(Ao.Provider,{value:{models:e,addModel:r},children:t})},Z_=()=>!0,Hh=t=>{const e=m.useContext(Ao);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||Z_;return m.useMemo(()=>e.models.filter(s),[e.models,s])},J_=t=>Hh({filter:s=>{const r=ke(s.id);return(r==null?void 0:r.type)===t}})[0],eT=g.createLogger({name:"kos-model-loader"}),tT=()=>_.jsx("div",{}),qh=({fallback:t,children:e,...s})=>_.jsx(Bh,{children:_.jsx(jh,{fallback:t,children:_.jsx(m.Suspense,{children:_.jsx(zh,{...s,children:e})})})}),zh=t=>{const[e,s]=m.useState(),[r,o]=m.useState(!1),{setModel:n}=m.useContext(xo),i=m.useContext(Ao);if(m.useEffect(()=>{t.model&&(s(t.model),n(t.model),o(!0),i&&i.addModel(t.model))},[i,t.model,n]),t.error)throw eT.error(t.error),new Error(t.error);const a=t.loading||_.jsx(tT,{});return _.jsx(_.Fragment,{children:e&&r?t.children:a})},_r={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Vh=m.createContext(_r),sT=({translations:t=_r,children:e})=>{const s={header:{..._r.header,...t.header},createModal:{..._r.createModal,...t.createModal}};return _.jsx(Vh.Provider,{value:s,children:e})};function rT(t,e){const s=S.create(t,!1,e),r=s.whenReady().then(()=>s);return xn(r)}const Gh=m.createContext(void 0),oT=(t={models:{},preloadModels:[]},e)=>{const s=rT(t,e),r=({children:o})=>{const n=s.read(),[i,a]=m.useState(n.isOnline);return m.useEffect(()=>{const c=X(()=>{a(n.isOnline)});return()=>{c()}},[n]),_.jsx(Gh.Provider,{value:{kosCore:n,online:i},children:o})};return{KosCoreContextProvider:Mn.observer(r)}},Yh=()=>{const t=m.useContext(Gh);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},nT=8,iT=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),ft=new Map;function aT(t,e){if(ft.has(t)){const s=ft.get(t);if(s.status==="finished"){const r=S.getInstance().modelManager.getModelById(t);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=e().then(()=>{ft.set(t,{status:"finished",key:t})},o=>{throw ft.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw ft.set(t,r),s}}function cT(t,e){return aT(t,e)}async function lT(t,e){const{modelId:s,factory:r,modelType:o,options:n,activate:i}=e;let a=0;await t.whenReady();let c;if(n){const d=typeof o=="string"?t.modelManager.getModelFactory(o):r;if(!d)throw Error("No Factory Specified. Cannot create a new instance");c=d.build(s,n)}const u=t.modelManager.getModelById(s);if(!u){if(a>nT)throw Error(`KOS Model ${s} has not been found`);await iT(a),a=a+1}return await(u==null?void 0:u.whenReady()),u?(c=u.modelData,{kosModel:u,model:c}):{kosModel:void 0,model:void 0}}const J=t=>{const{modelId:e,modelType:s,activate:r,destroyOnUnmount:o}=t,n=Yh(),[i,a]=m.useState(!1),[c,u]=m.useState(),{kosModel:d,model:h}=cT(e||s||"",()=>lT(n.kosCore,t));return m.useEffect(()=>{t.forceUpdate&&h&&zn(h)&&h.updateModel(t.options||{})},[h]),m.useEffect(()=>{async function f(){try{return await n.kosCore.whenReady(),r&&await(d==null?void 0:d.fsm.transitionTo(L.GO_ACTIVE,w.ACTIVE)),a(!0),d}catch(y){throw u(y.message),y}}let p;return n.kosCore&&e&&f().then(y=>{p=X(()=>{const v=(y==null?void 0:y.status)===w.READY;a(v)})}).catch(y=>{console.error(y)}),()=>{if(r){if(h!=null&&h.id){const y=n.kosCore.modelManager.getModelById(h.id);y==null||y.fsm.transitionTo(L.GO_INACTIVE,w.INACTIVE).then(()=>{if(o){const v=h.id;Re(h).then(()=>{ft.delete(v),p==null||p()})}})}}else o&&h&&Re(h).then(()=>{ft.delete(e),p==null||p()})}},[r,o,n.kosCore,d,h,e]),{model:h,ready:i,error:c,status:{model:h,ready:i,error:c},KosModelLoader:qh}},Gi=()=>{const t=
|
|
215
|
+
`;return _.jsxs("div",{css:o,children:[_.jsxs("div",{css:n,children:[_.jsx("div",{css:i,children:e}),_.jsx("div",{css:[a,t<0?c:""]})]}),_.jsx("div",{children:r})]})},Y_={setModel:()=>!1},xo=m.createContext(Y_),W_=()=>{const t=m.useContext(xo);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},Bh=({children:t})=>{const[e,s]=m.useState(),r=m.useCallback(o=>(s(o),!0),[s]);return _.jsx(xo.Provider,{value:{model:e,setModel:r},children:t})},Kh=g.createLogger({name:"kos-model-hierarchy-context"}),Q_={models:[],addModel:()=>{Kh.debug("Default implementation being used. Do Nothing.")}},Ao=m.createContext(Q_),X_=({children:t})=>{const[e,s]=m.useState([]),r=m.useCallback(o=>{e.includes(o)||(Kh.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[e]);return _.jsx(Ao.Provider,{value:{models:e,addModel:r},children:t})},Z_=()=>!0,Hh=t=>{const e=m.useContext(Ao);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||Z_;return m.useMemo(()=>e.models.filter(s),[e.models,s])},J_=t=>Hh({filter:s=>{const r=ke(s.id);return(r==null?void 0:r.type)===t}})[0],eT=g.createLogger({name:"kos-model-loader"}),tT=()=>_.jsx("div",{}),qh=({fallback:t,children:e,...s})=>_.jsx(Bh,{children:_.jsx(jh,{fallback:t,children:_.jsx(m.Suspense,{children:_.jsx(zh,{...s,children:e})})})}),zh=t=>{const[e,s]=m.useState(),[r,o]=m.useState(!1),{setModel:n}=m.useContext(xo),i=m.useContext(Ao);if(m.useEffect(()=>{t.model&&(s(t.model),n(t.model),o(!0),i&&i.addModel(t.model))},[i,t.model,n]),t.error)throw eT.error(t.error),new Error(t.error);const a=t.loading||_.jsx(tT,{});return _.jsx(_.Fragment,{children:e&&r?t.children:a})},_r={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},Vh=m.createContext(_r),sT=({translations:t=_r,children:e})=>{const s={header:{..._r.header,...t.header},createModal:{..._r.createModal,...t.createModal}};return _.jsx(Vh.Provider,{value:s,children:e})};function rT(t,e){const s=S.create(t,!1,e),r=s.whenReady().then(()=>s);return xn(r)}const Gh=m.createContext(void 0),oT=(t={models:{},preloadModels:[]},e)=>{const s=rT(t,e),r=({children:o})=>{const n=s.read(),[i,a]=m.useState(n.isOnline);return m.useEffect(()=>{const c=X(()=>{a(n.isOnline)});return()=>{c()}},[n]),_.jsx(Gh.Provider,{value:{kosCore:n,online:i},children:o})};return{KosCoreContextProvider:Mn.observer(r)}},Yh=()=>{const t=m.useContext(Gh);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},nT=8,iT=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),ft=new Map;function aT(t,e){if(ft.has(t)){const s=ft.get(t);if(s.status==="finished"){const r=S.getInstance().modelManager.getModelById(t);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=e().then(()=>{ft.set(t,{status:"finished",key:t})},o=>{throw ft.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw ft.set(t,r),s}}function cT(t,e){return aT(t,e)}async function lT(t,e){const{modelId:s,factory:r,modelType:o,options:n,activate:i}=e;let a=0;await t.whenReady();let c;if(n){const d=typeof o=="string"?t.modelManager.getModelFactory(o):r;if(!d)throw Error("No Factory Specified. Cannot create a new instance");c=d.build(s,n)}const u=t.modelManager.getModelById(s);if(!u){if(a>nT)throw Error(`KOS Model ${s} has not been found`);await iT(a),a=a+1}return await(u==null?void 0:u.whenReady()),u?(c=u.modelData,{kosModel:u,model:c}):{kosModel:void 0,model:void 0}}const J=t=>{const{modelId:e,modelType:s,activate:r,destroyOnUnmount:o}=t,n=Yh(),[i,a]=m.useState(!1),[c,u]=m.useState(),{kosModel:d,model:h}=cT(e||s||"",()=>lT(n.kosCore,t));return m.useEffect(()=>{t.forceUpdate&&h&&zn(h)&&h.updateModel(t.options||{})},[h]),m.useEffect(()=>{async function f(){try{return await n.kosCore.whenReady(),r&&await(d==null?void 0:d.fsm.transitionTo(L.GO_ACTIVE,w.ACTIVE)),a(!0),d}catch(y){throw u(y.message),y}}let p;return n.kosCore&&e&&f().then(y=>{p=X(()=>{const v=(y==null?void 0:y.status)===w.READY;a(v)})}).catch(y=>{console.error(y)}),()=>{if(r){if(h!=null&&h.id){const y=n.kosCore.modelManager.getModelById(h.id);y==null||y.fsm.transitionTo(L.GO_INACTIVE,w.INACTIVE).then(()=>{if(o){const v=h.id;Re(h).then(()=>{ft.delete(v),p==null||p()})}})}}else o&&h&&Re(h).then(()=>{ft.delete(e),p==null||p()})}},[r,o,n.kosCore,d,h,e]),{model:h,ready:i,error:c,status:{model:h,ready:i,error:c},KosModelLoader:qh}},Gi=()=>{const t=Fr.type;return J({modelId:t,modelType:Fr.type,options:{}})},Yi=m.createContext(void 0),uT=({children:t})=>{const{model:e,ready:s}=Gi(),r=m.useMemo(()=>s&&e?{model:e}:{},[s,e]);return _.jsx(Yi.Provider,{value:r,children:t})},dT=()=>{const t=m.useContext(Yi);if(!t)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return t},Wi=()=>{const t=eo.type;return J({modelId:t,modelType:eo.type,options:{}})};function hT(t){return()=>e=>{const{model:s,status:r,KosModelLoader:o}=Wi();return _.jsx(o,{...r,children:_.jsx(t,{...e,softwareInfo:s})})}}const Qi=m.createContext(void 0),fT=({children:t})=>{const{model:e,ready:s}=Wi(),r=m.useMemo(()=>s&&e?{model:e}:{},[s,e]);return _.jsx(Qi.Provider,{value:r,children:t})},pT=()=>{const t=m.useContext(Qi);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Wh=new pu,Qh=m.createContext(Wh);function gT({children:t}){return _.jsx(Qh.Provider,{value:Wh,children:t})}const Xi=m.createContext(void 0),mT=()=>{const t=window.location.origin,e=de();return(e==null?void 0:e.host)||t},yT=({children:t,appContext:e,locale:s="en",resolver:r,rootUrl:o,descriptorResolver:n})=>{const[i,a]=m.useState(!1),[c,u]=m.useState(),[d,h]=m.useState(),f=o||mT(),p=m.useMemo(()=>e??"app/system",[e]);m.useEffect(()=>{async function M(){const U=(Array.isArray(p)?p:[p]).map(V=>(n||lh(V))()),P=(await Promise.allSettled(U)).map(V=>{if(V.status==="rejected"){g.warn("Failed to load localization descriptor",V.reason);return}return V.value}).filter(V=>!!V).reverse().reduce((V,ee)=>{const K=ee.path;return Object.keys(ee.namespaces).forEach(as=>{const re=ee.namespaces[as];re.basePath=K}),{...V,namespaces:{...V.namespaces,...ee.namespaces}}},{});u(P)}M()},[p,n]),m.useEffect(()=>{async function M(){if(c){const $=f,{translations:U}=await ph.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:$});h(U),a(!0)}}M()},[s,c,r,f]);const y=m.useMemo(()=>i?{setLocale:M=>{d&&(d.currentLocale=M)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,d]),v=i?t:null;return _.jsx(Xi.Provider,{value:y,children:v})},bT=()=>{const t=m.useContext(Xi);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},vT=()=>{const t=zt.type;return J({modelId:t,modelType:zt.type,options:{}})};function wT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=vT();return _.jsx(o,{...r,children:_.jsx(t,{...e,canvasDispatcher:s})})}}const ET=(t,e,s)=>{const r=atob(t),o=new Uint8ClampedArray(e*s*4);for(let n=0,i=0;n<r.length&&i<o.length;n+=3,i+=4)o[i]=r.charCodeAt(n),o[i+1]=r.charCodeAt(n+1),o[i+2]=r.charCodeAt(n+2),o[i+3]=255;return o};function MT({ctx:t,format:e,dataString:s,width:r,height:o,pixelSize:n}){const i=ET(s,r,o),a=new ImageData(i,r,o),c=document.createElement("canvas");c.width=r,c.height=o;const u=c.getContext("2d");u==null||u.putImageData(a,0,0),t.imageSmoothingEnabled=!1,t.clearRect(0,0,r*n,o*n),t.drawImage(c,0,0,r*n,o*n)}const _T=g.createLogger({name:"canvas-streamer"});_T.debug("main-view component loaded");const Wo=10,Xh=Mn.observer(({canvasDispatcher:t,height:e=30,width:s=50,defaultFps:r=10,showPreview:o=!1,name:n,apiPath:i="/api/system/canvas"})=>{const a=m.useRef(null),[c,u]=m.useState();m.useEffect(()=>{const h=t.addNamedEndpoint(n,{apiPath:i,fps:r,width:s,height:e,id:n});u(h)},[t]);const d=m.useCallback(h=>{if(a.current&&o){const f=a.current.getContext("2d");f&&MT({ctx:f,format:"base64",dataString:h,height:e,width:s,pixelSize:Wo})}},[s,e,o]);return m.useEffect(()=>{c&&(c.onFrame=d,c.width=s,c.height=e,c.fps=r)},[c,d,s,e,r]),o&&sc.createPortal(_.jsx(ST,{children:_.jsx($T,{children:_.jsx("canvas",{ref:a,width:s*Wo,height:e*Wo,style:{border:"1px solid black"}})})}),document.body)}),TT=wT(Xh),ST=En.div`
|
|
216
216
|
display: flex;
|
|
217
217
|
flex-direction: column;
|
|
218
218
|
gap: 8px;
|
|
@@ -224,5 +224,5 @@ ${c}topics:${e}
|
|
|
224
224
|
display: flex;
|
|
225
225
|
flex-direction: column;
|
|
226
226
|
align-items: center;
|
|
227
|
-
`,Zh=()=>{const t=Xr.type;return J({modelId:t,modelType:Xr.type,options:{}})};function OT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Zh();return _.jsx(o,{...r,children:_.jsx(t,{...e,device:s})})}}function IT(t,e,s){const r=new Promise(o=>{S.getInstance().whenReady().then(()=>{const{model:n}=S.getInstance().modelManager.createModelInstance(t,e??t,s);return n.whenReady().then(()=>{o(n.modelData)})})});return xn(r)}function CT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Gi();return _.jsx(o,{...r,children:_.jsx(t,{...e,kosTime:s})})}}const Jh=()=>{const t=Hs.type;return J({modelId:t,modelType:Hs.type,options:{}})};function DT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Jh();return _.jsx(o,{...r,children:_.jsx(t,{...e,networkInterfaceContainer:s})})}}const ef=()=>{const t=jr.type;return J({modelId:t,modelType:jr.type,options:{}})};function xT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=ef();return _.jsx(o,{...r,children:_.jsx(t,{...e,oTA:s})})}}function AT(t,e){m.useEffect(()=>{function s(o){t.current&&!t.current.contains(o.target)&&e()}function r(o){o.key==="Escape"&&e()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[t,e])}function RT(t){const e=m.useRef(null),s=t.onAlert;return AT(e,s),_.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const PT=t=>{var u;const{stateProp:e}=t,[s,r]=m.useState((u=t.stateProp)==null?void 0:u.value),[o,n]=m.useState(!1),[i,a]=m.useState(void 0);return m.useEffect(()=>{async function d(h){try{h&&(await ye(h),n(!0))}catch(f){a(f.message)}}d(e)},[e]),m.useEffect(()=>{const d=X(()=>{e&&o&&r(e.value)});return()=>{d()}},[o,e]),[s,{ready:o,error:i}]},tf=()=>{const[t,e]=m.useState(!1),[s,r]=m.useState([]),o=Vt.type,n=J({modelId:o,modelType:Vt.type,options:{}});return m.useEffect(()=>{const i=X(()=>{var a,c;e(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:t,devices:s}};function kT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=tf();return _.jsx(o,{...r,children:_.jsx(t,{...e,storageDeviceContainer:s})})}}const Qo=g.createLogger({name:"use-timer"}),LT=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=Mh.getTimer(t);m.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const u=C(Bi,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===t&&(f===Hi?e({name:h,action:f,remainingTime:p,timer:n}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:p,timer:n}))});return o&&n.start(),()=>{u.unsubscribe()}},[o,e,r,t,n]),m.useEffect(()=>{if(!n||!s)return;const u=`${Ki}/${t}`,d=C(u,h=>{const{name:f,remainingTime:p}=h==null?void 0:h.body;f===t&&s({name:f,remainingTime:p,timer:n})});return()=>{d.unsubscribe()}},[s,t,n]);const i=m.useCallback(()=>{n?n.start():Qo.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=m.useCallback(()=>{n?n.reset():Qo.warn(`Timer with name ${t} does not exist.`)},[n,t]),c=m.useCallback(()=>{n?n.pause():Qo.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:c}},FT=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},NT=t=>t instanceof RegExp,UT=t=>typeof t=="string",jT=(t,e,s)=>{if(t===""||e==="")return t;let r=e;NT(r)||(r=new RegExp("("+FT(r)+")","gi"));const o=t.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},sf=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>UT(o)?jT(o,e,s):o)};function BT(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=sf(s,n,(i,a)=>o.type==="br"?_.jsx("br",{}):m.cloneElement(o,{key:`${r}-${a}`},i))}),s}const KT=t=>{const{i18nKey:e,t:s,defaults:r,components:o,values:n={},context:i}=t,a=s(e,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=BT(a,o||{});return _.jsx("span",{className:t.className,children:c})},xt=new Map;function HT(t,e){if(xt.has(t)){const s=xt.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{xt.set(t,{status:"finished",result:o})},o=>{throw xt.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw xt.set(t,r),s}}function vn(t,e){return HT(t,e)}const qT=async()=>{const t=await rl(Ve.type);return await ye(t.model),t.model},zT=async(t,e,s)=>{const r=t.resolveNamespace(e);await ye(r);for(const o of s){const n=t.resolveNamespace(o);await ye(n),xt.set(o,{status:"finished",result:n})}return r},VT=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=vn(Ve.type,qT),i=s.join("__"),a=vn(i,()=>zT(n,r,o)),c=m.useMemo(()=>({exists:d=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:m.useCallback((d,h)=>{const f=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(g.debug(`Translation model ${t} not ready for key: ${f}`),f)},[e==null?void 0:e.keyPrefix,t,a]),i18n:c}},rf=()=>{const t=Ve.type;return J({modelId:t,modelType:Ve.type,options:{}})};function GT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=rf();return _.jsx(o,{...r,children:_.jsx(t,{...e,translationContainer:s})})}}const YT=t=>J({modelId:t,modelType:Bs.type}),Zi=()=>J({modelId:Ht.type,modelType:Ht.type,options:{}}),WT=({troubleType:t,condition:e})=>{const{model:s}=Zi(),[r,o]=m.useState(!1),[n,i]=m.useState([]),a=m.useCallback(()=>{var c,u;return n.length>0&&((c=n[0])!=null&&c.resolvable)?(u=n[0])==null?void 0:u.resolve():Promise.resolve(void 0)},[n]);return m.useEffect(()=>X(()=>{const u=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],d=e?u.filter(e):u;o(d.length>0),i(d)}),[e,s,t]),[r,a,n.length>0?n[0]:void 0,n]};function QT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Zi();return _.jsx(o,{...r,children:_.jsx(t,{...e,troubleContainer:s})})}}const of=()=>{const t=zs.type,e=J({modelId:t,modelType:zs.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=m.useState(!1),[o,n]=m.useState(!1),[i,a]=m.useState([]);return m.useEffect(()=>{const c=X(()=>{var u,d,h;r(((u=e.model)==null?void 0:u.isUsbInserted)??!1),n(((d=e.model)==null?void 0:d.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{c()}},[e.model]),{...e,inserted:s,updateAvailable:o,updates:i}};function XT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=of();return _.jsx(o,{...r,children:_.jsx(t,{...e,usbUpdateContainer:s})})}}const ZT=({path:t,propKey:e})=>{const{status:s}=J({modelType:Rs.type,modelId:t,options:{path:t}}),[r,o]=m.useState(!1),[n,i]=m.useState(),[a,c]=m.useState(""),[u,d]=m.useState(),h=f=>{n&&e&&n.updateProperty(e,f)};return m.useEffect(()=>{var f;s.model&&i(s.model),s.model&&e&&((f=s.model)!=null&&f.props.has(e)?c(s.model.props[e]):d(`property ${e} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,e]),m.useEffect(()=>{e&&E.autorun(()=>{const f=n==null?void 0:n.props[e];c(f||"")})},[n,e]),{config:n,ready:r,value:a,error:u,updateValue:h}},JT=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},nf=({configProperty:t,optionsTransformer:e})=>{const[s,r]=m.useState(!1),[o,n]=m.useState(""),[i,a]=m.useReducer(JT,{value:String(t==null?void 0:t.value),displayValue:t==null?void 0:t.displayValue,significantValue:t==null?void 0:t.significantValue,unit:t==null?void 0:t.unit,options:t==null?void 0:t.options,mappedOptions:[],updateProperty:t==null?void 0:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}),c=m.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&(t==null||t.updateProperty(d))},[t]);return m.useEffect(()=>{async function u(d){try{d&&(await ye(d),r(!0))}catch(h){n(h.message)}}u(t)},[t]),m.useEffect(()=>{const u=X(()=>{if(t&&s){let d=[];e&&(d=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:d,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{u()}},[t,e,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function eS(t,e){const s=e??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return t===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[t]??0}function tS(t,e){return new Date(t,e,0).getDate()}function af(t,e){const s=eS(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function cf(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function lf(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function uf(t,e=[2018,2028]){const s=lf(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function Ji(t="numeric",e="en-US"){const s=new Intl.DateTimeFormat(e,{month:t,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function sS({locale:t="en-US",year:e,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(e,i,r),c=new Intl.DateTimeFormat(t,{month:o.month}).format(a),u=new Intl.DateTimeFormat(t,{year:o.year}).format(a),d=new Intl.DateTimeFormat(t,{day:o.day}).format(a);return n?n=="MMDDYY"?`${c} ${d} ${u}`:n==="DDMMYY"?`${d} ${c} ${u}`:n==="YYMMDD"?`${u} ${c} ${d}`:`${u} ${d} ${c}`:new Intl.DateTimeFormat(t,o).format(a)}function _e(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function rS(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function df(t,e,s){const r=_e(e),o=new Date(r,t,1).getDay(),n=new Date(r,t+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function vs(t,e,s){const r=e-1,o=new Date(t,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function ws(t,e){return new Date(t,e,0).getDate()}function hf(t="en-US",e="short"){const s=new Intl.DateTimeFormat(t,{weekday:e}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function ff({locale:t="en-US",year:e=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:o=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=ea(n,r),u=pf(n,r,t),d=gf(i,t),h=mf(i,t),f=ta(e,s),p=yf(e,s,t,o),y=wf(s,e,p),v=bf(t,a);return{daysArray:f,monthsArray:d,yearsArray:c,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:y,dayNamesArray:v}}function ea(t="long",e=[2018,2028]){return m.useMemo(()=>uf(t,e),[t,e])}function pf(t="long",e=[2018,2028],s="en-US"){const r=ea(t,e);return m.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function gf(t,e="en-US"){return m.useMemo(()=>Ji(t,e),[t,e])}function mf(t,e="en-US"){const s=m.useMemo(()=>cf(),[]),r=m.useMemo(()=>Ji(t,e),[t,e]);return m.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function ta(t,e){const s=_e(t);return m.useMemo(()=>af(s,e),[e,s])}const oS=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function yf(t,e,s="en-US",r=[]){const o=ta(t,e);return m.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:oS(t,e,i,r)})),[r,s,e,o,t])}function bf(t="en-US",e="short"){return m.useMemo(()=>hf(t,e),[t,e])}function vf({year:t=new Date().getFullYear(),month:e=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=e,n=new Date(t,o,s);return{formattedDate:Xe.format(n,r)}}function wf(t,e,s){return m.useMemo(()=>df(t,e,s),[t,e,s])}var Ef=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(Ef||{});function nS({locale:t="en-US",date:{year:e=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:o="long",monthFormat:n="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:u=[]}={}}){const[d,h]=m.useState(e),[f,p]=m.useState(c),[y,v]=m.useState(s),[M,$]=m.useState(r);m.useEffect(()=>{h(e)},[e]),m.useEffect(()=>{v(s)},[s]),m.useEffect(()=>{$(r)},[r]);const{yearsArray:U,yearsOptionsArray:x,monthsArray:O,monthsOptionsArray:P,daysArray:V,daysOptionsArray:ee,calendarDayArray:K,dayNamesArray:as}=ff({locale:t,year:d,yearRange:f,month:y,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:re}=vf({year:d,month:y,day:M,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:v,setDay:$,nextMonth:()=>{const ne=y<11?_e(d):_e(d+1),pe=y<11?y+1:0;if(!vs(ne,pe,M)){const nt=ws(ne,pe);$(nt)}pe===0&&h(ne),v(pe)},previousMonth:()=>{const ne=_e(y===0?d-1:d),pe=y===0?11:y-1;if(!vs(ne,pe,M)){const nt=ws(ne,pe);$(nt)}pe===11&&h(ne),v(pe)},nextYear:()=>{const ne=d<f[1]?d+1:f[0],pe=_e(ne);if(vs(pe,y,M))h(ne);else{const nt=ws(_e(d+1),y);$(nt),h(ne)}},previousYear:()=>{const ne=d>f[0]?d-1:f[0],pe=_e(ne);if(vs(pe,y,M))h(ne);else{const nt=ws(_e(d-1),y);$(nt),h(ne)}}},dateState:{year:d,yearRange:f,month:y,day:M,yearsArray:U,yearsOptionsArray:x,monthsArray:O,monthsOptionsArray:P,daysArray:V,daysOptionsArray:ee,calendarDayNames:as,calendarDayArray:K,formattedDate:re}}}function Mf({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[o,n]=m.useState("Formatting Time..."),[i,a]=m.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:u,ready:d}=J({modelId:ae.type,modelType:ae.type,options:{}}),h=typeof t=="string"?Xe.parseISO(t):t;return m.useEffect(()=>{c?a(""):e?a(Xe.format(h,e)):d&&a(Xe.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[c,t,e,h,u,d]),m.useEffect(()=>{s?n(Xe.format(h,s)):d&&n(Xe.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[t,s,h,u,d]),{formattedDate:i,formattedTime:o}}const _f=({secondsFromMidnight:t=0})=>{const[e,s]=m.useState(0),[r,o]=m.useState(0),[n,i]=m.useState(0),[a,c]=m.useState(new Date),{formattedTime:u}=Mf({date:a,options:{ignoreDateFormat:!0}});return m.useEffect(()=>{const d=Number(t),h=Math.floor(d/3600),f=Math.floor(d%3600/60),p=d%60;s(h),o(f),i(p);const y=new Date;y.setHours(0,0,0,0);const v=new Date(y.getTime()+d*1e3);c(new Date(v))},[t]),{hours:e,minutes:r,seconds:n,formattedTime:u,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},iS=({configProperty:t})=>{const{value:e}=nf({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=_f({secondsFromMidnight:s}),c=m.useRef();return m.useEffect(()=>{const u=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{t&&t.updateProperty(u.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[t,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function aS(t,e={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=e;m.useEffect(()=>{const o=()=>{try{t({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[t,s,r])}const cS=t=>_.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),lS=(t=cS)=>{const[e,s]=m.useState([]),[r,o]=m.useState(),{model:n,ready:i}=J({modelType:ae.type,modelId:ae.type,options:{}});m.useEffect(()=>{const c=X(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),m.useEffect(()=>{const c=X(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&o({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{c()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const a=m.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(n==null||n.setSelectedDateFormat(u))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(c=>c.id))??[],regionModel:n,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:e}}},uS=t=>_.jsx("option",{title:t,value:t,children:t},t),Tf="kos:service:region:settings",Sf="timeZone",dS=`${Tf}-${Sf}`,hS=(t=uS)=>{const[e,s]=m.useState([]),[r,o]=m.useState(""),{model:n,ready:i}=J({modelType:ae.type,modelId:ae.type,options:{}}),a=Et.factory(dS)({path:Tf,attribute:Sf});m.useEffect(()=>{const u=X(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&yn(n==null?void 0:n.timeZones[0])});return()=>{u()}},[n,i,t]),m.useEffect(()=>{const u=X(()=>{o(a.value||"")});return()=>{u()}},[a.value]);const c=m.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&yn(d)},[]);return{options:e,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:e}}},$f="kos:service:region",Of="regionId",fS=`${$f}-${Of}`,pS=t=>_.jsx("option",{title:t,value:t,children:t},t),If=(t=pS)=>{const[e,s]=m.useState([]),[r,o]=m.useState("factory"),{model:n,ready:i}=J({modelType:ae.type,modelId:ae.type}),a=Et.factory(fS)({path:$f,attribute:Of});m.useEffect(()=>{const u=X(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{u()}},[n,i,t]),m.useEffect(()=>{const u=X(()=>{o(a.value||"factory")});return()=>{u()}},[a.value]);const c=m.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&vh(d)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:e}}},gS=t=>_.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),mS=(t=gS)=>{const[e,s]=m.useState([]),[r,o]=m.useState(),{model:n,ready:i}=J({modelType:ae.type,modelId:ae.type,options:{}});m.useEffect(()=>{const c=X(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),m.useEffect(()=>{const c=X(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&o({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{c()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const a=m.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(n==null||n.setSelectedTimeFormat(u))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(c=>c.id))??[],regionModel:n,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:e}}},yS=(t,e)=>m.useMemo(()=>si(t),e),bS={config:{attributes:!0,childList:!0,subtree:!0}};function vS(t,e,s=bS){const[r,o]=m.useState(null);m.useEffect(()=>{if(!e||typeof e!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(e);o(n)},[e,s,o]),m.useEffect(()=>{if(!r)return()=>{};if(!t)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(t,n)}catch(i){g.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const Cf={validateStart:function(t){return!0},validateStop:function(t){const e=t.event.currentTarget.getBoundingClientRect(),[s,r]=t.xy;return s<e.left||s>e.right||r<e.top||r>e.bottom}},Xo=g.createLogger({name:"usePressGesture",group:"kos-hooks"});function wS({onPressed:t,onRelease:e,intersectionStrategy:s=Cf}){const r=m.useRef(!1),o=Nf.useGesture({onDragStart:c=>{Xo.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{Xo.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{Xo.info("onDragEnd",c.type),r.current&&e&&(e(),r.current=!1)}}),n=()=>{t&&t(),r.current=!0},i=()=>{r.current&&e&&(e(),r.current=!1)},a=()=>{r.current&&e&&(e(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const Df=()=>{const[t,e]=m.useState(!1),s=S.getInstance();return m.useEffect(()=>{const r=X(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function xf(t=!1,e="2-digit"){return m.useMemo(()=>{const s=t?12:24;return Array.from({length:s},(r,o)=>{const n=t&&o===0?12:o%s;return{id:o,label:e==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[e,t])}function wn(t,e="2-digit",s=0,r=0){return m.useMemo(()=>Array.from({length:t},(o,n)=>{const i=String(n+s);return{id:n+r,label:e==="2-digit"?i.padStart(2,"0"):i}}),[t,s,r,e])}function Af(t="en-US"){return m.useMemo(()=>["AM","PM"].map(e=>{const s=new Intl.DateTimeFormat(t,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(e==="AM"?0:12))[2].value;return{id:s,label:s}}),[t])}function Rf({formatOptions:{hour12:t=!0,hour:e="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=xf(t,e),i=wn(60,s),a=wn(60,r),c=Af(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function Pf(t,e){return Xe.format(t,e)}function kf({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=m.useState(e),i=m.useCallback(v=>{n(M=>{const $=new Date(M);return $.setHours(Number(v)),$})},[]),a=m.useCallback(v=>{n(M=>{const $=new Date(M);return $.setMinutes(Number(v)),$})},[]),c=m.useCallback(v=>{n(M=>{const $=new Date(M);return $.setSeconds(Number(v)),$})},[]),u=m.useCallback(v=>{const M=new Date(v);n(M)},[]),d=Pf(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:y}=Rf({formatOptions:t,locale:s});return{amPmOptions:y,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:c,setTime:u,time:new Date(o)}}const ES=t=>{const{regionModel:e}=If(),s=m.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return kf({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function MS(t,e,s={}){const{disposeOnUnmount:r=!0}=s,[o,n]=m.useState(!1),[i,a]=m.useState(void 0),c=m.useRef(null),u=m.useRef(!0),d=m.useRef(!1),h=m.useMemo(()=>{if(!u.current&&c.current&&r&&yr(c.current)){const p=c.current;Promise.resolve().then(()=>{yr(p)&&p.dispose()})}u.current=!1,d.current=!1;const f=t();return c.current=f,f},e);return m.useEffect(()=>{d.current||(fl(h)?(d.current=!0,n(!1),a(void 0),h.ready().then(()=>{n(!0)}).catch(f=>{a(f),n(!1)})):(n(!0),a(void 0)))},[h]),m.useEffect(()=>()=>{r&&c.current&&yr(c.current)&&c.current.dispose(),c.current=null},[r]),{viewModel:h,ready:o,error:i}}function _S(t){return e=>{const[s]=Df();return s?_.jsx(Uh,{message:"Wait a moment while your project reloads..."}):_.jsx(t,{...e})}}jf({"kos-ui-sdk":22});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>E.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>E.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>Mn.observer});exports.AncestorPathVisitor=vy;exports.AuthState=Gl;exports.BrowserKosRouter=gu;exports.BrowserRouter=gi;exports.CanvasDispatcher=zt;exports.CanvasDispatcherServices=jE;exports.CanvasRenderer=Ri;exports.CanvasStreamer=TT;exports.CanvasStreamerBase=Xh;exports.ChildModels=Je;exports.CompanionParentModel=et;exports.ConfigBean=Rs;exports.ContainerAwareSetup=Nn;exports.CoreExtensionManager=UM;exports.CoreModels=ji;exports.CreateModelTranslationsContext=Vh;exports.CreateModelTranslationsProvider=sT;exports.DateDisplayFormat=Ef;exports.DateHelpers=$y;exports.DependencyLifecycle=I;exports.DependencyModels=F;exports.DependencyResolutionPolicy=Ze;exports.Device=Xr;exports.DeviceServices=cM;exports.DomIntersectionStrategy=Cf;exports.EVENT_KOS_MODEL_READY=$n;exports.EVENT_TROUBLE_ADDED=ob;exports.EVENT_TROUBLE_REMOVED=nb;exports.EXTENSION_CANVAS_RENDERER=oe;exports.EXTENSION_FEATURE_FLAG_RESOLVER=ou;exports.EXTENSION_FUTURE_LIFECYCLE_WRAPPER=tl;exports.EXTENSION_TROUBLE_DATA_MAPPER=Nr;exports.EXTENSION_TROUBLE_MAPPER=sr;exports.ErrorBoundaryWithFallback=jh;exports.EventBus=qf;exports.EventBusFunctional=Vf;exports.EventBusState=Yf;exports.ExtensionException=mr;exports.ExtensionManager=T;exports.FUTURE_CONTAINER_MODEL_TYPE=Ku;exports.FUTURE_MODEL_TYPE=Uu;exports.FUTURE_NOT_ASSIGNED=oi;exports.FeatureFlagService=nu;exports.FetchError=z;exports.FutureAliases=Ts;exports.FutureContainerFactory=st;exports.FutureContainerModel=qu;exports.FutureContainerSetup=Pn;exports.FutureEndState=tt;exports.FutureFactory=ts;exports.FutureHandler=po;exports.FutureManager=mt;exports.FutureModel=Bu;exports.FutureService=Es;exports.GpioChip=ro;exports.GpioChipContainer=Lh;exports.GpioChipServices=x_;exports.GpioPin=zi;exports.GpioPinContainer=Vi;exports.HEADER_CACHE_CONTROL=ac;exports.HEADER_CONTENT_TYPE=ic;exports.HEADER_DESTINATION_ADDR=Ge;exports.HEADER_FOS_REQUEST_ID=cc;exports.HEADER_METHOD=oo;exports.HEADER_ORDERED=Tn;exports.HEADER_REQUEST_ID=Ys;exports.HEADER_REQUEST_TYPE=Le;exports.HEADER_RESPONSE_ID=no;exports.HEADER_SOURCE_ADDR=nc;exports.HEADER_TOPIC=oc;exports.HEADER_URL=Yt;exports.HEADER_WORK_TRACKER=Sn;exports.HttpRouteHandlers=Ke;exports.KOS_EXECUTION_CONTEXT=ho;exports.KOS_MODEL_ID=Tr;exports.KOS_SERVICE=WM;exports.KOS_SERVICE_1_6_5=qM;exports.KOS_SERVICE_1_8_1=VM;exports.KOS_SERVICE_1_9_X=GM;exports.KeyValue=bi;exports.KeyValueServices=tv;exports.Kos=he;exports.KosConfigPropertySpec=Et;exports.KosContainerIndex=qn;exports.KosContextBean=fu;exports.KosContextManager=Q;exports.KosCore=S;exports.KosCoreModelPropertyMapper=se;exports.KosDataContainer=ti;exports.KosDependencyTypes=Rp;exports.KosExpressionEvaluator=td;exports.KosExtensionUtils=Wp;exports.KosFeatureFlags=iu;exports.KosFetchMethods=Qc;exports.KosGlobalConfig=An;exports.KosHttpRouteManager=Yn;exports.KosLog=g;exports.KosLogManager=od;exports.KosLogManagerServices=cw;exports.KosLoggerFactory=Hn;exports.KosMockEvents=dc;exports.KosModel=ql;exports.KosModelCollectionProvider=X_;exports.KosModelContainer=Fe;exports.KosModelContext=xo;exports.KosModelEvents=L;exports.KosModelFactory=$s;exports.KosModelLoader=qh;exports.KosModelLoaderDisplay=zh;exports.KosModelManager=Vl;exports.KosModelProvider=Bh;exports.KosModelRegistrationFactory=Ee;exports.KosModelRegistry=gn;exports.KosModelState=w;exports.KosModelSymbol=Rn;exports.KosModelVisitor=Yl;exports.KosObservableData=Jc;exports.KosRegistration=Xy;exports.KosSingletonRegistration=Zy;exports.KosTime=kr;exports.KosTimeContext=Yi;exports.KosTimeProvider=uT;exports.KosTimeServices=gw;exports.KosTimer=Eh;exports.KosToken=pu;exports.KosTranslationProvider=yT;exports.KosTranslations=Hd;exports.KosViewModelSymbol=Uc;exports.KosWSTransportStatus=Hl;exports.KosWsEvents=Ws;exports.LOADER_FEATURE_FLAG=Oy;exports.LOGIN_HOST=lc;exports.LOGIN_URL=Bf;exports.LoadingMessage=Uh;exports.LogBlock=Us;exports.LogBlockContainer=So;exports.LogConfig=_s;exports.LogStream=Cs;exports.LogStreamContainer=tr;exports.LogStreamServices=$w;exports.LoggerSetup=Fn;exports.MODEL_DELETION_DELAY=zl;exports.MiddlewareChain=uu;exports.ModelEffects=Be;exports.ModelError=vl;exports.MultipleFutureContainerSetup=kn;exports.MultipleFutureHandler=Xc;exports.NestedModelContext=Ao;exports.NetworkInterface=Li;exports.NetworkInterfaceContainer=Hs;exports.NetworkInterfaceServices=bM;exports.ObservableData=Pe;exports.OptionsRequired=Qs;exports.Ota=jr;exports.OutsideAlerter=RT;exports.PLUGIN_EXTENSION_NAME=Qp;exports.PORT=uc;exports.PROFILE_ENABLE_RELEASES=Qf;exports.PROFILE_LOG_DEBUG=Cc;exports.PROFILE_LOG_INFO=Dc;exports.PROFILE_RELAX_STORE_VALIDATION=Xf;exports.PROFILE_TOOLS_PREVIEW=Ic;exports.ParentModel=Ms;exports.PluginExtensionManager=Xp;exports.ProgressBar=G_;exports.ReferenceConfig=gr;exports.RegionInfo=ae;exports.RegionServices=mb;exports.RegistrationManager=R;exports.Registry=FM;exports.ReloadAwareSetup=jc;exports.ReplayStrategy=pt;exports.ResponseRetention=ie;exports.STATUS=_n;exports.ServiceFactory=ce;exports.ServiceRequestError=Or;exports.ServiceRequestHandlers=gt;exports.SingletonKosModelRegistrationFactory=Ce;exports.SoftwareInfo=Br;exports.SoftwareInfoContext=Qi;exports.SoftwareInfoProvider=fT;exports.SoftwareInfoServices=cE;exports.StateActionHandlers=ip;exports.StateBean=Ks;exports.StateBeanServices=fE;exports.StateEntryHandlers=Rt;exports.StateExitHandlers=Ss;exports.StateMachineSetup=Wt;exports.StateProp=Ci;exports.StatePropServices=_E;exports.StorageDevice=Jr;exports.StorageDeviceContainer=Vt;exports.StorageDeviceServices=_M;exports.StudioProperties=B_;exports.StudioPropertiesServices=F_;exports.SubscriptionHandlers=Z;exports.TIMER_END=Hi;exports.TIMER_EVENT=Bi;exports.TOPIC_TIMER_TICK_EVENT=Ki;exports.TimerManager=Mh;exports.TokenContext=Qh;exports.TokenProvider=gT;exports.Topics=Is;exports.Trans=KT;exports.TransitionMap=vr;exports.Transitions=Vn;exports.Translation=qr;exports.TranslationContainer=Ve;exports.TranslationContainerContext=Xi;exports.TranslationContext=RE;exports.TransportFactory=rn;exports.Trouble=Bs;exports.TroubleAwareSetup=Ln;exports.TroubleContainer=Ht;exports.TroubleServices=qw;exports.Troubles=we;exports.UsbUpdate=Ui;exports.UsbUpdateContainer=zs;exports.UsbUpdateServices=xM;exports.VFS_SERVICE=r_;exports.VFS_SERVICE_1_6_5=XM;exports.VFS_SERVICE_1_8_1=JM;exports.VFS_SERVICE_1_9_X=t_;exports.ViewModelConfig=Un;exports.WS_EVENT_TYPE=qd;exports.WebSocketEvents=Te;exports.WebSocketTransport=Lt;exports.WsEventFactory=xi;exports.acceptOrgInvitation=Ih;exports.addDaysToDate=Zl;exports.addFuture=Pu;exports.addMonthsToDate=Xl;exports.api=Lu;exports.applyFunctionalEnhancements=hl;exports.applyMixins=wy;exports.arraysEqual=Ey;exports.buildConfigBeanModel=cb;exports.buildFuture=pi;exports.buildFutureModel=Au;exports.cancelFuture=ku;exports.checkAppsStarted=sb;exports.checkWildcardPattern=dl;exports.clearAllServiceResponses=zy;exports.clearPath=qy;exports.clearServiceResponse=Hy;exports.convert=ui;exports.convertFileSizeRaw=Wf;exports.convertWithUnits=_b;exports.createBaseMessage=Cl;exports.createBroadcastMessageResponse=kl;exports.createCancellablePromise=f_;exports.createClient=De;exports.createFosBaseMessage=Il;exports.createHeaders=Dl;exports.createKosHtpMessageResponse=Ll;exports.createKosMessage=Rl;exports.createKosMessageResponse=Fl;exports.createMessageBody=ot;exports.createModelDependency=Ml;exports.createOptionKey=Ip;exports.createPropKey=vt;exports.createReadableStream=xl;exports.createStudioMessage=Ol;exports.createStudioMessageRequest=Al;exports.createStudioMessageResponse=Pl;exports.debounce=ll;exports.del=qc;exports.deleteFuture=Ru;exports.destroyKosModel=Re;exports.evaluateScopes=_u;exports.executeApiMethod=Yc;exports.executeChildrenModelLifecycle=Sl;exports.executeDependentModelLifecycle=ls;exports.executeListLifecycle=Tl;exports.fetchModel=IT;exports.findModel=rg;exports.findModels=ol;exports.formatDate=tu;exports.formatDateSince=Ql;exports.formatDateTime=ru;exports.formatTime=su;exports.get=Hc;exports.getAllKosCompanionModels=nl;exports.getCalendarMonthArray=df;exports.getConfigBean=Mu;exports.getDayStrings=hf;exports.getDays=tS;exports.getDaysArray=af;exports.getDaysInMonth=Jn;exports.getDependenciesByLifecycle=_l;exports.getFormattedDate=sS;exports.getFormattedMonth=rS;exports.getFormattedMonthsArray=Ji;exports.getFormattedYear=_e;exports.getFormattedYearsArray=uf;exports.getFutures=jb;exports.getHttpRouteHandlers=zc;exports.getKosCompanionModel=og;exports.getKosConnectionId=Oi;exports.getKosLocalizationDescriptor=Nd;exports.getKosMessageLogging=Pc;exports.getKosModel=rl;exports.getKosModelSync=ke;exports.getKosModelType=sg;exports.getKosServiceApi=KM;exports.getKosSessionKey=hu;exports.getLastDayOfMonth=ws;exports.getLocalizationDescriptor=SE;exports.getLogLevel=Rc;exports.getLogMessageToStudio=kc;exports.getMessageBody=sn;exports.getMonthsArray=cf;exports.getObservableCompanions=ng;exports.getQueryParams=de;exports.getServiceResponse=By;exports.getStartedApps=rb;exports.getTranslations=Fd;exports.getYearsArray=lf;exports.handleServiceRequestError=Wc;exports.hasCachedResponse=Ky;exports.hasDecimals=wu;exports.hasHttpRouteHandlers=$r;exports.hasKosProfile=Zo;exports.hasReadyHook=fl;exports.hslStringToHex=cu;exports.hslToHex=au;exports.httpDelete=kp;exports.initKosProvider=oT;exports.initializeStateMachine=Bc;exports.injectStateMachineSupport=Bn;exports.isBoolean=ii;exports.isDisposable=yr;exports.isKosCompanionTypeFactory=gl;exports.isKosDataModel=Os;exports.isKosExecutionContext=Kn;exports.isKosLoggingEnabled=ep;exports.isKosModel=Ie;exports.isKosModelContainer=Gn;exports.isKosModelReady=Ir;exports.isLeapYear=Zn;exports.isLocalRefId=Gy;exports.isNumber=go;exports.isPrintable=Xg;exports.isTroubleAware=PE;exports.isValidDate=vs;exports.kosAction=te;exports.kosAutoEffect=X;exports.kosChild=Oe;exports.kosCompanion=Dp;exports.kosComputed=si;exports.kosConfigBean=mo;exports.kosConfigProperty=Rb;exports.kosContainerAware=uo;exports.kosContext=xp;exports.kosDependency=Xt;exports.kosEffect=bu;exports.kosFuture=Do;exports.kosFutureAware=Kc;exports.kosLogger=Lp;exports.kosLoggerAware=Qt;exports.kosModel=D;exports.kosModelEffect=Vc;exports.kosMultipleFutureAware=Ap;exports.kosObservable=ri;exports.kosParentAware=lo;exports.kosReference=Fp;exports.kosServiceRequest=Ye;exports.kosStateBean=a_;exports.kosStateEntry=Bp;exports.kosStateExit=Kp;exports.kosStateGuard=Hp;exports.kosStateMachine=jp;exports.kosStateProp=c_;exports.kosSubscribe=wg;exports.kosTopicHandler=B;exports.kosTroubleAware=qp;exports.kosViewModel=jg;exports.kosWhen=nn;exports.login=Sh;exports.mapConfigBeanModelToDto=Ou;exports.mapDataToModel=on;exports.mapDtoToConfigBeanModel=Su;exports.mapDtoToFutureModel=fi;exports.mapDtoToFutureOptions=hi;exports.mapUpdateDtoToConfigBeanModel=$u;exports.modelEventTopicFactory=ml;exports.modelFactory=Jt;exports.modelTypeEventTopicFactory=yl;exports.modifyConfigBean=Eu;exports.modifyFuture=Bb;exports.pairedClientHeartbeat=Ry;exports.parseWildcardSegment=ul;exports.pipe=du;exports.post=Xs;exports.preloadKosModel=cg;exports.processId=Sy;exports.processMiddleware=Dy;exports.put=Pp;exports.registerCompanionModel=ag;exports.registerCoreModels=mh;exports.registerExtensionPoint=Zt;exports.registerHttpRoutes=um;exports.registerKosModel=al;exports.registerLegacyModel=il;exports.resetKosModel=tg;exports.resetPassword=Oh;exports.resolveBaseUrl=jl;exports.resolveChild=El;exports.resolveContainerDeltas=My;exports.resolveItemListDeltas=Ty;exports.resolveKosCompanion=Jo;exports.resolveKosContext=Qy;exports.resolveKosProfiles=Ac;exports.resolveListDeltas=_y;exports.resolveServiceRequestParameters=Gc;exports.resolveServiceUrl=fe;exports.resolveVariable=lu;exports.retryWithExponentialBackoff=ky;exports.sendAsyncIntent=eb;exports.sendBroadcastMessage=Mm;exports.sendIntent=Jy;exports.sendKosHttpMessageResponse=Ul;exports.sendKosMessage=vm;exports.sendKosMessageResponse=Nl;exports.sendRequest=Yy;exports.sendStudioMessage=Em;exports.sendStudioMessageRequest=wm;exports.startPasswordReset=$h;exports.stringComponentInsert=sf;exports.studioAcceptOrgInvitation=h_;exports.studioLogin=l_;exports.studioResetPassword=d_;exports.studioStartPasswordReset=u_;exports.subscribeStore=jM;exports.syncPublish=Wy;exports.troubleByTypeReducer=Zc;exports.troubleDataFactory=Od;exports.unloadKosModel=eg;exports.updateCompanionModelRegistration=Ay;exports.updateModelRegistration=xy;exports.updateRegion=vh;exports.updateTimeZone=yn;exports.useAmPmValues=Af;exports.useCalendarDayArray=wf;exports.useConfigBean=ZT;exports.useConfigProperty=nf;exports.useContextModel=W_;exports.useContextModelHierarchy=Hh;exports.useDateArrays=ff;exports.useDateProps=nS;exports.useDateRelativeConfig=iS;exports.useDateRelativeData=_f;exports.useDayNames=bf;exports.useDayOptions=yf;exports.useDays=ta;exports.useDevice=Zh;exports.useFormattedDate=vf;exports.useFormattedTime=Pf;exports.useFunctionWarmup=aS;exports.useHourValues=xf;exports.useKosCore=Yh;exports.useKosDateFormats=lS;exports.useKosModel=J;exports.useKosRegions=If;exports.useKosTime=Gi;exports.useKosTimeContext=dT;exports.useKosTimeFormats=mS;exports.useKosTimeZones=hS;exports.useKosTranslation=VT;exports.useKosTranslationContext=bT;exports.useLocalComputed=yS;exports.useModelFromHierarchy=J_;exports.useMonths=gf;exports.useMonthsOptions=mf;exports.useMutationObserver=vS;exports.useNetworkInterfaceContainer=Jh;exports.useOta=ef;exports.usePressGesture=wS;exports.useProjectReload=Df;exports.useRegionTimeProps=ES;exports.useRegionalTimeDate=Mf;exports.useSoftwareInfo=Wi;exports.useSoftwareInfoContext=pT;exports.useStateProperty=PT;exports.useStorageDeviceContainer=tf;exports.useSuspenseData=vn;exports.useTimeOptions=Rf;exports.useTimeProps=kf;exports.useTimeValues=wn;exports.useTimer=LT;exports.useTranslationContainer=rf;exports.useTroubleContainerModel=Zi;exports.useTroubleModel=YT;exports.useTroublePresence=WT;exports.useUsbUpdateContainer=of;exports.useViewModel=MS;exports.useYears=ea;exports.useYearsOptions=pf;exports.uuid=wt;exports.variableToHex=Iy;exports.waitForAppToStart=tb;exports.waitForAppsToStart=yu;exports.waitForRequest=ei;exports.whenReady=ye;exports.withDevice=OT;exports.withKosTime=CT;exports.withNetworkInterfaceContainer=DT;exports.withOta=xT;exports.withProjectReloading=_S;exports.withSoftwareInfo=hT;exports.withStorageDeviceContainer=kT;exports.withTranslationContainer=GT;exports.withTroubleContainer=QT;exports.withUsbUpdateContainer=XT;exports.wrapPromise=xn;exports.wrapWithFutureLifecycle=qi;
|
|
227
|
+
`,Zh=()=>{const t=Yr.type;return J({modelId:t,modelType:Yr.type,options:{}})};function OT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Zh();return _.jsx(o,{...r,children:_.jsx(t,{...e,device:s})})}}function IT(t,e,s){const r=new Promise(o=>{S.getInstance().whenReady().then(()=>{const{model:n}=S.getInstance().modelManager.createModelInstance(t,e??t,s);return n.whenReady().then(()=>{o(n.modelData)})})});return xn(r)}function CT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Gi();return _.jsx(o,{...r,children:_.jsx(t,{...e,kosTime:s})})}}const Jh=()=>{const t=Hs.type;return J({modelId:t,modelType:Hs.type,options:{}})};function DT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Jh();return _.jsx(o,{...r,children:_.jsx(t,{...e,networkInterfaceContainer:s})})}}const ef=()=>{const t=Kr.type;return J({modelId:t,modelType:Kr.type,options:{}})};function xT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=ef();return _.jsx(o,{...r,children:_.jsx(t,{...e,oTA:s})})}}function AT(t,e){m.useEffect(()=>{function s(o){t.current&&!t.current.contains(o.target)&&e()}function r(o){o.key==="Escape"&&e()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r,!1),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r,!1)}},[t,e])}function RT(t){const e=m.useRef(null),s=t.onAlert;return AT(e,s),_.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const PT=t=>{var u;const{stateProp:e}=t,[s,r]=m.useState((u=t.stateProp)==null?void 0:u.value),[o,n]=m.useState(!1),[i,a]=m.useState(void 0);return m.useEffect(()=>{async function d(h){try{h&&(await ye(h),n(!0))}catch(f){a(f.message)}}d(e)},[e]),m.useEffect(()=>{const d=X(()=>{e&&o&&r(e.value)});return()=>{d()}},[o,e]),[s,{ready:o,error:i}]},tf=()=>{const[t,e]=m.useState(!1),[s,r]=m.useState([]),o=Vt.type,n=J({modelId:o,modelType:Vt.type,options:{}});return m.useEffect(()=>{const i=X(()=>{var a,c;e(((a=n.model)==null?void 0:a.isStorageInserted)??!1),r(((c=n.model)==null?void 0:c.data)??[])});return()=>{i()}},[n.model]),{...n,inserted:t,devices:s}};function kT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=tf();return _.jsx(o,{...r,children:_.jsx(t,{...e,storageDeviceContainer:s})})}}const Qo=g.createLogger({name:"use-timer"}),LT=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=Mh.getTimer(t);m.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const u=C(Bi,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===t&&(f===Hi?e({name:h,action:f,remainingTime:p,timer:n}):r!=null&&r[f]&&r[f]({name:h,action:f,remainingTime:p,timer:n}))});return o&&n.start(),()=>{u.unsubscribe()}},[o,e,r,t,n]),m.useEffect(()=>{if(!n||!s)return;const u=`${Ki}/${t}`,d=C(u,h=>{const{name:f,remainingTime:p}=h==null?void 0:h.body;f===t&&s({name:f,remainingTime:p,timer:n})});return()=>{d.unsubscribe()}},[s,t,n]);const i=m.useCallback(()=>{n?n.start():Qo.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=m.useCallback(()=>{n?n.reset():Qo.warn(`Timer with name ${t} does not exist.`)},[n,t]),c=m.useCallback(()=>{n?n.pause():Qo.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:c}},FT=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},NT=t=>t instanceof RegExp,UT=t=>typeof t=="string",jT=(t,e,s)=>{if(t===""||e==="")return t;let r=e;NT(r)||(r=new RegExp("("+FT(r)+")","gi"));const o=t.split(r);for(let n=1,i=o.length;n<i;n+=2)o[n]=s(o[n],n);return o},sf=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>UT(o)?jT(o,e,s):o)};function BT(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=sf(s,n,(i,a)=>o.type==="br"?_.jsx("br",{}):m.cloneElement(o,{key:`${r}-${a}`},i))}),s}const KT=t=>{const{i18nKey:e,t:s,defaults:r,components:o,values:n={},context:i}=t,a=s(e,{defaultValue:r,data:n,context:i,returnObjects:!0}),c=BT(a,o||{});return _.jsx("span",{className:t.className,children:c})},xt=new Map;function HT(t,e){if(xt.has(t)){const s=xt.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{xt.set(t,{status:"finished",result:o})},o=>{throw xt.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw xt.set(t,r),s}}function vn(t,e){return HT(t,e)}const qT=async()=>{const t=await rl(Ve.type);return await ye(t.model),t.model},zT=async(t,e,s)=>{const r=t.resolveNamespace(e);await ye(r);for(const o of s){const n=t.resolveNamespace(o);await ye(n),xt.set(o,{status:"finished",result:n})}return r},VT=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=vn(Ve.type,qT),i=s.join("__"),a=vn(i,()=>zT(n,r,o)),c=m.useMemo(()=>({exists:d=>{const h=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.exists(h):!1}}),[e==null?void 0:e.keyPrefix,a]);return{t:m.useCallback((d,h)=>{const f=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(g.debug(`Translation model ${t} not ready for key: ${f}`),f)},[e==null?void 0:e.keyPrefix,t,a]),i18n:c}},rf=()=>{const t=Ve.type;return J({modelId:t,modelType:Ve.type,options:{}})};function GT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=rf();return _.jsx(o,{...r,children:_.jsx(t,{...e,translationContainer:s})})}}const YT=t=>J({modelId:t,modelType:Ks.type}),Zi=()=>J({modelId:Ht.type,modelType:Ht.type,options:{}}),WT=({troubleType:t,condition:e})=>{const{model:s}=Zi(),[r,o]=m.useState(!1),[n,i]=m.useState([]),a=m.useCallback(()=>{var c,u;return n.length>0&&((c=n[0])!=null&&c.resolvable)?(u=n[0])==null?void 0:u.resolve():Promise.resolve(void 0)},[n]);return m.useEffect(()=>X(()=>{const u=(t?s==null?void 0:s.troubles.getIndexByKey("byType",t):s==null?void 0:s.troubles.data)||[],d=e?u.filter(e):u;o(d.length>0),i(d)}),[e,s,t]),[r,a,n.length>0?n[0]:void 0,n]};function QT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Zi();return _.jsx(o,{...r,children:_.jsx(t,{...e,troubleContainer:s})})}}const of=()=>{const t=zs.type,e=J({modelId:t,modelType:zs.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=m.useState(!1),[o,n]=m.useState(!1),[i,a]=m.useState([]);return m.useEffect(()=>{const c=X(()=>{var u,d,h;r(((u=e.model)==null?void 0:u.isUsbInserted)??!1),n(((d=e.model)==null?void 0:d.hasAvailableUpdates)??!1),a(((h=e.model)==null?void 0:h.data)??[])});return()=>{c()}},[e.model]),{...e,inserted:s,updateAvailable:o,updates:i}};function XT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=of();return _.jsx(o,{...r,children:_.jsx(t,{...e,usbUpdateContainer:s})})}}const ZT=({path:t,propKey:e})=>{const{status:s}=J({modelType:Rs.type,modelId:t,options:{path:t}}),[r,o]=m.useState(!1),[n,i]=m.useState(),[a,c]=m.useState(""),[u,d]=m.useState(),h=f=>{n&&e&&n.updateProperty(e,f)};return m.useEffect(()=>{var f;s.model&&i(s.model),s.model&&e&&((f=s.model)!=null&&f.props.has(e)?c(s.model.props[e]):d(`property ${e} not found`)),s.ready&&o(s.ready)},[s.ready,s.model,e]),m.useEffect(()=>{e&&E.autorun(()=>{const f=n==null?void 0:n.props[e];c(f||"")})},[n,e]),{config:n,ready:r,value:a,error:u,updateValue:h}},JT=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},nf=({configProperty:t,optionsTransformer:e})=>{const[s,r]=m.useState(!1),[o,n]=m.useState(""),[i,a]=m.useReducer(JT,{value:String(t==null?void 0:t.value),displayValue:t==null?void 0:t.displayValue,significantValue:t==null?void 0:t.significantValue,unit:t==null?void 0:t.unit,options:t==null?void 0:t.options,mappedOptions:[],updateProperty:t==null?void 0:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}),c=m.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&(t==null||t.updateProperty(d))},[t]);return m.useEffect(()=>{async function u(d){try{d&&(await ye(d),r(!0))}catch(h){n(h.message)}}u(t)},[t]),m.useEffect(()=>{const u=X(()=>{if(t&&s){let d=[];e&&(d=e(t.options)),a({type:"UPDATE",payload:{value:String(t.value),displayValue:t.displayValue,significantValue:t.significantValue,unit:t.unit,options:t.options,mappedOptions:d,updateProperty:t.updateProperty,displayOptions:t==null?void 0:t.displayOptions}})}});return()=>{u()}},[t,e,s]),{...i,configSelectProps:{onChange:c,value:i.value,options:e?i.mappedOptions||[]:i.options||[]},ready:s,error:o}};function eS(t,e){const s=e??new Date().getFullYear(),r=[31,28,31,30,31,30,31,31,30,31,30,31];return t===1&&(s%4===0&&s%100!==0||s%400===0)?29:r[t]??0}function tS(t,e){return new Date(t,e,0).getDate()}function af(t,e){const s=eS(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function cf(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function lf(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function uf(t,e=[2018,2028]){const s=lf(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function Ji(t="numeric",e="en-US"){const s=new Intl.DateTimeFormat(e,{month:t,timeZone:"UTC"}).format;return[...Array(12).keys()].map(r=>s(new Date(Date.UTC(0,r,1))))}function sS({locale:t="en-US",year:e,month:s,day:r,formatOptions:o={weekday:"long",year:"numeric",month:"long",day:"numeric"},displayOrder:n}){const i=s-1,a=new Date(e,i,r),c=new Intl.DateTimeFormat(t,{month:o.month}).format(a),u=new Intl.DateTimeFormat(t,{year:o.year}).format(a),d=new Intl.DateTimeFormat(t,{day:o.day}).format(a);return n?n=="MMDDYY"?`${c} ${d} ${u}`:n==="DDMMYY"?`${d} ${c} ${u}`:n==="YYMMDD"?`${u} ${c} ${d}`:`${u} ${d} ${c}`:new Intl.DateTimeFormat(t,o).format(a)}function _e(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function rS(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function df(t,e,s){const r=_e(e),o=new Date(r,t,1).getDay(),n=new Date(r,t+1,0).getDate();return[...Array(42).keys()].map(a=>a<o||a>n+o-1?{label:"",value:0,disabled:!0}:s[a-o])}function vs(t,e,s){const r=e-1,o=new Date(t,r,s);return new Date(o).getMonth()===r&&new Date(o).getDate()===s}function ws(t,e){return new Date(t,e,0).getDate()}function hf(t="en-US",e="short"){const s=new Intl.DateTimeFormat(t,{weekday:e}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function ff({locale:t="en-US",year:e=new Date().getFullYear(),month:s=new Date().getMonth(),yearRange:r=[2018,2028],daysOfWeekFilter:o=[],formatOptions:{yearFormat:n="long",monthFormat:i="long",dayFormat:a="short"}={}}){const c=ea(n,r),u=pf(n,r,t),d=gf(i,t),h=mf(i,t),f=ta(e,s),p=yf(e,s,t,o),y=wf(s,e,p),v=bf(t,a);return{daysArray:f,monthsArray:d,yearsArray:c,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:y,dayNamesArray:v}}function ea(t="long",e=[2018,2028]){return m.useMemo(()=>uf(t,e),[t,e])}function pf(t="long",e=[2018,2028],s="en-US"){const r=ea(t,e);return m.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function gf(t,e="en-US"){return m.useMemo(()=>Ji(t,e),[t,e])}function mf(t,e="en-US"){const s=m.useMemo(()=>cf(),[]),r=m.useMemo(()=>Ji(t,e),[t,e]);return m.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function ta(t,e){const s=_e(t);return m.useMemo(()=>af(s,e),[e,s])}const oS=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function yf(t,e,s="en-US",r=[]){const o=ta(t,e);return m.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:oS(t,e,i,r)})),[r,s,e,o,t])}function bf(t="en-US",e="short"){return m.useMemo(()=>hf(t,e),[t,e])}function vf({year:t=new Date().getFullYear(),month:e=new Date().getMonth(),day:s=new Date().getDate(),formatString:r}){const o=e,n=new Date(t,o,s);return{formattedDate:Xe.format(n,r)}}function wf(t,e,s){return m.useMemo(()=>df(t,e,s),[t,e,s])}var Ef=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(Ef||{});function nS({locale:t="en-US",date:{year:e=new Date().getFullYear(),month:s=new Date().getMonth(),day:r=new Date().getDate()}={year:new Date().getFullYear(),month:new Date().getMonth(),day:new Date().getDate()},formatOptions:{yearFormat:o="long",monthFormat:n="long",dayFormat:i="short",formatString:a="yyyy/MM/dd"}={},filterOptions:{yearsRange:c=[2018,2028],daysOfWeekFilter:u=[]}={}}){const[d,h]=m.useState(e),[f,p]=m.useState(c),[y,v]=m.useState(s),[M,$]=m.useState(r);m.useEffect(()=>{h(e)},[e]),m.useEffect(()=>{v(s)},[s]),m.useEffect(()=>{$(r)},[r]);const{yearsArray:U,yearsOptionsArray:x,monthsArray:O,monthsOptionsArray:P,daysArray:V,daysOptionsArray:ee,calendarDayArray:K,dayNamesArray:as}=ff({locale:t,year:d,yearRange:f,month:y,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:re}=vf({year:d,month:y,day:M,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:v,setDay:$,nextMonth:()=>{const ne=y<11?_e(d):_e(d+1),pe=y<11?y+1:0;if(!vs(ne,pe,M)){const nt=ws(ne,pe);$(nt)}pe===0&&h(ne),v(pe)},previousMonth:()=>{const ne=_e(y===0?d-1:d),pe=y===0?11:y-1;if(!vs(ne,pe,M)){const nt=ws(ne,pe);$(nt)}pe===11&&h(ne),v(pe)},nextYear:()=>{const ne=d<f[1]?d+1:f[0],pe=_e(ne);if(vs(pe,y,M))h(ne);else{const nt=ws(_e(d+1),y);$(nt),h(ne)}},previousYear:()=>{const ne=d>f[0]?d-1:f[0],pe=_e(ne);if(vs(pe,y,M))h(ne);else{const nt=ws(_e(d-1),y);$(nt),h(ne)}}},dateState:{year:d,yearRange:f,month:y,day:M,yearsArray:U,yearsOptionsArray:x,monthsArray:O,monthsOptionsArray:P,daysArray:V,daysOptionsArray:ee,calendarDayNames:as,calendarDayArray:K,formattedDate:re}}}function Mf({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[o,n]=m.useState("Formatting Time..."),[i,a]=m.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:u,ready:d}=J({modelId:ae.type,modelType:ae.type,options:{}}),h=typeof t=="string"?Xe.parseISO(t):t;return m.useEffect(()=>{c?a(""):e?a(Xe.format(h,e)):d&&a(Xe.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[c,t,e,h,u,d]),m.useEffect(()=>{s?n(Xe.format(h,s)):d&&n(Xe.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[t,s,h,u,d]),{formattedDate:i,formattedTime:o}}const _f=({secondsFromMidnight:t=0})=>{const[e,s]=m.useState(0),[r,o]=m.useState(0),[n,i]=m.useState(0),[a,c]=m.useState(new Date),{formattedTime:u}=Mf({date:a,options:{ignoreDateFormat:!0}});return m.useEffect(()=>{const d=Number(t),h=Math.floor(d/3600),f=Math.floor(d%3600/60),p=d%60;s(h),o(f),i(p);const y=new Date;y.setHours(0,0,0,0);const v=new Date(y.getTime()+d*1e3);c(new Date(v))},[t]),{hours:e,minutes:r,seconds:n,formattedTime:u,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},iS=({configProperty:t})=>{const{value:e}=nf({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=_f({secondsFromMidnight:s}),c=m.useRef();return m.useEffect(()=>{const u=r*3600+o*60+n;return c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{t&&t.updateProperty(u.toString())},100),()=>{c.current&&clearTimeout(c.current)}},[t,r,o,n]),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}};function aS(t,e={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=e;m.useEffect(()=>{const o=()=>{try{t({__warmup:!0})}catch{}};r&&("requestIdleCallback"in window?requestIdleCallback(o):setTimeout(o,1));const n=s?setInterval(o,s):null;return()=>{n&&clearInterval(n)}},[t,s,r])}const cS=t=>_.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),lS=(t=cS)=>{const[e,s]=m.useState([]),[r,o]=m.useState(),{model:n,ready:i}=J({modelType:ae.type,modelId:ae.type,options:{}});m.useEffect(()=>{const c=X(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),m.useEffect(()=>{const c=X(()=>{n!=null&&n.dateFormatId&&(n!=null&&n.selectedDateFormat)&&o({id:n==null?void 0:n.dateFormatId,value:n==null?void 0:n.selectedDateFormat})});return()=>{c()}},[n==null?void 0:n.selectedDateFormat,n==null?void 0:n.dateFormatId]);const a=m.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(n==null||n.setSelectedDateFormat(u))},[n]);return{raw:(n==null?void 0:n.dateFormatOptions.map(c=>c.id))??[],regionModel:n,selectedDateFormat:(r==null?void 0:r.value)||"",dateFormatId:(r==null?void 0:r.id)||"",updateDateFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)||"",options:e}}},uS=t=>_.jsx("option",{title:t,value:t,children:t},t),Tf="kos:service:region:settings",Sf="timeZone",dS=`${Tf}-${Sf}`,hS=(t=uS)=>{const[e,s]=m.useState([]),[r,o]=m.useState(""),{model:n,ready:i}=J({modelType:ae.type,modelId:ae.type,options:{}}),a=Et.factory(dS)({path:Tf,attribute:Sf});m.useEffect(()=>{const u=X(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&mn(n==null?void 0:n.timeZones[0])});return()=>{u()}},[n,i,t]),m.useEffect(()=>{const u=X(()=>{o(a.value||"")});return()=>{u()}},[a.value]);const c=m.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&mn(d)},[]);return{options:e,raw:(n==null?void 0:n.timeZones)??[],regionModel:n,selectedTimeZone:r,timeZones:(n==null?void 0:n.timeZones)??[],updateTimeZone:c,selectProps:{onChange:c,value:r,options:e}}},$f="kos:service:region",Of="regionId",fS=`${$f}-${Of}`,pS=t=>_.jsx("option",{title:t,value:t,children:t},t),If=(t=pS)=>{const[e,s]=m.useState([]),[r,o]=m.useState("factory"),{model:n,ready:i}=J({modelType:ae.type,modelId:ae.type}),a=Et.factory(fS)({path:$f,attribute:Of});m.useEffect(()=>{const u=X(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{u()}},[n,i,t]),m.useEffect(()=>{const u=X(()=>{o(a.value||"factory")});return()=>{u()}},[a.value]);const c=m.useCallback(u=>{var h;let d="factory";typeof u=="string"?d=u:(h=u==null?void 0:u.target)!=null&&h.value&&(d=u.target.value),d&&vh(d)},[]);return{raw:(n==null?void 0:n.availableRegions)??[],regionModel:n,regionData:n==null?void 0:n.selectedRegion,selectedRegion:r,updateRegion:c,regionSelectProps:{onChange:c,value:r,options:e}}},gS=t=>_.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),mS=(t=gS)=>{const[e,s]=m.useState([]),[r,o]=m.useState(),{model:n,ready:i}=J({modelType:ae.type,modelId:ae.type,options:{}});m.useEffect(()=>{const c=X(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),m.useEffect(()=>{const c=X(()=>{n!=null&&n.timeFormatId&&(n!=null&&n.selectedTimeFormat)&&o({id:n==null?void 0:n.timeFormatId,value:n==null?void 0:n.selectedTimeFormat})});return()=>{c()}},[n==null?void 0:n.selectedTimeFormat,n==null?void 0:n.timeFormatId]);const a=m.useCallback(c=>{var d;let u="";typeof c=="string"?u=c:(d=c==null?void 0:c.target)!=null&&d.value&&(u=c.target.value),u&&(n==null||n.setSelectedTimeFormat(u))},[n]);return{raw:(n==null?void 0:n.timeFormatOptions.map(c=>c.id))??[],regionModel:n,selectedTimeFormat:(r==null?void 0:r.value)??"",timeFormatId:(r==null?void 0:r.id)??"",updateTimeFormat:a,props:{onChange:a,value:(r==null?void 0:r.id)??"",options:e}}},yS=(t,e)=>m.useMemo(()=>si(t),e),bS={config:{attributes:!0,childList:!0,subtree:!0}};function vS(t,e,s=bS){const[r,o]=m.useState(null);m.useEffect(()=>{if(!e||typeof e!="function")throw new Error("A valid callback function is required");const n=new MutationObserver(e);o(n)},[e,s,o]),m.useEffect(()=>{if(!r)return()=>{};if(!t)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(t,n)}catch(i){g.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const Cf={validateStart:function(t){return!0},validateStop:function(t){const e=t.event.currentTarget.getBoundingClientRect(),[s,r]=t.xy;return s<e.left||s>e.right||r<e.top||r>e.bottom}},Xo=g.createLogger({name:"usePressGesture",group:"kos-hooks"});function wS({onPressed:t,onRelease:e,intersectionStrategy:s=Cf}){const r=m.useRef(!1),o=Nf.useGesture({onDragStart:c=>{Xo.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{Xo.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{Xo.info("onDragEnd",c.type),r.current&&e&&(e(),r.current=!1)}}),n=()=>{t&&t(),r.current=!0},i=()=>{r.current&&e&&(e(),r.current=!1)},a=()=>{r.current&&e&&(e(),r.current=!1)};return{dom:o,mesh:()=>({onPointerDown:n,onPointerUp:i,onPointerOut:a})}}const Df=()=>{const[t,e]=m.useState(!1),s=S.getInstance();return m.useEffect(()=>{const r=X(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function xf(t=!1,e="2-digit"){return m.useMemo(()=>{const s=t?12:24;return Array.from({length:s},(r,o)=>{const n=t&&o===0?12:o%s;return{id:o,label:e==="2-digit"?n.toString().padStart(2,"0"):n.toString()}})},[e,t])}function wn(t,e="2-digit",s=0,r=0){return m.useMemo(()=>Array.from({length:t},(o,n)=>{const i=String(n+s);return{id:n+r,label:e==="2-digit"?i.padStart(2,"0"):i}}),[t,s,r,e])}function Af(t="en-US"){return m.useMemo(()=>["AM","PM"].map(e=>{const s=new Intl.DateTimeFormat(t,{hour:"2-digit",hour12:!0}).formatToParts(new Date().setHours(e==="AM"?0:12))[2].value;return{id:s,label:s}}),[t])}function Rf({formatOptions:{hour12:t=!0,hour:e="2-digit",minute:s="2-digit",second:r="2-digit"}={hour12:!0,hour:"2-digit",minute:"2-digit",second:"2-digit"},locale:o="en-US"}){const n=xf(t,e),i=wn(60,s),a=wn(60,r),c=Af(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function Pf(t,e){return Xe.format(t,e)}function kf({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=m.useState(e),i=m.useCallback(v=>{n(M=>{const $=new Date(M);return $.setHours(Number(v)),$})},[]),a=m.useCallback(v=>{n(M=>{const $=new Date(M);return $.setMinutes(Number(v)),$})},[]),c=m.useCallback(v=>{n(M=>{const $=new Date(M);return $.setSeconds(Number(v)),$})},[]),u=m.useCallback(v=>{const M=new Date(v);n(M)},[]),d=Pf(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:y}=Rf({formatOptions:t,locale:s});return{amPmOptions:y,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:c,setTime:u,time:new Date(o)}}const ES=t=>{const{regionModel:e}=If(),s=m.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return kf({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function MS(t,e,s={}){const{disposeOnUnmount:r=!0}=s,[o,n]=m.useState(!1),[i,a]=m.useState(void 0),c=m.useRef(null),u=m.useRef(!0),d=m.useRef(!1),h=m.useMemo(()=>{if(!u.current&&c.current&&r&&yr(c.current)){const p=c.current;Promise.resolve().then(()=>{yr(p)&&p.dispose()})}u.current=!1,d.current=!1;const f=t();return c.current=f,f},e);return m.useEffect(()=>{d.current||(fl(h)?(d.current=!0,n(!1),a(void 0),h.ready().then(()=>{n(!0)}).catch(f=>{a(f),n(!1)})):(n(!0),a(void 0)))},[h]),m.useEffect(()=>()=>{r&&c.current&&yr(c.current)&&c.current.dispose(),c.current=null},[r]),{viewModel:h,ready:o,error:i}}function _S(t){return e=>{const[s]=Df();return s?_.jsx(Uh,{message:"Wait a moment while your project reloads..."}):_.jsx(t,{...e})}}jf({"kos-ui-sdk":22});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>E.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>E.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>Mn.observer});exports.AncestorPathVisitor=vy;exports.AuthState=Gl;exports.BrowserKosRouter=gu;exports.BrowserRouter=yi;exports.CanvasDispatcher=zt;exports.CanvasDispatcherServices=_E;exports.CanvasRenderer=Ci;exports.CanvasStreamer=TT;exports.CanvasStreamerBase=Xh;exports.ChildModels=Je;exports.CompanionParentModel=et;exports.ConfigBean=Rs;exports.ContainerAwareSetup=Nn;exports.CoreExtensionManager=kM;exports.CoreModels=ji;exports.CreateModelTranslationsContext=Vh;exports.CreateModelTranslationsProvider=sT;exports.DateDisplayFormat=Ef;exports.DateHelpers=$y;exports.DependencyLifecycle=I;exports.DependencyModels=F;exports.DependencyResolutionPolicy=Ze;exports.Device=Yr;exports.DeviceServices=zE;exports.DomIntersectionStrategy=Cf;exports.EVENT_KOS_MODEL_READY=$n;exports.EVENT_TROUBLE_ADDED=ob;exports.EVENT_TROUBLE_REMOVED=nb;exports.EXTENSION_CANVAS_RENDERER=oe;exports.EXTENSION_FEATURE_FLAG_RESOLVER=ou;exports.EXTENSION_FUTURE_LIFECYCLE_WRAPPER=tl;exports.EXTENSION_TROUBLE_DATA_MAPPER=jr;exports.EXTENSION_TROUBLE_MAPPER=sr;exports.ErrorBoundaryWithFallback=jh;exports.EventBus=qf;exports.EventBusFunctional=Vf;exports.EventBusState=Yf;exports.ExtensionException=mr;exports.ExtensionManager=T;exports.FUTURE_CONTAINER_MODEL_TYPE=Fu;exports.FUTURE_MODEL_TYPE=Lu;exports.FUTURE_NOT_ASSIGNED=oi;exports.FeatureFlagService=nu;exports.FetchError=z;exports.FutureAliases=Ts;exports.FutureContainerFactory=st;exports.FutureContainerModel=Gu;exports.FutureContainerSetup=Pn;exports.FutureEndState=tt;exports.FutureFactory=ts;exports.FutureHandler=po;exports.FutureManager=mt;exports.FutureModel=Vu;exports.FutureService=Es;exports.GpioChip=ro;exports.GpioChipContainer=Lh;exports.GpioChipServices=x_;exports.GpioPin=zi;exports.GpioPinContainer=Vi;exports.HEADER_CACHE_CONTROL=ac;exports.HEADER_CONTENT_TYPE=ic;exports.HEADER_DESTINATION_ADDR=Ge;exports.HEADER_FOS_REQUEST_ID=cc;exports.HEADER_METHOD=oo;exports.HEADER_ORDERED=Tn;exports.HEADER_REQUEST_ID=Ys;exports.HEADER_REQUEST_TYPE=Le;exports.HEADER_RESPONSE_ID=no;exports.HEADER_SOURCE_ADDR=nc;exports.HEADER_TOPIC=oc;exports.HEADER_URL=Yt;exports.HEADER_WORK_TRACKER=Sn;exports.HttpRouteHandlers=Ke;exports.KOS_EXECUTION_CONTEXT=ho;exports.KOS_MODEL_ID=Tr;exports.KOS_SERVICE=zM;exports.KOS_SERVICE_1_6_5=jM;exports.KOS_SERVICE_1_8_1=KM;exports.KOS_SERVICE_1_9_X=HM;exports.KeyValue=wi;exports.KeyValueServices=yv;exports.Kos=he;exports.KosConfigPropertySpec=Et;exports.KosContainerIndex=qn;exports.KosContextBean=fu;exports.KosContextManager=Q;exports.KosCore=S;exports.KosCoreModelPropertyMapper=se;exports.KosDataContainer=ti;exports.KosDependencyTypes=Rp;exports.KosExpressionEvaluator=od;exports.KosExtensionUtils=Wp;exports.KosFeatureFlags=iu;exports.KosFetchMethods=Qc;exports.KosGlobalConfig=An;exports.KosHttpRouteManager=Yn;exports.KosLog=g;exports.KosLogManager=ad;exports.KosLogManagerServices=Tw;exports.KosLoggerFactory=Hn;exports.KosMockEvents=dc;exports.KosModel=ql;exports.KosModelCollectionProvider=X_;exports.KosModelContainer=Fe;exports.KosModelContext=xo;exports.KosModelEvents=L;exports.KosModelFactory=$s;exports.KosModelLoader=qh;exports.KosModelLoaderDisplay=zh;exports.KosModelManager=Vl;exports.KosModelProvider=Bh;exports.KosModelRegistrationFactory=Ee;exports.KosModelRegistry=pn;exports.KosModelState=w;exports.KosModelSymbol=Rn;exports.KosModelVisitor=Yl;exports.KosObservableData=Jc;exports.KosRegistration=Xy;exports.KosSingletonRegistration=Zy;exports.KosTime=Fr;exports.KosTimeContext=Yi;exports.KosTimeProvider=uT;exports.KosTimeServices=xw;exports.KosTimer=Eh;exports.KosToken=pu;exports.KosTranslationProvider=yT;exports.KosTranslations=ph;exports.KosViewModelSymbol=Uc;exports.KosWSTransportStatus=Hl;exports.KosWsEvents=Ws;exports.LOADER_FEATURE_FLAG=Oy;exports.LOGIN_HOST=lc;exports.LOGIN_URL=Bf;exports.LoadingMessage=Uh;exports.LogBlock=js;exports.LogBlockContainer=$o;exports.LogConfig=_s;exports.LogStream=Cs;exports.LogStreamContainer=tr;exports.LogStreamServices=Kw;exports.LoggerSetup=Fn;exports.MODEL_DELETION_DELAY=zl;exports.MiddlewareChain=uu;exports.ModelEffects=Be;exports.ModelError=vl;exports.MultipleFutureContainerSetup=kn;exports.MultipleFutureHandler=Xc;exports.NestedModelContext=Ao;exports.NetworkInterface=Ai;exports.NetworkInterfaceContainer=Hs;exports.NetworkInterfaceServices=tM;exports.ObservableData=Pe;exports.OptionsRequired=Qs;exports.Ota=Kr;exports.OutsideAlerter=RT;exports.PLUGIN_EXTENSION_NAME=Qp;exports.PORT=uc;exports.PROFILE_ENABLE_RELEASES=Qf;exports.PROFILE_LOG_DEBUG=Cc;exports.PROFILE_LOG_INFO=Dc;exports.PROFILE_RELAX_STORE_VALIDATION=Xf;exports.PROFILE_TOOLS_PREVIEW=Ic;exports.ParentModel=Ms;exports.PluginExtensionManager=Xp;exports.ProgressBar=G_;exports.ReferenceConfig=gr;exports.RegionInfo=ae;exports.RegionServices=mb;exports.RegistrationManager=R;exports.Registry=RM;exports.ReloadAwareSetup=jc;exports.ReplayStrategy=pt;exports.ResponseRetention=ie;exports.STATUS=_n;exports.ServiceFactory=ce;exports.ServiceRequestError=Or;exports.ServiceRequestHandlers=gt;exports.SingletonKosModelRegistrationFactory=Ce;exports.SoftwareInfo=eo;exports.SoftwareInfoContext=Qi;exports.SoftwareInfoProvider=fT;exports.SoftwareInfoServices=n_;exports.StateActionHandlers=ip;exports.StateBean=Ls;exports.StateBeanServices=Gb;exports.StateEntryHandlers=Rt;exports.StateExitHandlers=Ss;exports.StateMachineSetup=Wt;exports.StateProp=mi;exports.StatePropServices=ov;exports.StorageDevice=Qr;exports.StorageDeviceContainer=Vt;exports.StorageDeviceServices=iM;exports.StudioProperties=B_;exports.StudioPropertiesServices=F_;exports.SubscriptionHandlers=Z;exports.TIMER_END=Hi;exports.TIMER_EVENT=Bi;exports.TOPIC_TIMER_TICK_EVENT=Ki;exports.TimerManager=Mh;exports.TokenContext=Qh;exports.TokenProvider=gT;exports.Topics=Is;exports.Trans=KT;exports.TransitionMap=vr;exports.Transitions=Vn;exports.Translation=Zr;exports.TranslationContainer=Ve;exports.TranslationContainerContext=Xi;exports.TranslationContext=IM;exports.TransportFactory=rn;exports.Trouble=Ks;exports.TroubleAwareSetup=Ln;exports.TroubleContainer=Ht;exports.TroubleServices=iE;exports.Troubles=we;exports.UsbUpdate=Li;exports.UsbUpdateContainer=zs;exports.UsbUpdateServices=pM;exports.VFS_SERVICE=JM;exports.VFS_SERVICE_1_6_5=GM;exports.VFS_SERVICE_1_8_1=WM;exports.VFS_SERVICE_1_9_X=XM;exports.ViewModelConfig=Un;exports.WS_EVENT_TYPE=gh;exports.WebSocketEvents=Te;exports.WebSocketTransport=Lt;exports.WsEventFactory=Ni;exports.acceptOrgInvitation=Ih;exports.addDaysToDate=Zl;exports.addFuture=Pu;exports.addMonthsToDate=Xl;exports.api=kd;exports.applyFunctionalEnhancements=hl;exports.applyMixins=wy;exports.arraysEqual=Ey;exports.buildConfigBeanModel=cb;exports.buildFuture=pi;exports.buildFutureModel=Au;exports.cancelFuture=ku;exports.checkAppsStarted=sb;exports.checkWildcardPattern=dl;exports.clearAllServiceResponses=zy;exports.clearPath=qy;exports.clearServiceResponse=Hy;exports.convert=ui;exports.convertFileSizeRaw=Wf;exports.convertWithUnits=_b;exports.createBaseMessage=Cl;exports.createBroadcastMessageResponse=kl;exports.createCancellablePromise=f_;exports.createClient=De;exports.createFosBaseMessage=Il;exports.createHeaders=Dl;exports.createKosHtpMessageResponse=Ll;exports.createKosMessage=Rl;exports.createKosMessageResponse=Fl;exports.createMessageBody=ot;exports.createModelDependency=Ml;exports.createOptionKey=Ip;exports.createPropKey=vt;exports.createReadableStream=xl;exports.createStudioMessage=Ol;exports.createStudioMessageRequest=Al;exports.createStudioMessageResponse=Pl;exports.debounce=ll;exports.del=qc;exports.deleteFuture=Ru;exports.destroyKosModel=Re;exports.evaluateScopes=_u;exports.executeApiMethod=Yc;exports.executeChildrenModelLifecycle=Sl;exports.executeDependentModelLifecycle=ls;exports.executeListLifecycle=Tl;exports.fetchModel=IT;exports.findModel=rg;exports.findModels=ol;exports.formatDate=tu;exports.formatDateSince=Ql;exports.formatDateTime=ru;exports.formatTime=su;exports.get=Hc;exports.getAllKosCompanionModels=nl;exports.getCalendarMonthArray=df;exports.getConfigBean=Mu;exports.getDayStrings=hf;exports.getDays=tS;exports.getDaysArray=af;exports.getDaysInMonth=Jn;exports.getDependenciesByLifecycle=_l;exports.getFormattedDate=sS;exports.getFormattedMonth=rS;exports.getFormattedMonthsArray=Ji;exports.getFormattedYear=_e;exports.getFormattedYearsArray=uf;exports.getFutures=jb;exports.getHttpRouteHandlers=zc;exports.getKosCompanionModel=og;exports.getKosConnectionId=Ri;exports.getKosLocalizationDescriptor=lh;exports.getKosMessageLogging=Pc;exports.getKosModel=rl;exports.getKosModelSync=ke;exports.getKosModelType=sg;exports.getKosServiceApi=NM;exports.getKosSessionKey=hu;exports.getLastDayOfMonth=ws;exports.getLocalizationDescriptor=wM;exports.getLogLevel=Rc;exports.getLogMessageToStudio=kc;exports.getMessageBody=sn;exports.getMonthsArray=cf;exports.getObservableCompanions=ng;exports.getQueryParams=de;exports.getServiceResponse=By;exports.getStartedApps=rb;exports.getTranslations=ch;exports.getYearsArray=lf;exports.handleServiceRequestError=Wc;exports.hasCachedResponse=Ky;exports.hasDecimals=wu;exports.hasHttpRouteHandlers=$r;exports.hasKosProfile=Zo;exports.hasReadyHook=fl;exports.hslStringToHex=cu;exports.hslToHex=au;exports.httpDelete=kp;exports.initKosProvider=oT;exports.initializeStateMachine=Bc;exports.injectStateMachineSupport=Bn;exports.isBoolean=ii;exports.isDisposable=yr;exports.isKosCompanionTypeFactory=gl;exports.isKosDataModel=Os;exports.isKosExecutionContext=Kn;exports.isKosLoggingEnabled=ep;exports.isKosModel=Ie;exports.isKosModelContainer=Gn;exports.isKosModelReady=Ir;exports.isLeapYear=Zn;exports.isLocalRefId=Gy;exports.isNumber=go;exports.isPrintable=Xg;exports.isTroubleAware=c_;exports.isValidDate=vs;exports.kosAction=te;exports.kosAutoEffect=X;exports.kosChild=Oe;exports.kosCompanion=Dp;exports.kosComputed=si;exports.kosConfigBean=mo;exports.kosConfigProperty=Rb;exports.kosContainerAware=uo;exports.kosContext=xp;exports.kosDependency=Xt;exports.kosEffect=bu;exports.kosFuture=bo;exports.kosFutureAware=Kc;exports.kosLogger=Lp;exports.kosLoggerAware=Qt;exports.kosModel=D;exports.kosModelEffect=Vc;exports.kosMultipleFutureAware=Ap;exports.kosObservable=ri;exports.kosParentAware=lo;exports.kosReference=Fp;exports.kosServiceRequest=Ye;exports.kosStateBean=Xb;exports.kosStateEntry=Bp;exports.kosStateExit=Kp;exports.kosStateGuard=Hp;exports.kosStateMachine=jp;exports.kosStateProp=nv;exports.kosSubscribe=wg;exports.kosTopicHandler=B;exports.kosTroubleAware=qp;exports.kosViewModel=jg;exports.kosWhen=nn;exports.login=Sh;exports.mapConfigBeanModelToDto=Ou;exports.mapDataToModel=on;exports.mapDtoToConfigBeanModel=Su;exports.mapDtoToFutureModel=fi;exports.mapDtoToFutureOptions=hi;exports.mapUpdateDtoToConfigBeanModel=$u;exports.modelEventTopicFactory=ml;exports.modelFactory=Jt;exports.modelTypeEventTopicFactory=yl;exports.modifyConfigBean=Eu;exports.modifyFuture=Bb;exports.pairedClientHeartbeat=Ry;exports.parseWildcardSegment=ul;exports.pipe=du;exports.post=Xs;exports.preloadKosModel=cg;exports.processId=Sy;exports.processMiddleware=Dy;exports.put=Pp;exports.registerCompanionModel=ag;exports.registerCoreModels=mh;exports.registerExtensionPoint=Zt;exports.registerHttpRoutes=um;exports.registerKosModel=al;exports.registerLegacyModel=il;exports.resetKosModel=tg;exports.resetPassword=Oh;exports.resolveBaseUrl=jl;exports.resolveChild=El;exports.resolveContainerDeltas=My;exports.resolveItemListDeltas=Ty;exports.resolveKosCompanion=Jo;exports.resolveKosContext=Qy;exports.resolveKosProfiles=Ac;exports.resolveListDeltas=_y;exports.resolveServiceRequestParameters=Gc;exports.resolveServiceUrl=fe;exports.resolveVariable=lu;exports.retryWithExponentialBackoff=ky;exports.sendAsyncIntent=eb;exports.sendBroadcastMessage=Mm;exports.sendIntent=Jy;exports.sendKosHttpMessageResponse=Ul;exports.sendKosMessage=vm;exports.sendKosMessageResponse=Nl;exports.sendRequest=Yy;exports.sendStudioMessage=Em;exports.sendStudioMessageRequest=wm;exports.startPasswordReset=$h;exports.stringComponentInsert=sf;exports.studioAcceptOrgInvitation=h_;exports.studioLogin=l_;exports.studioResetPassword=d_;exports.studioStartPasswordReset=u_;exports.subscribeStore=LM;exports.syncPublish=Wy;exports.troubleByTypeReducer=Zc;exports.troubleDataFactory=Dd;exports.unloadKosModel=eg;exports.updateCompanionModelRegistration=Ay;exports.updateModelRegistration=xy;exports.updateRegion=vh;exports.updateTimeZone=mn;exports.useAmPmValues=Af;exports.useCalendarDayArray=wf;exports.useConfigBean=ZT;exports.useConfigProperty=nf;exports.useContextModel=W_;exports.useContextModelHierarchy=Hh;exports.useDateArrays=ff;exports.useDateProps=nS;exports.useDateRelativeConfig=iS;exports.useDateRelativeData=_f;exports.useDayNames=bf;exports.useDayOptions=yf;exports.useDays=ta;exports.useDevice=Zh;exports.useFormattedDate=vf;exports.useFormattedTime=Pf;exports.useFunctionWarmup=aS;exports.useHourValues=xf;exports.useKosCore=Yh;exports.useKosDateFormats=lS;exports.useKosModel=J;exports.useKosRegions=If;exports.useKosTime=Gi;exports.useKosTimeContext=dT;exports.useKosTimeFormats=mS;exports.useKosTimeZones=hS;exports.useKosTranslation=VT;exports.useKosTranslationContext=bT;exports.useLocalComputed=yS;exports.useModelFromHierarchy=J_;exports.useMonths=gf;exports.useMonthsOptions=mf;exports.useMutationObserver=vS;exports.useNetworkInterfaceContainer=Jh;exports.useOta=ef;exports.usePressGesture=wS;exports.useProjectReload=Df;exports.useRegionTimeProps=ES;exports.useRegionalTimeDate=Mf;exports.useSoftwareInfo=Wi;exports.useSoftwareInfoContext=pT;exports.useStateProperty=PT;exports.useStorageDeviceContainer=tf;exports.useSuspenseData=vn;exports.useTimeOptions=Rf;exports.useTimeProps=kf;exports.useTimeValues=wn;exports.useTimer=LT;exports.useTranslationContainer=rf;exports.useTroubleContainerModel=Zi;exports.useTroubleModel=YT;exports.useTroublePresence=WT;exports.useUsbUpdateContainer=of;exports.useViewModel=MS;exports.useYears=ea;exports.useYearsOptions=pf;exports.uuid=wt;exports.variableToHex=Iy;exports.waitForAppToStart=tb;exports.waitForAppsToStart=yu;exports.waitForRequest=ei;exports.whenReady=ye;exports.withDevice=OT;exports.withKosTime=CT;exports.withNetworkInterfaceContainer=DT;exports.withOta=xT;exports.withProjectReloading=_S;exports.withSoftwareInfo=hT;exports.withStorageDeviceContainer=kT;exports.withTranslationContainer=GT;exports.withTroubleContainer=QT;exports.withUsbUpdateContainer=XT;exports.wrapPromise=xn;exports.wrapWithFutureLifecycle=gi;
|
|
228
228
|
//# sourceMappingURL=index.cjs.map
|