@kosdev-code/kos-ui-sdk 2.1.36 → 2.1.38

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.
Files changed (293) hide show
  1. package/common/events/eventBus.d.ts +30 -0
  2. package/common/events/eventBus.d.ts.map +1 -1
  3. package/common/events/eventBus.functional.d.ts +48 -0
  4. package/common/events/eventBus.functional.d.ts.map +1 -1
  5. package/common/events/eventBus.state.d.ts +33 -0
  6. package/common/events/eventBus.state.d.ts.map +1 -1
  7. package/core/core/decorators/fsm-injection-utils.d.ts.map +1 -1
  8. package/core/core/decorators/index.d.ts +1 -0
  9. package/core/core/decorators/index.d.ts.map +1 -1
  10. package/core/core/decorators/kos-child.d.ts +2 -0
  11. package/core/core/decorators/kos-child.d.ts.map +1 -1
  12. package/core/core/decorators/kos-companion.d.ts +14 -0
  13. package/core/core/decorators/kos-companion.d.ts.map +1 -1
  14. package/core/core/decorators/kos-container-aware.d.ts +21 -0
  15. package/core/core/decorators/kos-container-aware.d.ts.map +1 -1
  16. package/core/core/decorators/kos-context.d.ts +6 -0
  17. package/core/core/decorators/kos-context.d.ts.map +1 -1
  18. package/core/core/decorators/kos-execution-context.d.ts +4 -1
  19. package/core/core/decorators/kos-execution-context.d.ts.map +1 -1
  20. package/core/core/decorators/kos-future-aware.d.ts +12 -0
  21. package/core/core/decorators/kos-future-aware.d.ts.map +1 -1
  22. package/core/core/decorators/kos-http-decorators.d.ts +15 -0
  23. package/core/core/decorators/kos-http-decorators.d.ts.map +1 -1
  24. package/core/core/decorators/kos-log.d.ts +4 -0
  25. package/core/core/decorators/kos-log.d.ts.map +1 -1
  26. package/core/core/decorators/kos-logger-aware.d.ts +9 -0
  27. package/core/core/decorators/kos-logger-aware.d.ts.map +1 -1
  28. package/core/core/decorators/kos-model-effect.d.ts +9 -0
  29. package/core/core/decorators/kos-model-effect.d.ts.map +1 -1
  30. package/core/core/decorators/kos-multiple-future-aware.d.ts +14 -0
  31. package/core/core/decorators/kos-multiple-future-aware.d.ts.map +1 -1
  32. package/core/core/decorators/kos-parent.d.ts +4 -0
  33. package/core/core/decorators/kos-parent.d.ts.map +1 -1
  34. package/core/core/decorators/kos-reference.d.ts +9 -0
  35. package/core/core/decorators/kos-reference.d.ts.map +1 -1
  36. package/core/core/decorators/kos-service-request-helpers.d.ts +4 -2
  37. package/core/core/decorators/kos-service-request-helpers.d.ts.map +1 -1
  38. package/core/core/decorators/kos-service-request.d.ts +44 -3
  39. package/core/core/decorators/kos-service-request.d.ts.map +1 -1
  40. package/core/core/decorators/kos-state-machine.d.ts +24 -0
  41. package/core/core/decorators/kos-state-machine.d.ts.map +1 -1
  42. package/core/core/decorators/kos-topic-handler-flow-control.d.ts +17 -1
  43. package/core/core/decorators/kos-topic-handler-flow-control.d.ts.map +1 -1
  44. package/core/core/decorators/kos-trouble-aware.d.ts +6 -0
  45. package/core/core/decorators/kos-trouble-aware.d.ts.map +1 -1
  46. package/core/core/decorators/kos-view-model.d.ts +14 -0
  47. package/core/core/decorators/kos-view-model.d.ts.map +1 -1
  48. package/core/core/decorators/kosDependency.d.ts +2 -0
  49. package/core/core/decorators/kosDependency.d.ts.map +1 -1
  50. package/core/core/decorators/kosModel.d.ts +2 -0
  51. package/core/core/decorators/kosModel.d.ts.map +1 -1
  52. package/core/core/decorators/kosSubscribe.d.ts +9 -0
  53. package/core/core/decorators/kosSubscribe.d.ts.map +1 -1
  54. package/core/core/decorators/kosTopicHandler.d.ts +34 -0
  55. package/core/core/decorators/kosTopicHandler.d.ts.map +1 -1
  56. package/core/core/extension/extension-manager.d.ts +50 -0
  57. package/core/core/extension/extension-manager.d.ts.map +1 -1
  58. package/core/core/extension/initialize-extension.d.ts +24 -0
  59. package/core/core/extension/initialize-extension.d.ts.map +1 -1
  60. package/core/core/extension/plugin-extension-manager.d.ts +11 -0
  61. package/core/core/extension/plugin-extension-manager.d.ts.map +1 -1
  62. package/core/core/kosModel.d.ts +38 -0
  63. package/core/core/kosModel.d.ts.map +1 -1
  64. package/core/core/model/kos-service-request-manager.d.ts.map +1 -1
  65. package/core/core/model/kos-subscription-manager.d.ts.map +1 -1
  66. package/core/core/services/browser-router.d.ts.map +1 -1
  67. package/core/core/transport/webSocketTransport.d.ts +2 -1
  68. package/core/core/transport/webSocketTransport.d.ts.map +1 -1
  69. package/core/index.d.ts +1 -1
  70. package/core/index.d.ts.map +1 -1
  71. package/core/types/kos-dependency.d.ts +10 -1
  72. package/core/types/kos-dependency.d.ts.map +1 -1
  73. package/core/types/service-response-store.d.ts +10 -0
  74. package/core/types/service-response-store.d.ts.map +1 -1
  75. package/core/types/utils/kos-fetch.d.ts +121 -0
  76. package/core/types/utils/kos-fetch.d.ts.map +1 -1
  77. package/core/util/ancestor-path-visitor.d.ts +2 -0
  78. package/core/util/ancestor-path-visitor.d.ts.map +1 -1
  79. package/core/util/api-request-id.d.ts +4 -0
  80. package/core/util/api-request-id.d.ts.map +1 -1
  81. package/core/util/apply-mixins.d.ts +4 -0
  82. package/core/util/apply-mixins.d.ts.map +1 -1
  83. package/core/util/array-utils.d.ts +4 -0
  84. package/core/util/array-utils.d.ts.map +1 -1
  85. package/core/util/container-utils.d.ts +14 -0
  86. package/core/util/container-utils.d.ts.map +1 -1
  87. package/core/util/date-utils.d.ts +29 -0
  88. package/core/util/date-utils.d.ts.map +1 -1
  89. package/core/util/debounce.d.ts +3 -0
  90. package/core/util/debounce.d.ts.map +1 -1
  91. package/core/util/feature-flags.d.ts +19 -0
  92. package/core/util/feature-flags.d.ts.map +1 -1
  93. package/core/util/get-query-params.d.ts +4 -0
  94. package/core/util/get-query-params.d.ts.map +1 -1
  95. package/core/util/hsl-to-hex.d.ts +16 -0
  96. package/core/util/hsl-to-hex.d.ts.map +1 -1
  97. package/core/util/index.d.ts +2 -0
  98. package/core/util/index.d.ts.map +1 -1
  99. package/core/util/kos-config-init.d.ts +36 -0
  100. package/core/util/kos-config-init.d.ts.map +1 -1
  101. package/core/util/kos-data-mapper-utils.d.ts +9 -0
  102. package/core/util/kos-data-mapper-utils.d.ts.map +1 -1
  103. package/core/util/kos-fetch.d.ts +12 -0
  104. package/core/util/kos-fetch.d.ts.map +1 -1
  105. package/core/util/kos-message-utils.d.ts +88 -0
  106. package/core/util/kos-message-utils.d.ts.map +1 -1
  107. package/core/util/kos-model-utils.d.ts +46 -0
  108. package/core/util/kos-model-utils.d.ts.map +1 -1
  109. package/core/util/kos-model-visitor.d.ts +2 -0
  110. package/core/util/kos-model-visitor.d.ts.map +1 -1
  111. package/core/util/kos-org-utils.d.ts +3 -0
  112. package/core/util/kos-org-utils.d.ts.map +1 -0
  113. package/core/util/kos-service-request.d.ts +34 -2
  114. package/core/util/kos-service-request.d.ts.map +1 -1
  115. package/core/util/log-utils.d.ts +12 -0
  116. package/core/util/log-utils.d.ts.map +1 -1
  117. package/core/util/middleware.d.ts +15 -0
  118. package/core/util/middleware.d.ts.map +1 -1
  119. package/core/util/model-attribute-utils.d.ts +7 -0
  120. package/core/util/model-attribute-utils.d.ts.map +1 -1
  121. package/core/util/model-factory.d.ts +4 -0
  122. package/core/util/model-factory.d.ts.map +1 -1
  123. package/core/util/model-registration-utils.d.ts +8 -0
  124. package/core/util/model-registration-utils.d.ts.map +1 -1
  125. package/core/util/model-utils.d.ts +30 -6
  126. package/core/util/model-utils.d.ts.map +1 -1
  127. package/core/util/observable-proxy-map.d.ts +11 -0
  128. package/core/util/observable-proxy-map.d.ts.map +1 -1
  129. package/core/util/paired-client-heartbeat.d.ts +2 -0
  130. package/core/util/paired-client-heartbeat.d.ts.map +1 -1
  131. package/core/util/pipe.d.ts +4 -0
  132. package/core/util/pipe.d.ts.map +1 -1
  133. package/core/util/retry-with-exponential-backoff.d.ts +3 -0
  134. package/core/util/retry-with-exponential-backoff.d.ts.map +1 -1
  135. package/core/util/service-factory.d.ts +10 -0
  136. package/core/util/service-factory.d.ts.map +1 -1
  137. package/core/util/service-request-error.d.ts +60 -0
  138. package/core/util/service-request-error.d.ts.map +1 -0
  139. package/core/util/service-response.d.ts +15 -0
  140. package/core/util/service-response.d.ts.map +1 -1
  141. package/core/util/session-utils.d.ts +8 -0
  142. package/core/util/session-utils.d.ts.map +1 -1
  143. package/core/util/wait-for-request.d.ts +16 -0
  144. package/core/util/wait-for-request.d.ts.map +1 -1
  145. package/core/util/when-ready.d.ts +3 -0
  146. package/core/util/when-ready.d.ts.map +1 -1
  147. package/index.cjs +70 -70
  148. package/index.cjs.map +1 -1
  149. package/index.d.cts +6 -4
  150. package/index.d.ts +6 -4
  151. package/index.d.ts.map +1 -1
  152. package/index.js +9257 -9251
  153. package/index.js.map +1 -1
  154. package/kos-models.json +426 -0
  155. package/models/constants/index.d.ts +3 -1
  156. package/models/constants/index.d.ts.map +1 -1
  157. package/models/decorators/future-service.d.ts.map +1 -1
  158. package/models/models/browser-router/types/index.d.ts +1 -0
  159. package/models/models/canvas-dispatcher/types/index.d.ts +5 -0
  160. package/models/models/canvas-renderer/types/index.d.ts +5 -0
  161. package/models/models/config-bean/config-bean-model.d.ts.map +1 -1
  162. package/models/models/config-bean/types/index.d.ts +1 -0
  163. package/models/models/config-bean-prop/config-bean-prop-model.d.ts +1 -1
  164. package/models/models/config-bean-prop/config-bean-prop-model.d.ts.map +1 -1
  165. package/models/models/config-bean-prop/types/index.d.ts +8 -2
  166. package/models/models/device/types/index.d.ts +1 -0
  167. package/models/models/future/future-types.d.ts +14 -0
  168. package/models/models/future/future-types.d.ts.map +1 -1
  169. package/models/models/gpio-chip/gpio-chip-container-model.d.ts +25 -0
  170. package/models/models/gpio-chip/gpio-chip-container-model.d.ts.map +1 -0
  171. package/models/models/gpio-chip/gpio-chip-model.d.ts +30 -0
  172. package/models/models/gpio-chip/gpio-chip-model.d.ts.map +1 -0
  173. package/models/models/gpio-chip/index.d.ts +7 -0
  174. package/models/models/gpio-chip/index.d.ts.map +1 -0
  175. package/models/models/gpio-chip/services/gpio-chip-services.d.ts +86 -0
  176. package/models/models/gpio-chip/services/gpio-chip-services.d.ts.map +1 -0
  177. package/models/models/gpio-chip/services/index.d.ts +2 -0
  178. package/models/models/gpio-chip/services/index.d.ts.map +1 -0
  179. package/models/models/gpio-chip/types/index.d.ts +24 -0
  180. package/models/models/gpio-pin/gpio-pin-container-model.d.ts +23 -0
  181. package/models/models/gpio-pin/gpio-pin-container-model.d.ts.map +1 -0
  182. package/models/models/gpio-pin/gpio-pin-model.d.ts +26 -0
  183. package/models/models/gpio-pin/gpio-pin-model.d.ts.map +1 -0
  184. package/models/models/gpio-pin/index.d.ts +6 -0
  185. package/models/models/gpio-pin/index.d.ts.map +1 -0
  186. package/models/models/gpio-pin/types/index.d.ts +23 -0
  187. package/models/models/key-value/types/index.d.ts +1 -0
  188. package/models/models/kos-expression-evaluator/types/index.d.ts +5 -0
  189. package/models/models/kos-log-manager/types/index.d.ts +4 -0
  190. package/models/models/kos-time/types/index.d.ts +3 -0
  191. package/models/models/log-block/types/index.d.ts +4 -0
  192. package/models/models/log-stream/types/index.d.ts +3 -1
  193. package/models/models/network-interface/services/network-interface-services.d.ts.map +1 -1
  194. package/models/models/network-interface/types/index.d.ts +1 -0
  195. package/models/models/ota/types/index.d.ts +31 -0
  196. package/models/models/region-info/region-info-model.d.ts +1 -0
  197. package/models/models/region-info/region-info-model.d.ts.map +1 -1
  198. package/models/models/region-info/services/region-info-services.d.ts +2 -2
  199. package/models/models/region-info/services/region-info-services.d.ts.map +1 -1
  200. package/models/models/region-info/types/index.d.ts +50 -0
  201. package/models/models/region-info/types/index.d.ts.map +1 -1
  202. package/models/models/software-info/services/software-info-services.d.ts.map +1 -1
  203. package/models/models/software-info/types/index.d.ts +4 -1
  204. package/models/models/state-bean/types/index.d.ts +3 -0
  205. package/models/models/state-prop/types/index.d.ts +2 -0
  206. package/models/models/storage-device/types/index.d.ts +2 -0
  207. package/models/models/translation/types/index.d.ts +3 -0
  208. package/models/models/trouble/services/trouble-services.d.ts +1 -0
  209. package/models/models/trouble/services/trouble-services.d.ts.map +1 -1
  210. package/models/models/trouble/trouble-model.d.ts +3 -1
  211. package/models/models/trouble/trouble-model.d.ts.map +1 -1
  212. package/models/models/trouble/types/index.d.ts +12 -0
  213. package/models/models/trouble-container/trouble-container-model.d.ts +3 -2
  214. package/models/models/trouble-container/trouble-container-model.d.ts.map +1 -1
  215. package/models/models/trouble-container/types/index.d.ts +5 -0
  216. package/models/models/usb-update/types/index.d.ts +10 -0
  217. package/models/utils/client.d.ts +4 -0
  218. package/models/utils/client.d.ts.map +1 -1
  219. package/models/utils/extension-manager.d.ts +5 -0
  220. package/models/utils/extension-manager.d.ts.map +1 -1
  221. package/models/utils/get-kos-connection-id.d.ts +2 -0
  222. package/models/utils/get-kos-connection-id.d.ts.map +1 -0
  223. package/models/utils/index.d.ts +2 -0
  224. package/models/utils/index.d.ts.map +1 -1
  225. package/models/utils/openapi-index.d.ts +2 -2
  226. package/models/utils/service-accessor.d.ts +86 -0
  227. package/models/utils/service-accessor.d.ts.map +1 -0
  228. package/models/utils/service.d.ts +4 -0
  229. package/models/utils/service.d.ts.map +1 -1
  230. package/models/utils/services/kos/1.6.5/service.d.ts +4 -0
  231. package/models/utils/services/kos/1.6.5/service.d.ts.map +1 -1
  232. package/models/utils/services/kos/1.8.1/service.d.ts +4 -0
  233. package/models/utils/services/kos/1.8.1/service.d.ts.map +1 -1
  234. package/models/utils/services/kos/1.9.x/openapi.d.ts +4597 -0
  235. package/models/utils/services/kos/1.9.x/service.d.ts +124 -0
  236. package/models/utils/services/kos/1.9.x/service.d.ts.map +1 -0
  237. package/models/utils/services/kos/daily/service.d.ts +4 -0
  238. package/models/utils/services/kos/daily/service.d.ts.map +1 -1
  239. package/models/utils/services/vfs/1.6.5/service.d.ts +4 -0
  240. package/models/utils/services/vfs/1.6.5/service.d.ts.map +1 -1
  241. package/models/utils/services/vfs/1.8.1/service.d.ts +4 -0
  242. package/models/utils/services/vfs/1.8.1/service.d.ts.map +1 -1
  243. package/models/utils/services/vfs/1.9.x/openapi.d.ts +51 -0
  244. package/models/utils/services/vfs/1.9.x/service.d.ts +124 -0
  245. package/models/utils/services/vfs/1.9.x/service.d.ts.map +1 -0
  246. package/models/utils/services/vfs/daily/service.d.ts +4 -0
  247. package/models/utils/services/vfs/daily/service.d.ts.map +1 -1
  248. package/models/utils/services-index.d.ts +2 -0
  249. package/models/utils/services-index.d.ts.map +1 -1
  250. package/package.json +4 -2
  251. package/ui/hooks/device/use-device.d.ts +6 -0
  252. package/ui/hooks/device/use-device.d.ts.map +1 -1
  253. package/ui/hooks/kos-time/use-kos-time.d.ts +6 -0
  254. package/ui/hooks/kos-time/use-kos-time.d.ts.map +1 -1
  255. package/ui/hooks/network-interface-container/use-network-interface-container.d.ts +6 -0
  256. package/ui/hooks/network-interface-container/use-network-interface-container.d.ts.map +1 -1
  257. package/ui/hooks/ota/use-ota.d.ts +6 -0
  258. package/ui/hooks/ota/use-ota.d.ts.map +1 -1
  259. package/ui/hooks/software-info/use-software-info.d.ts +6 -0
  260. package/ui/hooks/software-info/use-software-info.d.ts.map +1 -1
  261. package/ui/hooks/storage-device-container/use-storage-device-container.d.ts +6 -0
  262. package/ui/hooks/storage-device-container/use-storage-device-container.d.ts.map +1 -1
  263. package/ui/hooks/translation-container/trans.d.ts +6 -0
  264. package/ui/hooks/translation-container/trans.d.ts.map +1 -1
  265. package/ui/hooks/translation-container/use-translation-container.d.ts +6 -0
  266. package/ui/hooks/translation-container/use-translation-container.d.ts.map +1 -1
  267. package/ui/hooks/translation-container/use-translation.d.ts +7 -0
  268. package/ui/hooks/translation-container/use-translation.d.ts.map +1 -1
  269. package/ui/hooks/translation-container/with-translation-container.d.ts +6 -0
  270. package/ui/hooks/translation-container/with-translation-container.d.ts.map +1 -1
  271. package/ui/hooks/usb-update-container/use-usb-update-container.d.ts +6 -0
  272. package/ui/hooks/usb-update-container/use-usb-update-container.d.ts.map +1 -1
  273. package/ui/hooks/use-config-bean.d.ts +6 -0
  274. package/ui/hooks/use-config-bean.d.ts.map +1 -1
  275. package/ui/hooks/use-config-property.d.ts +6 -0
  276. package/ui/hooks/use-config-property.d.ts.map +1 -1
  277. package/ui/hooks/use-kos-model.d.ts +6 -0
  278. package/ui/hooks/use-kos-model.d.ts.map +1 -1
  279. package/ui/hooks/use-kos-regions.d.ts.map +1 -1
  280. package/core/core/declarative/declarative-actions-wiring.d.ts +0 -13
  281. package/core/core/declarative/declarative-actions-wiring.d.ts.map +0 -1
  282. package/core/core/declarative/declarative-model-bindings.d.ts +0 -191
  283. package/core/core/declarative/declarative-model-bindings.d.ts.map +0 -1
  284. package/core/core/declarative/declarative-model-discovery.d.ts +0 -74
  285. package/core/core/declarative/declarative-model-discovery.d.ts.map +0 -1
  286. package/core/core/declarative/declarative-model-factory.d.ts +0 -58
  287. package/core/core/declarative/declarative-model-factory.d.ts.map +0 -1
  288. package/core/core/declarative/declarative-model-types.d.ts +0 -96
  289. package/core/core/declarative/declarative-model-types.d.ts.map +0 -1
  290. package/core/core/declarative/index.d.ts +0 -7
  291. package/core/core/declarative/index.d.ts.map +0 -1
  292. package/core/core/declarative/types.d.ts +0 -304
  293. package/core/core/declarative/types.d.ts.map +0 -1
package/index.cjs CHANGED
@@ -1,19 +1,19 @@
1
- "use strict";var hf=Object.defineProperty;var ff=(t,e,s)=>e in t?hf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var l=(t,e,s)=>(ff(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("loglevel"),M=require("mobx"),b=require("robot3"),Ze=require("date-fns"),T=require("@emotion/react/jsx-runtime"),mn=require("@emotion/styled"),Va=require("react-dom"),ut=require("@emotion/react"),y=require("react"),yn=require("mobx-react-lite"),pf=require("@use-gesture/react"),Zr="method",Ga="topic",Zt="url",qs="request-id",Xr="response-id",bn="status",Ge="dst-addr",Ya="src-addr",ke="type",vn="ordered",wn="tracker",Wa="Content-Type",Qa="Cache-Control",Za="requestId",Xa=process.env.KOS_LOGIN_URL||"http://localhost",Ja=process.env.KOS_APP_PORT||"8080",gf=`${Xa}:${Ja}`,Mr="{MODEL_ID}";var zs=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(zs||{}),ec=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(ec||{});const En="/kos/model/ready/";A.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const V=globalThis.kos.subscriptions,mf=()=>Symbol("eventKey");function Mn(t){return V[t]&&Object.getOwnPropertySymbols(V[t]).length>0}function C(t,e){const s=mf();return V[t]||(A.debug(`Initializing subscription for ${t}`),V[t]={}),A.debug(`Subscribing to ${t} with id ${s.toString()}`),V[t][s]=e,{count:V[t]?Object.getOwnPropertySymbols(V[t]).length:0,unsubscribe:()=>(A.debug(`Unsubscribing from ${t} with id ${s.toString()}`),V[t]&&V[t][s]&&delete V[t][s],V[t]&&Object.getOwnPropertySymbols(V[t]).length===0&&delete V[t],{count:V[t]?Object.getOwnPropertySymbols(V[t]).length:0})}}function K(t,e,s={}){if(!V[t]||Object.getOwnPropertySymbols(V[t]).length===0)return A.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(V[t]).length;return Object.getOwnPropertySymbols(V[t]).forEach(o=>{if(s.sync){const n=s.sync;A.debug(`Performing sync publish for ${t} with sync id ${n}`),V[t][o]({body:e,headers:s}).then(i=>{A.debug(`Response recieved for ${n}, publishing back to source.`),K(n,i)})}else A.debug(`Performing async publish for ${t}`),V[t][o]({body:e,headers:s})}),{eventType:t,subscribers:r}}function yf(){A.warn("Resetting event bus"),Object.keys(V).forEach(t=>delete V[t])}function tc(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function Tn(t,e){return new Promise((s,r)=>{let o=null;const n=tc(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const bf=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:Mn,once:tc,publish:K,reset:yf,subscribe:C,waitFor:Tn},Symbol.toStringTag,{value:"Module"}));function Jr(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function eo(t,e){return new Promise((s,r)=>{let o=null;const n=Jr(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function sc(t,e){const s=t.map(r=>eo(r,e));return Promise.all(s)}function rc(t,e){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};t.forEach(c=>{const u=Jr(c,d=>{i||(i=!0,a(),s({eventType:c,data:d}))});o.push(u)}),e&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function oc(t,e,s){return C(t,o=>{o&&e(o)&&s(o)}).unsubscribe}function nc(t,e,s){return C(t,o=>{if(o){const n=e(o);s(n)}}).unsubscribe}function ic(t,e,s){let r=null;const o=C(t,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},e)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function ac(t,e,s){let r=0,o=null;const n=C(t,i=>{const a=Date.now(),c=a-r;c>=e?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},e-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function cc(t,e,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=C(t,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},e)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function _n(t,e=1){const s=[];return C(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),C(t,r))}}function lc(t,e){const s=t.map(r=>C(r,o=>{o&&e(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function uc(t,e){let s=t;const r=[],o=new Set;return Object.values(e).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=C(n,a=>{const c=e[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function dc(t,e,s,r){const o=eo(e,r);return K(t,s),o}async function*hc(t){const e=[],s=[],r=C(t,o=>{o&&(s.length>0?s.shift()(o):e.push(o))});try{for(;;)e.length>0?yield e.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const vf={once:Jr,waitFor:eo,waitForAll:sc,race:rc,filter:oc,map:nc,debounce:ic,throttle:ac,buffer:cc,replay:_n,merge:lc,stateMachine:uc,request:dc,eventIterator:hc},wf=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:vf,buffer:cc,debounce:ic,eventIterator:hc,filter:oc,map:nc,merge:lc,once:Jr,race:rc,replay:_n,request:dc,stateMachine:uc,throttle:ac,waitFor:eo,waitForAll:sc},Symbol.toStringTag,{value:"Module"}));async function to(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=e,i=Tn(t,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(c),100)})])}function fc(t,e,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=C(t,a=>{a&&(n=!0,e(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||e(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function pc(t,e){let s;const r=new Set,o=async()=>{try{typeof e=="string"?s=await(await fetch(e)).json():s=await e(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};C(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let n=!1;const i=()=>{n||(n=!0,o())};return{get state(){return s},async getState(){return i(),s===void 0&&await new Promise(a=>{const c=()=>{s!==void 0?a():setTimeout(c,10)};c()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function Sn(t,e){if(typeof t=="string")return to(t,e);const s=t,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=e,i=await r(),a=e.transformState?e.transformState(i):i;if(o&&o(a))return a;const c=s.map(d=>Tn(d,n)),u=await Promise.all(c);return u[u.length-1]}function gc(t,e,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=C(t,async u=>{if(u){if(n){const d=n(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await e(u)}}),c=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(n){const f=n(h);i.has(f)||(i.add(f),await e(h))}else await e(h)}catch(u){console.error("Failed to fetch missed events:",u)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function mc(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await to(e,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:d});return a.state="connected",a.data=h,u(),h},subscribe(d){return c.add(d),d(a),()=>{c.delete(d)}},async reconnect(){a.state="connecting",u();try{const d=await n();a.state="connected",a.data=d,u()}catch{a.state="error",u(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,u=()=>{c.forEach(d=>d(a))};return C(e,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),C(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&C(r,()=>{a.state="error",u()}),o&&C(o,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const Ef={waitForOrGetState:to,subscribeWithInitialState:fc,createStatefulEventStream:pc,waitForAllWithState:Sn,createResilientEventHandler:gc,createConnectionStateManager:mc},Mf=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Ef,createConnectionStateManager:mc,createResilientEventHandler:gc,createStatefulEventStream:pc,subscribeWithInitialState:fc,waitForAllWithState:Sn,waitForOrGetState:to},Symbol.toStringTag,{value:"Module"})),Tf=(t,e=0)=>{if(!+t)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=e<0?0:e,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(t)/Math.log(s)),i=parseFloat((t/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function On(t){let e="pending",s;const r=t.then(n=>{e="success",s=n},n=>{e="error",s=n});return{read:()=>{switch(e){case"pending":throw r;case"error":throw s;default:return s}}}}const be=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),_f="studio.enable.releases",yc="studio.tools.preview",Sf="studio.relax.store.validation",bc="studio.log.debug",vc="studio.log.info",Of={profiles:[yc]};var za;const If=((za=globalThis.getKosConfig)==null?void 0:za.call(globalThis))||JSON.stringify(Of),wc=JSON.parse(If);globalThis.kosConfig=wc;const In=wc,Ec=()=>In.profiles||[],Go=t=>Ec().includes(t),$f=()=>In.logging||!1,Cf=()=>{const t=Go(bc),e=Go(vc);return t?"DEBUG":e?"INFO":void 0},Mc=()=>{const t=be(),e=Cf(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},Tc=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",_c=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Sc="ws-log",Df=A.methodFactory,Oc=Tc(),Af=_c();A.methodFactory=function(t,e,s){const r=Df(t,e,s);return function(...o){var c;const n=s?String(s):"",i=n?`[${String(n).substring(n.lastIndexOf(":")+1)}] | `:"[root] | ",a=o.map(u=>typeof u=="object"?JSON.stringify(u):String(u)).join(" ");r(`${i}${a}`),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==Sc||Oc&&Af)&&globalThis.kosLog(`UI: ${i}${a}`)}};let Ic=Mc();A.setLevel(Ic);window.setKosLogLevel=t=>{Ic=t,A.setLevel(t)};const Tr=A.getLogger(Sc);window.enableKosMessageLog=()=>{Tr.setLevel(A.levels.INFO)};window.disableKosMessageLog=()=>{Tr.setLevel(A.levels.ERROR)};Oc?window.enableKosMessageLog():window.disableKosMessageLog();const xf=["color: black","display: block","background-color: lightgreen","padding: 4px","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),Rf=["color: black","display: block","padding: 4px","background-color: yellow","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),er=t=>e=>{A.getLevel()<=t&&e()},m={...A,ifDebug:er(A.levels.DEBUG),ifInfo:er(A.levels.INFO),ifWarn:er(A.levels.WARN),ifError:er(A.levels.ERROR),getLogger:t=>A.getLogger(`kos::${t}`),getLoggers:()=>A.getLoggers(),createLogger:({name:t,group:e})=>{var n,i,a,c;const s=`${e?`${e}:`:"kos"}::${t}`,r=A.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(u=>u.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Tr.info(`%c⬆ ${e}`,xf)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Tr.info(`%c⬇ ${e}`,Rf)}},X=Symbol("SubscriptionHandlers"),x=Symbol("DependencyModels"),xt=Symbol("FutureService"),_e=Symbol("ChildModels"),_s=Symbol("ParentModel"),Rt=Symbol("LogConfig"),fr=Symbol("ReferenceConfig"),$n=Symbol("KosModelSymbol"),xe=Symbol("ModelEffects"),Je=Symbol("CompanionParentModel"),so=Symbol("FutureContainerSetup"),ro=Symbol("MultipleFutureContainerSetup"),Pt=Symbol("FutureAliases"),Cn=Symbol("TroubleAwareSetup"),oo=Symbol("LoggerSetup"),no=Symbol("ContainerAwareSetup"),Xt=Symbol("StateMachineSetup"),kt=Symbol("StateEntryHandlers"),Ss=Symbol("StateExitHandlers"),Pf=Symbol("StateActionHandlers"),Vs=Symbol("OptionsRequired"),$c=Symbol("KosViewModelSymbol"),Dn=Symbol("ViewModelConfig"),Cc=Symbol("ReloadAwareSetup"),An=m.createLogger({group:"decorators",name:"fsm-injection"});function xn(t){const e=t[Xt];if(!e)return;const{config:s,options:r}=e;Nf(t,s,r),Uf(t,r);const o=Ff(t);kf(t,s,r,o),Lf(t,s,r)}function kf(t,e,s,r){t.transition=Hf(t,e,s,r.entry,r.exit),t.canTransition=Zf(t,e,s),t.isInState=Xf(t,s)}function Lf(t,e,s){jf(t),Bf(t,e,s)}function Ff(t){const e=t.constructor.prototype[kt]||new Map,s=t.constructor.prototype[Ss]||new Map;return{entry:e,exit:s}}function Nf(t,e,s){t._fsmConfig=e,t._fsmOptions=s}function Uf(t,e){const{stateProperty:s,trackHistory:r,computeInitialState:o}=e,n=t._fsmConfig,i=o?o(t):n.initial;o&&!n.states[i]?(An.warn(`computeInitialState returned "${i}" which is not a valid state. Falling back to "${n.initial}".`),t[s]=n.initial):t[s]=i,t._fsmInitialized=!0,t.isTransitioning=!1,r&&(t.stateHistory=[{state:t[s],timestamp:new Date}])}function jf(t){Object.defineProperty(t,"isFsmInitialized",{get(){return this._fsmInitialized},enumerable:!0,configurable:!0})}function Bf(t,e,s){const{stateProperty:r}=s;Object.defineProperty(t,"allowedTransitions",{get(){if(!this._fsmInitialized)return[];const o=this[r],n=this._fsmConfig.states[o];return n!=null&&n.on?Object.keys(n.on):[]},enumerable:!0,configurable:!0})}function Hf(t,e,s,r,o){const{stateProperty:n,throwOnInvalid:i}=s;return function(a){if(!this._fsmInitialized){Kf(e.initializeAt,i);return}const c=this[n],u=qf(c,a,this._fsmConfig,i);u&&Vf(this,c,u,a,n,r,o,s)}}function Kf(t,e){const s=`Cannot transition: FSM not initialized. Waiting for ${t} lifecycle phase.`;if(e)throw new Error(s);console.warn(s)}function qf(t,e,s,r){var i;const o=s.states[t],n=(i=o==null?void 0:o.on)==null?void 0:i[e];if(!n){zf(t,e,r);return}return n}function zf(t,e,s){const r=`Invalid transition: Event "${e}" not allowed from state "${t}"`;if(s)throw new Error(r);console.warn(r)}function Vf(t,e,s,r,o,n,i,a){t.isTransitioning=!0;try{Gf(t,e,i),t[o]=s,Qf(t,s,r,a);const c=Yf(t,s,n);Wf(t,s,o,c)}finally{t.isTransitioning=!1}}function Gf(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function Yf(t,e,s){const r=s.get(e);if(r&&typeof t[r]=="function")return t[r]()}function Wf(t,e,s,r){var n,i;if(!r||typeof r.then!="function")return;const o=(i=(n=t._fsmConfig)==null?void 0:n.states)==null?void 0:i[e];!(o!=null&&o.onDone)&&!(o!=null&&o.onError)||r.then(()=>{o.onDone&&t[s]===e&&t.transition(o.onDone)},a=>{o.onError&&t[s]===e?t.transition(o.onError):An.error(`Async entry handler for state "${e}" failed:`,a)})}function Qf(t,e,s,r){r.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date,event:s})}function Zf(t,e,s){const{stateProperty:r}=s;return function(o){var a;if(!this._fsmInitialized)return!1;const n=this[r],i=this._fsmConfig.states[n];return((a=i==null?void 0:i.on)==null?void 0:a[o])!==void 0}}function Xf(t,e){const{stateProperty:s}=e;return function(r){return this._fsmInitialized?this[s]===r:!1}}function Dc(t,e){const s=t[Xt];if(!s)return;const{config:r,options:o}=s,{stateProperty:n}=o;r.initializeAt===e&&(t._fsmInitialized||(Jf(t,n,r.initial),t._fsmInitialized=!0,ep(t,r.initial,o),tp(t,r.initial),An.debug(`FSM initialized for model ${t.id} at lifecycle ${e} with initial state "${r.initial}"`)))}function Jf(t,e,s){t[e]=s}function ep(t,e,s){s.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date})}function tp(t,e){const r=(t.constructor.prototype[kt]||new Map).get(e);r&&typeof t[r]=="function"&&t[r]()}const Le=(t,e)=>{t[_e]=t[_e]||{},t[_e][e]=!0},yt=t=>`{PROP_${String(t)}}`,sp=t=>`{PROP_${String(t)}}`,rp=yt("kosParentId"),io=t=>e=>{e[_s]=e[_s]||{};const s=(t==null?void 0:t.parentId)||rp;e[_s]={parentId:s},e.prototype[Vs]=!0};function op(t){return e=>{const s=(t==null?void 0:t.mode)||"decorator",r=(t==null?void 0:t.parentProperty)||"companionParent",o=(t==null?void 0:t.excludeProperties)||[],n=t==null?void 0:t.lifecycle;return io()(e),e.prototype[Je]={mode:s,parentProperty:r,excludeProperties:o,lifecycle:n},e}}function Ac(t){return e=>{const s=t!=null&&t.legacy?"_models":(t==null?void 0:t.containerProperty)||"container",r=(t==null?void 0:t.includeMethods)!==!1,o=(t==null?void 0:t.includeGetters)!==!1,n=(t==null?void 0:t.modelsProperty)||"models",i=(t==null?void 0:t.containerOptions)||{};return e.prototype[no]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(t==null?void 0:t.legacy)||!1},e}}function np(t,e,s){const r=s.value;s.value=function(...o){const n=W.getContext(this.id);return o.push(n),r.apply(this,o)}}const ao=Symbol("KosExecutionContext");function Rn(t){return t&&typeof t=="object"&&ao in t}function ip(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[so]={mode:s,handlerProperty:r},e}}function ap(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[ro]={mode:s,handlerProperty:r},e}}var D=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(D||{}),Xe=(t=>(t.CREATE="create",t.CONTINUE="continue",t.FAIL="fail",t))(Xe||{});const cp=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:D,DependencyResolutionPolicy:Xe},Symbol.toStringTag,{value:"Module"})),Be=Symbol("HttpRouteHandlers"),Yi="__httpBrowserRouter";function co(t){return function(s){return function(r,o,n){r[Be]=r[Be]||[];const i={method:t,path:s,handler:o};return r[Be].push(i),r[x]=r[x]||{},r[x][Yi]||(r[x][Yi]={modelType:"browser-router-model",lifecycle:D.INIT}),n}}}const xc=co("GET"),Gs=co("POST"),lp=co("PUT"),Rc=co("DELETE"),up=Rc;function _r(t){return!!(t!=null&&t[Be])&&t[Be].length>0}function Pc(t){return(t==null?void 0:t[Be])||[]}const dp=({group:t}={group:""})=>e=>{e[Rt]=e[Rt]||{},e[Rt]={group:t}};class Pn{static create({modelId:e,modelTypeName:s,component:r}){const o=[r??"kos",s,e].filter(Boolean).join(".");return m.createLogger({name:o})}}function kc(t){return e=>{const s=(t==null?void 0:t.loggerProperty)||"logger",r=t==null?void 0:t.loggerContext;e.prototype[oo]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=e.prototype[$n])==null?void 0:i.type};let n;return Object.defineProperty(e.prototype,s,{get(){if(!n){const i=o();n=Pn.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),e}}function Lc(t){return(e,s,r)=>{e[xe]=e[xe]||{},e[xe][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const hp=t=>(e,s)=>{e[fr]=e[fr]||{},e[fr][s]=t},Io=m.createLogger({name:"resolve-parameters"}),fe=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=fe({value:r[n],modelId:e,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp("{PROP_(.+?)}","g");let n=r!=null&&r.includes(Mr)?r.replace(Mr,e):r;if(s){let i=!1;const a=/^{PROP_.+?}$/.test(n);if(n=n.replace(o,(c,u)=>{if(Object.getOwnPropertyNames(s).includes(u)||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(u)){const h=s[u];return h!=null?(Io.debug(`Resolved ${c} to ${h}`),h):(Io[a?"debug":"warn"](`Property ${u} is null or undefined${a?"":" in composite string"}, marking for undefined return`),i=!0,c)}return Io[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),c}),i)return}return n}else return r;return r};function fp(t,e,s,r){const o=fe({value:t.path,modelId:e.id,modelData:e}),n=fe({modelId:e.id,modelData:e,value:{...typeof t.pathParams=="function"?t.pathParams(e):t.pathParams||{},...(r==null?void 0:r.pathParams)||{}}}),i=fe({modelId:e.id,modelData:e,value:{...typeof t.queryParams=="function"?t.queryParams(e):t.queryParams||{},...(r==null?void 0:r.queryParams)||{}}}),a=(r==null?void 0:r.body)||(typeof t.body=="function"?t.body(e):t.body),u={...(typeof t.requestOptions=="function"?t.requestOptions(e,...s):t.requestOptions)||{},...(r==null?void 0:r.requestOptions)||{}},d={};return n&&Object.keys(n).length>0&&(d.path=n),i&&Object.keys(i).length>0&&(d.query=i),{resolvedPath:o,apiParams:d,finalBody:a,finalRequestOptions:u}}async function pp(t,e,s,r,o,n){const i=(e||"get").toLowerCase(),a=t;switch(i){case"get":return await a.get(s,r,n);case"post":return await a.post(s,r,o,n);case"put":return await a.put(s,r,o,n);case"delete":return await a.delete(s,r,o,n);default:return await a.get(s,r,n)}}function gp(t,e,s,r){if(!s)return[t,null];switch(s.strategy){case"log":return console.error(`Service request status ${e==null?void 0:e.status} error: ${t}`),s.onError&&s.onError(new Error(t),r),[null,s.defaultValue];case"ignore":return[null,s.defaultValue];case"default":return[null,s.defaultValue];case"throw":default:return[t,null]}}const He=Symbol("ServiceRequestHandlers"),Wi=new WeakMap;function bt(t){return(e,s,r)=>{var a;e[He]=e[He]||{};const o=r.value,n={...t,handlerMethod:s,originalHandler:o},i=`${((a=t.method)==null?void 0:a.toUpperCase())||"GET"}:${String(t.path)}`;if(e[He][i]=n,!t.lifecycle){const c=function(...u){const d=u[u.length-1],h=async f=>{const p=Wi.get(c);if(!p)throw new Error("Service request metadata not found for method");try{const{default:g}=await Promise.resolve().then(()=>Ol),{resolvedPath:v,apiParams:E,finalBody:_,finalRequestOptions:k}=fp(p,this,u,f),[S,O]=await pp(g,p.method,v,E,_,k);if(S)return gp(S,O,p.errorHandler,this);let N=O;return p.transform&&(N=p.transform(O)),[null,N]}catch(g){return[g.message||"Unknown error",null]}};if(Rn(d))return d.$request=h,o.apply(this,u);{const f={[ao]:!0,$request:h};return o.apply(this,[...u,f])}};Wi.set(c,n),r.value=c}return r}}var Fc=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(Fc||{}),Z=(t=>(t.IMMEDIATE="immediate",t.SINGLE="single",t.TTL="ttl",t.PERMANENT="permanent",t.MANUAL="manual",t))(Z||{}),pt=(t=>(t.ALL="all",t.AFTER_REQUEST="after-request",t.AFTER_RESPONSE="after-response",t.NONE="none",t))(pt||{});const mp=m.createLogger({name:"kos-state-machine"});function yp(t,e){return s=>(s.prototype[Xt]={config:{...t,initializeAt:t.initializeAt||D.READY},options:{stateProperty:(e==null?void 0:e.stateProperty)||"currentState",trackHistory:(e==null?void 0:e.trackHistory)||!1,throwOnInvalid:(e==null?void 0:e.throwOnInvalid)!==!1,computeInitialState:e==null?void 0:e.computeInitialState}},s)}function bp(t){return(e,s)=>{e[kt]||(e[kt]=new Map),e[kt].set(t,s)}}function vp(t){return(e,s)=>{e[Ss]||(e[Ss]=new Map),e[Ss].set(t,s)}}function wp(t){return(e,s,r)=>{const o=r.value;return r.value=function(...n){var u,d;if(!this.isFsmInitialized)return o.apply(this,n);const a=this.currentState;if(!t.allowedStates.includes(a)){const h=`Method ${String(s)} cannot be called from state "${a}". Allowed states: ${t.allowedStates.join(", ")}`;if(t.throwOnInvalid!==void 0?t.throwOnInvalid:((d=(u=this[Xt])==null?void 0:u.options)==null?void 0:d.throwOnInvalid)!==!1)throw new Error(h);mp.warn(h);return}return o.apply(this,n)},r}}function Ep(t){return e=>{const s=(t==null?void 0:t.pathProperty)||"path";return e.prototype[Cn]={pathProperty:s},e.prototype[x]=e.prototype[x]||{},e.prototype[x].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},e}}const Jt=({modelType:t,id:e,options:s,lifecycle:r,resolutionPolicy:o})=>(n,i)=>{n[x]=n[x]||{},n[x][i]={modelType:t,id:e,options:s,lifecycle:r||D.INIT,resolutionPolicy:o}};class Nc{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=Li.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,M.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=s,o=Q(()=>{var n,i;(e.endState||e.progress)&&((i=(n=this.container)==null?void 0:n.onFutureUpdate)==null||i.call(n,e,r))});this.disposers.set(s||e.id,o)}removeFuture(e){var s;this.futures.delete(e||this.context),(s=this.disposers.get(e||this.context))==null||s(),this.disposers.delete(e||this.context)}getFuture(e){return this.futures.get(e||this.context)}get futureMap(){return this.futures}}class lo{constructor(e){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,M.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=Q(()=>{var r,o;(e.endState||e.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw m.error(e),e}}}const Uc=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},jc=Symbol("KosObservableData"),Qe=Symbol("revision");var B_;class Bc{constructor(){l(this,"map");l(this,B_,1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return s===Qe||e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var o;return this.map.has(s),this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,M.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:e=>[...Array.from(this.map.keys()),Qe],getOwnPropertyDescriptor:(e,s)=>{if(this.map.has(s))return{enumerable:!0,configurable:!0,writable:!0,value:this.getValue(s)};if(s===Qe)return{enumerable:!1,configurable:!0,writable:!0,value:e[Qe]}}});this.map=M.observable.map(new Map),M.makeObservable(this,{[Qe]:M.observable})}setValue(e,s){const r=this.map.has(e);this.map.set(e,s),r||M.action(()=>{this[Qe]++})()}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return this[Qe],Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}B_=Qe;Bc.prototype[jc]=!0;function Mp(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const Re=t=>{const e=Mp(Bc,t);return new e(t)},$o={failurePolicy:"throw"};class pr extends Error{constructor(s,r,o,n){super(n||`Extension failure in ${r} for id "${s}"`);l(this,"extensionId");l(this,"extensionType");l(this,"cause");this.name="ExtensionException",this.extensionId=s,this.extensionType=r,this.cause=o}}const re="canvas-renderer",Co=new Map,Qi=new Map,Do=new Map,Ao=new Map,Ys=(t,e)=>{Hc[t]=e},Hc={indexExtension:{registerIndexExtension:(t,e)=>{const s=Ao.get(t)||{};Object.assign(s,e),Ao.set(t,e)},loadIndexExtensions:t=>Ao.get(t)||{}},loader:{registerLoader:(t,e,s)=>{Qi.set(t,{loader:e,options:{...$o,...s}})},executeLoader:async(t,e)=>{const s=Qi.get(t);if(!s)return;const{loader:r,options:o}=s;try{return await r(e)}catch(n){if(o.failurePolicy==="continue"){m.error(`Error executing data loader for id ${t}`),m.error(n);return}throw new pr(t,"dataLoader",n)}}},propertyMapper:{registerPropertyMapper:(t,e,s)=>{Do.set(t,{mapper:e,options:{...$o,...s}})},hasMapper:t=>Do.has(t),executeMapper:(t,e,s)=>{const r=Do.get(t);if(!r)return"";const{mapper:o,options:n}=r;try{return o(e,s)}catch(i){if(n.failurePolicy==="continue")return m.error(`Error executing property mapper for id ${t}`),m.error(i),"";throw new pr(t,"propertyMapper",i)}}},dataMapper:{registerDataMapper:(t,e,s)=>{const r=Co.get(t)||[];r.push({mapper:e,options:{...$o,...s}}),Co.set(t,r)},executeMapper:async(t,e,s)=>{const r=Co.get(t);if(!r)return{};const o={};for(const{mapper:n,options:i}of r)try{const a=await n(e,s);Object.assign(o,a)}catch(a){if(i.failurePolicy==="continue"){m.error(`Error executing data mapper for id ${t}`),m.error(a);continue}throw new pr(t,"dataMapper",a)}return o}},canvas:{registerRenderer:(t,e)=>{if(!$[re]){m.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}$[re].register(t,e)}}},$=Hc,Tp=async({context:t,extension:e})=>{const s=await $.loader.executeLoader(e,{});return t==null||t.set(e,s),s},_p=async({extension:t,contextData:e,data:s})=>await $.dataMapper.executeMapper(t,s,e),Sp=async({extension:t,contextData:e,data:s})=>await $.propertyMapper.executeMapper(t,s,e),Op=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:_p,executeLoaderExtension:Tp,executePropertyMapperExtension:Sp},Symbol.toStringTag,{value:"Module"})),Ip="Extensions";class $p{constructor(){l(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}function Cp(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class kn{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=M.observable.map(new Map),this._key=s,this.data=Re(),this.generateIndex(),M.autorun(()=>{this._container.revision&&this.generateIndex()}),M.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(e,s,r=this._map,o=this.data){const n=r.get(e)||new Set;n.add(s),r.set(e,n),o[e]=Array.from(n)}resolveIndex(e,s){this.data.keys.filter(o=>!Object.keys(s).includes(o)).forEach(o=>{delete this.data[o],this._map.delete(o)}),Object.keys(s).forEach(o=>{const n=s[o],i=this.data[o]||[];if(Cp(n,i))m.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=e.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){M.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,e,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,e,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function Dp(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>M.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>M.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const ae=m.createLogger({name:"kos-container-model"});class Fe{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");l(this,"_maxCapacity");l(this,"_evictionStrategy");l(this,"_evictionBatchSize");l(this,"_insertionOrder",[]);l(this,"_accessTimes");l(this,"_customEvictionFilter");this._data=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1;const s=e!=null&&e.extensionId?$.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const o=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=M.observable.map(o),this.idx=Re(),this._parentId=e==null?void 0:e.parentId,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=M.observable.map(new Map)),M.makeAutoObservable(this),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new kn({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}async removeAndDestroy(e){const s=this.getModel(e);if(!s){ae.debug(`Model ${e} not found in container, skipping destroy`);return}this.removeModel(e);try{await Ae(s)}catch(r){throw ae.error(`Failed to destroy model ${e}:`,r),r}}async removeAndDestroyAll(e){const s=e.map(n=>this.getModel(n)).filter(n=>n!==void 0);if(s.length===0){ae.debug("No models found to destroy");return}this.removeAll(e);const r=await Promise.allSettled(s.map(n=>Ae(n)));r.forEach((n,i)=>{n.status==="rejected"&&ae.error(`Failed to destroy model ${s[i].id}:`,n.reason)});const o=r.filter(n=>n.status==="rejected");if(o.length>0)throw new Error(`Failed to destroy ${o.length} of ${s.length} models`)}addModel(e,s){this._persistModel(e),this._trackModelMetadata(e),this._establishModelRelationships(e),this._enforceCapacityLimits(),this._configureModelMonitoring(e),s||this.increment()}_persistModel(e){this._data.set(e.id||"",e)}_trackModelMetadata(e){this._maxCapacity&&(this._insertionOrder.push(e.id||""),this._accessTimes&&this._accessTimes.set(e.id||"",Date.now()))}_establishModelRelationships(e){e.id&&this._parentId&&W.setParentContext(e.id,this._parentId)}_enforceCapacityLimits(){this._maxCapacity&&this._data.size>this._maxCapacity&&this._evictModels()}_configureModelMonitoring(e){const s=this._disposerMap.get(e.id);s&&(s(),this._disposerMap.delete(e.id));const r=Object.entries(this._optionsMap||{}),o=Object.values(this._optionsMap||{}),n=new Map(r.map(([u,d])=>[d,u])),i=u=>{var h,f;o.includes(u.name)&&((h=this.index.get(n.get(u.name)))==null||h.refresh());const d=r.filter(([,p])=>typeof p=="function");for(const[p]of d)(f=this.index.get(p))==null||f.refresh()},a=Dp(e,i,o.filter(u=>typeof u=="string")),c=M.observe(e,i);this._disposerMap.set(e.id||"",()=>[c,...a].forEach(u=>u()))}removeModel(e,s){this._data.delete(e);const r=this._insertionOrder.indexOf(e);r!==-1&&this._insertionOrder.splice(r,1),this._accessTimes&&this._accessTimes.delete(e),s||this.increment();const o=this._disposerMap.get(e);o&&(o(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),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??[]:(ae.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):(ae.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return ae.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async _evictModels(){if(!this._maxCapacity)return;const e=this._data.size-this._maxCapacity;if(e<=0)return;const s=Math.min(this._evictionBatchSize,e);this._logCapacityWarning(s);const r=this._selectModelsForEviction(s);await this._removeEvictedModels(r),this._logEvictionComplete(r.length),this.increment()}_logCapacityWarning(e){ae.info(`Container capacity exceeded (${this._data.size}/${this._maxCapacity}). Evicting ${e} models using ${this._evictionStrategy} strategy.`,{parentId:this._parentId})}_selectModelsForEviction(e){switch(this._evictionStrategy){case"fifo":return this._selectFifoModels(e);case"lru":return this._selectLruModels(e);case"custom":return this._selectCustomModels(e);default:return this._selectFifoModels(e)}}_selectFifoModels(e){const s=[];for(let r=0;r<e&&this._insertionOrder.length>0;r++){const o=this._insertionOrder.shift();if(!o)continue;const n=this._data.get(o);n&&s.push(n)}return s}_selectLruModels(e){const s=[];return this._accessTimes&&Array.from(this._accessTimes.entries()).sort((o,n)=>o[1]-n[1]).slice(0,e).forEach(([o])=>{const n=this._data.get(o);n&&s.push(n)}),s}_selectCustomModels(e){return this._customEvictionFilter?this._customEvictionFilter(this.data).slice(0,e):(ae.error("Custom eviction strategy specified but no customEvictionFilter provided. Falling back to FIFO.",{parentId:this._parentId}),this._selectFifoModels(e))}async _removeEvictedModels(e){for(const s of e)ae.info(`Evicting model: ${s.id} (type: ${s.constructor.name})`,{modelId:s.id,parentId:this._parentId,strategy:this._evictionStrategy}),this.removeModel(s.id,!0),Ae(s).catch(r=>ae.error(`Failed to destroy evicted model ${s.id}:`,r))}_logEvictionComplete(e){ae.info(`Evicted ${e} models. Current size: ${this._data.size}/${this._maxCapacity}`,{parentId:this._parentId})}async clear(){this._data.forEach(e=>{const s=e.id;Ae(e).then(()=>{ae.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>ae.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}var w=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(w||{}),F=(t=>(t.CREATE="create",t.INITIALIZE="init",t.LOAD="load",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.RESET="go_offline",t.UNLOAD="unload",t.FAILED="failed",t.GO_ACTIVE="go_active",t.GO_INACTIVE="go_inactive",t.TIMEOUT="timeout",t))(F||{});const pe=async t=>{if(t.id){const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},Ae=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.initiateDestroyModel(t)},Ap=async t=>{if(await I.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(F.UNLOAD,w.UNLOADED)},xp=async t=>{await I.getInstance().whenReady(),await I.getInstance().modelManager.reloadModel(t),m.debug(`reload model initiated for model ${t.id}, model ready: ${Sr(t)} - ${Date.now()} `),await pe(t),m.debug(`reload model complete for model ${t.id}, model ready: ${Sr(t)} - ${Date.now()} `)},Rp=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},Kc=async t=>{if(await I.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},Pe=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},qc=(t,e)=>{if(!t)throw new Error("Model type is required");return I.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},Pp=(t,e)=>qc(t,e)[0],kp=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=I.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},zc=t=>{if(!t.id)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},Lp=t=>{if(!t)throw new Error("Model ID is required");const e=I.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},Yo=(t,e)=>{const s=I.getInstance().modelManager.getModelById(t);if(!s){m.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},$e=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,Sr=t=>{const e=I.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},Fp=m.createLogger({name:"kos-model-factory"}),Os={byModelType:t=>I.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=Os.byModelType(e);if(!r)throw Fp.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},le={Factory:{create:t=>e=>(s,r)=>(r&&W.setParentContext(e,r),Os.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&W.setParentContext(t,s),Os.getModelInstance(t,t,e))},Model:{instance:t=>e=>Os.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const Zi=window.KosRegistry.coreModels,xo=window.KosRegistry.preloadModels,Ro=window.KosRegistry.companionModels,tr=window.KosRegistry.models,R={model:{registerLegacyModel:t=>(e,s)=>(Zi.set(e,s),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(xo.includes(e)||xo.push(e),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=Po(e)?e.registration():e;return tr.set(r.type,r),Po(e)&&e.relatedModels.forEach(o=>tr.set(o.type,o.registration())),I.getInstance().isReady&&(I.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),I.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],Po(e)&&e.relatedModels.forEach(o=>I.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&R.model.preloadModel(t)(r.type),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t),root:t}},get:t=>tr.get(t),getAll:()=>Array.from(tr.entries()),getPreloadModels:()=>xo,getLegacyModels:()=>Array.from(Zi.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=Ro.get(e)||[];return r.push(s),Ro.set(e,r),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(Ro.entries())}},Vc=R.model.registerLegacyModel,Gc=R.model.register,Np=R.companion.register,Up=R.model.preloadModel,Ln=t=>typeof t.updateModel=="function",Po=t=>t.registration!==void 0&&typeof t.registration=="function";class Yc{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=$e(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){R.model.register({})(this.registration()),this.registerRelatedModels()}}class ve extends Yc{constructor(e){super({...e,singleton:!1,factory:le.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=Pe(e);if(!r)throw new Error("Model not found with id "+e);if(this.guard(r.model))return r.model;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(Ln(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error("Model is not of type "+this.type)}})},options:r=>({build:()=>{const o=s(r);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class Ce extends Yc{constructor(e){super({...e,singleton:!0,factory:le.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=Pe(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=e(r);if(this.guard(o)){if(Ln(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})},options:r=>({build:()=>{const o=e(r);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const Wo=m.createLogger({group:"decorators",name:"kos-model"});function jp(t,e,s){var n;const r=(n=t[_s])==null?void 0:n.parentId;if(!r)return;const o=fe({value:r,modelData:s,modelId:e});o&&typeof o=="string"&&W.setParentContext(e,o)}function Bp(t){const e=t[xt];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function Hp(t,e){const s=t[x]||{};Object.entries(s).forEach(([r,o])=>{const n=fe({value:o.id||o.modelType,modelData:t,modelId:e}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,u])=>(a[c]=fe({value:u,modelData:t,modelId:e}),a),{});if(typeof n=="string"){if(!o.lazy){const a=I.getInstance().modelManager.createModelInstance(o.modelType,n,i);t[r]=a.data}I.getInstance().modelManager.addDependency(e,n)}})}function Kp(t){const e=t[so];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new lo(t);t[r]=o,s==="full"&&(Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){var n;return((n=o.future)==null?void 0:n.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var n;return((n=o.future)==null?void 0:n.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var n;return((n=o.future)==null?void 0:n.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function qp(t){const e=t[ro];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new Nc(t);t[r]=o,Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0});const n=t[Pt];n instanceof Map&&n.forEach(i=>{const a=`${i}Future`;Object.defineProperty(t,a,{get(){return o.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(t,`${i}Progress`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}Status`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsRunning`,{get(){const c=o.futureMap.get(i);return c?!c.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsCancelled`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const c=o.futureMap.get(i);c&&await c.cancelFuture()})}),s==="full"&&(Object.defineProperty(t,"progress",{get(){var i;return((i=o.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var i;return((i=o.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var i;return((i=o.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function zp(t){const e=t[Cn];if(!e)return;const{pathProperty:s}=e;Object.defineProperty(t,"troubles",{get(){const r=this[s];if(r==null){const o=`@kosTroubleAware: Path property '${s}' is undefined on model ${this.id||"unknown"}. Returning empty troubles array.`;return this.logger&&typeof this.logger.warn=="function"?this.logger.warn(o):console.warn(o),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((o,n)=>n.rank-o.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troublesByType",{get(){return this.troubles.reduce(Uc,{})},enumerable:!0,configurable:!0})}function Vp(t,e){const s=t[no];if(!s)return;const{containerProperty:r,includeMethods:o,includeGetters:n,modelsProperty:i,containerOptions:a,legacy:c}=s,u={...a,parentId:a.parentId||e},d=new Fe(u);t[r]=d,t[_e]||(t[_e]={}),t[_e][r]=d,o&&(t.getModel=h=>d.getModel(h),t.addModel=h=>{d.addModel(h)},t.removeModel=h=>{d.removeModel(h)},t.addAll=h=>{d.addAll(h)},t.removeAll=h=>{d.removeAll(h)},t.removeAndDestroy=async h=>d.removeAndDestroy(h),t.removeAndDestroyAll=async h=>d.removeAndDestroyAll(h)),n&&(Object.defineProperty(t,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(t,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function Gp(t,e){const s=t.constructor.prototype[Je];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=e.companionParent;if(!i){Wo.warn("Companion decorator configured but no parent model found in initialData.companionParent");return}if(t.getCompanionParent=()=>i,Object.defineProperty(t,o,{get:()=>i,enumerable:!0,configurable:!0}),r==="composition")return;const a=["init","load","unload","ready","dispose","destroy","activate"],c=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace","getCompanionParent"],u=p=>{const g=i.constructor.prototype[X]||{};return Object.values(g).some(v=>{const E=v==null?void 0:v.handler;return E===i[p]||E===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||c.includes(p)||n.includes(p)||u(p)||p in t,h=new Set;Object.getOwnPropertyNames(i).filter(p=>!d(p)).forEach(p=>h.add(p));let f=Object.getPrototypeOf(i);for(;f&&f!==Object.prototype;)Object.getOwnPropertyNames(f).filter(p=>!d(p)).forEach(p=>h.add(p)),f=Object.getPrototypeOf(f);for(const p of h)try{const g=i[p];typeof g=="function"?t[p]=(...v)=>g.apply(i,v):Object.defineProperty(t,p,{get:()=>i[p],set:v=>{i[p]=v},enumerable:!0,configurable:!0})}catch(g){Wo.debug(`Skipping companion proxy for property ${p}:`,g)}}function Yp(t){const e=t[Cc];if(!e)return;const{reloadDependencies:s=[]}=e;t._isReloading=!1,Object.defineProperty(t,"isReloading",{get(){var r;if(this._isReloading)return!0;for(const o of s)if((r=this[o])!=null&&r.isReloading)return!0;return!1},enumerable:!0,configurable:!0})}function Wp(t){try{return M.makeAutoObservable(t)}catch(e){return Wo.error("Failed to make observable:",e),t}}const Qp={construct(t,e){var c;const[s,r={}]=e,o=W.createContext(s);jp(t,s,r);const i=!!t.prototype[oo]?null:m.createLogger({name:t.prototype.modelTypeId,group:((c=t[Rt])==null?void 0:c.group)??"kos-model"}),a=new t(s,r,{logger:i,kosContext:o});return Gp(a,r),Bp(a),Kp(a),qp(a),zp(a),Vp(a,s),xn(a),Yp(a),Hp(a,s),Wp(a)}};function P(t){return e=>{var n,i;const s=e,r=typeof t=="string"?{modelTypeId:t,autoRegister:!1}:{autoRegister:!1,...t};s.prototype.modelTypeId=r.modelTypeId,s.prototype[$n]=!0,(n=s.prototype)[X]??(n[X]={}),(i=s.prototype)[x]??(i[x]={}),r.optionsRequired&&(s.prototype[Vs]=!0),m.ifDebug(()=>{m.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,Qp);if(r.singleton!==void 0){let a;r.singleton?a=new Ce({class:o,type:r.modelTypeId}):a=new ve({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}function Wc(t,e,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,o)},s)}}const Zp=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>o=>{o[X]=o[X]||{},Array.isArray(t)?t.forEach(n=>{o[X][n]={websocket:s,handler:e,condition:r}}):o[X][t]={websocket:s,handler:Wc(o,M.action(e),200),condition:r}};function Qc(t,e,s){const r={};if(!t.endsWith("/*"))return r;const o=t.slice(0,-2);if(e.startsWith(o)){const n=e.slice(o.length+1),i=s||"path";r[i]=n}return r}function Zc(t){return t.endsWith("/*")}function B(t){return(e,s,r)=>{const o=Xp(t,r);eg(e,t.topic,o),t.replay&&tg(t.topic,t.replay.bufferSize)}}function Xp(t,e){const{condition:s=(N,ee)=>!0,transform:r=N=>N,websocket:o=!1,fos:n=!1,bridge:i=!1,skipParse:a=!1,lifecycle:c,destinationAddress:u,debounce:d,throttle:h,buffer:f,filter:p,once:g,wildcardName:v,flow:E,requiresBaseline:_}=t,k=e.value,S=Fn(k,{debounce:d,throttle:h,buffer:f,once:g}),O=Jp(p,s);return{websocket:o,fos:n,bridge:i,handler:S,condition:O,transform:r,lifecycle:c,skipParse:a,destinationAddress:u,wildcardName:v,flow:E,requiresBaseline:_,once:g}}function Fn(t,e){var n,i;let s=t;const r=typeof e.debounce=="number"?e.debounce:(n=e.debounce)==null?void 0:n.delay,o=typeof e.throttle=="number"?e.throttle:(i=e.throttle)==null?void 0:i.interval;return r&&r>0?s=sg(s,e.debounce):o&&o>0?s=ig(s,e.throttle):e.buffer?s=ag(async function(c){for(const u of c)await s.call(this,u)},e.buffer):e.once&&(s=cg(s)),s}function Jp(t,e){return t?(s,r,o)=>t(o)?e(s,r,o):!1:e}function eg(t,e,s){t[X]=t[X]||{},Array.isArray(e)?e.forEach(r=>{t[X][r]=s}):t[X][e]=s}function tg(t,e){lg(t,e)}function sg(t,e){const s=typeof e=="number"?e:e.delay;return rg(e)==="discard"?og(t,s):ng(t,s)}function rg(t){return(typeof t=="object"?t.discardIntermediate:!1)?"discard":"accumulate"}function og(t,e){let s=null;return function(r){s&&clearTimeout(s),s=setTimeout(()=>{t.call(this,r),s=null},e)}}function ng(t,e){let s=null,r=[];return function(o){r.push(o),s&&clearTimeout(s),s=setTimeout(()=>{const n=[...r];r=[],t.call(this,n),s=null},e)}}function ig(t,e){const s=typeof e=="number"?e:e.interval,r=typeof e=="object"?e.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const u=[...i];i=[],t.call(this,u)}};return function(u){const d=Date.now(),h=d-o;r?h>=s?(o=d,t.call(this,u)):n||(n=setTimeout(()=>{o=Date.now(),t.call(this,u),n=null},s-h)):(i.push(u),h>=s?(o=d,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function ag(t,e){const s=[];let r=null;const o=e.maxSize||1e3,n=i=>{s.length>0&&(t.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=o){r&&(clearTimeout(r),r=null),n(this);return}r||(r=setTimeout(()=>{n(this),r=null},e.time))}}function cg(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function lg(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{_n(r,e)})}function Xc(t){return t!==null&&typeof t=="object"&&"ready"in t&&typeof t.ready=="function"}function gr(t){return t!==null&&typeof t=="object"&&"dispose"in t&&typeof t.dispose=="function"}let ug=0;const dg=Symbol("ViewModelEffectDisposers");function hg(t){const e=t[xe];return!!e&&Object.keys(e).length>0}function fg(t,e){if(!hg(t))return;const s=t[xe],r=[];for(const a of Object.keys(s)){const{value:c,dependencies:u,options:d}=s[a],h=c.bind(t),f=()=>{M.runInAction(()=>h())},p=u?M.reaction(()=>u(t),f,{fireImmediately:!!(d!=null&&d.fireImmediately)}):M.autorun(f);r.push(p)}Object.defineProperty(t,dg,{value:r,writable:!1,enumerable:!1,configurable:!0});const o=t,n=o.dispose,i=()=>{for(const a of r)try{a()}catch(c){console.warn(`[kosViewModel] Failed to dispose effect for ${e}:`,c)}};typeof n=="function"?o.dispose=function(){return i(),n.call(this)}:o.dispose=i}function pg(t,e){const s=t[Xt];if(!s)return;const{config:r}=s;r.initializeAt&&r.initializeAt!==D.INIT&&console.warn(`[kosViewModel] ViewModel "${e}" has @kosStateMachine with initializeAt: ${r.initializeAt}. ViewModels do not have lifecycle phases, so the FSM will initialize immediately. Consider removing initializeAt or using @kosModel if lifecycle-aware FSM initialization is required.`),xn(t)}function gg(t){try{return M.makeAutoObservable(t)}catch(e){return console.error("[kosViewModel] Failed to make observable:",e),t}}const mg={construct(t,e){var a;const s=t.prototype[Dn]||{},r=s.typeId||t.name,o=`${r}-${++ug}`,n=new t(...e);pg(n,r),fg(n,r),Object.defineProperty(n,"__viewModelTypeId",{value:r,writable:!1,enumerable:!1,configurable:!0}),Object.defineProperty(n,"__viewModelInstanceId",{value:o,writable:!1,enumerable:!1,configurable:!0});const i=gg(n);return s.devToolsEnabled&&((a=globalThis.__KOS_DEVTOOLS__)!=null&&a.registerViewModel)&&globalThis.__KOS_DEVTOOLS__.registerViewModel(o,i),i}};function yg(t){return e=>{const s=t||{},r=s.typeId||e.name;e.prototype[$c]={type:r},e.prototype[Dn]=s;const o=new Proxy(e,mg);return Object.defineProperty(o,"name",{value:e.name}),o}}const ko=new Map,Jc={addToDeletionQueue:(t,e)=>{const s=ko.get(t)||[];s.push(e),ko.set(t,s)},cancelDeletion:t=>{const e=ko.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},bg=m.createLogger({name:"kos-dependency-manager"});class vg{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(e,s){Jc.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(e)||r.push(e),this._usedByCache.set(s,r);const o=this._usesCache.get(e)||[];o.includes(s)||o.push(s),this._usesCache.set(e,o)}remove(e,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==e));const o=this._usesCache.get(e)||[];this._usesCache.set(e,o.filter(n=>n!==s))}canDestroy(e){const s=this._usedByCache.get(e);return s!=null&&s.length?(bg.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}const Xi=m.createLogger({name:"kos-model-cache"});class wg{constructor(e=[]){l(this,"_modelsById",M.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).map(e=>e).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?(Xi.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(Xi.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}class mr extends Error{constructor(s,r,o){super(s,{cause:o});l(this,"context");l(this,"originalCause");this.name="KosModelError",this.context=r,this.originalCause=o,o!=null&&o.stack&&(this.stack=`${this.stack}
1
+ "use strict";var Nf=Object.defineProperty;var Uf=(t,e,s)=>e in t?Nf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var l=(t,e,s)=>(Uf(t,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("loglevel"),E=require("mobx"),b=require("robot3"),Xe=require("date-fns"),_=require("@emotion/react/jsx-runtime"),En=require("@emotion/styled"),rc=require("react-dom"),dt=require("@emotion/react"),m=require("react"),Mn=require("mobx-react-lite"),jf=require("@use-gesture/react"),oa=new Set;function oc(t,e,s,r,o){typeof process<"u"&&process.env.NODE_ENV==="production"||oa.has(t)||(oa.add(t),console.warn(`[KOS] "${t}" is deprecated since ${e} level ${s}. Use "${r}" instead. Will be removed at level ${o}.`))}const Bf={};function Kf(t){Object.assign(Bf,t)}const oo="method",nc="topic",Yt="url",Ys="request-id",no="response-id",_n="status",Ge="dst-addr",ic="src-addr",Le="type",Tn="ordered",Sn="tracker",ac="Content-Type",cc="Cache-Control",lc="requestId",uc=process.env.KOS_LOGIN_URL||"http://localhost",dc=process.env.KOS_APP_PORT||"8080",Hf=`${uc}:${dc}`,Tr="{MODEL_ID}";var Ws=(t=>(t.SEND="/ws/log/msg/send",t.RECEIVED="/ws/log/msg/receive",t))(Ws||{}),hc=(t=>(t.MSG_RECEIVE="/mock/msg/receive",t))(hc||{});const On="/kos/model/ready/";x.info("Initializing event bus");globalThis.kos=globalThis.kos||{};globalThis.kos.subscriptions=globalThis.kos.subscriptions||{};const G=globalThis.kos.subscriptions,qf=()=>Symbol("eventKey");function $n(t){return G[t]&&Object.getOwnPropertySymbols(G[t]).length>0}function C(t,e){const s=qf();return G[t]||(x.debug(`Initializing subscription for ${t}`),G[t]={}),x.debug(`Subscribing to ${t} with id ${s.toString()}`),G[t][s]=e,{count:G[t]?Object.getOwnPropertySymbols(G[t]).length:0,unsubscribe:()=>(x.debug(`Unsubscribing from ${t} with id ${s.toString()}`),G[t]&&G[t][s]&&delete G[t][s],G[t]&&Object.getOwnPropertySymbols(G[t]).length===0&&delete G[t],{count:G[t]?Object.getOwnPropertySymbols(G[t]).length:0})}}function H(t,e,s={}){if(!G[t]||Object.getOwnPropertySymbols(G[t]).length===0)return x.debug(`No subscriptions for ${t}. Not publishing.`),{eventType:t,subscribers:0};const r=Object.getOwnPropertySymbols(G[t]).length;return Object.getOwnPropertySymbols(G[t]).forEach(o=>{if(s.sync){const n=s.sync;x.debug(`Performing sync publish for ${t} with sync id ${n}`),G[t][o]({body:e,headers:s}).then(i=>{x.debug(`Response recieved for ${n}, publishing back to source.`),H(n,i)})}else x.debug(`Performing async publish for ${t}`),G[t][o]({body:e,headers:s})}),{eventType:t,subscribers:r}}function zf(){x.warn("Resetting event bus"),Object.keys(G).forEach(t=>delete G[t])}function fc(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function In(t,e){return new Promise((s,r)=>{let o=null;const n=fc(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}const Vf=Object.freeze(Object.defineProperty({__proto__:null,hasEventSubscriptions:$n,once:fc,publish:H,reset:zf,subscribe:C,waitFor:In},Symbol.toStringTag,{value:"Module"}));function io(t,e){const s=C(t,r=>{s.unsubscribe(),e(r)});return s.unsubscribe}function ao(t,e){return new Promise((s,r)=>{let o=null;const n=io(t,i=>{o&&clearTimeout(o),s(i)});e&&(o=setTimeout(()=>{n(),r(new Error(`Timeout waiting for event: ${t}`))},e))})}function pc(t,e){const s=t.map(r=>ao(r,e));return Promise.all(s)}function gc(t,e){return new Promise((s,r)=>{const o=[];let n=null,i=!1;const a=()=>{o.forEach(c=>c()),n&&clearTimeout(n)};t.forEach(c=>{const u=io(c,d=>{i||(i=!0,a(),s({eventType:c,data:d}))});o.push(u)}),e&&(n=setTimeout(()=>{i||(i=!0,a(),r(new Error(`Timeout waiting for any event: ${t.join(", ")}`)))},e))})}function mc(t,e,s){return C(t,o=>{o&&e(o)&&s(o)}).unsubscribe}function yc(t,e,s){return C(t,o=>{if(o){const n=e(o);s(n)}}).unsubscribe}function bc(t,e,s){let r=null;const o=C(t,n=>{r&&clearTimeout(r),r=setTimeout(()=>{s(n)},e)});return()=>{r&&clearTimeout(r),o.unsubscribe()}}function vc(t,e,s){let r=0,o=null;const n=C(t,i=>{const a=Date.now(),c=a-r;c>=e?(r=a,s(i)):o||(o=setTimeout(()=>{r=Date.now(),s(i),o=null},e-c))});return()=>{o&&clearTimeout(o),n.unsubscribe()}}function wc(t,e,s){let r=[],o=null;const n=()=>{r.length>0&&(s([...r]),r=[])},i=C(t,a=>{a&&(r.push(a),o||(o=setTimeout(()=>{n(),o=null},e)))});return()=>{o&&(clearTimeout(o),n()),i.unsubscribe()}}function Cn(t,e=1){const s=[];return C(t,r=>{r&&(s.push(r),s.length>e&&s.shift())}),{subscribe:r=>(s.forEach(o=>r(o)),C(t,r))}}function Ec(t,e){const s=t.map(r=>C(r,o=>{o&&e(r,o)}));return()=>{s.forEach(r=>r.unsubscribe())}}function Mc(t,e){let s=t;const r=[],o=new Set;return Object.values(e).forEach(n=>{Object.keys(n).forEach(i=>{o.add(i)})}),o.forEach(n=>{const{unsubscribe:i}=C(n,a=>{const c=e[s];c&&c[n]&&(s=c[n](a))});r.push(i)}),{get state(){return s},unsubscribe:()=>{r.forEach(n=>n())}}}function _c(t,e,s,r){const o=ao(e,r);return H(t,s),o}async function*Tc(t){const e=[],s=[],r=C(t,o=>{o&&(s.length>0?s.shift()(o):e.push(o))});try{for(;;)e.length>0?yield e.shift():yield await new Promise(o=>{s.push(o)})}finally{r.unsubscribe()}}const Gf={once:io,waitFor:ao,waitForAll:pc,race:gc,filter:mc,map:yc,debounce:bc,throttle:vc,buffer:wc,replay:Cn,merge:Ec,stateMachine:Mc,request:_c,eventIterator:Tc},Yf=Object.freeze(Object.defineProperty({__proto__:null,EventBusFunctional:Gf,buffer:wc,debounce:bc,eventIterator:Tc,filter:mc,map:yc,merge:Ec,once:io,race:gc,replay:Cn,request:_c,stateMachine:Mc,throttle:vc,waitFor:ao,waitForAll:pc},Symbol.toStringTag,{value:"Module"}));async function co(t,e){const{getCurrentState:s,transformState:r,shouldUseFetchedState:o,timeout:n}=e,i=In(t,n),a=await s(),c=r?r(a):a;return o&&o(c)?(i.catch(()=>{}),c):await Promise.race([i,new Promise(d=>{setTimeout(()=>d(c),100)})])}function Sc(t,e,s){const{getCurrentState:r,transformState:o}=s;let n=!1;const i=C(t,a=>{a&&(n=!0,e(a))});return Promise.resolve(r()).then(a=>{const c=o?o(a):a;n||e(c)}).catch(a=>{console.error("Failed to fetch initial state:",a)}),i.unsubscribe}function Oc(t,e){let s;const r=new Set,o=async()=>{try{typeof e=="string"?s=await(await fetch(e)).json():s=await e(),r.forEach(a=>a(s))}catch(a){throw console.error("Failed to fetch initial state:",a),a}};C(t,a=>{a!=null&&a.body&&(s=a.body,r.forEach(c=>c(s)))});let n=!1;const i=()=>{n||(n=!0,o())};return{get state(){return s},async getState(){return i(),s===void 0&&await new Promise(a=>{const c=()=>{s!==void 0?a():setTimeout(c,10)};c()}),s},subscribe(a){return i(),r.add(a),s!==void 0&&a(s),()=>{r.delete(a)}},async refresh(){return await o(),s}}}async function Dn(t,e){if(typeof t=="string")return co(t,e);const s=t,{getCurrentState:r,shouldUseFetchedState:o,timeout:n}=e,i=await r(),a=e.transformState?e.transformState(i):i;if(o&&o(a))return a;const c=s.map(d=>In(d,n)),u=await Promise.all(c);return u[u.length-1]}function $c(t,e,s){const{fetchMissedEvents:r,checkInterval:o=3e4,deduplicateById:n}=s,i=new Set,a=C(t,async u=>{if(u){if(n){const d=n(u);if(i.has(d))return;i.add(d),i.size>1e3&&Array.from(i).slice(0,500).forEach(f=>i.delete(f))}await e(u)}}),c=setInterval(async()=>{try{const u=await r(),d=Array.isArray(u)?u:[u];for(const h of d)if(n){const f=n(h);i.has(f)||(i.add(f),await e(h))}else await e(h)}catch(u){console.error("Failed to fetch missed events:",u)}},o);return()=>{a.unsubscribe(),clearInterval(c)}}function Ic(t){const{connectEvent:e,disconnectEvent:s,errorEvent:r,dataEvent:o,fetchInitialState:n,reconnectDelay:i=5e3}=t,a={state:"disconnected",data:void 0,async waitForConnection(d){if(a.state==="connected"&&a.data)return a.data;const h=await co(e,{getCurrentState:n,shouldUseFetchedState:f=>!!f,timeout:d});return a.state="connected",a.data=h,u(),h},subscribe(d){return c.add(d),d(a),()=>{c.delete(d)}},async reconnect(){a.state="connecting",u();try{const d=await n();a.state="connected",a.data=d,u()}catch{a.state="error",u(),setTimeout(()=>{a.state==="error"&&a.reconnect()},i)}}},c=new Set,u=()=>{c.forEach(d=>d(a))};return C(e,d=>{a.state="connected",d!=null&&d.body&&(a.data=d.body),u()}),C(s,()=>{a.state="disconnected",u(),setTimeout(()=>{a.state==="disconnected"&&a.reconnect()},i)}),r&&C(r,()=>{a.state="error",u()}),o&&C(o,d=>{d!=null&&d.body&&a.state==="connected"&&(a.data=d.body,u())}),a.reconnect(),a}const Wf={waitForOrGetState:co,subscribeWithInitialState:Sc,createStatefulEventStream:Oc,waitForAllWithState:Dn,createResilientEventHandler:$c,createConnectionStateManager:Ic},Qf=Object.freeze(Object.defineProperty({__proto__:null,EventBusState:Wf,createConnectionStateManager:Ic,createResilientEventHandler:$c,createStatefulEventStream:Oc,subscribeWithInitialState:Sc,waitForAllWithState:Dn,waitForOrGetState:co},Symbol.toStringTag,{value:"Module"})),Xf=(t,e=0)=>{if(!+t)return{value:0,scale:"bytes",toString:()=>"0 bytes"};const s=1024,r=e<0?0:e,o=["bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(t)/Math.log(s)),i=parseFloat((t/Math.pow(s,n)).toFixed(r)),a=o[n];return{value:i,scale:a,toString:()=>`${i} ${a}`}};function An(t){let e="pending",s;const r=t.then(n=>{e="success",s=n},n=>{e="error",s=n});return{read:()=>{switch(e){case"pending":throw r;case"error":throw s;default:return s}}}}const de=(t=null)=>(t||window.location.search.replace("?","")).split("&").map(e=>{const[s,r]=e.split("=");return[s,decodeURIComponent(r||"")]}).reduce((e,[s,r])=>(e[s]=r,e),{}),Zf="studio.enable.releases",Cc="studio.tools.preview",Jf="studio.relax.store.validation",Dc="studio.log.debug",Ac="studio.log.info",ep={profiles:[Cc]};var tc;const tp=((tc=globalThis.getKosConfig)==null?void 0:tc.call(globalThis))||JSON.stringify(ep),xc=JSON.parse(tp);globalThis.kosConfig=xc;const xn=xc,Rc=()=>xn.profiles||[],Zo=t=>Rc().includes(t),sp=()=>xn.logging||!1,rp=()=>{const t=Zo(Dc),e=Zo(Ac);return t?"DEBUG":e?"INFO":void 0},Pc=()=>{const t=de(),e=rp(),r=t.kosLogLevel??e??window.kosLogLevel??process.env.KOS_LOG_LEVEL;return r||"WARN"},kc=()=>window.kosMessageLogging||process.env.KOS_MESSAGE_LOGGING==="true",Lc=()=>window.kosMessageStudioLogging||process.env.KOS_MESSAGE_STUDIO_LOGGING==="true",Fc="ws-log",op=x.methodFactory,Nc=kc(),np=Lc();x.methodFactory=function(t,e,s){const r=op(t,e,s);return function(...o){var c;const n=s?String(s):"",i=n?`[${String(n).substring(n.lastIndexOf(":")+1)}] | `:"[root] | ",a=o.map(u=>typeof u=="object"?JSON.stringify(u):String(u)).join(" ");r(`${i}${a}`),(c=globalThis==null?void 0:globalThis.kosConfig)!=null&&c.logging&&globalThis.kosLog&&(s!==Fc||Nc&&np)&&globalThis.kosLog(`UI: ${i}${a}`)}};let Uc=Pc();x.setLevel(Uc);window.setKosLogLevel=t=>{Uc=t,x.setLevel(t)};const Sr=x.getLogger(Fc);window.enableKosMessageLog=()=>{Sr.setLevel(x.levels.INFO)};window.disableKosMessageLog=()=>{Sr.setLevel(x.levels.ERROR)};Nc?window.enableKosMessageLog():window.disableKosMessageLog();const ip=["color: black","display: block","background-color: lightgreen","padding: 4px","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),ap=["color: black","display: block","padding: 4px","background-color: yellow","margin: 0","text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)","box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset","font-weight: bold"].join(";"),rr=t=>e=>{x.getLevel()<=t&&e()},g={...x,ifDebug:rr(x.levels.DEBUG),ifInfo:rr(x.levels.INFO),ifWarn:rr(x.levels.WARN),ifError:rr(x.levels.ERROR),getLogger:t=>x.getLogger(`kos::${t}`),getLoggers:()=>x.getLoggers(),createLogger:({name:t,group:e})=>{var n,i,a,c;const s=`${e?`${e}:`:"kos"}::${t}`,r=x.getLogger(s);let o=(i=(n=globalThis.kos.logOverrides)==null?void 0:n.find(u=>u.name===s))==null?void 0:i.level;return o?r.setLevel(o):(o=(c=(a=globalThis.kos.logOverrides)==null?void 0:a.find(u=>s.startsWith(u.name)))==null?void 0:c.level,o&&r.setLevel(o)),r},wsSend:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Sr.info(`%c⬆ ${e}`,ip)},wsReceive:(...t)=>{const e=String(t).replace(/\n/g,"\\n");Sr.info(`%c⬇ ${e}`,ap)}},Z=Symbol("SubscriptionHandlers"),F=Symbol("DependencyModels"),Es=Symbol("FutureService"),Je=Symbol("ChildModels"),Ms=Symbol("ParentModel"),_s=Symbol("LogConfig"),gr=Symbol("ReferenceConfig"),Rn=Symbol("KosModelSymbol"),Be=Symbol("ModelEffects"),et=Symbol("CompanionParentModel"),Pn=Symbol("FutureContainerSetup"),kn=Symbol("MultipleFutureContainerSetup"),Ts=Symbol("FutureAliases"),Ln=Symbol("TroubleAwareSetup"),Fn=Symbol("LoggerSetup"),Nn=Symbol("ContainerAwareSetup"),Wt=Symbol("StateMachineSetup"),Rt=Symbol("StateEntryHandlers"),Ss=Symbol("StateExitHandlers"),cp=Symbol("StateActionHandlers"),Qs=Symbol("OptionsRequired"),jc=Symbol("KosViewModelSymbol"),Un=Symbol("ViewModelConfig"),Bc=Symbol("ReloadAwareSetup"),jn=g.createLogger({group:"decorators",name:"fsm-injection"});function Bn(t){const e=t[Wt];if(!e)return;const{config:s,options:r}=e;hp(t,s,r),fp(t,r);const o=dp(t);lp(t,s,r,o),up(t,s,r)}function lp(t,e,s,r){t.transition=mp(t,e,s,r.entry,r.exit),t.canTransition=Sp(t,e,s),t.isInState=Op(t,s)}function up(t,e,s){pp(t),gp(t,e,s)}function dp(t){const e=t.constructor.prototype[Rt]||new Map,s=t.constructor.prototype[Ss]||new Map;return{entry:e,exit:s}}function hp(t,e,s){t._fsmConfig=e,t._fsmOptions=s}function fp(t,e){const{stateProperty:s,trackHistory:r,computeInitialState:o}=e,n=t._fsmConfig,i=o?o(t):n.initial;o&&!n.states[i]?(jn.warn(`computeInitialState returned "${i}" which is not a valid state. Falling back to "${n.initial}".`),t[s]=n.initial):t[s]=i,t._fsmInitialized=!!o,t.isTransitioning=!1,r&&(t.stateHistory=o?[{state:t[s],timestamp:new Date}]:[])}function pp(t){Object.defineProperty(t,"isFsmInitialized",{get(){return this._fsmInitialized},enumerable:!0,configurable:!0})}function gp(t,e,s){const{stateProperty:r}=s;Object.defineProperty(t,"allowedTransitions",{get(){if(!this._fsmInitialized)return[];const o=this[r],n=this._fsmConfig.states[o];return n!=null&&n.on?Object.keys(n.on):[]},enumerable:!0,configurable:!0})}function mp(t,e,s,r,o){const{stateProperty:n,throwOnInvalid:i}=s;return function(a){if(!this._fsmInitialized){yp(e.initializeAt,i);return}const c=this[n],u=bp(c,a,this._fsmConfig,i);u&&wp(this,c,u,a,n,r,o,s)}}function yp(t,e){const s=`Cannot transition: FSM not initialized. Waiting for ${t} lifecycle phase.`;if(e)throw new Error(s);console.warn(s)}function bp(t,e,s,r){var i;const o=s.states[t],n=(i=o==null?void 0:o.on)==null?void 0:i[e];if(!n){vp(t,e,r);return}return n}function vp(t,e,s){const r=`Invalid transition: Event "${e}" not allowed from state "${t}"`;if(s)throw new Error(r);console.warn(r)}function wp(t,e,s,r,o,n,i,a){t.isTransitioning=!0;try{Ep(t,e,i),t[o]=s,Tp(t,s,r,a);const c=Mp(t,s,n);_p(t,s,o,c)}finally{t.isTransitioning=!1}}function Ep(t,e,s){const r=s.get(e);r&&typeof t[r]=="function"&&t[r]()}function Mp(t,e,s){const r=s.get(e);if(r&&typeof t[r]=="function")return t[r]()}function _p(t,e,s,r){var n,i;if(!r||typeof r.then!="function")return;const o=(i=(n=t._fsmConfig)==null?void 0:n.states)==null?void 0:i[e];!(o!=null&&o.onDone)&&!(o!=null&&o.onError)||r.then(()=>{o.onDone&&t[s]===e&&t.transition(o.onDone)},a=>{o.onError&&t[s]===e?t.transition(o.onError):jn.error(`Async entry handler for state "${e}" failed:`,a)})}function Tp(t,e,s,r){r.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date,event:s})}function Sp(t,e,s){const{stateProperty:r}=s;return function(o){var a;if(!this._fsmInitialized)return!1;const n=this[r],i=this._fsmConfig.states[n];return((a=i==null?void 0:i.on)==null?void 0:a[o])!==void 0}}function Op(t,e){const{stateProperty:s}=e;return function(r){return this._fsmInitialized?this[s]===r:!1}}function Kc(t,e){const s=t[Wt];if(!s)return;const{config:r,options:o}=s,{stateProperty:n}=o;r.initializeAt===e&&(t._fsmInitialized||($p(t,n,r.initial),t._fsmInitialized=!0,Ip(t,r.initial,o),Cp(t,r.initial),jn.debug(`FSM initialized for model ${t.id} at lifecycle ${e} with initial state "${r.initial}"`)))}function $p(t,e,s){t[e]=s}function Ip(t,e,s){s.trackHistory&&t.stateHistory&&t.stateHistory.push({state:e,timestamp:new Date})}function Cp(t,e){const r=(t.constructor.prototype[Rt]||new Map).get(e);r&&typeof t[r]=="function"&&t[r]()}const $e=(t,e)=>{t[Je]=t[Je]||{},t[Je][e]=!0},vt=t=>`{PROP_${String(t)}}`,Dp=t=>`{PROP_${String(t)}}`,Ap=vt("kosParentId"),lo=t=>e=>{e[Ms]=e[Ms]||{};const s=(t==null?void 0:t.parentId)||Ap;e[Ms]={parentId:s},e.prototype[Qs]=!0};function xp(t){return e=>{const s=(t==null?void 0:t.mode)||"decorator",r=(t==null?void 0:t.parentProperty)||"companionParent",o=(t==null?void 0:t.excludeProperties)||[],n=t==null?void 0:t.lifecycle;return lo()(e),e.prototype[et]={mode:s,parentProperty:r,excludeProperties:o,lifecycle:n},e}}function uo(t){return e=>{const s=t!=null&&t.legacy?"_models":(t==null?void 0:t.containerProperty)||"container",r=(t==null?void 0:t.includeMethods)!==!1,o=(t==null?void 0:t.includeGetters)!==!1,n=(t==null?void 0:t.modelsProperty)||"models",i=(t==null?void 0:t.containerOptions)||{};return e.prototype[Nn]={containerProperty:s,includeMethods:r,includeGetters:o,modelsProperty:n,containerOptions:i,legacy:(t==null?void 0:t.legacy)||!1},e}}function Rp(t,e,s){const r=s.value;s.value=function(...o){const n=Q.getContext(this.id);return o.push(n),r.apply(this,o)}}const ho=Symbol("KosExecutionContext");function Kn(t){return t&&typeof t=="object"&&ho in t}function Hc(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[Pn]={mode:s,handlerProperty:r},e}}function Pp(t){return e=>{const s=(t==null?void 0:t.mode)||"full",r=(t==null?void 0:t.handlerProperty)||"futureHandler";return e.prototype[kn]={mode:s,handlerProperty:r},e}}var I=(t=>(t.INIT="init",t.LOAD="load",t.READY="ready",t.ACTIVATE="activate",t.ONLINE="online",t))(I||{}),Ze=(t=>(t.CREATE="create",t.CONTINUE="continue",t.FAIL="fail",t))(Ze||{});const kp=Object.freeze(Object.defineProperty({__proto__:null,DependencyLifecycle:I,DependencyResolutionPolicy:Ze},Symbol.toStringTag,{value:"Module"})),Ke=Symbol("HttpRouteHandlers"),na="__httpBrowserRouter";function fo(t){return function(s){return function(r,o,n){r[Ke]=r[Ke]||[];const i={method:t,path:s,handler:o};return r[Ke].push(i),r[F]=r[F]||{},r[F][na]||(r[F][na]={modelType:"browser-router-model",lifecycle:I.INIT}),n}}}const qc=fo("GET"),Xs=fo("POST"),Lp=fo("PUT"),zc=fo("DELETE"),Fp=zc;function Or(t){return!!(t!=null&&t[Ke])&&t[Ke].length>0}function Vc(t){return(t==null?void 0:t[Ke])||[]}const Np=({group:t}={group:""})=>e=>{e[_s]=e[_s]||{},e[_s]={group:t}};class Hn{static create({modelId:e,modelTypeName:s,component:r}){const o=[r??"kos",s,e].filter(Boolean).join(".");return g.createLogger({name:o})}}function Qt(t){return e=>{const s=(t==null?void 0:t.loggerProperty)||"logger",r=t==null?void 0:t.loggerContext;e.prototype[Fn]={loggerProperty:s,loggerContext:r};const o=()=>{var i;return(i=e.prototype[Rn])==null?void 0:i.type};let n;return Object.defineProperty(e.prototype,s,{get(){if(!n){const i=o();n=Hn.create({modelTypeName:r||i,component:"kos-model"})}return n},enumerable:!1,configurable:!1}),e}}function Gc(t){return(e,s,r)=>{e[Be]=e[Be]||{},e[Be][s]={dependencies:t==null?void 0:t.dependencies,value:r.value},r.value=function(){throw new Error(`Method ${s} cannot be called directly.`)}}}const Up=t=>(e,s)=>{oc("@kosReference","core.reference",1,"@kosDependency",3),e[gr]=e[gr]||{},e[gr][s]=t};class $r extends Error{constructor(s,r){super(s);l(this,"status");l(this,"statusText");l(this,"responseBody");l(this,"responseHeaders");this.name="ServiceRequestError",this.status=r.status,this.statusText=r.statusText,this.responseBody=r.responseBody,this.responseHeaders=r.responseHeaders??{}}}const Ro=g.createLogger({name:"resolve-parameters"}),me=({value:t,modelId:e,modelData:s})=>{let r=t;if(Array.isArray(r))return[...t];if(typeof r!="string"&&typeof r!="object")return r;if(typeof r=="object")r=Object.keys(r).reduce((o,n)=>(o[n]=me({value:r[n],modelId:e,modelData:s}),o),{});else if(typeof r=="string"){const o=new RegExp("{PROP_(.+?)}","g");let n=r!=null&&r.includes(Tr)?r.replace(Tr,e):r;if(s){let i=!1;const a=/^{PROP_.+?}$/.test(n);if(n=n.replace(o,(c,u)=>{if(Object.getOwnPropertyNames(s).includes(u)||Object.getOwnPropertyNames(Object.getPrototypeOf(s)).includes(u)){const h=s[u];return h!=null?(Ro.debug(`Resolved ${c} to ${h}`),h):(Ro[a?"debug":"warn"](`Property ${u} is null or undefined${a?"":" in composite string"}, marking for undefined return`),i=!0,c)}return Ro[a?"debug":"warn"](`Property ${u} not found in modelData${a?"":" for composite string"}`),c}),i)return}return n}else return r;return r},jp=g.createLogger({name:"ServiceRequestHelpers"});function Yc(t,e,s,r){const o=me({value:t.path,modelId:e.id,modelData:e}),n=me({modelId:e.id,modelData:e,value:{...typeof t.pathParams=="function"?t.pathParams(e):t.pathParams||{},...(r==null?void 0:r.pathParams)||{}}}),i=me({modelId:e.id,modelData:e,value:{...typeof t.queryParams=="function"?t.queryParams(e):t.queryParams||{},...(r==null?void 0:r.queryParams)||{}}}),a=(r==null?void 0:r.body)||(typeof t.body=="function"?t.body(e):t.body),u={...(typeof t.requestOptions=="function"?t.requestOptions(e,...s):t.requestOptions)||{},...(r==null?void 0:r.requestOptions)||{}},d={};return n&&Object.keys(n).length>0&&(d.path=n),i&&Object.keys(i).length>0&&(d.query=i),{resolvedPath:o,apiParams:d,finalBody:a,finalRequestOptions:u}}async function Wc(t,e,s,r,o,n){const i=(e||"get").toLowerCase(),a=t;switch(i){case"get":return await a.get(s,r,n);case"post":return await a.post(s,r,o,n);case"put":return await a.put(s,r,o,n);case"delete":return await a.delete(s,r,o,n);default:return await a.get(s,r,n)}}function Qc(t,e,s,r,o){if(!s)return[t,null];const n=o?new $r(t,o):new $r(t,{status:(e==null?void 0:e.status)??0,statusText:t});switch(s.strategy){case"log":return jp.error(`Service request status ${n.status} error: ${t}`),s.onError&&s.onError(n,r),[null,s.defaultValue];case"ignore":return s.onError&&s.onError(n,r),[null,s.defaultValue];case"default":return s.onError&&s.onError(n,r),[null,s.defaultValue];case"throw":default:return s.onError&&s.onError(n,r),[t,null]}}const gt=Symbol("ServiceRequestHandlers"),ia=new WeakMap;function Ye(t){return(e,s,r)=>{var a;e[gt]=e[gt]||{};const o=r.value,n={...t,handlerMethod:s,originalHandler:o},i=`${((a=t.method)==null?void 0:a.toUpperCase())||"GET"}:${String(t.path)}`;if(e[gt][i]=n,!t.lifecycle){const c=function(...u){const d=u[u.length-1],h=async f=>{const p=ia.get(c);if(!p)throw new Error("Service request metadata not found for method");try{const{default:y}=await Promise.resolve().then(()=>Wn),{resolvedPath:v,apiParams:M,finalBody:O,finalRequestOptions:U}=Yc(p,this,u,f),A=await Wc(y,p.method,v,M,O,U),[$,P]=A,V=A[2];if($)return Qc($,P,p.errorHandler,this,V);let ee=P;return p.transform&&(ee=p.transform(P)),[null,ee]}catch(y){return[y.message||"Unknown error",null]}};if(Kn(d))return d.$request=h,o.apply(this,u);{const f={[ho]:!0,$request:h};return o.apply(this,[...u,f])}};ia.set(c,n),r.value=c}return r}}var Xc=(t=>(t.GET="GET",t.PUT="PUT",t.POST="POST",t.DELETE="DELETE",t))(Xc||{}),ie=(t=>(t.IMMEDIATE="immediate",t.SINGLE="single",t.TTL="ttl",t.PERMANENT="permanent",t.MANUAL="manual",t))(ie||{}),pt=(t=>(t.ALL="all",t.AFTER_REQUEST="after-request",t.AFTER_RESPONSE="after-response",t.NONE="none",t))(pt||{});const Bp=g.createLogger({name:"kos-state-machine"});function Kp(t,e){return s=>(s.prototype[Wt]={config:{...t,initializeAt:t.initializeAt||I.READY},options:{stateProperty:(e==null?void 0:e.stateProperty)||"currentState",trackHistory:(e==null?void 0:e.trackHistory)||!1,throwOnInvalid:(e==null?void 0:e.throwOnInvalid)!==!1,computeInitialState:e==null?void 0:e.computeInitialState}},s)}function Hp(t){return(e,s)=>{e[Rt]||(e[Rt]=new Map),e[Rt].set(t,s)}}function qp(t){return(e,s)=>{e[Ss]||(e[Ss]=new Map),e[Ss].set(t,s)}}function zp(t){return(e,s,r)=>{const o=r.value;return r.value=function(...n){var u,d;if(!this.isFsmInitialized)return o.apply(this,n);const a=this.currentState;if(!t.allowedStates.includes(a)){const h=`Method ${String(s)} cannot be called from state "${a}". Allowed states: ${t.allowedStates.join(", ")}`;if(t.throwOnInvalid!==void 0?t.throwOnInvalid:((d=(u=this[Wt])==null?void 0:u.options)==null?void 0:d.throwOnInvalid)!==!1)throw new Error(h);Bp.warn(h);return}return o.apply(this,n)},r}}function Vp(t){return e=>{const s=(t==null?void 0:t.pathProperty)||"path";return e.prototype[Ln]={pathProperty:s},e.prototype[F]=e.prototype[F]||{},e.prototype[F].troubleContainer={modelType:"trouble-container-model",id:"trouble-container-model",options:{},lazy:!1},e}}const Xt=({modelType:t,id:e,options:s,lifecycle:r,resolutionPolicy:o})=>(n,i)=>{n[F]=n[F]||{},n[F][i]={modelType:t,id:e,options:s,lifecycle:r||I.INIT,resolutionPolicy:o}};class Zc{constructor(e,s){l(this,"futures");l(this,"defaultContext");l(this,"context");l(this,"disposers",new Map);l(this,"container");this.futures=ri.map(new Map),this.context="",this.defaultContext=s||"",this.container=e,E.makeAutoObservable(this)}get allFutures(){return Array.from(this.futures.values())}get future(){return this.futures.get(this.defaultContext)}addFuture(e,s){this.futures.set(s||e.id,e),this.context=s||e.id;const r=s,o=X(()=>{var n,i;(e.endState||e.progress)&&((i=(n=this.container)==null?void 0:n.onFutureUpdate)==null||i.call(n,e,r))});this.disposers.set(s||e.id,o)}removeFuture(e){var s;this.futures.delete(e||this.context),(s=this.disposers.get(e||this.context))==null||s(),this.disposers.delete(e||this.context)}getFuture(e){return this.futures.get(e||this.context)}get futureMap(){return this.futures}}class po{constructor(e){l(this,"disposer");l(this,"_future");l(this,"container");l(this,"onFutureUpdate");this._future=void 0,this.container=e,E.makeAutoObservable(this)}removeFuture(){var e;this._future=void 0,(e=this.disposer)==null||e.call(this),this.disposer=void 0}get future(){return this._future}getFuture(){return this._future}addFuture(e){this._future=e;const s=X(()=>{var r,o;(e.endState||e.progress)&&((o=(r=this.container)==null?void 0:r.onFutureUpdate)==null||o.call(r,e))});this.disposer=s}get allFutures(){return this._future?[this._future]:[]}get timeRemaining(){var e;return((e=this._future)==null?void 0:e.timeRemaining)||""}get status(){var e;return((e=this._future)==null?void 0:e.status)||"NOT_RESOLVED"}get progress(){var e;return((e=this._future)==null?void 0:e.progress)||-1}async cancel(){if(this._future)try{await this._future.cancelFuture()}catch(e){throw g.error(e),e}}}const Jc=(t,e)=>{const s=e.type;return t[s]||(t[s]=[]),t[s].push(e),t},el=Symbol("KosObservableData"),Qe=Symbol("revision");var IS;class tl{constructor(){l(this,"map");l(this,IS,1);l(this,"atomMap",new Map);l(this,"proxyHandler",{get:(e,s)=>{var r;return s===Qe||e[s]!==void 0?e[s]:this.atomMap.has(s)&&(r=this.atomMap.get(s))!=null&&r.reportObserved()?this.getValue(s):this.getValue(s)},set:(e,s,r)=>{var o;return this.map.has(s),this.setValue(s,r),this.atomMap.has(s)||this.atomMap.set(s,E.createAtom(s.toString())),(o=this.atomMap.get(s))==null||o.reportChanged(),!0},ownKeys:e=>[...Array.from(this.map.keys()),Qe],getOwnPropertyDescriptor:(e,s)=>{if(this.map.has(s))return{enumerable:!0,configurable:!0,writable:!0,value:this.getValue(s)};if(s===Qe)return{enumerable:!1,configurable:!0,writable:!0,value:e[Qe]}}});this.map=E.observable.map(new Map),E.makeObservable(this,{[Qe]:E.observable})}setValue(e,s){const r=this.map.has(e);this.map.set(e,s),r||E.action(()=>{this[Qe]++})()}getValue(e){return this.map.get(e)}has(e){return this.map.has(e)}get entries(){return Array.from(this.map.entries())}get keys(){return this[Qe],Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}setValues(e){e&&Object.keys(e).forEach(s=>{this.setValue(s,e[s])})}get proxy(){return new Proxy(this,this.proxyHandler)}}IS=Qe;tl.prototype[el]=!0;function Gp(t,e){return new Proxy(t,{construct:(s,r)=>{const o=new t(...r);return o.setValues(e),o.proxy}})}const Pe=t=>{const e=Gp(tl,t);return new e(t)},Po={failurePolicy:"throw"};class mr extends Error{constructor(s,r,o,n){super(n||`Extension failure in ${r} for id "${s}"`);l(this,"extensionId");l(this,"extensionType");l(this,"cause");this.name="ExtensionException",this.extensionId=s,this.extensionType=r,this.cause=o}}const oe="canvas-renderer",sl="kos.declarative.futureLifecycleWrapper",ko=new Map,aa=new Map,Lo=new Map,Fo=new Map,Zt=(t,e)=>{rl[t]=e},rl={indexExtension:{registerIndexExtension:(t,e)=>{const s=Fo.get(t)||{};Object.assign(s,e),Fo.set(t,e)},loadIndexExtensions:t=>Fo.get(t)||{}},loader:{registerLoader:(t,e,s)=>{aa.set(t,{loader:e,options:{...Po,...s}})},executeLoader:async(t,e)=>{const s=aa.get(t);if(!s)return;const{loader:r,options:o}=s;try{return await r(e)}catch(n){if(o.failurePolicy==="continue"){g.error(`Error executing data loader for id ${t}`),g.error(n);return}throw new mr(t,"dataLoader",n)}}},propertyMapper:{registerPropertyMapper:(t,e,s)=>{Lo.set(t,{mapper:e,options:{...Po,...s}})},hasMapper:t=>Lo.has(t),executeMapper:(t,e,s)=>{const r=Lo.get(t);if(!r)return"";const{mapper:o,options:n}=r;try{return o(e,s)}catch(i){if(n.failurePolicy==="continue")return g.error(`Error executing property mapper for id ${t}`),g.error(i),"";throw new mr(t,"propertyMapper",i)}}},dataMapper:{registerDataMapper:(t,e,s)=>{const r=ko.get(t)||[];r.push({mapper:e,options:{...Po,...s}}),ko.set(t,r)},executeMapper:async(t,e,s)=>{const r=ko.get(t);if(!r)return{};const o={};for(const{mapper:n,options:i}of r)try{const a=await n(e,s);Object.assign(o,a)}catch(a){if(i.failurePolicy==="continue"){g.error(`Error executing data mapper for id ${t}`),g.error(a);continue}throw new mr(t,"dataMapper",a)}return o}},canvas:{registerRenderer:(t,e)=>{if(!T[oe]){g.warn(`Canvas renderer extension point is not registered. Cannot register renderer "${t}".`);return}T[oe].register(t,e)}}},T=rl,Yp=async({context:t,extension:e})=>{const s=await T.loader.executeLoader(e,{});return t==null||t.set(e,s),s},Wp=async({extension:t,contextData:e,data:s})=>await T.dataMapper.executeMapper(t,s,e),Qp=async({extension:t,contextData:e,data:s})=>await T.propertyMapper.executeMapper(t,s,e),Xp=Object.freeze(Object.defineProperty({__proto__:null,executeDataMapperExtension:Wp,executeLoaderExtension:Yp,executePropertyMapperExtension:Qp},Symbol.toStringTag,{value:"Module"})),Zp="Extensions";class Jp{constructor(){l(this,"extensions");this.extensions={}}register(e,s,r){this.extensions[e]={},this.extensions[e][s]={component:r}}get(e,s){if(!this.extensions[e])throw new Error(`Extension point ${e} not found`);return this.extensions[e][s]}get allExtensions(){return this.extensions}}function eg(t,e){return t.length!==e.length?!1:t.every(s=>e.includes(s))}class qn{constructor({container:e,key:s}){l(this,"_container");l(this,"_map");l(this,"_key");l(this,"data");this._container=e,this._map=E.observable.map(new Map),this._key=s,this.data=Pe(),this.generateIndex(),E.autorun(()=>{this._container.revision&&this.generateIndex()}),E.makeAutoObservable(this)}refresh(){this.generateIndex()}addItemToIndex(e,s,r=this._map,o=this.data){const n=r.get(e)||new Set;n.add(s),r.set(e,n),o[e]=Array.from(n)}resolveIndex(e,s){this.data.keys.filter(o=>!Object.keys(s).includes(o)).forEach(o=>{delete this.data[o],this._map.delete(o)}),Object.keys(s).forEach(o=>{const n=s[o],i=this.data[o]||[];if(eg(n,i))g.debug(`KosContainerIndex - Index ${o} is the same`);else{this.data[o]=n;const a=e.get(o)||new Set;this._map.set(o,a)}})}generateIndex(){E.runInAction(async()=>{const e=new Map,s={};for(const r of this._container.data){const o=typeof this._key=="function"?await this._key(r):r[this._key];Array.isArray(o)?o.forEach(n=>{this.addItemToIndex(n,r,e,s)}):typeof o=="string"||typeof o=="number"?this.addItemToIndex(String(o),r,e,s):typeof o=="boolean"&&this.addItemToIndex(String(o),r,e,s)}this.resolveIndex(e,s)})}get keys(){return Array.from(this._map.keys())}get index(){return this._map}getByKey(e){const s=this._map.get(e);return s?Array.from(s):[]}}function tg(t,e,s=[]){const r=Object.getOwnPropertyDescriptors(t);return Object.keys(r).filter(i=>E.isComputedProp(t,i)).filter(i=>s.includes(i)).map(i=>E.reaction(()=>t[i],(a,c)=>{e({name:i,newValue:a,oldValue:c})}))}const le=g.createLogger({name:"kos-container-model"});class Fe{constructor(e){l(this,"_data");l(this,"_sortKey");l(this,"_revision");l(this,"_index");l(this,"_optionsMap");l(this,"_disposerMap",new Map);l(this,"_parentId");l(this,"idx");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;const s=e!=null&&e.extensionId?T.indexExtension.loadIndexExtensions(e.extensionId):{},r=(e==null?void 0:e.indexMap)||{};this._optionsMap={...r,...s};const o=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((n,i)=>(n[i]=void 0,n),{}):{};this._index=E.observable.map(o),this.idx=Pe(),this._parentId=e==null?void 0:e.parentId,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 revision(){return this._revision}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){E.runInAction(()=>{this._revision=this._revision+1})}addAll(e){E.runInAction(()=>{e.forEach(s=>this.addModel(s,!0))}),this.increment()}removeAll(e){E.runInAction(()=>{e.forEach(s=>this.removeModel(s,!0)),this.increment()})}async removeAndDestroy(e){const s=this.getModel(e);if(!s){le.debug(`Model ${e} not found in container, skipping destroy`);return}this.removeModel(e);try{await Re(s)}catch(r){throw le.error(`Failed to destroy model ${e}:`,r),r}}async removeAndDestroyAll(e){const s=e.map(n=>this.getModel(n)).filter(n=>n!==void 0);if(s.length===0){le.debug("No models found to destroy");return}this.removeAll(e);const r=await Promise.allSettled(s.map(n=>Re(n)));r.forEach((n,i)=>{n.status==="rejected"&&le.error(`Failed to destroy model ${s[i].id}:`,n.reason)});const o=r.filter(n=>n.status==="rejected");if(o.length>0)throw new Error(`Failed to destroy ${o.length} of ${s.length} models`)}addModel(e,s){this._persistModel(e),this._trackModelMetadata(e),this._establishModelRelationships(e),this._enforceCapacityLimits(),this._configureModelMonitoring(e),s||this.increment()}_persistModel(e){this._data.set(e.id||"",e)}_trackModelMetadata(e){this._maxCapacity&&(this._insertionOrder.push(e.id||""),this._accessTimes&&this._accessTimes.set(e.id||"",Date.now()))}_establishModelRelationships(e){e.id&&this._parentId&&Q.setParentContext(e.id,this._parentId)}_enforceCapacityLimits(){this._maxCapacity&&this._data.size>this._maxCapacity&&this._evictModels()}_configureModelMonitoring(e){const s=this._disposerMap.get(e.id);s&&(s(),this._disposerMap.delete(e.id));const r=Object.entries(this._optionsMap||{}),o=Object.values(this._optionsMap||{}),n=new Map(r.map(([u,d])=>[d,u])),i=u=>{var h,f;o.includes(u.name)&&((h=this.index.get(n.get(u.name)))==null||h.refresh());const d=r.filter(([,p])=>typeof p=="function");for(const[p]of d)(f=this.index.get(p))==null||f.refresh()},a=tg(e,i,o.filter(u=>typeof u=="string")),c=E.observe(e,i);this._disposerMap.set(e.id||"",()=>[c,...a].forEach(u=>u()))}removeModel(e,s){this._data.delete(e);const r=this._insertionOrder.indexOf(e);r!==-1&&this._insertionOrder.splice(r,1),this._accessTimes&&this._accessTimes.delete(e),s||this.increment();const o=this._disposerMap.get(e);o&&(o(),this._disposerMap.delete(e))}updateModel(e){this._data.set(e.id||"",e),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??[]:(le.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):(le.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return le.info(`index ${e} not found in ${Array.from(this.index.keys())}`),[]}async _evictModels(){if(!this._maxCapacity)return;const e=this._data.size-this._maxCapacity;if(e<=0)return;const s=Math.min(this._evictionBatchSize,e);this._logCapacityWarning(s);const r=this._selectModelsForEviction(s);await this._removeEvictedModels(r),this._logEvictionComplete(r.length),this.increment()}_logCapacityWarning(e){le.info(`Container capacity exceeded (${this._data.size}/${this._maxCapacity}). Evicting ${e} models using ${this._evictionStrategy} strategy.`,{parentId:this._parentId})}_selectModelsForEviction(e){switch(this._evictionStrategy){case"fifo":return this._selectFifoModels(e);case"lru":return this._selectLruModels(e);case"custom":return this._selectCustomModels(e);default:return this._selectFifoModels(e)}}_selectFifoModels(e){const s=[];for(let r=0;r<e&&this._insertionOrder.length>0;r++){const o=this._insertionOrder.shift();if(!o)continue;const n=this._data.get(o);n&&s.push(n)}return s}_selectLruModels(e){const s=[];return this._accessTimes&&Array.from(this._accessTimes.entries()).sort((o,n)=>o[1]-n[1]).slice(0,e).forEach(([o])=>{const n=this._data.get(o);n&&s.push(n)}),s}_selectCustomModels(e){return this._customEvictionFilter?this._customEvictionFilter(this.data).slice(0,e):(le.error("Custom eviction strategy specified but no customEvictionFilter provided. Falling back to FIFO.",{parentId:this._parentId}),this._selectFifoModels(e))}async _removeEvictedModels(e){for(const s of e)le.info(`Evicting model: ${s.id} (type: ${s.constructor.name})`,{modelId:s.id,parentId:this._parentId,strategy:this._evictionStrategy}),this.removeModel(s.id,!0),Re(s).catch(r=>le.error(`Failed to destroy evicted model ${s.id}:`,r))}_logEvictionComplete(e){le.info(`Evicted ${e} models. Current size: ${this._data.size}/${this._maxCapacity}`,{parentId:this._parentId})}async clear(){this._data.forEach(e=>{const s=e.id;Re(e).then(()=>{le.debug(`${s} destroyed, removing from map`),this.removeModel(s,!0)}).catch(r=>le.error(r))}),this.increment()}filter(e,s){return this.data.filter(e,s)}sort(e){return this.data.sort(e)}map(e,s){return this.data.map(e,s)}forEach(e,s){this.data.forEach(e,s)}toJSON(){return{indexes:this.indexKeys,data:this.data.map(s=>({id:s.id,type:s.constructor.name}))}}}var w=(t=>(t.CREATING="creating",t.CREATED="created",t.INITIALIZING="initializing",t.INITIALIZED="initialized",t.LOADING="loading",t.LOADED="loaded",t.ONLINE="online",t.READYING="readying",t.READY="ready",t.READY_FAILED="ready_failed",t.RESETTING="resetting",t.RESET="reset",t.OFFLINE="offline",t.UNLOADING="unloading",t.UNLOADED="unloaded",t.FAILED="failed",t.INACTIVE="inactive",t.ACTIVE="active",t.ACTIVATING="activating",t.DEACTIVATING="deactivating",t))(w||{}),L=(t=>(t.CREATE="create",t.INITIALIZE="init",t.LOAD="load",t.READY="ready",t.GO_ONLINE="go_online",t.GO_OFFLINE="go_offline",t.RESET="go_offline",t.UNLOAD="unload",t.FAILED="failed",t.GO_ACTIVE="go_active",t.GO_INACTIVE="go_inactive",t.TIMEOUT="timeout",t))(L||{});const ye=async t=>{if(t.id){const e=S.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error(`Model with ID ${t.id} not found`);await(e==null?void 0:e.whenReady())}else throw new Error("Data model must have a valid ID");return t},Re=async t=>{await S.getInstance().whenReady(),await S.getInstance().modelManager.initiateDestroyModel(t)},sg=async t=>{if(await S.getInstance().whenReady(),!t.id)throw new Error("Model ID is required");const e=S.getInstance().modelManager.getModelById(t.id);e&&await e.fsm.transitionTo(L.UNLOAD,w.UNLOADED)},rg=async t=>{await S.getInstance().whenReady(),await S.getInstance().modelManager.reloadModel(t),g.debug(`reload model initiated for model ${t.id}, model ready: ${Ir(t)} - ${Date.now()} `),await ye(t),g.debug(`reload model complete for model ${t.id}, model ready: ${Ir(t)} - ${Date.now()} `)},og=async t=>{if(await S.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=S.getInstance().modelManager.getModelById(t);return e==null?void 0:e.modelTypeName},ol=async t=>{if(await S.getInstance().whenReady(),!t)throw new Error("Model ID is required");const e=S.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},ke=t=>{if(!t)throw new Error("Model ID is required");const e=S.getInstance().modelManager.getModelById(t);return{model:e==null?void 0:e.modelData,type:e==null?void 0:e.modelTypeName}},nl=(t,e)=>{if(!t)throw new Error("Model type is required");return S.getInstance().modelManager.getModelsByType(t).filter(o=>Object.keys(e).every(n=>o[n]===e[n]))},ng=(t,e)=>nl(t,e)[0],ig=(t,e)=>{if(!t.id)throw new Error("Model ID is required");const s=S.getInstance().modelManager.getModelById(t.id);if(!s)throw new Error("Model not found");const r=s.companionModels.get(e);return r==null?void 0:r.modelData},il=t=>{if(!t.id)throw new Error("Model ID is required");const e=S.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return Array.from(e.companionModels.all()).map(r=>r.modelData)},ag=t=>{if(!t)throw new Error("Model ID is required");const e=S.getInstance().modelManager.getModelById(t);if(!e)throw new Error("Model not found");return e.companionModels.data},Jo=(t,e)=>{const s=S.getInstance().modelManager.getModelById(t);if(!s){g.info(`Model not found for id ${t}`);return}return Array.from(s.companionModels.all()).find(o=>e(o.modelData))},Ie=t=>e=>Object.getPrototypeOf(e).modelTypeId===t,Ir=t=>{const e=S.getInstance().modelManager.getModelById(t.id);if(!e)throw new Error("Model not found");return e.isReady()},cg=g.createLogger({name:"kos-model-factory"}),Os={byModelType:t=>S.getInstance().modelManager.getModelFactory(t),getModelInstance:(t,e,s)=>{const r=Os.byModelType(e);if(!r)throw cg.error(`No registered factory found for model type ${e}. Please register a factory for this model type. `),Error(`No factory found for model type ${e}`);return r.build(t,s)}},he={Factory:{create:t=>e=>(s,r)=>(r&&Q.setParentContext(e,r),Os.getModelInstance(e,t,s))},Singleton:{create:t=>(e,s)=>(s&&Q.setParentContext(t,s),Os.getModelInstance(t,t,e))},Model:{instance:t=>e=>Os.getModelInstance(e,t)}};window.KosRegistry=window.KosRegistry||{coreModels:new Map,preloadModels:[],companionModels:new Map,models:new Map};const ca=window.KosRegistry.coreModels,No=window.KosRegistry.preloadModels,Uo=window.KosRegistry.companionModels,or=window.KosRegistry.models,R={model:{registerLegacyModel:t=>(e,s)=>(ca.set(e,s),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t),root:t}),preloadModel:t=>e=>(No.includes(e)||No.push(e),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t),root:t}),register:t=>(e,s)=>{const r=jo(e)?e.registration():e;return or.set(r.type,r),jo(e)&&e.relatedModels.forEach(o=>or.set(o.type,o.registration())),S.getInstance().isReady&&(S.getInstance().modelManager.registry.models[r.type]||(console.info(`Model with type ${r.type} doesn't exist. Adding new registration`),S.getInstance().modelManager.registry.models[r.type]=r.registration[r.type],jo(e)&&e.relatedModels.forEach(o=>S.getInstance().modelManager.registry.models[o.type]=o.registration().registration))),s&&R.model.preloadModel(t)(r.type),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t),root:t}},get:t=>or.get(t),getAll:()=>Array.from(or.entries()),getPreloadModels:()=>No,getLegacyModels:()=>Array.from(ca.entries()).reduce((t,[e,s])=>(t[e]=s,t),{})},companion:{register:t=>(e,s)=>{const r=Uo.get(e)||[];return r.push(s),Uo.set(e,r),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t),root:t}},getAll:()=>Array.from(Uo.entries())}},al=R.model.registerLegacyModel,cl=R.model.register,lg=R.companion.register,ug=R.model.preloadModel,zn=t=>typeof t.updateModel=="function",jo=t=>t.registration!==void 0&&typeof t.registration=="function";class ll{constructor(e){l(this,"singleton");l(this,"type");l(this,"loader");l(this,"class");l(this,"guard");l(this,"factory");l(this,"relatedModels",[]);this.singleton=e.singleton,this.guard=Ie(e.type),this.type=e.type,this.loader=`kos.extension.model.loader.${e.type}`,this.factory=e.factory,this.class=e.class}addRelatedModel(e){this.relatedModels.push(e)}registerRelatedModels(){this.relatedModels.forEach(e=>e.register())}register(){R.model.register({})(this.registration()),this.registerRelatedModels()}}class Ee extends ll{constructor(e){super({...e,singleton:!1,factory:he.Factory.create(e.type)})}instance(e){const s=this.factory(e);return{get:()=>{const r=ke(e);if(!r)throw new Error("Model not found with id "+e);if(this.guard(r.model))return r.model;throw new Error("Model is not of type "+this.type)},forceUpdate:{options:r=>({build:()=>{const o=s(r);if(this.guard(o)){if(zn(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error("Model is not of type "+this.type)}})},options:r=>({build:()=>{const o=s(r);if(this.guard(o))return o;throw new Error("Model is not of type "+this.type)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!1}},factory:this.factory}}}class Ce extends ll{constructor(e){super({...e,singleton:!0,factory:he.Singleton.create(e.type)})}instance(){const e=this.factory;return{get:()=>{const r=ke(this.type);if(!r)throw new Error("Model not found with id "+this.type);if(this.guard(r))return r;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(r).modelTypeId}`)},forceUpdate:{options:r=>({build:()=>{const o=e(r);if(this.guard(o)){if(zn(o))o.updateModel(r);else throw new Error(`Model ${this.type} is not updateable. Please implement UpdateAware interface`);return o}else throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})},options:r=>({build:()=>{const o=e(r);if(this.guard(o))return o;throw new Error(`Model is not of type ${this.type}. Received type ${Object.getPrototypeOf(o).modelTypeId}`)}})}}registration(){return{type:this.type,predicate:this.guard,registration:{[this.type]:{class:this.class,singleton:!0}},factory:this.factory}}}const en=g.createLogger({group:"decorators",name:"kos-model"});function dg(t,e,s){var n;const r=(n=t[Ms])==null?void 0:n.parentId;if(!r)return;const o=me({value:r,modelData:s,modelId:e});o&&typeof o=="string"&&Q.setParentContext(e,o)}function hg(t){const e=t[Es];e&&Object.entries(e).forEach(([s,{handler:r}])=>{t[s]=r})}function fg(t,e){const s=t[F]||{};Object.entries(s).forEach(([r,o])=>{const n=me({value:o.id||o.modelType,modelData:t,modelId:e}),i=Object.entries((o==null?void 0:o.options)||{}).reduce((a,[c,u])=>(a[c]=me({value:u,modelData:t,modelId:e}),a),{});if(typeof n=="string"){if(!o.lazy){const a=S.getInstance().modelManager.createModelInstance(o.modelType,n,i);t[r]=a.data}S.getInstance().modelManager.addDependency(e,n)}})}function pg(t){const e=t[Pn];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new po(t);t[r]=o,s==="full"&&(Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0}),Object.defineProperty(t,"progress",{get(){var n;return((n=o.future)==null?void 0:n.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var n;return((n=o.future)==null?void 0:n.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var n;return((n=o.future)==null?void 0:n.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function gg(t){const e=t[kn];if(!e)return;const{mode:s,handlerProperty:r}=e,o=new Zc(t);t[r]=o,Object.defineProperty(t,"future",{get(){return o.future},enumerable:!0,configurable:!0});const n=t[Ts];n instanceof Map&&n.forEach(i=>{const a=`${i}Future`;Object.defineProperty(t,a,{get(){return o.futureMap.get(i)},enumerable:!0,configurable:!0}),s==="full"&&(Object.defineProperty(t,`${i}Progress`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}Status`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsRunning`,{get(){const c=o.futureMap.get(i);return c?!c.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,`${i}IsCancelled`,{get(){const c=o.futureMap.get(i);return(c==null?void 0:c.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t[`cancel${i.charAt(0).toUpperCase()}${i.slice(1)}`]=async()=>{const c=o.futureMap.get(i);c&&await c.cancelFuture()})}),s==="full"&&(Object.defineProperty(t,"progress",{get(){var i;return((i=o.future)==null?void 0:i.progress)||0},enumerable:!0,configurable:!0}),Object.defineProperty(t,"status",{get(){var i;return((i=o.future)==null?void 0:i.status)||"IDLE"},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isRunning",{get(){return o.future?!o.future.endState:!1},enumerable:!0,configurable:!0}),Object.defineProperty(t,"isCancelled",{get(){var i;return((i=o.future)==null?void 0:i.status)==="CANCELLED"||!1},enumerable:!0,configurable:!0}),t.cancelFuture=async()=>{o.future&&await o.future.cancelFuture()})}function mg(t){const e=t[Ln];if(!e)return;const{pathProperty:s}=e;Object.defineProperty(t,"troubles",{get(){const r=this[s];if(r==null){const o=`@kosTroubleAware: Path property '${s}' is undefined on model ${this.id||"unknown"}. Returning empty troubles array.`;return this.logger&&typeof this.logger.warn=="function"?this.logger.warn(o):console.warn(o),[]}return this.troubleContainer.troubles.getIndexByKey("byIface",r).sort((o,n)=>n.rank-o.rank)},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troubleStatus",{get(){return""},enumerable:!0,configurable:!0}),Object.defineProperty(t,"troublesByType",{get(){return this.troubles.reduce(Jc,{})},enumerable:!0,configurable:!0})}function yg(t,e){const s=t[Nn];if(!s)return;const{containerProperty:r,includeMethods:o,includeGetters:n,modelsProperty:i,containerOptions:a,legacy:c}=s,u={...a,parentId:a.parentId||e},d=new Fe(u);t[r]=d,t[Je]||(t[Je]={}),t[Je][r]=d,o&&(t.getModel=h=>d.getModel(h),t.addModel=h=>{d.addModel(h)},t.removeModel=h=>{d.removeModel(h)},t.addAll=h=>{d.addAll(h)},t.removeAll=h=>{d.removeAll(h)},t.removeAndDestroy=async h=>d.removeAndDestroy(h),t.removeAndDestroyAll=async h=>d.removeAndDestroyAll(h)),n&&(Object.defineProperty(t,i,{get(){return d},enumerable:!0,configurable:!0}),Object.defineProperty(t,"data",{get(){return d.data},enumerable:!0,configurable:!0}))}function bg(t,e){const s=t.constructor.prototype[et];if(!s)return;const{mode:r,parentProperty:o,excludeProperties:n}=s,i=e.companionParent;if(!i){en.warn("Companion decorator configured but no parent model found in initialData.companionParent");return}if(t.getCompanionParent=()=>i,Object.defineProperty(t,o,{get:()=>i,enumerable:!0,configurable:!0}),r==="composition")return;const a=["init","load","unload","ready","dispose","destroy","activate"],c=["getDependencies","getChildren","update","toJSON","forceUpdate","makeAutoObservable","runInAction","transaction","observe","unobserve","intercept","spy","trace","getCompanionParent"],u=p=>{const y=i.constructor.prototype[Z]||{};return Object.values(y).some(v=>{const M=v==null?void 0:v.handler;return M===i[p]||M===i.constructor.prototype[p]})},d=p=>p==="constructor"||p.startsWith("_")||p.startsWith("__")||a.includes(p)||c.includes(p)||n.includes(p)||u(p)||p in t,h=new Set;Object.getOwnPropertyNames(i).filter(p=>!d(p)).forEach(p=>h.add(p));let f=Object.getPrototypeOf(i);for(;f&&f!==Object.prototype;)Object.getOwnPropertyNames(f).filter(p=>!d(p)).forEach(p=>h.add(p)),f=Object.getPrototypeOf(f);for(const p of h)try{const y=i[p];typeof y=="function"?t[p]=(...v)=>y.apply(i,v):Object.defineProperty(t,p,{get:()=>i[p],set:v=>{i[p]=v},enumerable:!0,configurable:!0})}catch(y){en.debug(`Skipping companion proxy for property ${p}:`,y)}}function vg(t){const e=t[Bc];if(!e)return;const{reloadDependencies:s=[]}=e;t._isReloading=!1,Object.defineProperty(t,"isReloading",{get(){var r;if(this._isReloading)return!0;for(const o of s)if((r=this[o])!=null&&r.isReloading)return!0;return!1},enumerable:!0,configurable:!0})}function wg(t){try{return E.makeAutoObservable(t)}catch(e){return en.error("Failed to make observable:",e),t}}const Eg={construct(t,e){var c;const[s,r={}]=e,o=Q.createContext(s);dg(t,s,r);const i=!!t.prototype[Fn]?null:g.createLogger({name:t.prototype.modelTypeId,group:((c=t[_s])==null?void 0:c.group)??"kos-model"}),a=new t(s,r,{logger:i,kosContext:o});return bg(a,r),hg(a),pg(a),gg(a),mg(a),yg(a,s),Bn(a),vg(a),fg(a,s),wg(a)}};function D(t){return e=>{var n,i;const s=e,r=typeof t=="string"?{modelTypeId:t,autoRegister:!1}:{autoRegister:!1,...t};s.prototype.modelTypeId=r.modelTypeId,s.prototype[Rn]=!0,(n=s.prototype)[Z]??(n[Z]={}),(i=s.prototype)[F]??(i[F]={}),r.optionsRequired&&(s.prototype[Qs]=!0),g.ifDebug(()=>{g.debug(`Registering model with id ${r.modelTypeId}`)});const o=new Proxy(s,Eg);if(r.singleton!==void 0){let a;r.singleton?a=new Ce({class:o,type:r.modelTypeId}):a=new Ee({class:o,type:r.modelTypeId}),Object.defineProperty(o,"Registration",{value:a,writable:!1,enumerable:!0,configurable:!1}),r.autoRegister&&a.register()}return o}}function ul(t,e,s=300){let r;return(...o)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(t,o)},s)}}const Mg=({topic:t,handler:e,websocket:s=!1,condition:r=()=>!0})=>o=>{oc("@kosSubscribe","core.subscribe",1,"@kosTopicHandler",3),o[Z]=o[Z]||{},Array.isArray(t)?t.forEach(n=>{o[Z][n]={websocket:s,handler:e,condition:r}}):o[Z][t]={websocket:s,handler:ul(o,E.action(e),200),condition:r}};function dl(t,e,s){const r={};if(!t.endsWith("/*"))return r;const o=t.slice(0,-2);if(e.startsWith(o)){const n=e.slice(o.length+1),i=s||"path";r[i]=n}return r}function hl(t){return t.endsWith("/*")}function B(t){return(e,s,r)=>{const o=_g(t,r);Sg(e,t.topic,o),t.replay&&Og(t.topic,t.replay.bufferSize)}}function _g(t,e){const{condition:s=(V,ee)=>!0,transform:r=V=>V,websocket:o=!1,fos:n=!1,bridge:i=!1,skipParse:a=!1,lifecycle:c,destinationAddress:u,explicitDestination:d=!1,debounce:h,throttle:f,buffer:p,filter:y,once:v,wildcardName:M,flow:O,requiresBaseline:U}=t,A=e.value,$=fl(A,{debounce:h,throttle:f,buffer:p,once:v}),P=Tg(y,s);return{websocket:o,fos:n,bridge:i,handler:$,condition:P,transform:r,lifecycle:c,skipParse:a,destinationAddress:u,explicitDestination:d,wildcardName:M,flow:O,requiresBaseline:U,once:v}}function fl(t,e){var n,i;let s=t;const r=typeof e.debounce=="number"?e.debounce:(n=e.debounce)==null?void 0:n.delay,o=typeof e.throttle=="number"?e.throttle:(i=e.throttle)==null?void 0:i.interval;return r&&r>0?s=$g(s,e.debounce):o&&o>0?s=Ag(s,e.throttle):e.buffer?s=xg(async function(c){for(const u of c)await s.call(this,u)},e.buffer):e.once&&(s=Rg(s)),s}function Tg(t,e){return t?(s,r,o)=>t(o)?e(s,r,o):!1:e}function Sg(t,e,s){t[Z]=t[Z]||{},Array.isArray(e)?e.forEach(r=>{t[Z][r]=s}):t[Z][e]=s}function Og(t,e){Pg(t,e)}function $g(t,e){const s=typeof e=="number"?e:e.delay;return Ig(e)==="discard"?Cg(t,s):Dg(t,s)}function Ig(t){return(typeof t=="object"?t.discardIntermediate:!1)?"discard":"accumulate"}function Cg(t,e){let s=null;return function(r){s&&clearTimeout(s),s=setTimeout(()=>{t.call(this,r),s=null},e)}}function Dg(t,e){let s=null,r=[];return function(o){r.push(o),s&&clearTimeout(s),s=setTimeout(()=>{const n=[...r];r=[],t.call(this,n),s=null},e)}}function Ag(t,e){const s=typeof e=="number"?e:e.interval,r=typeof e=="object"?e.discardIntermediate:!1;let o=0,n=null,i=[],a=!1;const c=function(){if(i.length>0){const u=[...i];i=[],t.call(this,u)}};return function(u){const d=Date.now(),h=d-o;r?h>=s?(o=d,t.call(this,u)):n||(n=setTimeout(()=>{o=Date.now(),t.call(this,u),n=null},s-h)):(i.push(u),h>=s?(o=d,c.call(this)):a||(a=!0,n=setTimeout(()=>{o=Date.now(),c.call(this),n=null,a=!1},s-h)))}}function xg(t,e){const s=[];let r=null;const o=e.maxSize||1e3,n=i=>{s.length>0&&(t.call(i,[...s]),s.length=0)};return function(i){if(s.push(i),s.length>=o){r&&(clearTimeout(r),r=null),n(this);return}r||(r=setTimeout(()=>{n(this),r=null},e.time))}}function Rg(t){let e=!1;return function(s){e||(e=!0,t.call(this,s))}}function Pg(t,e){(Array.isArray(t)?t:[t]).forEach(r=>{Cn(r,e)})}function pl(t){return t!==null&&typeof t=="object"&&"ready"in t&&typeof t.ready=="function"}function yr(t){return t!==null&&typeof t=="object"&&"dispose"in t&&typeof t.dispose=="function"}let kg=0;const Lg=Symbol("ViewModelEffectDisposers");function Fg(t){const e=t[Be];return!!e&&Object.keys(e).length>0}function Ng(t,e){if(!Fg(t))return;const s=t[Be],r=[];for(const a of Object.keys(s)){const{value:c,dependencies:u,options:d}=s[a],h=c.bind(t),f=()=>{E.runInAction(()=>h())},p=u?E.reaction(()=>u(t),f,{fireImmediately:!!(d!=null&&d.fireImmediately)}):E.autorun(f);r.push(p)}Object.defineProperty(t,Lg,{value:r,writable:!1,enumerable:!1,configurable:!0});const o=t,n=o.dispose,i=()=>{for(const a of r)try{a()}catch(c){console.warn(`[kosViewModel] Failed to dispose effect for ${e}:`,c)}};typeof n=="function"?o.dispose=function(){return i(),n.call(this)}:o.dispose=i}function Ug(t,e){const s=t[Wt];if(!s)return;const{config:r}=s;r.initializeAt&&r.initializeAt!==I.INIT&&console.warn(`[kosViewModel] ViewModel "${e}" has @kosStateMachine with initializeAt: ${r.initializeAt}. ViewModels do not have lifecycle phases, so the FSM will initialize immediately. Consider removing initializeAt or using @kosModel if lifecycle-aware FSM initialization is required.`),Bn(t)}function jg(t){try{return E.makeAutoObservable(t)}catch(e){return console.error("[kosViewModel] Failed to make observable:",e),t}}const Bg={construct(t,e){var a;const s=t.prototype[Un]||{},r=s.typeId||t.name,o=`${r}-${++kg}`,n=new t(...e);Ug(n,r),Ng(n,r),Object.defineProperty(n,"__viewModelTypeId",{value:r,writable:!1,enumerable:!1,configurable:!0}),Object.defineProperty(n,"__viewModelInstanceId",{value:o,writable:!1,enumerable:!1,configurable:!0});const i=jg(n);return s.devToolsEnabled&&((a=globalThis.__KOS_DEVTOOLS__)!=null&&a.registerViewModel)&&globalThis.__KOS_DEVTOOLS__.registerViewModel(o,i),i}};function Kg(t){return e=>{const s=t||{},r=s.typeId||e.name;e.prototype[jc]={type:r},e.prototype[Un]=s;const o=new Proxy(e,Bg);return Object.defineProperty(o,"name",{value:e.name}),o}}const Bo=new Map,gl={addToDeletionQueue:(t,e)=>{const s=Bo.get(t)||[];s.push(e),Bo.set(t,s)},cancelDeletion:t=>{const e=Bo.get(t);e&&e.forEach(s=>{clearTimeout(s)})}},Hg=g.createLogger({name:"kos-dependency-manager"});class qg{constructor(){l(this,"_usedByCache",new Map);l(this,"_usesCache",new Map)}add(e,s){gl.cancelDeletion(s);const r=this._usedByCache.get(s)||[];r.includes(e)||r.push(e),this._usedByCache.set(s,r);const o=this._usesCache.get(e)||[];o.includes(s)||o.push(s),this._usesCache.set(e,o)}remove(e,s){const r=this._usedByCache.get(s)||[];this._usedByCache.set(s,r.filter(n=>n!==e));const o=this._usesCache.get(e)||[];this._usesCache.set(e,o.filter(n=>n!==s))}canDestroy(e){const s=this._usedByCache.get(e);return s!=null&&s.length?(Hg.info(`Model ${e} is still used by: ${s.join(", ")}`),!1):!0}clear(){this._usedByCache.clear(),this._usesCache.clear()}}const la=g.createLogger({name:"kos-model-cache"});class zg{constructor(e=[]){l(this,"_modelsById",E.observable.map(new Map));l(this,"_toDelete",new Map);l(this,"_preloaded",[]);l(this,"_isPreloaded",!1);this.preloadKeys=e}get models(){return Array.from(this._modelsById.values()).map(e=>e).filter(e=>!this._toDelete.has(e.modelId))}getModelById(e){if(e&&!this._toDelete.has(e))return this._modelsById.get(e)}addModel(e){const s=this.getModelById(e.modelId)||e;return this._modelsById.set(s.modelId,s),s}removeModel(e){this._modelsById.delete(e),this._toDelete.delete(e)}hasModel(e){return!!e&&this._modelsById.has(e)&&!this._toDelete.has(e)}restoreFromDeleteCache(e){if(e&&this._toDelete.has(e)){const s=this._toDelete.get(e);this._toDelete.delete(e),this._modelsById.set(e,s)}}markForDeletion(e){this._modelsById.delete(e.modelId),this._toDelete.set(e.modelId,e)}preload(e){return this._isPreloaded?(la.debug("Returning cached preloaded models"),this._preloaded):(this._preloaded=this.preloadKeys.map(s=>(la.debug(`Preloading model: ${typeof s=="string"?s:s.modelType}`),e(s))).filter(s=>!!s),this._isPreloaded=!0,this._preloaded)}}class br extends Error{constructor(s,r,o){super(s,{cause:o});l(this,"context");l(this,"originalCause");this.name="KosModelError",this.context=r,this.originalCause=o,o!=null&&o.stack&&(this.stack=`${this.stack}
2
2
  Caused by: ${o.stack}`)}toDetailedString(){const s=[`KosModelError: ${this.message}`,"","Context:",` Model Type: ${this.context.modelType}`,` Model ID: ${this.context.modelId}`];return this.context.parentModel&&s.push(` Parent Model: ${this.context.parentModel.type} [${this.context.parentModel.id}]`),this.context.lifecycle&&s.push(` Lifecycle: ${this.context.lifecycle}`),this.context.operation&&s.push(` Operation: ${this.context.operation}`),this.context.options&&Object.keys(this.context.options).length>0&&s.push(` Options: ${JSON.stringify(this.context.options,null,2)}`),this.originalCause&&s.push("",`Original Error: ${this.originalCause.message}`),s.join(`
3
- `)}}function Lt(t,e){const s=t instanceof Error?t:new Error(String(t));return t instanceof mr?new mr(`${t.message} (enriched with additional context)`,{...t.context,...e},t.originalCause||s):new mr(`Error in ${e.operation||"model operation"}: ${s.message}`,e,s)}function Eg(t,e){t.length!==0&&(m.error(`${e} - ${t.length} error(s) occurred:`),t.forEach(({error:s,context:r},o)=>{const n=s instanceof mr?s:Lt(s,r);m.error(` [${o+1}/${t.length}] ${n.toDetailedString()}`)}))}function Ji(t,e){console.error("Model instantiation failed",{modelType:e.modelType,options:e.options,registryId:e.registryId,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,timestamp:new Date().toISOString()})}const el=t=>typeof t=="function",sr=m.createLogger({name:"kos-companion-instantiator"});class Mg{constructor(e,s,r){this.registry=e,this.cache=s,this.createModel=r}createCompanionModels(e,s,r){const o=this.getCompanionDefinitions(e.modelTypeName);r!==void 0&&sr.debug(`Creating ${r} lifecycle companions for ${e.modelTypeName} [${e.modelId}]`);for(const n of o){const i=this.resolveCompanionType(n,e,s,r);i&&this.shouldCreateCompanion(i.lifecycle,r)&&this.instantiateCompanion(i.type,e,s,r)}}getCompanionDefinitions(e){var s;return((s=this.registry.companionModels)==null?void 0:s[e])||[]}resolveCompanionType(e,s,r,o){return el(e.type)?this.resolveFactoryCompanion(e,s,r,o):this.resolveStringCompanion(e)}resolveFactoryCompanion(e,s,r,o){const n=e.type(s.modelData,r);if(!n)return sr.debug(`Companion factory returned undefined for ${s.modelTypeName} at ${o||"INIT"} phase`),null;const i=this.extractLifecycleFromType(n);return{type:n,lifecycle:i}}resolveStringCompanion(e){return{type:e.type,lifecycle:e.lifecycle}}extractLifecycleFromType(e){const s=this.registry.models[e];if(!(s!=null&&s.class))return;const r=s.class.prototype[Je];return r==null?void 0:r.lifecycle}shouldCreateCompanion(e,s){return s!==void 0?e===s:e===void 0}instantiateCompanion(e,s,r,o){const n=this.generateCompanionId(e,s.modelId);if(this.companionAlreadyExists(n,e,s.modelTypeName))return;const i=this.createCompanionInstance(e,n,s,r);i&&(this.attachCompanionToParent(i,s),sr.debug(`Created ${o||"INIT"} companion ${e} for ${s.modelTypeName} [${s.modelId}]`))}generateCompanionId(e,s){return`${e}-${s}`}companionAlreadyExists(e,s,r){return this.cache.hasModel(e)?(sr.debug(`Companion ${s} already exists for ${r}`),!0):!1}createCompanionInstance(e,s,r,o){const n=this.createModel(e,s,{data:o,companionParent:r.modelData,kosParentId:r.modelId});return(n==null?void 0:n.model)||null}attachCompanionToParent(e,s){e[Je]=s,s.addCompanionModel(e)}}function tl(t,e){return`${En}${t}${e?`/${e}`:`/${t}`}`}function sl(t){return`${En}${t}`}function Lo(t){const e=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of t){const i=M.when(o,()=>{e.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});e.push(i)}})}const rl=5e3,Tg=t=>t.fsm.transitionTo(F.GO_ACTIVE,w.ACTIVE),_g=t=>t.whenReady(),Sg=t=>t.fsm.transitionTo(F.LOAD,w.LOADED),Og=t=>t.fsm.transitionTo(F.UNLOAD,w.UNLOADED),Ig=t=>t.fsm.transitionTo(F.INITIALIZE,w.INITIALIZED);var Nn=(t=>(t.ACTIVE="active",t.READY="ready",t.LOAD="load",t.UNLOAD="unload",t.INIT="init",t))(Nn||{});const yr={active:Tg,ready:_g,load:Sg,unload:Og,init:Ig};class ol extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const nl=(t,e,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{m.error(`Model ${e.modelId} - ${e.modelTypeName} - ${s} timed out after ${t}ms`),a(new ol(`${e.modelId} - ${e.modelTypeName} - ${s}`,e))},t)}),cancel:()=>{r&&clearTimeout(r)}}},$g=t=>typeof t.toJSON=="function",Is=t=>t[x]!==void 0,Un=t=>t.revision!==void 0&&t.index!==void 0,il=t=>{if(t){if(Is(t))return t;if(Un(t))return t.data;if(t instanceof Map||t instanceof M.ObservableMap||t instanceof Set)return Array.from(t.values()).filter(Is);if(Array.isArray(t))return t.filter(Is)}},al=(t,e)=>{var f;const s=e.id||e.modelType,r=fe({value:s,modelData:t.modelData,modelId:t.modelId}),o=e.resolutionPolicy||Xe.CREATE;m.debug(`Resolving dependent model ${e.modelType} with id ${r} (policy: ${o})`);const n=Object.keys((e==null?void 0:e.options)||{}).reduce((p,g)=>{const v=e.options[g];return p[g]=fe({value:v,modelData:t.modelData,modelId:t.modelId}),p},{}),i=I.getInstance().modelManager,a=i.registry.models[e.modelType];if(!a){const p=`No model registered for type ${e.modelType}`;if(m.error(`Failed to resolve dependency for model ${t.modelId}:
3
+ `)}}function Pt(t,e){const s=t instanceof Error?t:new Error(String(t));return t instanceof br?new br(`${t.message} (enriched with additional context)`,{...t.context,...e},t.originalCause||s):new br(`Error in ${e.operation||"model operation"}: ${s.message}`,e,s)}function Vg(t,e){t.length!==0&&(g.error(`${e} - ${t.length} error(s) occurred:`),t.forEach(({error:s,context:r},o)=>{const n=s instanceof br?s:Pt(s,r);g.error(` [${o+1}/${t.length}] ${n.toDetailedString()}`)}))}function ua(t,e){console.error("Model instantiation failed",{modelType:e.modelType,options:e.options,registryId:e.registryId,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,timestamp:new Date().toISOString()})}const ml=t=>typeof t=="function",nr=g.createLogger({name:"kos-companion-instantiator"});class Gg{constructor(e,s,r){this.registry=e,this.cache=s,this.createModel=r}createCompanionModels(e,s,r){const o=this.getCompanionDefinitions(e.modelTypeName);r!==void 0&&nr.debug(`Creating ${r} lifecycle companions for ${e.modelTypeName} [${e.modelId}]`);for(const n of o){const i=this.resolveCompanionType(n,e,s,r);i&&this.shouldCreateCompanion(i.lifecycle,r)&&this.instantiateCompanion(i.type,e,s,r)}}getCompanionDefinitions(e){var s;return((s=this.registry.companionModels)==null?void 0:s[e])||[]}resolveCompanionType(e,s,r,o){return ml(e.type)?this.resolveFactoryCompanion(e,s,r,o):this.resolveStringCompanion(e)}resolveFactoryCompanion(e,s,r,o){const n=e.type(s.modelData,r);if(!n)return nr.debug(`Companion factory returned undefined for ${s.modelTypeName} at ${o||"INIT"} phase`),null;const i=this.extractLifecycleFromType(n);return{type:n,lifecycle:i}}resolveStringCompanion(e){return{type:e.type,lifecycle:e.lifecycle}}extractLifecycleFromType(e){const s=this.registry.models[e];if(!(s!=null&&s.class))return;const r=s.class.prototype[et];return r==null?void 0:r.lifecycle}shouldCreateCompanion(e,s){return s!==void 0?e===s:e===void 0}instantiateCompanion(e,s,r,o){const n=this.generateCompanionId(e,s.modelId);if(this.companionAlreadyExists(n,e,s.modelTypeName))return;const i=this.createCompanionInstance(e,n,s,r);i&&(this.attachCompanionToParent(i,s),nr.debug(`Created ${o||"INIT"} companion ${e} for ${s.modelTypeName} [${s.modelId}]`))}generateCompanionId(e,s){return`${e}-${s}`}companionAlreadyExists(e,s,r){return this.cache.hasModel(e)?(nr.debug(`Companion ${s} already exists for ${r}`),!0):!1}createCompanionInstance(e,s,r,o){const n=this.createModel(e,s,{data:o,companionParent:r.modelData,kosParentId:r.modelId});return(n==null?void 0:n.model)||null}attachCompanionToParent(e,s){e[et]=s,s.addCompanionModel(e)}}function yl(t,e){return`${On}${t}${e?`/${e}`:`/${t}`}`}function bl(t){return`${On}${t}`}function Ko(t){const e=[];return new Promise((s,r)=>{for(const{condition:o,onMatch:n}of t){const i=E.when(o,()=>{e.forEach(a=>a());try{n==null||n(),s()}catch(a){r(a)}});e.push(i)}})}const vl=5e3,Yg=t=>t.fsm.transitionTo(L.GO_ACTIVE,w.ACTIVE),Wg=t=>t.whenReady(),Qg=t=>t.fsm.transitionTo(L.LOAD,w.LOADED),Xg=t=>t.fsm.transitionTo(L.UNLOAD,w.UNLOADED),Zg=t=>t.fsm.transitionTo(L.INITIALIZE,w.INITIALIZED);var Vn=(t=>(t.ACTIVE="active",t.READY="ready",t.LOAD="load",t.UNLOAD="unload",t.INIT="init",t))(Vn||{});const vr={active:Yg,ready:Wg,load:Qg,unload:Xg,init:Zg};class wl extends Error{constructor(s,r){super(s);l(this,"model");this.model=r}}const El=(t,e,s)=>{let r;return{promise:new Promise((i,a)=>{r=setTimeout(()=>{g.error(`Model ${e.modelId} - ${e.modelTypeName} - ${s} timed out after ${t}ms`),a(new wl(`${e.modelId} - ${e.modelTypeName} - ${s}`,e))},t)}),cancel:()=>{r&&clearTimeout(r)}}},Jg=t=>typeof t.toJSON=="function",$s=t=>t[F]!==void 0,Gn=t=>t.revision!==void 0&&t.index!==void 0,Ml=t=>{if(t){if($s(t))return t;if(Gn(t))return t.data;if(t instanceof Map||t instanceof E.ObservableMap||t instanceof Set)return Array.from(t.values()).filter($s);if(Array.isArray(t))return t.filter($s)}},_l=(t,e)=>{var f;const s=e.id||e.modelType,r=me({value:s,modelData:t.modelData,modelId:t.modelId}),o=e.resolutionPolicy||Ze.CREATE;g.debug(`Resolving dependent model ${e.modelType} with id ${r} (policy: ${o})`);const n=Object.keys((e==null?void 0:e.options)||{}).reduce((p,y)=>{const v=e.options[y];return p[y]=me({value:v,modelData:t.modelData,modelId:t.modelId}),p},{}),i=S.getInstance().modelManager,a=i.registry.models[e.modelType];if(!a){const p=`No model registered for type ${e.modelType}`;if(g.error(`Failed to resolve dependency for model ${t.modelId}:
4
4
  - Dependency Type: ${e.modelType}
5
5
  - Dependency ID: ${r}
6
6
  - Resolution Policy: ${o}
7
7
  - Parent Model: ${t.modelTypeName}
8
8
  - Parent Model ID: ${t.modelId}
9
- - Error: ${p}`),o===Xe.CONTINUE)return m.warn(`Model type not registered (policy: CONTINUE) - Model ${t.modelId} will continue without dependency ${e.modelType} [${r}]`),{dependentModel:null,dataModelId:r,success:!1};throw new Error(`Dependency resolution failed - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${p}`)}const c=i.getModelById(r);if(c){if(c.modelTypeName!==e.modelType){const p=`Model type mismatch: expected ${e.modelType}, found ${c.modelTypeName}`;if(m.error(`Failed to resolve dependency for model ${t.modelId}:
9
+ - Error: ${p}`),o===Ze.CONTINUE)return g.warn(`Model type not registered (policy: CONTINUE) - Model ${t.modelId} will continue without dependency ${e.modelType} [${r}]`),{dependentModel:null,dataModelId:r,success:!1};throw new Error(`Dependency resolution failed - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${p}`)}const c=i.getModelById(r);if(c){if(c.modelTypeName!==e.modelType){const p=`Model type mismatch: expected ${e.modelType}, found ${c.modelTypeName}`;if(g.error(`Failed to resolve dependency for model ${t.modelId}:
10
10
  - Dependency Type: ${e.modelType}
11
11
  - Dependency ID: ${r}
12
12
  - Resolution Policy: ${o}
13
13
  - Parent Model: ${t.modelTypeName}
14
14
  - Parent Model ID: ${t.modelId}
15
15
  - Found Model Type: ${c.modelTypeName}
16
- - Error: ${p}`),o===Xe.CONTINUE)return m.warn(`Model type mismatch (policy: CONTINUE) - Model ${t.modelId} will continue without dependency`),{dependentModel:null,dataModelId:r,success:!1};throw new Error(`Dependency resolution failed - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${p}`)}return m.debug(`Found existing dependent model ${e.modelType} with id ${r}`),{dependentModel:{model:c,data:c.modelData},dataModelId:r,success:!0}}if(m.debug(`Model ${e.modelType} [${r}] does not exist. Applying resolution policy: ${o}`),o===Xe.CONTINUE)return m.warn(`Model ${e.modelType} [${r}] not found (policy: CONTINUE) - Model ${t.modelId} will continue without this dependency`),{dependentModel:null,dataModelId:r,success:!1};const u=Object.keys(n).length>0,d=a.class||a.create;if(((f=d==null?void 0:d.prototype)==null?void 0:f[Vs])===!0&&!u){const p=`Model ${e.modelType} requires options but none were provided`;throw m.error(`Failed to resolve dependency for model ${t.modelId}:
16
+ - Error: ${p}`),o===Ze.CONTINUE)return g.warn(`Model type mismatch (policy: CONTINUE) - Model ${t.modelId} will continue without dependency`),{dependentModel:null,dataModelId:r,success:!1};throw new Error(`Dependency resolution failed - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${p}`)}return g.debug(`Found existing dependent model ${e.modelType} with id ${r}`),{dependentModel:{model:c,data:c.modelData},dataModelId:r,success:!0}}if(g.debug(`Model ${e.modelType} [${r}] does not exist. Applying resolution policy: ${o}`),o===Ze.CONTINUE)return g.warn(`Model ${e.modelType} [${r}] not found (policy: CONTINUE) - Model ${t.modelId} will continue without this dependency`),{dependentModel:null,dataModelId:r,success:!1};const u=Object.keys(n).length>0,d=a.class||a.create;if(((f=d==null?void 0:d.prototype)==null?void 0:f[Qs])===!0&&!u){const p=`Model ${e.modelType} requires options but none were provided`;throw g.error(`Failed to resolve dependency for model ${t.modelId}:
17
17
  - Dependency Type: ${e.modelType}
18
18
  - Dependency ID: ${r}
19
19
  - Resolution Policy: ${o}
@@ -21,93 +21,93 @@ Caused by: ${o.stack}`)}toDetailedString(){const s=[`KosModelError: ${this.messa
21
21
  - Parent Model ID: ${t.modelId}
22
22
  - Provided Options: ${JSON.stringify(n,null,2)}
23
23
  - Error: ${p}
24
- - Model requires options but dependency declaration provides none`),new Error(`Dependency resolution failed - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${p}. Use resolutionPolicy: DependencyResolutionPolicy.CONTINUE if this dependency is optional.`)}try{const p=I.getInstance().modelManager.createModelInstance(e.modelType,r,n);return m.debug(`Successfully created dependent model ${e.modelType} with id ${r}`),{dependentModel:p,dataModelId:r,success:!0}}catch(p){const g=p instanceof Error?p.message:String(p);throw m.error(`Failed to create dependency for model ${t.modelId}:
24
+ - Model requires options but dependency declaration provides none`),new Error(`Dependency resolution failed - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${p}. Use resolutionPolicy: DependencyResolutionPolicy.CONTINUE if this dependency is optional.`)}try{const p=S.getInstance().modelManager.createModelInstance(e.modelType,r,n);return g.debug(`Successfully created dependent model ${e.modelType} with id ${r}`),{dependentModel:p,dataModelId:r,success:!0}}catch(p){const y=p instanceof Error?p.message:String(p);throw g.error(`Failed to create dependency for model ${t.modelId}:
25
25
  - Dependency Type: ${e.modelType}
26
26
  - Dependency ID: ${r}
27
27
  - Resolution Policy: ${o}
28
28
  - Parent Model: ${t.modelTypeName}
29
29
  - Parent Model ID: ${t.modelId}
30
30
  - Provided Options: ${JSON.stringify(n,null,2)}
31
- - Error: ${g}`),o===Xe.FAIL?new Error(`Dependency resolution failed (policy: FAIL) - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${g}`):p}},cl=(t,e=D.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[x])||{};return Object.keys(s).length===0?(m.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],a=al(t,i);if(!a.success||!a.dependentModel)return m.debug(`Skipping dependency ${i.modelType} with id ${a.dataModelId} - resolution failed with CONTINUE policy`),t.modelData[n]=void 0,null;const{dependentModel:c,dataModelId:u}=a;t.modelData[n]=c.data,m.debug(`waiting for dependent model ${i.modelType} with id ${u} - waiting for WHENREADY`);const d=async(p,g,v)=>{var E;await((E=p.whenReady)==null?void 0:E.call(p)),m.debug(`dependent model ${g} with id ${v} - READY`)},{promise:h,cancel:f}=nl(rl,t,t.status);return Promise.race([d(c.model,i.modelType,u).then(()=>{f()}).catch(p=>{const g=Lt(p,{modelType:i.modelType,modelId:u,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:e,operation:"dependency whenReady()"});throw m.error(g.toDetailedString()),f(),g}),h])}).filter(n=>!!n)},ll=async(t,e,s,r)=>{if(m.debug(`Execute lifecycle with ${e.length} models`),e.length===0){m.debug(`${t.modelId} has no children. Returning`);return}if(!s){m.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return yr[s]&&a?c=yr[s](a):(a||m.error("model is undefined. This shouldn't happen"),yr[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),n=await Promise.allSettled(o.map(a=>{var d;if(!a.model||!a.status)return Promise.resolve();const{promise:c,cancel:u}=nl(rl,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{const f=Lt(h,{modelType:a.type||"unknown",modelId:a.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`});throw m.error(f.toDetailedString()),u(),f}),c])})),i=n.filter(a=>a.status==="rejected");if(i.length>0){const a=i.map(c=>{const u=o[n.indexOf(c)];return{error:c.status==="rejected"?c.reason:new Error("Unknown error"),context:{modelType:u.type||"unknown",modelId:u.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`}}});Eg(a,`Model ${t.modelId} had ${i.length} failed child model(s) on ${r}`)}},ul=async(t,e,s)=>{await ll(t,t.getChildren().filter(r=>!!r),e,s)},ds=async(t,e)=>{const r=(await Promise.allSettled(cl(t,e))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))};function Cg(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subscriptions:!!t.subscriptionManager}}}),Dg(t.modelData,t.modelTypeName,t.modelId,t)}function Dg(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[x]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.call(t))||{},subscriptions:(()=>{const d=t[X]||{},h=Object.keys(d);return h.length===0?{count:0,data:[]}:{count:h.length,data:h.map(f=>{const p=d[f];return{topic:f,websocket:!!p.websocket,...p.lifecycle&&{lifecycle:p.lifecycle},...p.fos&&{fos:!0},...p.bridge&&{bridge:!0},...p.destinationAddress&&{destinationAddress:p.destinationAddress},...p.wildcardName&&{wildcardName:p.wildcardName},...p.flow&&{flow:!0},...p.requiresBaseline&&{requiresBaseline:!0}}})}})()}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];Is(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:Un(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class Ag{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==w.FAILED).filter(r=>!!r);return s.forEach(r=>{try{W.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[_e])||{};return Object.keys(e).map(r=>il(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class xg{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class Rg{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[xe])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},u=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const Pg=m.createLogger({name:"model-active-machine"}),kg=t=>{const e=b.createMachine(w.INACTIVE,{[w.FAILED]:b.state(b.transition(F.GO_ACTIVE,w.ACTIVATING)),[w.INACTIVE]:b.state(b.transition(F.GO_ACTIVE,w.ACTIVATING)),[w.ACTIVATING]:b.invoke(()=>(t.activeStatus=w.ACTIVATING,t.activate()),b.transition("done",w.ACTIVE,b.action(()=>{t.activeStatus=w.ACTIVE})),b.transition("error",w.FAILED,b.action(()=>{t.activeStatus=w.FAILED}))),[w.ACTIVE]:b.state(b.transition(F.GO_INACTIVE,w.DEACTIVATING)),[w.DEACTIVATING]:b.invoke(()=>(t.activeStatus=w.DEACTIVATING,t.deactivate()),b.transition("done",w.INACTIVE,b.action(()=>{t.activeStatus=w.INACTIVE})),b.transition("error",w.FAILED,b.action(()=>{t.activeStatus=w.FAILED})))});return{service:b.interpret(e,r=>Pg.debug(r.machine.current)),machine:e}},ea=m.createLogger({name:"model-online-machine"}),Lg=t=>{const e=b.createMachine(w.OFFLINE,{[w.ONLINE]:b.state(b.transition(F.GO_OFFLINE,w.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=w.OFFLINE}))),[w.OFFLINE]:b.state(b.transition(F.GO_ONLINE,w.ONLINE,b.action(async()=>{ea.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=w.ONLINE,await t.fsm.transitionTo(F.INITIALIZE,w.INITIALIZED)})))}),s=b.interpret(e,r=>ea.debug(r.machine.current));return{machine:e,service:s}},Fg=t=>{var r;const e=kg(t).service,s=Lg(t).service;return b.createMachine(w.CREATING,{[w.CREATING]:b.state(b.transition(F.CREATE,w.CREATED)),[w.CREATED]:b.state(b.immediate(w.INITIALIZING)),[w.INITIALIZING]:b.invoke(()=>(te(()=>{t.status=w.INITIALIZING}),t.init()),b.transition("done",w.INITIALIZED,b.action(()=>{t.status=w.INITIALIZED})),b.transition("error",w.FAILED,b.action(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=w.FAILED}))),[w.INITIALIZED]:b.state(b.immediate(w.LOADING)),[w.LOADING]:b.invoke(()=>(te(()=>{t.status=w.LOADING}),t.load()),b.transition("done",w.LOADED,b.action(()=>{t.status=w.LOADED})),b.transition("error",w.FAILED,b.action(()=>{t.status=w.FAILED}))),[w.LOADED]:b.state(b.immediate(w.READYING),b.transition(F.UNLOAD,w.UNLOADING)),[w.RESETTING]:b.invoke(()=>{var o;return te(()=>{t.status=w.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",w.LOADED,b.action(()=>{t.status=w.LOADED}))),[w.READYING]:b.invoke(()=>(te(()=>{t.status=w.READYING}),t.ready()),b.transition("done",w.READY,b.action(()=>{te(()=>{t.status=w.READY}),s.send(F.GO_ONLINE)})),b.transition("error",w.FAILED,b.action(()=>{t.status=w.FAILED}))),[w.READY]:b.state(b.transition(F.UNLOAD,w.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(F.RESET,w.RESETTING),b.transition(F.GO_ONLINE,w.READY,b.action(()=>{s.send(F.GO_ONLINE)})),b.transition(F.GO_OFFLINE,w.READY,b.action(()=>{s.send(F.GO_OFFLINE)})),b.transition(F.GO_ACTIVE,w.READY,b.action(()=>{e.send(F.GO_ACTIVE)})),b.transition(F.GO_INACTIVE,w.READY,b.action(()=>{e.send(F.GO_INACTIVE)}))),[w.UNLOADED]:b.state(),[w.FAILED]:b.state()})},Ng=m.createLogger({name:"kos-model-lifecycle"}),Ug=t=>({service:b.interpret(Fg(t),s=>Ng.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class jg{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=Ug(e);this.service=r.service,this.service.send(F.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=w.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[w.ACTIVE,w.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const dl="browser-router-model";class jn{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!_r(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=Pe(dl))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return _r(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=Pc(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function Bg(t,e){if(!_r(t))return;const s=Pe(dl);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new jn(t,e).setRouter(s.model)}class Hg{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const o=this.queue.length,n=this.filterEventsByStrategy(e,s,r),i=o-n.length;this.log.warn(`Processing ${n.length}/${o} offline message(s) with strategy: ${e}`);for(const a of n)try{a.handler()}catch(c){this.log.error(`Error while processing offline message for topic ${a.topic}:`,c)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${n.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case pt.ALL:return[...this.queue];case pt.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=s);case pt.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=r);case pt.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(n=>n.receivedAt),o={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(o.afterRequest=this.queue.filter(n=>n.receivedAt>=e).length),s!==void 0&&(o.afterResponse=this.queue.filter(n=>n.receivedAt>=s).length),o}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class Kg{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(F.GO_ONLINE,w.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(F.GO_OFFLINE,w.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}function vt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function Qo(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function qg(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function zg(t){return await t.arrayBuffer()}function Vg(t,e){return new Blob([t],{type:e})}async function Gg(t){const e={},s=[],r=[];t.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:Qo(i)})}else e[o]=n.toString();return{fields:e,files:s}}function Yg(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function Wg(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:Qo(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await zg(t);return{data:Qo(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await Gg(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const hl=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${Zr}:${s}
31
+ - Error: ${y}`),o===Ze.FAIL?new Error(`Dependency resolution failed (policy: FAIL) - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${y}`):p}},Tl=(t,e=I.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[F])||{};return Object.keys(s).length===0?(g.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],a=_l(t,i);if(!a.success||!a.dependentModel)return g.debug(`Skipping dependency ${i.modelType} with id ${a.dataModelId} - resolution failed with CONTINUE policy`),t.modelData[n]=void 0,null;const{dependentModel:c,dataModelId:u}=a;t.modelData[n]=c.data,g.debug(`waiting for dependent model ${i.modelType} with id ${u} - waiting for WHENREADY`);const d=async(p,y,v)=>{var M;await((M=p.whenReady)==null?void 0:M.call(p)),g.debug(`dependent model ${y} with id ${v} - READY`)},{promise:h,cancel:f}=El(vl,t,t.status);return Promise.race([d(c.model,i.modelType,u).then(()=>{f()}).catch(p=>{const y=Pt(p,{modelType:i.modelType,modelId:u,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:e,operation:"dependency whenReady()"});throw g.error(y.toDetailedString()),f(),y}),h])}).filter(n=>!!n)},Sl=async(t,e,s,r)=>{if(g.debug(`Execute lifecycle with ${e.length} models`),e.length===0){g.debug(`${t.modelId} has no children. Returning`);return}if(!s){g.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return vr[s]&&a?c=vr[s](a):(a||g.error("model is undefined. This shouldn't happen"),vr[s]||g.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(g.error(`No model found ${a.modelId}`),!1):(g.error(`No promise found ${a.modelId}`),!1)),n=await Promise.allSettled(o.map(a=>{var d;if(!a.model||!a.status)return Promise.resolve();const{promise:c,cancel:u}=El(vl,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{const f=Pt(h,{modelType:a.type||"unknown",modelId:a.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`});throw g.error(f.toDetailedString()),u(),f}),c])})),i=n.filter(a=>a.status==="rejected");if(i.length>0){const a=i.map(c=>{const u=o[n.indexOf(c)];return{error:c.status==="rejected"?c.reason:new Error("Unknown error"),context:{modelType:u.type||"unknown",modelId:u.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`}}});Vg(a,`Model ${t.modelId} had ${i.length} failed child model(s) on ${r}`)}},Ol=async(t,e,s)=>{await Sl(t,t.getChildren().filter(r=>!!r),e,s)},ls=async(t,e)=>{const r=(await Promise.allSettled(Tl(t,e))).filter(o=>o.status==="rejected");r.length&&(g.error(`There were ${r.length} failed dependent models on ${e}`),g.error(r))};function em(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subscriptions:!!t.subscriptionManager}}}),tm(t.modelData,t.modelTypeName,t.modelId,t)}function tm(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[F]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.call(t))||{},subscriptions:(()=>{const d=t[Z]||{},h=Object.keys(d);return h.length===0?{count:0,data:[]}:{count:h.length,data:h.map(f=>{const p=d[f];return{topic:f,websocket:!!p.websocket,...p.lifecycle&&{lifecycle:p.lifecycle},...p.fos&&{fos:!0},...p.bridge&&{bridge:!0},...p.destinationAddress&&{destinationAddress:p.destinationAddress},...p.wildcardName&&{wildcardName:p.wildcardName},...p.flow&&{flow:!0},...p.requiresBaseline&&{requiresBaseline:!0}}})}})()}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];$s(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:Gn(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class sm{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==w.FAILED).filter(r=>!!r);return s.forEach(r=>{try{Q.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[Je])||{};return Object.keys(e).map(r=>Ml(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class rm{constructor(e){l(this,"companions",new E.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class om{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[Be])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),E.runInAction(()=>a())},u=n?E.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):E.autorun(c);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const nm=g.createLogger({name:"model-active-machine"}),im=t=>{const e=b.createMachine(w.INACTIVE,{[w.FAILED]:b.state(b.transition(L.GO_ACTIVE,w.ACTIVATING)),[w.INACTIVE]:b.state(b.transition(L.GO_ACTIVE,w.ACTIVATING)),[w.ACTIVATING]:b.invoke(()=>(t.activeStatus=w.ACTIVATING,t.activate()),b.transition("done",w.ACTIVE,b.action(()=>{t.activeStatus=w.ACTIVE})),b.transition("error",w.FAILED,b.action(()=>{t.activeStatus=w.FAILED}))),[w.ACTIVE]:b.state(b.transition(L.GO_INACTIVE,w.DEACTIVATING)),[w.DEACTIVATING]:b.invoke(()=>(t.activeStatus=w.DEACTIVATING,t.deactivate()),b.transition("done",w.INACTIVE,b.action(()=>{t.activeStatus=w.INACTIVE})),b.transition("error",w.FAILED,b.action(()=>{t.activeStatus=w.FAILED})))});return{service:b.interpret(e,r=>nm.debug(r.machine.current)),machine:e}},da=g.createLogger({name:"model-online-machine"}),am=t=>{const e=b.createMachine(w.OFFLINE,{[w.ONLINE]:b.state(b.transition(L.GO_OFFLINE,w.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=w.OFFLINE}))),[w.OFFLINE]:b.state(b.transition(L.GO_ONLINE,w.ONLINE,b.action(async()=>{da.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=w.ONLINE,await t.fsm.transitionTo(L.INITIALIZE,w.INITIALIZED)})))}),s=b.interpret(e,r=>da.debug(r.machine.current));return{machine:e,service:s}},cm=t=>{var r;const e=im(t).service,s=am(t).service;return b.createMachine(w.CREATING,{[w.CREATING]:b.state(b.transition(L.CREATE,w.CREATED)),[w.CREATED]:b.state(b.immediate(w.INITIALIZING)),[w.INITIALIZING]:b.invoke(()=>(te(()=>{t.status=w.INITIALIZING}),t.init()),b.transition("done",w.INITIALIZED,b.action(()=>{t.status=w.INITIALIZED})),b.transition("error",w.FAILED,b.action(()=>{g.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=w.FAILED}))),[w.INITIALIZED]:b.state(b.immediate(w.LOADING)),[w.LOADING]:b.invoke(()=>(te(()=>{t.status=w.LOADING}),t.load()),b.transition("done",w.LOADED,b.action(()=>{t.status=w.LOADED})),b.transition("error",w.FAILED,b.action(()=>{t.status=w.FAILED}))),[w.LOADED]:b.state(b.immediate(w.READYING),b.transition(L.UNLOAD,w.UNLOADING)),[w.RESETTING]:b.invoke(()=>{var o;return te(()=>{t.status=w.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",w.LOADED,b.action(()=>{t.status=w.LOADED}))),[w.READYING]:b.invoke(()=>(te(()=>{t.status=w.READYING}),t.ready()),b.transition("done",w.READY,b.action(()=>{te(()=>{t.status=w.READY}),s.send(L.GO_ONLINE)})),b.transition("error",w.FAILED,b.action(()=>{t.status=w.FAILED}))),[w.READY]:b.state(b.transition(L.UNLOAD,w.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(L.RESET,w.RESETTING),b.transition(L.GO_ONLINE,w.READY,b.action(()=>{s.send(L.GO_ONLINE)})),b.transition(L.GO_OFFLINE,w.READY,b.action(()=>{s.send(L.GO_OFFLINE)})),b.transition(L.GO_ACTIVE,w.READY,b.action(()=>{e.send(L.GO_ACTIVE)})),b.transition(L.GO_INACTIVE,w.READY,b.action(()=>{e.send(L.GO_INACTIVE)}))),[w.UNLOADED]:b.state(),[w.FAILED]:b.state()})},lm=g.createLogger({name:"kos-model-lifecycle"}),um=t=>({service:b.interpret(cm(t),s=>lm.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class dm{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=um(e);this.service=r.service,this.service.send(L.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=w.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=E.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[w.ACTIVE,w.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const $l="browser-router-model";class Yn{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!Or(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=ke($l))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return Or(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=Vc(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function hm(t,e){if(!Or(t))return;const s=ke($l);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new Yn(t,e).setRouter(s.model)}class fm{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const o=this.queue.length,n=this.filterEventsByStrategy(e,s,r),i=o-n.length;this.log.warn(`Processing ${n.length}/${o} offline message(s) with strategy: ${e}`);for(const a of n)try{a.handler()}catch(c){this.log.error(`Error while processing offline message for topic ${a.topic}:`,c)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${n.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case pt.ALL:return[...this.queue];case pt.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=s);case pt.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=r);case pt.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(n=>n.receivedAt),o={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(o.afterRequest=this.queue.filter(n=>n.receivedAt>=e).length),s!==void 0&&(o.afterResponse=this.queue.filter(n=>n.receivedAt>=s).length),o}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class pm{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(L.GO_ONLINE,w.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(L.GO_OFFLINE,w.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}function wt(){return"xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}function tn(t){const e=new Uint8Array(t);let s="";for(let r=0;r<e.byteLength;r++)s+=String.fromCharCode(e[r]);return btoa(s)}function gm(t){const e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s.buffer}async function mm(t){return await t.arrayBuffer()}function ym(t,e){return new Blob([t],{type:e})}async function bm(t){const e={},s=[],r=[];t.forEach((o,n)=>{r.push([n,o])});for(const[o,n]of r)if(n instanceof File){const i=await n.arrayBuffer();s.push({name:o,filename:n.name,type:n.type,data:tn(i)})}else e[o]=n.toString();return{fields:e,files:s}}function vm(t){return new ReadableStream({async start(){},async pull(e){await t(e)},cancel(){}})}async function wm(t){if(!t)return{data:"",contentType:"text/plain"};if(typeof t=="string")return{data:t,contentType:"text/plain"};if(t instanceof ArrayBuffer||t instanceof Uint8Array){let e;return t instanceof Uint8Array?(e=new ArrayBuffer(t.byteLength),new Uint8Array(e).set(t)):e=t,{data:tn(e),contentType:"application/octet-stream",encoding:"base64"}}if(t instanceof Blob){const e=await mm(t);return{data:tn(e),contentType:t.type||"application/octet-stream",encoding:"base64"}}if(t instanceof FormData){const e=await bm(t);return{data:JSON.stringify(e),contentType:"multipart/form-data",encoding:"json"}}throw new Error("Unsupported body type")}const Il=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${oo}:${s}
32
32
  `;return o+=`topic:${t}
33
- `,o+=`${Zt}:${t}
34
- `,o+=`${qs}:${e}
33
+ `,o+=`${Yt}:${t}
34
+ `,o+=`${Ys}:${e}
35
35
  `,r&&(o+=`${Ge}:${r}
36
- `),o+=`${ke}:kos.studio.request
36
+ `),o+=`${Le}:kos.studio.request
37
37
  `,o+=`
38
- `,o},fl=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n})=>{let i=`${Ga}:/http${t}
39
- `;return i+=`${Zr}:${s}
40
- `,i+=`${Zt}:${t}
41
- `,i+=`${Za}:${e}
38
+ `,o},Cl=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n})=>{let i=`${nc}:/http${t}
39
+ `;return i+=`${oo}:${s}
40
+ `,i+=`${Yt}:${t}
41
+ `,i+=`${lc}:${e}
42
42
  `,r&&(i+=`${Ge}:${r}
43
- `),o&&(i+=`${vn}:true
44
- `),n&&(i+=`${wn}:${n}
45
- `),i+=`${ke}:fos.http.request
43
+ `),o&&(i+=`${Tn}:true
44
+ `),n&&(i+=`${Sn}:${n}
45
+ `),i+=`${Le}:fos.http.request
46
46
  `,i+=`
47
- `,i},pl=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n,bridge:i,headers:a})=>{let c=`${Zr}:${s}
48
- `;return c+=`${Zt}:${t}
49
- `,c+=`${qs}:${e}
47
+ `,i},Dl=({path:t,requestId:e,method:s,destinationAddress:r,ordered:o,tracker:n,bridge:i,headers:a})=>{let c=`${oo}:${s}
48
+ `;return c+=`${Yt}:${t}
49
+ `,c+=`${Ys}:${e}
50
50
  `,r&&(c+=`${Ge}:${r}
51
- `),o&&(c+=`${vn}:true
52
- `),n&&(c+=`${wn}:${n}
51
+ `),o&&(c+=`${Tn}:true
52
+ `),n&&(c+=`${Sn}:${n}
53
53
  `),a&&Object.keys(a).forEach(u=>{c+=`${u}:${a[u]}
54
- `}),c+=`${ke}:${i?"fos":"kos"}.http.request
54
+ `}),c+=`${Le}:${i?"fos":"kos"}.http.request
55
55
  `,c+=`
56
- `,c},rt=(t,e)=>{let s=t;return e&&(s+=e),s};function gl(t){const e={...t};return{append(s,r){e[s]=r},delete(s){delete e[s]},get(s){return e[s]},forEach(s){Object.keys(e).forEach(r=>s(e[r],r,this))},has(s){return Object.hasOwn(e,s)},set(s,r){e[s]=r},keys(){return Object.keys(e)},values(){return Object.values(e)},entries(){return Object.entries(e)}}}function ml(t){let e=!1;return window.ReadableStream?new ReadableStream({start(r){function o(){return Promise.resolve({done:e,value:t}).then(({done:n,value:i})=>{if(n){r.close();return}r.enqueue(i),e=!0,o()})}o()}}):t}const yl=({path:t,requestId:e,destinationAddress:s})=>{let r=`topic:${t}
57
- `;return r+=`${Zt}:${t}
58
- `,r+=`${qs}:${e}
56
+ `,c},ot=(t,e)=>{let s=t;return e&&(s+=e),s};function Al(t){const e={...t};return{append(s,r){e[s]=r},delete(s){delete e[s]},get(s){return e[s]},forEach(s){Object.keys(e).forEach(r=>s(e[r],r,this))},has(s){return Object.hasOwn(e,s)},set(s,r){e[s]=r},keys(){return Object.keys(e)},values(){return Object.values(e)},entries(){return Object.entries(e)}}}function xl(t){let e=!1;return window.ReadableStream?new ReadableStream({start(r){function o(){return Promise.resolve({done:e,value:t}).then(({done:n,value:i})=>{if(n){r.close();return}r.enqueue(i),e=!0,o()})}o()}}):t}const Rl=({path:t,requestId:e,destinationAddress:s})=>{let r=`topic:${t}
57
+ `;return r+=`${Yt}:${t}
58
+ `,r+=`${Ys}:${e}
59
59
  `,r+=`${Ge}:${s}
60
- `,r+=`${ke}:kos.studio.request
60
+ `,r+=`${Le}:kos.studio.request
61
61
  `,r+=`
62
- `,r},bl=({requestId:t,destinationAddress:e,requestType:s,headers:r})=>{let o=`${qs}:${t}
62
+ `,r},Pl=({requestId:t,destinationAddress:e,requestType:s,headers:r})=>{let o=`${Ys}:${t}
63
63
  `;return o+=`${Ge}:${e}
64
- `,o+=`${ke}:${s}
64
+ `,o+=`${Le}:${s}
65
65
  `,r&&Object.keys(r).forEach(n=>{o+=`${n}:${r[n]}
66
66
  `}),o+=`
67
- `,o},Qg=(t,e)=>{const s=t,r=rt(bl(e),typeof s=="string"?s:JSON.stringify(s)),o=I.getInstance().transport.socket;o?(m.debug("Sending message",r),o.socket.send(r)):m.error("socket transport is not initialized")},vl=({path:t,responseId:e,status:s,destinationAddress:r})=>{let o=`topic:${t}
68
- `;return o+=`${Zt}:${t}
69
- `,e&&(o+=`${Xr}:${e}
70
- `),o+=`${bn}:${s}
67
+ `,o},Em=(t,e)=>{const s=t,r=ot(Pl(e),typeof s=="string"?s:JSON.stringify(s)),o=S.getInstance().transport.socket;o?(g.debug("Sending message",r),o.socket.send(r)):g.error("socket transport is not initialized")},kl=({path:t,responseId:e,status:s,destinationAddress:r})=>{let o=`topic:${t}
68
+ `;return o+=`${Yt}:${t}
69
+ `,e&&(o+=`${no}:${e}
70
+ `),o+=`${_n}:${s}
71
71
  `,o+=`${Ge}:${r}
72
- `,o+=`${ke}:kos.studio.response
72
+ `,o+=`${Le}:kos.studio.response
73
73
  `,o+=`
74
- `,o},Zg=(t,e)=>{const s=t,r=rt(yl(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},Xg=(t,e)=>{const s=e.responseId?{status:e.status,data:t}:t,r=rt(vl(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},wl=({topic:t})=>{let e=`topic:${t}
75
- `;return e+=`${ke}:kos.broker.send
74
+ `,o},Mm=(t,e)=>{const s=t,r=ot(Rl(e),JSON.stringify(s)),o=S.getInstance().transport.socket;o?o.socket.send(r):g.error("socket transport is not initialized")},_m=(t,e)=>{const s=e.responseId?{status:e.status,data:t}:t,r=ot(kl(e),JSON.stringify(s)),o=S.getInstance().transport.socket;o?o.socket.send(r):g.error("socket transport is not initialized")},Ll=({topic:t})=>{let e=`topic:${t}
75
+ `;return e+=`${Le}:kos.broker.send
76
76
  `,e+=`
77
- `,e},El=({responseId:t,destinationAddress:e,type:s,sourceAddress:r,status:o})=>{let n=`${Xr}:${t}
77
+ `,e},Fl=({responseId:t,destinationAddress:e,type:s,sourceAddress:r,status:o})=>{let n=`${no}:${t}
78
78
  `;return n+=`${Ge}:${e}
79
- `,n+=`${Ya}:${r}
80
- `,n+=`${ke}:${s??"kos.message.request"}
81
- `,n+=`${bn}:${o}
82
- `,n+=`${Wa}:application/json
83
- `,n+=`${Qa}:no-cache
79
+ `,n+=`${ic}:${r}
80
+ `,n+=`${Le}:${s??"kos.message.request"}
81
+ `,n+=`${_n}:${o}
82
+ `,n+=`${ac}:application/json
83
+ `,n+=`${cc}:no-cache
84
84
  `,n+=`
85
- `,n},Ml=({topic:t,responseId:e,destinationAddress:s,type:r})=>{let o=`topic:${t}
86
- `;return e&&(o+=`${Xr}:${e}
85
+ `,n},Nl=({topic:t,responseId:e,destinationAddress:s,type:r})=>{let o=`topic:${t}
86
+ `;return e&&(o+=`${no}:${e}
87
87
  `),o+=`${Ge}:${s}
88
- `,o+=`${ke}:${r??"kos.message.request"}
88
+ `,o+=`${Le}:${r??"kos.message.request"}
89
89
  `,o+=`
90
- `,o},Jg=({msg:t,options:e})=>{const s=t,r=rt(wl(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},Tl=({msg:t,options:e})=>{const s=t,r=rt(Ml(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},_l=({msg:t,options:e})=>{const s=t,r=rt(El(e),JSON.stringify(s)),o=I.getInstance().transport.socket;o?o.socket.send(r):m.error("socket transport is not initialized")},Zo=(t,e)=>{try{return e?t.body??t:JSON.parse(t.body)}catch{return t.body||t}},nt=m.createLogger({name:"kos-fetch"}),em=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,tm=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),sm=t=>{if("timeout"in AbortSignal)return AbortSignal.timeout(t);const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException(`Request timed out after ${t}ms`,"TimeoutError"))},t),e.signal},rm=t=>{if("any"in AbortSignal)return AbortSignal.any(t);const e=new AbortController;for(const s of t){if(s.aborted)return e.abort(s.reason),e.signal;s.addEventListener("abort",()=>e.abort(s.reason),{once:!0})}return e.signal},om=t=>t!=null&&t.studio?hl:t!=null&&t.fos?fl:pl,nm=async(t,e)=>{const s=I.getInstance().transport;await s.whenReady();const r=vt(),o=new URL(t),n=`${o.pathname}${o.search}`;nt.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||em,a=om(e),c=sm(i),u=e!=null&&e.signal?rm([e.signal,c]):c,d=await Wg(e==null?void 0:e.body),h={};d.contentType&&(h["content-type"]=d.contentType),d.encoding&&(h["content-encoding"]=d.encoding);const f=rt(a({path:n,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...h}}),d.data);return new Promise((p,g)=>{let v=null;if(u.aborted){const S=u.reason;(S==null?void 0:S.name)==="TimeoutError"?nt.error(`Timeout occurred - url: ${t}`):nt.debug(`Request aborted - url: ${t}`),g(S||new DOMException("Aborted","AbortError"));return}const E=()=>{v&&v();const S=u.reason;(S==null?void 0:S.name)==="TimeoutError"?nt.error(`Timeout occurred - url: ${t}`):nt.debug(`Request aborted - url: ${t}`),g(S||new DOMException("Aborted","AbortError"))};u.addEventListener("abort",E,{once:!0});const _=C(r,S=>{u.removeEventListener("abort",E);const O=(S==null?void 0:S.headers)||{},N=O["content-type"]||"text/plain",ee=O["content-encoding"],we=(S==null?void 0:S.body)||"";let H=we;if(ee==="base64"&&we)try{H=qg(we)}catch(se){nt.error("Failed to decode base64 response",se)}const ls={headers:gl(O),status:O.status&&parseInt(O.status)||200,ok:O.status==="200",json:async()=>{try{if(typeof H=="string")return H.length?JSON.parse(H):null;{const De=new TextDecoder().decode(H);return De.length?JSON.parse(De):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof H=="string"?H:new TextDecoder().decode(H),arrayBuffer:async()=>H instanceof ArrayBuffer?H:new TextEncoder().encode(H).buffer,blob:async()=>H instanceof ArrayBuffer?Vg(H,N):new Blob([H],{type:N}),formData:async()=>{const se=new FormData;if(N==="multipart/form-data"&&typeof H=="string")try{const De=JSON.parse(H);De.fields&&Object.entries(De.fields).forEach(([Vi,Gi])=>{se.append(Vi,Gi)}),De.files&&nt.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return se},body:e!=null&&e.stream?Yg(async se=>{if(H instanceof ArrayBuffer)se.enqueue(new Uint8Array(H));else{const De=new TextEncoder;se.enqueue(De.encode(H))}se.close()}):ml(typeof H=="string"?H:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};_.unsubscribe(),tm().then(()=>p(ls))});v=_.unsubscribe;const k=e!=null&&e.fos?s.fosSocket:s.socket;if(!k)throw Error(`No web socket transport available: ${e}`);k==null||k.send(f)})};exports.BASE_URL="kos:";exports.kosFetch=nm;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const Sl=()=>({isMock:!1,URL:exports.BASE_URL}),rr=m.createLogger({name:"kos-service-request"}),ta="errUnknown";async function or(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((u,d)=>String(u).replace(`{${d}}`,r==null?void 0:r.path[d]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(u=>`${encodeURIComponent(u)}=${encodeURIComponent(r.query[u])}`).join("&"):"",a=`${Sl().URL}${n}${i?`?${i}`:""}`;rr.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));try{const u=await exports.kosFetch(a,c);return u.status<200||u.status>=400?[`${u.statusText||ta}`,null]:[null,(await u.json()).data]}catch(u){if(u instanceof DOMException){if(u.name==="TimeoutError")return rr.error(`Request timed out: ${a}`),["Request timed out",null];if(u.name==="AbortError")return rr.debug(`Request aborted: ${a}`),["Request aborted",null]}return rr.error(`Unexpected error during fetch: ${u}`),[u instanceof Error?u.message:ta,null]}}function Ye(){return{get:(t,e,s)=>or(t,"get",s,e),post:(t,e,s,r)=>or(t,"post",r,e,s),put:(t,e,s,r)=>or(t,"put",r,e,s),delete:(t,e,s,r)=>or(t,"delete",r,e,s)}}const Ne=Ye(),Ol=Object.freeze(Object.defineProperty({__proto__:null,default:Ne},Symbol.toStringTag,{value:"Module"})),ct=m.createLogger({name:"kos-service-request-manager",group:"Model"});function im(t,e){return!t.condition||t.condition(e)}function am(t,e){return fe({value:t.path,modelId:e.id,modelData:e})}function cm(t,e){if(t.pathParams)return fe({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function lm(t,e){if(t.queryParams)return fe({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function um(t,e){if(t.body)return fe({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function dm(t,e){if(t.requestOptions)return typeof t.requestOptions=="function"?t.requestOptions(e):t.requestOptions}function hm(t){return(t||"get").toLowerCase()}function nr(t,e){return`${e.toUpperCase()}:${t}`}function Il(t){return t==null}function fm(t,e,s,r){r&&Il(t)&&ct.warn(`Required field '${e}' is missing in response for ${s}`)}function pm(t,e){return Il(t)&&e!==void 0?e:t}class gm{constructor(e,s){l(this,"model");l(this,"responseStore");l(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[He]||{};Object.values(s).forEach(r=>{const o=r.lifecycle;this.handlers.has(o)||this.handlers.set(o,[]),this.handlers.get(o).push(r)}),Object.keys(s).length>0&&ct.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(ct.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return im(e,this.model)?!0:(ct.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),[o,n]=await this.performRequest(s),i=this.captureResponseTiming();return{requestContext:s,error:o,response:n,requestedAt:r.requestedAt,receivedAt:i.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=am(e,this.model),r=cm(e,this.model),o=lm(e,this.model),n=um(e,this.model),i=dm(e,this.model),a=hm(e.method);return{resolvedPath:s,method:a,pathParams:r,queryParams:o,body:n,requestOptions:i}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body,e.requestOptions)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,o,n){const i=s.cache||{retention:Z.SINGLE},a=nr(r,s.method||"get");this.responseStore.set(a,e,i,o,n),await s.originalHandler.call(this.model,null,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,o,n){const i=Ne;switch(s){case"get":return await i.get(e,r,n);case"post":return await i.post(e,r,o,n);case"put":return await i.put(e,r,o,n);case"delete":return await i.delete(e,r,o,n);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(o=>{const n=this.getNestedValue(e,o.from),i=o.transform?this.applyTransform(n,o.transform):n;fm(i,o.from,s.path,o.required||!1);const a=pm(i,o.default);r[o.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,o)=>r==null?void 0:r[o],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return ct.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(o=>{const n=s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o,i=s.idExtractor?s.idExtractor(n):n.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(n):a.instance(i).options(n).build()}):r.map(o=>s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o):(ct.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s){const r=s.errorHandler||{strategy:"throw"};switch(r.onError&&r.onError(e,this.model),r.strategy){case"throw":throw e;case"log":if(ct.error(`Service request failed for ${s.path}:`,e.message),r.defaultValue!==void 0){const o=nr(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:Z.SINGLE}),await s.originalHandler.call(this.model,e.message,r.defaultValue)}break;case"ignore":if(r.defaultValue!==void 0){const o=nr(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:Z.SINGLE}),await s.originalHandler.call(this.model,e.message,r.defaultValue)}break;case"default":if(r.defaultValue!==void 0){const o=nr(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:Z.SINGLE}),await s.originalHandler.call(this.model,e.message,r.defaultValue)}break}}}class mm{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function sa(t){return new mm(t)}class ym{constructor(e){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=e,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(e){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of e)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(e,s)}async*processSingleEvent(e){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(e))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(e),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([e]):[e],this.updateProcessingStats([e])}}async*processBatchedEvents(e,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const u=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(u.length===0)return;this.config.backpressure&&await this.waitForCapacity();const d=this.config.transform?this.config.transform(u):u;return this.stats.batchesProcessed++,this.updateProcessingStats(u),d};try{for await(const u of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(u);this.eventQueue.length>0;){const d=this.dequeueEvent();d&&n.push(d);const f=Date.now()-i;if(n.length>=r||f>=o){const p=await a();p!==void 0&&(yield p);break}}else{n.push(u);const h=Date.now()-i;if(n.length>=r||h>=o){const f=await a();f!==void 0&&(yield f)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(e){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(e,s);return this.config.filter.historySize&&(this.filterHistory.push(e),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const e=Date.now(),s=Math.floor(e/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const e=Date.now(),o=(Math.floor(e/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-e;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=e;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-e;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(e){if(this.eventQueue.push(e),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const e=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,e}updateProcessingStats(e){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+e.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?e.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(e){return this.activePromises.add(e),e.finally(()=>this.activePromises.delete(e)),e}getStats(){return{...this.stats}}}class bm extends WebSocket{constructor(e){super(e)}}var Te=(t=>(t.CONNECTED="websocket.connected",t.DISCONNECTED="websocket.disconnected",t.ERROR="websocket.error",t.MAX_RETRIES_EXCEEDED="websocket.max_retries_exceeded",t.RELOAD="websocket.reload",t))(Te||{});function ra(t){const e=`
90
+ `,o},Tm=({msg:t,options:e})=>{const s=t,r=ot(Ll(e),JSON.stringify(s)),o=S.getInstance().transport.socket;o?o.socket.send(r):g.error("socket transport is not initialized")},Ul=({msg:t,options:e})=>{const s=t,r=ot(Nl(e),JSON.stringify(s)),o=S.getInstance().transport.socket;o?o.socket.send(r):g.error("socket transport is not initialized")},jl=({msg:t,options:e})=>{const s=t,r=ot(Fl(e),JSON.stringify(s)),o=S.getInstance().transport.socket;o?o.socket.send(r):g.error("socket transport is not initialized")},sn=(t,e)=>{try{return e?t.body??t:JSON.parse(t.body)}catch{return t.body||t}},it=g.createLogger({name:"kos-fetch"}),Sm=process.env.KOS_WS_TIMEOUT?parseInt(process.env.KOS_WS_TIMEOUT):3e4,Om=()=>new Promise(t=>{setTimeout(()=>{t(!0)},0)}),$m=t=>{if("timeout"in AbortSignal)return AbortSignal.timeout(t);const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException(`Request timed out after ${t}ms`,"TimeoutError"))},t),e.signal},Im=t=>{if("any"in AbortSignal)return AbortSignal.any(t);const e=new AbortController;for(const s of t){if(s.aborted)return e.abort(s.reason),e.signal;s.addEventListener("abort",()=>e.abort(s.reason),{once:!0})}return e.signal},Cm=t=>t!=null&&t.studio?Il:t!=null&&t.fos?Cl:Dl,Dm=async(t,e)=>{const s=S.getInstance().transport;await s.whenReady();const r=wt(),o=new URL(t),n=`${o.pathname}${o.search}`;it.debug(`path: ${n}`);const i=(e==null?void 0:e.timeout)||Sm,a=Cm(e),c=$m(i),u=e!=null&&e.signal?Im([e.signal,c]):c,d=await wm(e==null?void 0:e.body),h={};d.contentType&&(h["content-type"]=d.contentType),d.encoding&&(h["content-encoding"]=d.encoding);const f=ot(a({path:n,requestId:r,method:(e==null?void 0:e.method)||"GET",destinationAddress:(e==null?void 0:e.destinationAddress)||"",ordered:e==null?void 0:e.ordered,tracker:e==null?void 0:e.tracker,bridge:e==null?void 0:e.bridge,headers:{...e==null?void 0:e.headers,...h}}),d.data);return new Promise((p,y)=>{let v=null;if(u.aborted){const A=u.reason;(A==null?void 0:A.name)==="TimeoutError"?it.error(`Timeout occurred - url: ${t}`):it.debug(`Request aborted - url: ${t}`),y(A||new DOMException("Aborted","AbortError"));return}const M=()=>{v&&v();const A=u.reason;(A==null?void 0:A.name)==="TimeoutError"?it.error(`Timeout occurred - url: ${t}`):it.debug(`Request aborted - url: ${t}`),y(A||new DOMException("Aborted","AbortError"))};u.addEventListener("abort",M,{once:!0});const O=C(r,A=>{u.removeEventListener("abort",M);const $=(A==null?void 0:A.headers)||{},P=$["content-type"]||"text/plain",V=$["content-encoding"],ee=(A==null?void 0:A.body)||"";let K=ee;if(V==="base64"&&ee)try{K=gm(ee)}catch(re){it.error("Failed to decode base64 response",re)}const as={headers:Al($),status:$.status&&parseInt($.status)||200,ok:$.status==="200",json:async()=>{try{if(typeof K=="string")return K.length?JSON.parse(K):null;{const Ae=new TextDecoder().decode(K);return Ae.length?JSON.parse(Ae):null}}catch{throw Error("Not a JSON response")}},text:async()=>typeof K=="string"?K:new TextDecoder().decode(K),arrayBuffer:async()=>K instanceof ArrayBuffer?K:new TextEncoder().encode(K).buffer,blob:async()=>K instanceof ArrayBuffer?ym(K,P):new Blob([K],{type:P}),formData:async()=>{const re=new FormData;if(P==="multipart/form-data"&&typeof K=="string")try{const Ae=JSON.parse(K);Ae.fields&&Object.entries(Ae.fields).forEach(([sa,ra])=>{re.append(sa,ra)}),Ae.files&&it.warn("File reconstruction in FormData not fully implemented")}catch{throw new Error("Failed to parse FormData")}return re},body:e!=null&&e.stream?vm(async re=>{if(K instanceof ArrayBuffer)re.enqueue(new Uint8Array(K));else{const Ae=new TextEncoder;re.enqueue(Ae.encode(K))}re.close()}):xl(typeof K=="string"?K:""),redirected:!1,statusText:"",type:"basic",url:"",clone:function(){return{...this}},bodyUsed:!1};O.unsubscribe(),Om().then(()=>p(as))});v=O.unsubscribe;const U=e!=null&&e.fos?s.fosSocket:s.socket;if(!U)throw Error(`No web socket transport available: ${e}`);U==null||U.send(f)})};exports.BASE_URL="kos:";exports.kosFetch=Dm;if(process.env.KOS_MOCK_FETCH==="true"){const t=process.env.KOS_PORT||"9999";exports.kosFetch=fetch,exports.BASE_URL=`http://localhost:${t}`}const Bl=()=>({isMock:!1,URL:exports.BASE_URL}),xe=g.createLogger({name:"kos-service-request"}),Cr="errUnknown",Am=new Set(["POST","PUT","DELETE","PATCH"]),ha={maxAttempts:3,baseDelayMs:350,backoffFactor:2,retryMutations:!1};function xm(t){if(t)return t===!0?{...ha}:{...ha,...t}}async function ir(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((h,f)=>String(h).replace(`{${f}}`,r==null?void 0:r.path[f]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${encodeURIComponent(h)}=${encodeURIComponent(r.query[h])}`).join("&"):"",a=`${Bl().URL}${n}${i?`?${i}`:""}`;xe.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const u=xm(s==null?void 0:s.retry);return u&&(u.retryMutations||!Am.has(c.method))?Pm(a,c,u):Rm(a,c)}async function Rm(t,e){try{const s=await exports.kosFetch(t,e);if(s.status<200||s.status>=400){const o=await Kl(s);return[`${s.statusText||Cr}`,null,o]}const r=await s.json();return[null,r.data??r]}catch(s){if(s instanceof DOMException){if(s.name==="TimeoutError")return xe.error(`Request timed out: ${t}`),["Request timed out",null];if(s.name==="AbortError")return xe.debug(`Request aborted: ${t}`),["Request aborted",null]}return xe.error(`Unexpected error during fetch: ${s}`),[s instanceof Error?s.message:Cr,null]}}async function Pm(t,e,s){let r;for(let o=1;o<=s.maxAttempts;o++)try{const n=await exports.kosFetch(t,e);if(n.status>=200&&n.status<400){const a=await n.json();return[null,a.data??a]}const i=await Kl(n);if(r=[`${n.statusText||Cr}`,null,i],s.retryOn&&!s.retryOn(n))return xe.debug(`Retry predicate returned false for ${t} (status ${n.status}), stopping`),r;if(o<s.maxAttempts){const a=s.baseDelayMs*Math.pow(s.backoffFactor,o-1);xe.warn(`Request to ${t} failed (status ${n.status}), retrying in ${a}ms (attempt ${o}/${s.maxAttempts})`),await new Promise(c=>setTimeout(c,a))}}catch(n){if(n instanceof DOMException){if(n.name==="TimeoutError")return xe.error(`Request timed out: ${t}`),["Request timed out",null];if(n.name==="AbortError")return xe.debug(`Request aborted: ${t}`),["Request aborted",null]}return xe.error(`Unexpected error during fetch: ${n}`),[n instanceof Error?n.message:Cr,null]}return xe.error(`All ${s.maxAttempts} attempts failed for ${t}`),r}async function Kl(t){let e;try{const r=await t.text();try{e=JSON.parse(r)}catch{e=r}}catch{e=void 0}const s={};return t.headers.forEach((r,o)=>{s[o]=r}),{status:t.status,statusText:t.statusText,responseBody:e,responseHeaders:s}}function De(){return{get:(t,e,s)=>ir(t,"get",s,e),post:(t,e,s,r)=>ir(t,"post",r,e,s),put:(t,e,s,r)=>ir(t,"put",r,e,s),delete:(t,e,s,r)=>ir(t,"delete",r,e,s)}}const Ne=De(),Wn=Object.freeze(Object.defineProperty({__proto__:null,default:Ne},Symbol.toStringTag,{value:"Module"})),lt=g.createLogger({name:"kos-service-request-manager",group:"Model"});function km(t,e){return!t.condition||t.condition(e)}function Lm(t,e){return me({value:t.path,modelId:e.id,modelData:e})}function Fm(t,e){if(t.pathParams)return me({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function Nm(t,e){if(t.queryParams)return me({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function Um(t,e){if(t.body)return me({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function jm(t,e){if(t.requestOptions)return typeof t.requestOptions=="function"?t.requestOptions(e):t.requestOptions}function Bm(t){return(t||"get").toLowerCase()}function ar(t,e){return`${e.toUpperCase()}:${t}`}function Hl(t){return t==null}function Km(t,e,s,r){r&&Hl(t)&&lt.warn(`Required field '${e}' is missing in response for ${s}`)}function Hm(t,e){return Hl(t)&&e!==void 0?e:t}class qm{constructor(e,s){l(this,"model");l(this,"responseStore");l(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[gt]||{};Object.values(s).forEach(r=>{const o=r.lifecycle;this.handlers.has(o)||this.handlers.set(o,[]),this.handlers.get(o).push(r)}),Object.keys(s).length>0&&lt.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(lt.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return km(e,this.model)?!0:(lt.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),o=await this.performRequest(s),[n,i]=o,a=o[2],c=this.captureResponseTiming();return{requestContext:s,error:n,response:i,errorContext:a,requestedAt:r.requestedAt,receivedAt:c.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s,e.errorContext);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=Lm(e,this.model),r=Fm(e,this.model),o=Nm(e,this.model),n=Um(e,this.model),i=jm(e,this.model),a=Bm(e.method);return{resolvedPath:s,method:a,pathParams:r,queryParams:o,body:n,requestOptions:i}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body,e.requestOptions)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,o,n){const i=s.cache||{retention:ie.SINGLE},a=ar(r,s.method||"get");this.responseStore.set(a,e,i,o,n),await s.originalHandler.call(this.model,null,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,o,n){const i=Ne;switch(s){case"get":return await i.get(e,r,n);case"post":return await i.post(e,r,o,n);case"put":return await i.put(e,r,o,n);case"delete":return await i.delete(e,r,o,n);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(o=>{const n=this.getNestedValue(e,o.from),i=o.transform?this.applyTransform(n,o.transform):n;Km(i,o.from,s.path,o.required||!1);const a=Hm(i,o.default);r[o.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,o)=>r==null?void 0:r[o],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return lt.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(o=>{const n=s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o,i=s.idExtractor?s.idExtractor(n):n.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(n):a.instance(i).options(n).build()}):r.map(o=>s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o):(lt.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s,r){const o=s.errorHandler||{strategy:"throw"},n=r?new $r(e.message,r):e;switch(o.onError&&o.onError(n,this.model),o.strategy){case"throw":throw e;case"log":if(lt.error(`Service request failed for ${s.path}:`,e.message),o.defaultValue!==void 0){const i=ar(s.path,s.method||"get");this.responseStore.set(i,o.defaultValue,s.cache||{retention:ie.SINGLE}),await s.originalHandler.call(this.model,e.message,o.defaultValue)}break;case"ignore":if(o.defaultValue!==void 0){const i=ar(s.path,s.method||"get");this.responseStore.set(i,o.defaultValue,s.cache||{retention:ie.SINGLE}),await s.originalHandler.call(this.model,e.message,o.defaultValue)}break;case"default":if(o.defaultValue!==void 0){const i=ar(s.path,s.method||"get");this.responseStore.set(i,o.defaultValue,s.cache||{retention:ie.SINGLE}),await s.originalHandler.call(this.model,e.message,o.defaultValue)}break}}}class zm{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function fa(t){return new zm(t)}class Vm{constructor(e){l(this,"config");l(this,"stats");l(this,"filterHistory",[]);l(this,"activePromises",new Set);l(this,"eventQueue",[]);l(this,"rateLimitWindow",new Map);this.config=e,this.stats={eventsReceived:0,batchesProcessed:0,eventsDropped:0,currentQueueSize:0,averageBatchSize:0,processingRate:0,lastProcessedAt:Date.now()}}async*processEvents(e){const s=this.config.batch||{size:1,window:0};if(s.size===1&&!s.window)for await(const r of e)yield*this.processSingleEvent(r);else yield*this.processBatchedEvents(e,s)}async*processSingleEvent(e){if(this.stats.eventsReceived++,!(this.config.filter&&!this.shouldProcessEvent(e))){if(this.config.rateLimit&&!this.checkRateLimit())if(this.config.rateLimit.onExceeded==="drop"){this.stats.eventsDropped++;return}else this.config.rateLimit.onExceeded==="delay"&&await this.waitForRateLimit();if(this.config.backpressure){this.enqueueEvent(e),await this.waitForCapacity();const s=this.dequeueEvent();s&&(yield this.config.transform?this.config.transform([s]):[s],this.updateProcessingStats([s]))}else yield this.config.transform?this.config.transform([e]):[e],this.updateProcessingStats([e])}}async*processBatchedEvents(e,s){const r=s.size||100,o=s.window||1e3;let n=[],i=Date.now();const a=async()=>{if(n.length===0)return;const c=[...n];n=[],i=Date.now();const u=this.config.filter?c.filter(h=>this.shouldProcessEvent(h)):c;if(u.length===0)return;this.config.backpressure&&await this.waitForCapacity();const d=this.config.transform?this.config.transform(u):u;return this.stats.batchesProcessed++,this.updateProcessingStats(u),d};try{for await(const u of e)if(this.stats.eventsReceived++,this.config.backpressure)for(this.enqueueEvent(u);this.eventQueue.length>0;){const d=this.dequeueEvent();d&&n.push(d);const f=Date.now()-i;if(n.length>=r||f>=o){const p=await a();p!==void 0&&(yield p);break}}else{n.push(u);const h=Date.now()-i;if(n.length>=r||h>=o){const f=await a();f!==void 0&&(yield f)}}const c=await a();c!==void 0&&(yield c)}finally{}}shouldProcessEvent(e){if(!this.config.filter)return!0;const s={history:[...this.filterHistory],currentBatch:[],startTime:Date.now()},r=this.config.filter.predicate(e,s);return this.config.filter.historySize&&(this.filterHistory.push(e),this.filterHistory.length>this.config.filter.historySize&&this.filterHistory.shift()),r}checkRateLimit(){if(!this.config.rateLimit)return!0;const e=Date.now(),s=Math.floor(e/this.config.rateLimit.windowMs),r=this.rateLimitWindow.get(s)||0;if(r>=this.config.rateLimit.maxEvents)return!1;this.rateLimitWindow.set(s,r+1);for(const[o]of this.rateLimitWindow)o<s-1&&this.rateLimitWindow.delete(o);return!0}async waitForRateLimit(){if(!this.config.rateLimit)return;const e=Date.now(),o=(Math.floor(e/this.config.rateLimit.windowMs)+1)*this.config.rateLimit.windowMs-e;o>0&&await new Promise(n=>setTimeout(n,o))}async waitForCapacity(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxConcurrent||5,s=this.config.backpressure.maxQueue||1e3;for(;this.activePromises.size>=e;)await Promise.race(this.activePromises);this.eventQueue.length>=s&&this.handleQueueOverflow()}handleQueueOverflow(){if(!this.config.backpressure)return;const e=this.config.backpressure.maxQueue||1e3,s=this.config.backpressure.dropPolicy||"oldest",r=this.config.backpressure.onQueueFull;if(s==="none")return;const o=this.eventQueue.length-e;if(o<=0)return;let n=[];if(s==="oldest"?n=this.eventQueue.splice(0,o):s==="newest"&&(n=this.eventQueue.splice(-o)),this.stats.eventsDropped+=n.length,this.stats.currentQueueSize=this.eventQueue.length,r&&n.length>0)try{r(n)}catch(i){console.warn("Error in onQueueFull callback:",i)}}enqueueEvent(e){if(this.eventQueue.push(e),this.stats.currentQueueSize=this.eventQueue.length,this.config.backpressure){const s=this.config.backpressure.maxQueue||1e3;this.eventQueue.length>s&&this.handleQueueOverflow()}}dequeueEvent(){const e=this.eventQueue.shift();return this.stats.currentQueueSize=this.eventQueue.length,e}updateProcessingStats(e){const s=Date.now(),r=s-this.stats.lastProcessedAt;this.stats.averageBatchSize=(this.stats.averageBatchSize*this.stats.batchesProcessed+e.length)/(this.stats.batchesProcessed+1),this.stats.processingRate=r>0?e.length/(r/1e3):this.stats.processingRate,this.stats.lastProcessedAt=s,this.stats.currentQueueSize=this.eventQueue.length}trackPromise(e){return this.activePromises.add(e),e.finally(()=>this.activePromises.delete(e)),e}getStats(){return{...this.stats}}}class Gm extends WebSocket{constructor(e){super(e)}}var Te=(t=>(t.CONNECTED="websocket.connected",t.DISCONNECTED="websocket.disconnected",t.ERROR="websocket.error",t.MAX_RETRIES_EXCEEDED="websocket.max_retries_exceeded",t.RELOAD="websocket.reload",t))(Te||{});function pa(t){const e=`
91
91
 
92
92
  `,s=`
93
- `,r=/:(.*)/s,[o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}function vm(t){const e=`
93
+ `,r=/:(.*)/s,[o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}function Ym(t){const e=`
94
94
 
95
95
  `,s=`
96
- `,r=/:(.*)/s,[,o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}const Ee=class Ee{constructor({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:n,onConnectionLost:i,Transport:a=bm}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"socket");l(this,"connectionEstablished");l(this,"alias");l(this,"onConnectionEstablished");l(this,"onConnectionLost");l(this,"offlineMessages",[]);l(this,"oldSend");l(this,"reconnectAttempts",0);this.host=e,this.port=s,this.protocol=r,this.onConnectionEstablished=n,this.onConnectionLost=i,this.alias=o,this.socket=new a(`${this.protocol}${this.host}:${this.port}/events`),this.socket.onmessage=this.onMessage.bind(this),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.oldSend=this.socket.send,this.connectionEstablished=!1,C("/mock/msg/receive",c=>{var u,d;if(c!=null&&c.body){m.wsReceive(c==null?void 0:c.body);const h={data:c.body};(d=(u=this.socket)==null?void 0:u.onmessage)==null||d.call(u,h)}}),M.makeObservable(this,{connectionEstablished:M.observable})}addOfflineMessage(e){this.offlineMessages.push({msg:e})}processMessageEvent(e){const{data:s}=e;return ra(s)}onMessage(e){try{m.debug("webSocketTransport: onMessage received");const{headers:s,body:r}=this.processMessageEvent(e);m.wsReceive(e.data);const o=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(o){let n=r,i=s;if(o==="kos.sniffer.msg"){const{headers:a,body:c}=vm(e.data);n=c,i={...s,...a}}K(o,n,i)}}catch(s){m.error("onMessage exception",s.message,s.stack)}}onOpen(e){m.info("websocket connection opened"),this.reconnectAttempts=0,this.socket=e.currentTarget,M.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
96
+ `,r=/:(.*)/s,[,o,n]=t.split(e).map(a=>a.trim());return{headers:o.split(s).reduce((a,c)=>{const[u,d]=c.split(r).map(h=>h.trim());return u&&d&&(a[u]=d),a},{}),body:n}}const Me=class Me{constructor({host:e,port:s,protocol:r,alias:o,onConnectionEstablished:n,onConnectionLost:i,Transport:a=Gm}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"socket");l(this,"connectionEstablished");l(this,"alias");l(this,"onConnectionEstablished");l(this,"onConnectionLost");l(this,"offlineMessages",[]);l(this,"oldSend");l(this,"reconnectAttempts",0);this.host=e,this.port=s,this.protocol=r,this.onConnectionEstablished=n,this.onConnectionLost=i,this.alias=o,this.socket=new a(`${this.protocol}${this.host}:${this.port}/events`),this.socket.onmessage=this.onMessage.bind(this),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.oldSend=this.socket.send,this.connectionEstablished=!1,C("/mock/msg/receive",c=>{var u,d;if(c!=null&&c.body){g.wsReceive(c==null?void 0:c.body);const h={data:c.body};(d=(u=this.socket)==null?void 0:u.onmessage)==null||d.call(u,h)}}),E.makeObservable(this,{connectionEstablished:E.observable})}addOfflineMessage(e){this.offlineMessages.push({msg:e})}processMessageEvent(e){const{data:s}=e;return pa(s)}onMessage(e){try{g.debug("webSocketTransport: onMessage received");const{headers:s,body:r}=this.processMessageEvent(e);g.wsReceive(e.data);const o=s.subscription||s[this.RESPONSE_ID_HEADER]||s.topic||s.type;if(o){let n=r,i=s;if(o==="kos.sniffer.msg"){const{headers:a,body:c}=Ym(e.data);n=c,i={...s,...a}}H(o,n,i)}}catch(s){g.error("onMessage exception",s.message,s.stack)}}onOpen(e){g.info("websocket connection opened"),this.reconnectAttempts=0,this.socket=e.currentTarget,E.runInAction(()=>{var s;this.connectionEstablished=!0,this.alias&&this.socket.send(`type:kos.addr.alias
97
97
  alias:${this.alias}
98
98
 
99
- `),m.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;m.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(e){const{code:s,reason:r,wasClean:o}=e;m.warn(`WebSocket closed: code=${s}, reason=${r||"none"}, wasClean=${o}`),M.runInAction(()=>{this.connectionEstablished=!1}),K("websocket.disconnected",{code:s,reason:r,wasClean:o});const n=this.shouldAttemptReconnection(s);if(this.onConnectionLost)if(n&&this.reconnectAttempts<Ee.MAX_RECONNECT_ATTEMPTS){const i=this.calculateBackoffDelay();m.debug(`Reconnecting in ${i}ms (attempt ${this.reconnectAttempts+1}/${Ee.MAX_RECONNECT_ATTEMPTS})`),setTimeout(()=>{var a;this.reconnectAttempts++,(a=this.onConnectionLost)==null||a.call(this)},i)}else this.reconnectAttempts>=Ee.MAX_RECONNECT_ATTEMPTS?(m.error(`Max reconnection attempts (${Ee.MAX_RECONNECT_ATTEMPTS}) reached. Giving up.`),K("websocket.max_retries_exceeded",{attempts:this.reconnectAttempts})):m.info(`Not reconnecting due to close code ${s} (intentional close or configuration error)`)}onError(e){m.error("websocket error: ",e),K("websocket.error",{event:e})}shouldAttemptReconnection(e){switch(e){case 1e3:return!1;case 1001:return!0;case 1002:return!1;case 1003:return!1;case 1005:return!0;case 1006:return!0;case 1007:return!1;case 1008:return!1;case 1009:return!1;case 1010:return!1;case 1011:return!0;case 1012:return!0;case 1013:return!0;case 1014:return!0;case 1015:return!1;default:return!0}}calculateBackoffDelay(){const e=Math.min(Ee.BASE_DELAY_MS*Math.pow(2,this.reconnectAttempts),Ee.MAX_DELAY_MS),s=e*.25*(Math.random()*2-1);return Math.floor(e+s)}send(e){var s,r;if(m.wsSend(e),window.kosLogEvents){const{headers:o,body:n}=ra(String(e));K(zs.SEND,{headers:o,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:o,requestId:n}=window.kosTopicIntercept(e);if(o){e=`mocked:true
99
+ `),g.debug(`sending ${this.offlineMessages.length} offline FOS messages`),this.offlineMessages.forEach(r=>{var o;g.debug(`sending offline message ${r.msg}`),(o=this.socket)==null||o.send(r.msg)}),this.offlineMessages=[],(s=this.onConnectionEstablished)==null||s.call(this)})}onClose(e){const{code:s,reason:r,wasClean:o}=e;g.warn(`WebSocket closed: code=${s}, reason=${r||"none"}, wasClean=${o}`),E.runInAction(()=>{this.connectionEstablished=!1}),H("websocket.disconnected",{code:s,reason:r,wasClean:o});const n=this.shouldAttemptReconnection(s);if(this.onConnectionLost)if(n&&this.reconnectAttempts<Me.MAX_RECONNECT_ATTEMPTS){const i=this.calculateBackoffDelay();g.debug(`Reconnecting in ${i}ms (attempt ${this.reconnectAttempts+1}/${Me.MAX_RECONNECT_ATTEMPTS})`),setTimeout(()=>{var a;this.reconnectAttempts++,(a=this.onConnectionLost)==null||a.call(this)},i)}else this.reconnectAttempts>=Me.MAX_RECONNECT_ATTEMPTS?(g.error(`Max reconnection attempts (${Me.MAX_RECONNECT_ATTEMPTS}) reached. Giving up.`),H("websocket.max_retries_exceeded",{attempts:this.reconnectAttempts})):g.info(`Not reconnecting due to close code ${s} (intentional close or configuration error)`)}onError(e){g.error("websocket error: ",e),H("websocket.error",{event:e})}shouldAttemptReconnection(e){switch(e){case 1e3:return!1;case 1001:return!0;case 1002:return!1;case 1003:return!1;case 1005:return!0;case 1006:return!0;case 1007:return!1;case 1008:return!1;case 1009:return!1;case 1010:return!1;case 1011:return!0;case 1012:return!0;case 1013:return!0;case 1014:return!0;case 1015:return!1;default:return!0}}calculateBackoffDelay(){const e=Math.min(Me.BASE_DELAY_MS*Math.pow(2,this.reconnectAttempts),Me.MAX_DELAY_MS),s=e*.25*(Math.random()*2-1);return Math.floor(e+s)}send(e){var s,r;if(g.wsSend(e),window.kosLogEvents){const{headers:o,body:n}=pa(String(e));H(Ws.SEND,{headers:o,body:n})}if(window.kosTopicIntercept&&window.kosEnableMocks){const{handler:o,requestId:n}=window.kosTopicIntercept(e);if(o){e=`mocked:true
100
100
  ${e}`;const a={data:`mocked:true
101
- ${o(n)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,e)}else this.oldSend.call(this.socket,e)}};l(Ee,"MAX_RECONNECT_ATTEMPTS",10),l(Ee,"BASE_DELAY_MS",1e3),l(Ee,"MAX_DELAY_MS",3e4);let As=Ee;class wm{constructor(e){l(this,"addEventListener");l(this,"dispatchEvent");l(this,"removeEventListener");l(this,"_onclose");l(this,"_onerror");l(this,"_onmessage");l(this,"_onopen");l(this,"messageQueue",[]);l(this,"isSending",!1);A.debug(`called Bridge Transport with addr ${e}`);const s=this;globalThis.kosWindowWebsocketRecv=r=>{if(s.onmessage){const o={data:r};s.onmessage(o)}},A.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),A.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>A.debug("not implemented"),this.dispatchEvent=()=>A.debug("not implemented"),this.removeEventListener=()=>A.debug("not implemented")}close(){A.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const e=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(e),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(e){this.messageQueue.push(e),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(e){globalThis.kosWindowWebsocketSend(e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage=e}get onopen(){return this._onopen}set onopen(e){this._onopen=e}get onclose(){return this._onclose}set onclose(e){this._onclose=e}get onerror(){return this._onerror}set onerror(e){this._onerror=e}}class Em extends As{constructor({host:s,port:r,alias:o}){super({host:s,port:r,Transport:wm,alias:o,protocol:"kos://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class Mm extends As{constructor({host:s,port:r}){super({host:s,port:r,protocol:"ws://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class Tm extends As{constructor({host:s,port:r,protocol:o,onConnectionEstablished:n,onConnectionLost:i,alias:a}){super({host:s,port:r,onConnectionEstablished:n,onConnectionLost:i,alias:a,protocol:o});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}window.kosEnableMocks=process.env.KOS_MOCK_WS==="true";window.kosLogEvents=process.env.KOS_LOG_WS==="true";class Xo{static build({host:e,port:s,protocol:r,fos:o,alias:n,onConnectionEstablished:i,onConnectionLost:a}){return m.debug("initializing websocket connection"),m.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),m.warn(`fos: ${o?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!o?(m.warn("Using bridged message transport"),new Em({host:e,port:s,protocol:r,onConnectionEstablished:i,onConnectionLost:a,alias:n})):o?new Mm({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a}):new Tm({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a})}}const _m=be();_m.fos&&(window.kosUseFos=!0);const oa=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=oa?parseInt(oa):0;const it=A.getLogger("web-socket-transport");var $l=(t=>(t.NOT_INITIALIZED="not_initialized",t.INITIALIZED="initialized",t.OFFLINE="OFFLINE",t.ONLINE="ONLINE",t))($l||{});class Nt{constructor({host:e="localhost",port:s=8080,protocol:r="ws://",token:o,initialize:n,alias:i,fos:a}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"_token");l(this,"webSocketSupported",!!globalThis.WebSocket);l(this,"authorized");l(this,"alias");l(this,"socket");l(this,"fosSocket");l(this,"fosPort");l(this,"useFosTransport");this.host=e,this.port=s,this.protocol=r,this._token=o,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!a,this.fosPort=a==null?void 0:a.port,this.socket=void 0,this.fosSocket=void 0;let c=!1;M.makeObservable(this,{authorized:M.observable,socket:M.observable,fosSocket:M.observable,init:M.action,connectionEstablished:M.computed}),M.reaction(()=>this.connectionEstablished,u=>{u&&(it.warn("Connection Established"),K(Te.CONNECTED,Te.CONNECTED),c&&K(Te.RELOAD,Te.RELOAD),c=!0)}),n&&this.init()}get connectionEstablished(){return!this.webSocketSupported||!this.socket||this.useFosTransport&&!this.fosSocket?!1:this.useFosTransport&&this.fosSocket?this.socket.connectionEstablished&&this.fosSocket.connectionEstablished:!this.useFosTransport&&this.socket?this.socket.connectionEstablished:!1}init(){var e,s;if(m.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=Xo.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=Xo.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{it.error("Connection Lost"),K(Te.DISCONNECTED,Te.DISCONNECTED),this.init()}}),globalThis.kosWindowWebsocketOpen){const r={currentTarget:this.socket.socket};(s=(e=this.socket.socket)==null?void 0:e.onopen)==null||s.call(e,r)}return this}_sendSubscriptionMessage(e,s,r=!1,o=!1,n){var f,p,g,v;it.debug(`${s} to topic ${e}`);const i=be(),a=i==null?void 0:i.connId,c=n??a??((f=window==null?void 0:window.kosBridge)==null?void 0:f.call(window,"connId"));it.debug(`subscribing with connId ${c}`);const u=c?`dst-addr:${c}
102
- `:"",d=r?`subscribe:${e}`:o?`type:fos.broker
101
+ ${o(n)}`};(r=(s=this.socket)==null?void 0:s.onmessage)==null||r.call(s,a)}else this.oldSend.call(this.socket,e)}else this.oldSend.call(this.socket,e)}};l(Me,"MAX_RECONNECT_ATTEMPTS",10),l(Me,"BASE_DELAY_MS",1e3),l(Me,"MAX_DELAY_MS",3e4);let xs=Me;class Wm{constructor(e){l(this,"addEventListener");l(this,"dispatchEvent");l(this,"removeEventListener");l(this,"_onclose");l(this,"_onerror");l(this,"_onmessage");l(this,"_onopen");l(this,"messageQueue",[]);l(this,"isSending",!1);x.debug(`called Bridge Transport with addr ${e}`);const s=this;globalThis.kosWindowWebsocketRecv=r=>{if(s.onmessage){const o={data:r};s.onmessage(o)}},x.debug("Opening bridge transport"),globalThis.kosWindowWebsocketOpen(),x.debug("Opened bridge transport"),this._onclose=null,this._onerror=null,this._onmessage=null,this._onopen=null,this.addEventListener=()=>x.debug("not implemented"),this.dispatchEvent=()=>x.debug("not implemented"),this.removeEventListener=()=>x.debug("not implemented")}close(){x.debug("closing")}sendNextMessage(){if(this.messageQueue.length>0){const e=this.messageQueue.shift();globalThis.kosWindowWebsocketSend(e),setTimeout(()=>this.sendNextMessage(),1)}else this.isSending=!1}enqueueMessage(e){this.messageQueue.push(e),this.isSending||(this.isSending=!0,this.sendNextMessage())}send(e){globalThis.kosWindowWebsocketSend(e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage=e}get onopen(){return this._onopen}set onopen(e){this._onopen=e}get onclose(){return this._onclose}set onclose(e){this._onclose=e}get onerror(){return this._onerror}set onerror(e){this._onerror=e}}class Qm extends xs{constructor({host:s,port:r,alias:o}){super({host:s,port:r,Transport:Wm,alias:o,protocol:"kos://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}class Xm extends xs{constructor({host:s,port:r}){super({host:s,port:r,protocol:"ws://"});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="requestId"}}class Zm extends xs{constructor({host:s,port:r,protocol:o,onConnectionEstablished:n,onConnectionLost:i,alias:a}){super({host:s,port:r,onConnectionEstablished:n,onConnectionLost:i,alias:a,protocol:o});l(this,"RESPONSE_ID_HEADER");this.RESPONSE_ID_HEADER="response-id"}}window.kosEnableMocks=process.env.KOS_MOCK_WS==="true";window.kosLogEvents=process.env.KOS_LOG_WS==="true";class rn{static build({host:e,port:s,protocol:r,fos:o,alias:n,onConnectionEstablished:i,onConnectionLost:a}){return g.debug("initializing websocket connection"),g.warn(`kosWindowWebsocketOpen: ${globalThis.kosWindowWebsocketOpen?"true":"false"}`),g.warn(`fos: ${o?"true":"false"}`),window.kosMockWs||globalThis.kosWindowWebsocketOpen&&!o?(g.warn("Using bridged message transport"),new Qm({host:e,port:s,protocol:r,onConnectionEstablished:i,onConnectionLost:a,alias:n})):o?new Xm({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a}):new Zm({host:e,port:s,protocol:r,alias:n,onConnectionEstablished:i,onConnectionLost:a})}}const Jm=de();Jm.fos&&(window.kosUseFos=!0);const ga=process.env.KOS_FOS_PORT;window.kosUseFos=!!(window.kosUseFos||process.env.KOS_USE_FOS==="true");window.kosFosPort=ga?parseInt(ga):0;const at=x.getLogger("web-socket-transport");var ql=(t=>(t.NOT_INITIALIZED="not_initialized",t.INITIALIZED="initialized",t.OFFLINE="OFFLINE",t.ONLINE="ONLINE",t))(ql||{});class Lt{constructor({host:e="localhost",port:s=8080,protocol:r="ws://",token:o,initialize:n,alias:i,fos:a}){l(this,"host");l(this,"port");l(this,"protocol");l(this,"_token");l(this,"webSocketSupported",!!globalThis.WebSocket);l(this,"authorized");l(this,"alias");l(this,"socket");l(this,"fosSocket");l(this,"fosPort");l(this,"useFosTransport");this.host=e,this.port=s,this.protocol=r,this._token=o,this.alias=i,this.authorized=process.env.KOS_ALLOW_ANONYMOUS==="true",this.useFosTransport=!!a,this.fosPort=a==null?void 0:a.port,this.socket=void 0,this.fosSocket=void 0;let c=!1;E.makeObservable(this,{authorized:E.observable,socket:E.observable,fosSocket:E.observable,init:E.action,connectionEstablished:E.computed}),E.reaction(()=>this.connectionEstablished,u=>{u&&(at.warn("Connection Established"),H(Te.CONNECTED,Te.CONNECTED),c&&H(Te.RELOAD,Te.RELOAD),c=!0)}),n&&this.init()}get connectionEstablished(){return!this.webSocketSupported||!this.socket||this.useFosTransport&&!this.fosSocket?!1:this.useFosTransport&&this.fosSocket?this.socket.connectionEstablished&&this.fosSocket.connectionEstablished:!this.useFosTransport&&this.socket?this.socket.connectionEstablished:!1}init(){var e,s;if(g.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`),this.useFosTransport&&(this.fosSocket=rn.build({host:this.host,port:this.fosPort||9854,protocol:this.protocol,fos:!0})),this.socket=rn.build({host:this.host,port:this.port,protocol:this.protocol,alias:this.alias,onConnectionLost:()=>{at.error("Connection Lost"),H(Te.DISCONNECTED,Te.DISCONNECTED),this.init()}}),globalThis.kosWindowWebsocketOpen){const r={currentTarget:this.socket.socket};(s=(e=this.socket.socket)==null?void 0:e.onopen)==null||s.call(e,r)}return this}_sendSubscriptionMessage(e,s,r=!1,o=!1,n,i=!1){var h,f,p,y;at.debug(`${s} to topic ${e}`);let a;if(i)a=n;else{const v=de(),M=v==null?void 0:v.connId;a=n??M??((h=window==null?void 0:window.kosBridge)==null?void 0:h.call(window,"connId"))}at.debug(`subscribing with connId ${a}`);const c=a?`dst-addr:${a}
102
+ `:"",u=r?`subscribe:${e}`:o?`type:fos.broker
103
103
  cmd:${s}
104
- ${u}topics:${e}
105
- `:`${u}type:kos.broker.${s}
104
+ ${c}topics:${e}
105
+ `:`${c}type:kos.broker.${s}
106
106
 
107
- ["${e}"]`;if(r?(p=this.fosSocket)==null?void 0:p.connectionEstablished:(g=this.socket)==null?void 0:g.connectionEstablished){const E=r?this.fosSocket:this.socket;(v=E==null?void 0:E.socket)==null||v.send(d)}else{it.debug("no connection adding to offline messages");const E=r?this.fosSocket:this.socket;E==null||E.addOfflineMessage(d)}}subscribeTopic({topic:e,callback:s,fos:r,bridge:o,destinationAddress:n}){const{unsubscribe:i,count:a}=C(e,s);return it.debug(`Topic ${e} currently has ${a} subscribers`),this._sendSubscriptionMessage(e,"subscribe",r,o,n),()=>{const{count:c}=i();it.debug(`Topic ${e} currently has ${c} subscribers`),c===0&&this._sendSubscriptionMessage(e,"unsubscribe",r,o,n)}}async whenReady(){const e=this;return this.webSocketSupported?(await M.when(()=>{var s,r;return!!((s=e.socket)!=null&&s.connectionEstablished)&&(!e.useFosTransport||!!((r=e.fosSocket)!=null&&r.connectionEstablished))&&e.authorized}),{status:"success"}):{status:"not supported"}}get token(){return this._token}set token(e){this._token=e,this.init()}static host(e="localhost"){return this.getInstance().host=e,this}static port(e=8080){return this.getInstance().port=e,this}static alias(e){this.getInstance().alias=e}static getInstance(e=8080,s){if(!this._instance){const r=window.kosUseFos?{port:window.kosFosPort||8081}:void 0;this._instance=new this({port:e,token:s,fos:r})}return this._instance}}l(Nt,"_instance");class Sm{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[X])||{},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===D.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[X])||{};for(const[r,o]of Object.entries(e))if(o.lifecycle===D.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=Nt.getInstance().subscribeTopic({topic:s,callback:r,fos:e.fos,bridge:e.bridge,destinationAddress:n});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=>{var o;try{const n=(o=r==null?void 0:r.headers)==null?void 0:o["src-addr"],i=s.destinationAddress&&this.resolvePropKey(s.destinationAddress),a=i?n===i:!0,c=this.extractWildcardCapture(e,r,s),u=this.isBaselineReady(e);if(!this.model.isReady()||!u){u?this.log.warn(`Model ${this.modelId} not ready. Queuing message for ${e}`):this.log.warn(`Baseline not ready for ${e}. Queuing message.`);const d=()=>{const h=Zo(r,s.skipParse),f=s.transform(h);if(a&&s.condition(f,this.modelData,r))return this.callHandlerWithWildcard(s,f,c,r)};this.offlineQueue.enqueue(d,e,r)}else{const d=Zo(r,s.skipParse),h=s.transform(d);if(a&&s.condition(h,this.modelData,r))return this.callHandlerWithWildcard(s,h,c,r)}}catch(n){this.log.error(`Error handling subscription for ${e}`,n)}}}extractWildcardCapture(e,s,r){var n;if(!r.wildcardName||!Zc(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return Qc(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 ym(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===D.ACTIVATE?this.activatableDisposers.push(a):this.disposers.push(a)}async startFlowProcessing(e,s,r,o){const n=new AbortController;try{let i;if(e.websocket){const a=e.destinationAddress?this.resolvePropKey(e.destinationAddress):null;Nt.getInstance().subscribeTopic({topic:s,callback:()=>{},fos:e.fos,bridge:e.bridge,destinationAddress:a}),i=sa(s)}else i=sa(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 St(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 Om(t){return!!(t!=null&&t[xe])&&Object.keys(t[xe]).length>0}function Im(t){return!!(t!=null&&t[X])&&Object.keys(t[X]).length>0}function $m(t){return!!(t!=null&&t[Be])&&t[Be].length>0}function Cm(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[He])&&Object.keys(e[He]).length>0}function Dm(t){return t.retention===Z.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function Am(t,e){return t.has(e)}function xm(t){return!t.expiresAt||Date.now()<t.expiresAt}function na(t,e,s,r){const o=setTimeout(()=>r(t),e);s.set(t,o)}class Rm{constructor(){l(this,"responses",new Map);l(this,"retentionPolicies",new Map);l(this,"cleanupTimers",new Map)}set(e,s,r={retention:Z.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)===Z.IMMEDIATE}shouldExtendTTL(e,s){if(!Dm(s)||!Am(this.responses,e))return!1;const r=this.responses.get(e);return xm(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),na(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===Z.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 Z.IMMEDIATE:break;case Z.TTL:s.ttl&&na(e,s.ttl,this.cleanupTimers,r=>this.delete(r));break;case Z.SINGLE:break;case Z.PERMANENT:case Z.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 Pm{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=Pn.create({modelId:s,modelTypeName:r}),i=new jg(e,St(n,"fsm")),a=new Hg(St(n,"offline-queue")),c=new xg(e),u=new Ag(e),d=new Rm;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(Om(o)&&(h.effectManager=new Rg(r,s,o,St(n,"effect"))),Im(o)){const f=St(n,"subscription");h.subscriptionManager=new Sm(e,o,s,a,f),h.onlineLifecycleManager=new Kg(e,St(n,"online"))}return $m(o)&&(h.httpRouteManager=new jn(o,St(n,"http-routes"))),Cm(o)&&(h.serviceRequestManager=new gm(o,d)),h}}const U=A.getLogger("kos-model"),km="kos.extension.model.loader";class Cl{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=Pm.createAll(this);this.fsm=o.fsm,this.offlineQueue=o.offlineQueue,this.companionManager=o.companionManager,this.childResolver=o.childResolver,this.serviceResponses=o.serviceResponseStore,o.effectManager&&(this.effectManager=o.effectManager),o.subscriptionManager&&(this.subscriptionManager=o.subscriptionManager),o.httpRouteManager&&(this.httpRouteManager=o.httpRouteManager),o.onlineLifecycleManager&&(this.onlineLifecycleManager=o.onlineLifecycleManager),o.serviceRequestManager&&(this.serviceRequestManager=o.serviceRequestManager),M.makeAutoObservable(this,{fsm:!1,effectManager:!1,subscriptionManager:!1,onlineLifecycleManager:!1,serviceRequestManager:!1,serviceResponses:!1,companionManager:!1,childResolver:!1,offlineQueue:!1}),Cg(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;U.debug(`deactivating model ${this.modelTypeName} with id ${this.modelId}`);try{const o=W.getContext(this.modelId);await((s=(e=this.modelData)==null?void 0:e.deactivate)==null?void 0:s.call(e,o)),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} deactivated`),(r=this.subscriptionManager)==null||r.deactivate()}catch(o){throw U.debug(`Model ${this.modelId} failed to deactivated`),o}}async activate(){var e,s,r,o;U.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`),await ds(this,D.ACTIVATE);try{await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(D.ACTIVATE));const n=W.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.activate)==null?void 0:r.call(s,n)),this.initializeStateMachineForLifecycle(D.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`),(o=this.subscriptionManager)==null||o.registerAll(D.ACTIVATE),this.createLifecycleCompanions(D.ACTIVATE),U.debug(`Model ${this.modelTypeName} with id ${this.modelId} activated`)}catch(n){throw U.debug(`Model ${this.modelId} failed to activate`),n}}async whenLoaded(){await Lo([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.loaded,onMatch:()=>{U.debug(`Model ${this.modelId} is loaded`)}}])}async whenInitialized(){await Lo([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to initialize model ${this.modelId}`)}},{condition:()=>this.initialized,onMatch:()=>{U.debug(`Model ${this.modelId} is initialized`)}}])}async whenReady(){await Lo([{condition:()=>this.status===w.FAILED,onMatch:()=>{throw new Error(`Failed to ready model ${this.modelId}`)}},{condition:()=>this.status===w.READY,onMatch:()=>{U.debug(`Model ${this.modelId} is ready`)}}])}async ready(){var e,s,r,o;if(this.fsm.current===w.READY){U.debug(`already readying model ${this.modelTypeName} with id ${this.modelId} returning`);return}try{U.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`),await ds(this,D.READY),await ul(this,Nn.READY,D.READY),await((e=this.serviceRequestManager)==null?void 0:e.executeForLifecycle(D.READY));const n=W.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(D.READY),(o=this.subscriptionManager)==null||o.registerAll(D.READY),this.createLifecycleCompanions(D.READY),U.debug(`Model ${this.modelId} is ready`);const i={modelId:this.modelId,modelType:this.modelTypeName};K(tl(this.modelTypeName,this.modelId),i),K(sl(this.modelTypeName),i)}catch(n){throw U.error(n),Error(n)}}async load(){var o,n,i,a,c,u;const e=this[Je];e&&await e.whenLoaded();const{modelTypeName:s,modelId:r}=this;if(this.fsm.current===w.LOADED){U.debug(`Model ${s} with id ${r} already loaded`);return}if(this._isLoadExecuting){U.debug(`Model ${s} with id ${r} is currently executing load`);return}this._isLoadExecuting=!0;try{U.debug(`Loading model ${s} with id ${r}`),await ds(this,D.LOAD);const d=W.getContext(r),h=`${km}.${s}`,f=await $.loader.executeLoader(h,{});f&&(U.info(`Setting loaded context for ${r}, type: ${s}`),d==null||d.set(h,f)),await((o=this.serviceRequestManager)==null?void 0:o.executeForLifecycle(D.LOAD)),await((i=(n=this.modelData)==null?void 0:n.load)==null?void 0:i.call(n,d)),te(()=>{this.loaded=!0}),U.debug(`Model ${s} with id ${r} successfully loaded`),this.initializeStateMachineForLifecycle(D.LOAD),(a=this.subscriptionManager)==null||a.registerAll(D.LOAD),(c=this.httpRouteManager)==null||c.registerAll(),(u=this.effectManager)==null||u.setup(),this.createLifecycleCompanions(D.LOAD)}catch(d){throw U.error(`Model ${r} failed to load`,d),d}finally{this._isLoadExecuting=!1}}async unload(){var e,s,r,o,n,i,a;U.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=W.getContext(this.modelId);if(await((s=(e=this.modelData)==null?void 0:e.unload)==null?void 0:s.call(e,u)),this.loaded=!1,(r=this.onlineLifecycleManager)==null||r.dispose(),this.modelData){const d=this.modelData;if(d._fsmInitialized=!1,d._fsmConfig){const h=((o=d._fsmOptions)==null?void 0:o.stateProperty)||"currentState";d[h]=void 0}d.stateHistory&&(d.stateHistory=[])}U.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`),(n=this.effectManager)==null||n.disposeAll(),(i=this.subscriptionManager)==null||i.disposeAll(),(a=this.httpRouteManager)==null||a.dispose()}catch(c){throw U.debug(`Model ${this.modelId} failed to unload`),c}}async init(){var n,i,a,c;const e=this[Je];e&&await e.whenInitialized();const{modelId:s,modelTypeName:r}=this,o=W.getContext(s);U.debug(`Initializing model ${r} with id ${s}`),await ds(this,D.INIT);try{await((n=this.serviceRequestManager)==null?void 0:n.executeForLifecycle(D.INIT)),await((a=(i=this.modelData)==null?void 0:i.init)==null?void 0:a.call(i,o)),this.initialized=!0,U.debug(`Model ${r} with id ${s} initialized`),(c=this.onlineLifecycleManager)==null||c.register(),this.initializeStateMachineForLifecycle(D.INIT),this.registerSubscribers(D.INIT),this.createLifecycleCompanions(D.INIT)}catch(u){throw U.error(`Model ${s} failed to initialize`,u),u}}async registerSubscribers(e){var s;U.debug(`registering subscribers in ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.registerAll(e)}initializeStateMachineForLifecycle(e){this.modelData&&Dc(this.modelData,e)}createLifecycleCompanions(e){this.modelManager.createLifecycleCompanions(this,{},e)}async online(){var s,r;U.debug(`online model ${this.modelTypeName} with id ${this.modelId}`),this.registerSubscribers();const e=W.getContext(this.modelId);await((r=(s=this.modelData)==null?void 0:s.online)==null?void 0:r.call(s,e)),this.createLifecycleCompanions(D.ONLINE)}async offline(){var s,r,o;U.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`),(s=this.subscriptionManager)==null||s.disposeAll();const e=W.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 Fo=m.createLogger({name:"kos-model-instantiator"});class Lm{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new Mg(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 Fo.error(c,{modelType:e,requestedId:s,providedOptions:r,availableModelTypes:Object.keys(this.registry.models)}),Lt(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)){Fo.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[Vs])===!0&&!c){const h=new Error(`Model ${e} requires options but none were provided`);throw Ji(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Lt(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 Cl({modelTypeName:e,id:n,modelData:h});this.cache.addModel(f),this._createCompanionModels(f,r)}catch(h){throw Ji(h,{modelType:e,options:r,registryId:this.registry.alias||"unknown"}),Lt(h,{modelType:e,modelId:n,operation:"model instantiation",options:r})}}const i=this.cache.getModelById(n);if(!i)throw Fo.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 Fm=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 es(e)}};const Dl=10,ia=m.createLogger({name:"kos-model-manager"});class Al{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new vg,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 Fm(e),r.cache=new wg(e.preloadModels),r.instantiator=new Lm(e,r.cache),r}static getInstance(e){var s,r;return(!((s=globalThis.kos)!=null&&s.modelManager)||e)&&(ia.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=>(ia.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 es(e)}addDependency(e,s){this.cache.restoreFromDeleteCache(s),this.dependencies.add(e,s)}removeDependency(e,s){this.dependencies.remove(e,s)}async reloadModel(e){if(e.id){const s=this.getModelById(e.id);s&&await s.fsm.transitionTo(F.RESET,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),Jc.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),Dl)))}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 br=(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))(br||{}),lt=(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))(lt||{});const Nm=t=>{const e=b.createMachine("offline",{online:b.state(b.transition("go_offline","offline",b.action(()=>{t.offline(),M.runInAction(()=>{t.isOnline=!1})}))),offline:b.state(b.transition("go_online","online",b.action(()=>{t.online(),M.runInAction(()=>{t.isOnline=!0})})))}),s=b.interpret(e,n=>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(()=>{M.runInAction(()=>{t.status="ready"})}))),reloading:b.invoke(()=>t.reload(),b.transition("done","loading")),ready:b.state(b.transition("reload","reloading"),b.transition("unload","unloaded",b.action(t.unload.bind(t))),b.transition("go_online","ready",b.action(()=>{s.send("go_online")})),b.transition("go_offline","ready",b.action(()=>{s.send("go_offline")}))),unloaded:b.state()});return{service:b.interpret(r,n=>A.debug(n.machine.current)),online:s}},Y=m.createLogger({name:"kos-core"}),Um=()=>{const t=be(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},jm=()=>{const t=window.location.protocol,e=be(),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://")},Bm=()=>{const t=window.location.hostname,e=process.env.KOS_HOST,s=be(),r=s==null?void 0:s.host;let o;try{o=new URL(r).hostname}catch{}return o??e??t},Hm=()=>{const t=window.location.port,e=process.env.KOS_PORT,s=be(),r=s==null?void 0:s.host;let o;try{o=new URL(r).port}catch{}return o??e??t},Km=(t,e)=>{let s;return{promise:new Promise((n,i)=>{s=setTimeout(()=>{e?m.error(`Model ${e.modelId} - ${e.modelTypeName} preloading - timed out after ${t}ms`):m.error(`KOS Core preloading timed out after ${t}ms`),i(new Error(`Model ${e==null?void 0:e.modelId} - ${e==null?void 0:e.modelTypeName} - timed out after ${t}ms`))},t)}),cancel:()=>{s&&clearTimeout(s)}}},aa=t=>typeof t.reload=="function",qm=t=>typeof t.unload=="function";var xl=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(xl||{});class I{constructor(e){l(this,"fsmService");l(this,"status");l(this,"initialized");l(this,"loaded");l(this,"_transport");l(this,"modelManager");l(this,"authState");l(this,"isOnline");l(this,"_reloading");l(this,"_unloading");l(this,"connectionAlias");this.initialized=!1,this.connectionAlias=e,this.loaded=!1,this.isOnline=!1,this.status=br.CREATED,this.authState="logged_out",this._reloading=!1,this._unloading=!1,M.makeAutoObservable(this),C("token",a=>{a&&(this.transport.token=a.body)}),C(Te.CONNECTED,async()=>{await this.whenReady(),this.fsmService.service.send(lt.GO_ONLINE)}),C(Te.DISCONNECTED,async()=>{this.fsmService.service.send(lt.GO_OFFLINE)}),C("/studioServer/auth/LOGGED_IN",()=>{this.authState="logged_in",this.transport.authorized=!0,this.fsmService.service.send(lt.RELOAD)}),C("/studioServer/auth/LOGIN_REQUIRED",()=>{this.authState="logged_out",this.transport.authorized=!1}),C(Te.RELOAD,()=>{Y.warn("WebSocket requested reload"),this.fsmService.service.send(lt.RELOAD)}),C("/studio/project/reload",()=>{Y.warn("Project requested reload"),this.fsmService.service.send(lt.RELOAD)});const s=Nt.getInstance(),r=Bm(),o=Hm(),n=jm();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=Um()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=Nm(this),this.fsmService.service.send(lt.CREATE)}get onlineStatus(){return this.isOnline&&!this._reloading&&!this._unloading}get reloading(){return this._reloading}get unloading(){return this._unloading}async reload(){var o,n,i,a;const e=Date.now();if(this._reloading){Y.info("reload already in progress");return}this._reloading=!0,Y.warn("reloading KOS Core"),Y.warn("reloading preloaded models");const s=this.modelManager;for(const c of s.preloadedModels)aa(c.modelData)&&(Y.info(`reloading model ${c.modelId}`),(o=c.unload)==null||o.call(c),await c.modelData.reload(),(n=c.registerSubscribers)==null||n.call(c),Y.info(`reloading model ${c.modelId} complete`));for(const c of s.models)!s.preloadedModels.includes(c)&&aa(c.modelData)&&(Y.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(()=>{M.runInAction(()=>{Y.warn("reloading KOS Core complete"),this._reloading=!1})},1e3-r)}async online(){Y.debug("KOS Core going online"),await this._transport.whenReady(),Y.debug("KOS Transport Ready. Calling online() for models"),K("/kosCore/online","/kosCore/online"),console.timeEnd("kosCore:startup")}async offline(){Y.debug("KOS Core going offline"),K("/kosCore/offline","/kosCore/offline")}async unload(){var o;Y.debug("Unloading KOS Core");const e=Date.now();this._unloading=!0,Y.debug("unloading KOS Core");const s=this.modelManager;for(const n of s.models)qm(n.modelData)&&((o=n.unload)==null||o.call(n));const r=Date.now()-e;setTimeout(()=>{M.runInAction(()=>{this._unloading=!1})},1e3-r)}async whenReady(){await M.when(()=>this.status===br.READY)}async ready(){Y.debug("Readying KOS Core"),await this._transport.whenReady();const e=this.modelManager.preloadedModels.map(o=>({modelId:o.modelId,model:o,promise:o.whenReady()})),r=(await Promise.allSettled(e.map(o=>{const{promise:n,cancel:i}=Km(5e3,o.model);Promise.race([o.promise.then(()=>{i()}),n])}))).filter(o=>o.status==="rejected");if(r.length)throw Y.error(`There were ${r.length} failed models on model preloading`),Error(`There were ${r.length} failed models on model preloading`);Y.debug("leaving kos-core ready() ")}get isReady(){return this.status===br.READY}set transport(e){this._transport=e}get transport(){return this._transport}get coreInitialized(){return this.initialized}get modelsLoaded(){return this.loaded}async init(){Y.debug("entering kos-core init()"),console.time("kosCore:startup"),console.time("kosCore:init"),await this._transport.whenReady(),this.initialized=!0,Y.debug("initialized - leaving kos-core init()"),console.timeEnd("kosCore:init")}async load(){Y.debug("entering kos-core load()"),console.time("kosCore:load"),this.loaded=!0,Y.debug("loaded - leaving kos-core load()"),console.timeEnd("kosCore:load")}static create(e,s,r){var i,a,c;const o=this.getInstance({reset:s,connectionAlias:r});(i=e.extensions)!=null&&i.dataMapper&&Object.keys(e.extensions.dataMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.dataMapper)==null?void 0:f[u];d&&(Array.isArray(d)?d.forEach(p=>{$.dataMapper.registerDataMapper(u,p)}):$.dataMapper.registerDataMapper(u,d))}),(a=e.extensions)!=null&&a.propertyMapper&&Object.keys(e.extensions.propertyMapper).forEach(u=>{var h,f;const d=(f=(h=e.extensions)==null?void 0:h.propertyMapper)==null?void 0:f[u];d&&$.propertyMapper.registerPropertyMapper(u,d)}),(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&&$.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 g=p.class.prototype[Je];f=g==null?void 0:g.lifecycle}}e.companionModels[u].push({type:h,lifecycle:f})}}),R.model.getPreloadModels().forEach(u=>{e.preloadModels.includes(u)||e.preloadModels.push(u)});const n=Al.create(e,s);return o.modelManager=n,o}static getInstance(e){return this._instance=window.KosCore,(!this._instance||e!=null&&e.reset)&&(window.KosCore=new this(e==null?void 0:e.connectionAlias),this._instance=window.KosCore),this._instance}}l(I,"_instance");const zm=m.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Rl{constructor(){l(this,"visitedModels",new Set);this.visitedModels=new Set}start(e){var r;if(e.id===void 0)throw new Error("rootModel must have an id");const s=I.getInstance().modelManager.getModelById(e.id);if(!s)throw new Error(`Could not find rootModel with id: ${e.id}`);this.visitedModels.clear(),(r=s.accept)==null||r.call(s,this)}visit(e){var r;if(this.visitedModels.has(e.modelId)){zm.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 Vm extends Rl{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 Gm(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 Ym(t,e){const s=t??[],r=e??[];return s.length!==r.length?!1:s.every((o,n)=>o===r[n])}const Bn=(t,e)=>{const s=t.map(n=>n.id);return e.map(n=>n.id).filter(n=>!s.includes(n))},Pl=t=>t,Hn=t=>t,Wm=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=Pl,idMapper:o=Hn})=>n=>{const i=n.map(o),c=Bn(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)},Qm=({container:t,onAddItem:e,onRemoveItem:s=Pl,idMapper:r=Hn})=>o=>{const n=o.map(r);Bn(n,t.models).forEach(s),n.forEach(e)},Zm=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=Hn})=>o=>{const n=o.map(r);Bn(n,t).forEach(s),n.forEach(e)},Xm=(t,e="parent-")=>{let s=t;return s.startsWith(e)&&(s=s.replace(e,"")),s},ca=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),la=[{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 kl(t){let e=(t.getTime()-Date.now())/1e3;for(let s=0;s<=la.length;s++){const r=la[s];if(Math.abs(e)<r.amount)return ca.format(Math.round(e),r.name);e/=r.amount}return ca.format(Math.round(e),"years")}const Kn=t=>t%4===0&&t%100!==0||t%400===0,qn=(t,e)=>[31,Kn(t)?29:28,31,30,31,30,31,31,30,31,30,31][e],Ll=(t,e)=>{const s=new Date(t),r=t.getDate();return s.setDate(1),s.setMonth(s.getMonth()+e),s.setDate(Math.min(r,qn(s.getFullYear(),s.getMonth()))),s},Fl=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},Ut="en-US",Nl={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"}},Ul={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"}},jl=(t,{dateStyle:e="short",locales:s=Ut}={dateStyle:"short",locales:Ut})=>{const r=e==="short"?Nl.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},Bl=(t,{locales:e=Ut,timeStyle:s="short"}={locales:Ut,timeStyle:"short"})=>{const r=Ul[s];return new Intl.DateTimeFormat(e,r).format(t)},Hl=(t,{dateStyle:e="short",locales:s=Ut,timeStyle:r="short"}={dateStyle:"short",locales:Ut,timeStyle:"short"})=>{const o={...e&&Nl[e],...r&&Ul[r]};return new Intl.DateTimeFormat(s,o).format(t)},Jm=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Fl,addMonthsToDate:Ll,formatDate:jl,formatDateSince:kl,formatDateTime:Hl,formatTime:Bl,getDaysInMonth:qn,isLeapYear:Kn},Symbol.toStringTag,{value:"Module"})),Kl="featureFlagResolver",ir=new Map;Ys(Kl,{register:(t,e)=>{var s;ir.has(t)||ir.set(t,[]),(s=ir.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=ir.get(t);if(!s)return[];const r=s.map(a=>a(e)),n=(await Promise.allSettled(r)).map(a=>a.status==="fulfilled"?a.value:(m.info(`Feature flag resolver ${t} failed: ${a.reason}`),[])).flat(),i=Array.from(new Set(n)).reduce((a,c)=>(a[c]=!0,a),{});return zl.updateFlags(i),Object.keys(i)}});const ey="kos.loader.featureFlag";class ql{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 ql;const zl=window.KosFeatureFlags,Vl=(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)}`},Gl=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return Vl(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},Yl=(t,e)=>getComputedStyle(t).getPropertyValue(e),ty=(t,e)=>Gl(Yl(t,e)),sy=(t,e)=>{const s={...t};return s.id&&delete s.id,s},Jo=(t,e,s=sy)=>{const r=s(t,e);M.runInAction(()=>{Object.assign(e,r)})};class Wl{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 ry=async(t,e)=>{const s=new Wl;e.forEach(o=>s.use(o));const r={data:t,result:{}};return await s.execute(r),r.result},es=t=>({type:t,build:(e,s)=>I.getInstance().modelManager.createModelInstance(t,e,s).data,buildAsync:async(e,s)=>{const r=I.getInstance().modelManager.createModelInstance(t,e,s);return await r.model.whenInitialized(),r.data}}),oy=t=>{I.getInstance().modelManager.registerModel(t)},ny=(t,e)=>{I.getInstance().modelManager.registerCompanionModel(t,e)},ua="/kos/ui/internal/heartbeat/",iy=({relationshipId:t,destinationAddress:e,onAbort:s,waitTime:r,beatTime:o})=>{const n=I.getInstance().transport,i=new AbortController;let a=performance.now();const c=n.subscribeTopic({topic:`${ua}${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(()=>{Tl({msg:{},options:{topic:`${ua}${t}`,destinationAddress:e}})},h),p=()=>{window.clearInterval(f),window.clearInterval(d),c()},g=()=>{p(),s&&s(),i.signal.removeEventListener("abort",g)};return i.signal.addEventListener("abort",g),{cleanUpHeartbeat:p}},Ql=(...t)=>e=>t.reduce((s,r)=>r(s),e),ay={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function cy(t,e){let s=1;const r={...ay,...e},{maxAttempts:o,baseDelayMs:n,backoffFactor:i}=r;let a=n;for(;s<=o;)try{return await t()}catch(c){if(m.error(`Attempt ${s} failed: ${c}`),s<o)a=n*Math.pow(i,s),await new Promise(u=>setTimeout(u,a)),s++;else throw c}throw new Error("All attempts failed")}const ly=m.createLogger({name:"kos-service-request"}),ue=t=>({isMock:!1,URL:exports.BASE_URL}),uy=(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),ts(p,{ordered:i,studio:a,fos:c,bridge:u,timeout:d,signal:h,destinationAddress:f});try{const g=await s(n||`${e}/${r}`,p);if(!g.ok)throw Error(`There was a problem deleting the model; returned status ${g.status}`);return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while deleting model");if(g.name==="AbortError")throw new z("Request was cancelled while deleting model")}throw g}},ts=(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),dy=(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),ts(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}},hy=(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),ts(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 g=await s(p,f);if(!g.ok){let E;try{E=await g.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${g.status}`,E??void 0)}return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while retrieving model");if(g.name==="AbortError")throw new z("Request was cancelled while retrieving model")}throw g}},fy=(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),ts(f,{timeout:u,ordered:n,studio:i,fos:a,bridge:c,signal:d,destinationAddress:h});const p=r||`${e}/${o}`;try{const g=await s(p,f);if(!g.ok){let E;try{E=await g.json()}catch{}throw new z(`There was a problem retrieving the model; returned status ${g.status}`,E??void 0)}return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while retrieving model by ID");if(g.name==="AbortError")throw new z("Request was cancelled while retrieving model by ID")}throw g}};class z extends Error{constructor(s,r){super(s);l(this,"payload");this.name="FetchException",this.payload=r}}const da=(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),ts(p,{timeout:d,ordered:n,studio:a,fos:c,bridge:u,signal:h,destinationAddress:f});try{const g=await s(o||e,p);if(!g.ok){let E;try{E=await g.json()}catch{}throw new z(`There was a problem sending the POST data; returned status ${g.status}`,E??void 0)}return await g.json()??void 0}catch(g){if(g instanceof DOMException){if(g.name==="TimeoutError")throw new z("Request timed out while adding model");if(g.name==="AbortError")throw new z("Request was cancelled while adding model")}throw g}},ha=(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 g={method:t};o&&(g.body=JSON.stringify(o)),e&&(g.destinationAddress=e),ts(g,{timeout:h,ordered:a,studio:c,fos:u,bridge:d,signal:f,destinationAddress:p});try{const v=await r(i||`${s}/${n}`,g);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}},ie={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:dy(t,s||e,c),getModelById:fy(t,r||e,c),getOne:hy(t,r||e,c),addModel:da(t,n||e,c),deleteModel:uy(t,o||e,c),modifyModel:ha("POST",t,i||e,c),putModel:ha("PUT",t,i||e,c),postModel:da(t,n||e,c)}}};function py(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function gy(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function my(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function yy(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function by(t){const e=t.serviceResponses;e&&e.clear()}const vy=vt(),Zl=()=>`kos-${vy}`,wy=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(Zl()),zn=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)}),Ey=async(t,e,s)=>{const r=zn(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)},My=async({topic:t,msg:e,requestId:s})=>{const r=s??vt(),o=zn(r);K(t,e,{sync:r});const n=await o;if(n.error)throw Error(n.error);return n},ge=new Map;class Xl{constructor(e){l(this,"_context");l(this,"_parent");l(this,"_id");this._id=e,this._context=new M.ObservableMap({}),this._parent="",M.makeAutoObservable(this)}setParent(e){te(()=>{this._parent=e})}get id(){return this._id}get context(){return this._context}get parentModel(){var e;if(this._parent)return(e=Pe(this._parent))==null?void 0:e.model}get companionModels(){const e=Pe(this._id);return e!=null&&e.model?zc(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||!ge.has(n.id)?!1:(i=ge.get(n.id))==null?void 0:i.context.has(e)});if(o)return(s=ge.get(o.id))==null?void 0:s.get(e)}if(this._parent)return(r=ge.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 W={createContext:(t,e)=>{const s=ge.get(t)??new Xl(t);if(e){if(!ge.has(e))throw new Error(`Parent context ${e} does not exist`);s.setParent(e)}else t!=="root"&&s.setParent("root");return ge.set(t,s),s},getContext:t=>ge.get(t),deleteContext:t=>{ge.delete(t)},setParentContext:(t,e)=>{var s;if(!ge.has(e))throw new Error(`Parent context ${e} does not exist`);(s=ge.get(t))==null||s.setParent(e)},rootContext:()=>ge.get("root")};W.createContext("root");const Ty=t=>W.getContext(t.id),Vn="Not Assigned",_y="kos.trouble.added",Sy="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))(Se||{}),$s=(t=>(t.TIME_CHANGE="/kos/internal/time/time",t.DAY_CHANGE="/kos/internal/time/day",t.TIMEZONE_CHANGE="/kos/internal/time/timezone",t))($s||{});const Jl="future-model",ss=es(Jl),uo=m.createLogger({name:"future-service",group:"Services"}),{isMock:Oy,URL:Ws}=ue();var et=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(et||{});const{getAll:Iy,modifyModel:$y,addModel:Cy,deleteModel:Dy,postModel:Ay}=ie.build({destinationAddress:"",basePath:`${Ws}/api/future`,mock:Oy}),xy=async()=>await Iy({}),eu=async(t,e="/api/kos/future")=>(uo.info(`sending delete request for Future: ${t}`),await Dy({id:t,urlOverride:`${Ws}${e}/${t}`})),tu=async(t,e="/api/kos/future")=>(uo.info("sending add request for Future"),await Cy({model:t,urlOverride:`${Ws}${e}`})),Ry=async(t,e,s="/api/kos/future")=>(uo.info(`sending modify request for Future: ${t}`),$y({model:e,id:t,urlOverride:`${Ws}${s}/${t}`})),su=async(t,e="/api/kos/future")=>(uo.info(`sending cancel request for Future: ${t}`),Ay({urlOverride:`${Ws}${e}/${t}/cancel`,ordered:!0,model:{}})),Gn=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}),Yn=(t,e)=>{m.debug(`future dto ${t.id} end state ${t.endState}`),m.debug(`future model ${e.id} end state ${e.endState}`),e.endState?m.debug(`future model ${e.id} is already complete`):(m.debug(`updating future model ${e.id}`),M.runInAction(()=>{const s=Gn(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]})})}))},ru=t=>e=>s=>t.build(String(e),s),Wn=t=>e=>Ql(Gn,ru(t)(e.tracker||e.id))(e);var Py=Object.defineProperty,ky=Object.getOwnPropertyDescriptor,ou=(t,e,s,r)=>{for(var o=r>1?void 0:r?ky(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Py(e,s,o),o};const No=m.getLogger(ss.type);let Or=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=su,hn(()=>this.status===et.Success||this.status===et.Fail,()=>{No.info(`Future ${this.id} has completed with status ${this.status}`),Ae(this)})}async load(){No.debug(`loading Future ${this.id}`)}unload(){No.info(`unloading Future ${this.id}`)}async cancelFuture(){const t=this.namespace==="studio"?"/api/future":`/api/${this.namespace}/future`;await hn(()=>this.futureId!==Vn),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}`),Yn(t,this)}};ou([B({topic:`kos.future/${Mr}`})],Or.prototype,"handleFutureUpdated",1);Or=ou([P(ss.type)],Or);const nu=Or,iu=Ye(),au=m.createLogger({name:"config-bean-service",group:"Services"}),Qn=exports.BASE_URL,cu=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:Ly,getOne:Fy}=ie.build({destinationAddress:"",basePath:`${Qn}/kos/config/`}),lu=async(t,e,s="/api/kos/config")=>(au.debug(`sending modify request for ConfigBean: ${t}`),Ly({model:e,urlOverride:`${Qn}${s}/${t}`})),uu=async(t,e="/api/kos/config")=>(au.debug(`sending get request for ConfigBean: ${t}`),await Fy({urlOverride:`${Qn}${e}/details/${t}/15`})),Zn=t=>t.toLowerCase()==="true"||t.toLowerCase()==="false",ho=t=>{try{const e=Number(t);return!isNaN(e)}catch{return!1}};function du(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function hu(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])?hu(t[r],o,s):s[o]=t[r]}return s}const fu=(t,e)=>{const s=t.details[0].bean||du(t.details[0].scopes),r=hu(s);M.runInAction(()=>{const o={...r};e.props.setValues(o)})},pu=(t,e)=>{M.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"&&Zn(a)&&(a=a.toLowerCase()=="true",c=(c==null?void 0:c.toLowerCase())=="true"),typeof a=="string"&&ho(a)&&(a=Number(a),c=Number(c)),e.props[i]=a,e.prevProps[i]=c})})},gu=t=>Object.fromEntries(t.props.entries),Ny=t=>e=>s=>t.build(e,s);var Uy=Object.defineProperty,jy=Object.getOwnPropertyDescriptor,mu=(t,e,s,r)=>{for(var o=r>1?void 0:r?jy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Uy(e,s,o),o};function By(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const Xn="config-bean-model",ar=m.getLogger(Xn),Hy=yt("path");let Ir=class{constructor(t,e){l(this,"_modifyConfigBean");l(this,"_getConfigBean");l(this,"_schema");l(this,"id");l(this,"path");l(this,"props");l(this,"prevProps");l(this,"serviceBasePath");Object.assign(this,e),this.id=t,this.path=e.path,this.serviceBasePath=e.serviceBasePath;const{modifyConfigBean:s=lu,getConfigBean:r=uu}=e;this._modifyConfigBean=s,this._getConfigBean=r,this.props=Re(),this.prevProps=Re()}get values(){return this.props.values}async ready(){ar.debug(`readying config bean ${this.path}`),ar.debug(`complete readying config bean ${this.path}`)}async load(){ar.debug(`loading config bean ${this.path}`);const t=await this._getConfigBean(this.path,this.serviceBasePath);if(t!=null&&t.data){const e=t.data;fu(e,this),ar.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=By(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=gu(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){pu(t,this)}};mu([B({topic:`/kos/config/${Hy}`,websocket:!0})],Ir.prototype,"handleConfigBeanUpdated",1);Ir=mu([P(Xn)],Ir);const xs=new ve({class:Ir,type:Xn}),fo=({path:t,lazy:e,serviceBasePath:s})=>(r,o)=>{r[x]=r[x]||{},r[x][o]={modelType:xs.type,id:`${xs.type}-${t}`,options:{path:t,serviceBasePath:s},lifecycle:D.INIT,lazy:e}},{URL:yu}=ue(),{getOne:Ky,getAll:qy}=ie.build({basePath:`${yu}/api/kos/regions/info`}),bu=async()=>{try{return await Ky({})}catch{return}},vu=async()=>{try{return await qy({urlOverride:`${yu}/api/kos/regions`})}catch{return}},zy=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:bu,getRegions:vu},Symbol.toStringTag,{value:"Module"}));var he=(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))(he||{});const wu={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 Vy(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},{...wu});return{...t,...r}}function Gy(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]:{...wu}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function Yy(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 Wy=Object.defineProperty,Qy=Object.getOwnPropertyDescriptor,Jn=(t,e,s,r)=>{for(var o=r>1?void 0:r?Qy(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&&Wy(e,s,o),o};const vr="region-info-model",us=m.createLogger({name:"region-info-model"});let Rs=class{constructor(t){l(this,"id");l(this,"unitSystemMap");l(this,"measureMap");l(this,"defaultMeasureMap");l(this,"regionMap");l(this,"timeFormats");l(this,"dateFormats");l(this,"unitSystems");l(this,"regionSource");l(this,"region");l(this,"regions",[]);l(this,"timeZoneMap",{});this.id=t,this.unitSystems={},this.unitSystemMap={},this.measureMap={},this.defaultMeasureMap={},this.timeFormats={},this.regions=[],this.dateFormats={},this.timeZoneMap={},this.regionMap={}}get availableRegions(){return this.regions}get defaultUnitSystem(){return String(this.regionSource.props.unitSystemId).toLowerCase()||""}get unitSystemId(){return this.defaultUnitSystem}get timeFormatId(){const t=this.regionSource.props.timeFormatId;if(!t)return"";const e=String(t),s=this.timeFormats[e];return s?String(s.id):""}get selectedTimeFormat(){const t=this.timeFormatId;return t?String(this.timeFormats[t].format):"HH:mm:ss"}get is12HourTimeFormat(){const t=this.timeFormatId;return t?this.timeFormats[t].ampm:!0}get dateFormatId(){const t=this.regionSource.props.dateFormatId;if(!t)return"";const e=String(t);return e?this.dateFormats[e].id:""}get selectedDateFormat(){const t=this.dateFormatId;return t?this.dateFormats[t].format:""}get selectedDateOrder(){const t=this.dateFormatId;return t?this.dateFormats[t].order.toLowerCase():"dmy"}get selectedCountry(){return this.regionSource.props.country||"en"}get selectedTimeZone(){return this.regionSource.props.timeZone||""}get timeZones(){return this.regionId?this.timeZoneMap[this.regionId]||[]:[]}get allTimeZones(){return Intl.supportedValuesOf("timeZone")}get regionId(){return this.region.props.regionId||""}get selectedRegion(){return this.regionMap[this.regionId]}get selectedUnitSystem(){return String(this.regionSource.props.unitSystemId)||""}get timeFormatOptions(){return Object.keys(this.timeFormats).map(t=>({id:t,format:this.timeFormats[t].format,ampm:this.timeFormats[t].ampm}))}get dateFormatOptions(){return Object.keys(this.dateFormats).map(t=>({id:t,format:this.dateFormats[t].format,order:this.dateFormats[t].order}))}get unitSystemOptions(){return Object.keys(this.unitSystems).map(t=>({id:t,name:t}))}setSelectedTimeFormat(t){if(!this.timeFormatOptions.find(e=>e.id===t))throw Error(`Invalid time format id. Must be one of ${this.timeFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("timeFormatId",t)}setSelectedDateFormat(t){if(!this.dateFormatOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.dateFormatOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("dateFormatId",t)}setSelectedUnitSystem(t){if(!this.unitSystemOptions.find(e=>e.id===t))throw Error(`Invalid date format id. Must be one of ${this.unitSystemOptions.map(e=>e.id).join(", ")}`);this.regionSource.updateProperty("unitSystemId",t)}getUnitSystem(t){if(!t)return this.defaultUnitSystem;const e=t==="drt"?"second":t,s=this.unitSystemMap[e];if(!s)throw Error(`No unit found with name: ${e}. Unit should be one of ${Object.keys(this.unitSystemMap).join(", ")}`);return s[he.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[he.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[he.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[he.family]!==s[he.family])throw new Error(`Cannot convert between units of different families: ${e[he.family]} and ${s[he.family]}`);const r=e[he.offset],o=e[he.scale],n=s[he.scale],i=s[he.offset],a=s[he.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||us.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||us.info("Could not find default unit for measure",e.measure)}return!n||!i?(us.warn("Could not find unit to convert to or from. Return value as is"),String(t)):this.convertByUnit(t,n,i)}async init(){us.debug("initializing region info")}async load(){us.debug("loading region info");const t=await vu();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 bu();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(Vy,{}),this.measureMap=e.data.unitSystems.reduce(Gy,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(Yy,{}),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))}};Jn([fo({path:"kos:service:region:settings"})],Rs.prototype,"regionSource",2);Jn([fo({path:"kos:service:region"})],Rs.prototype,"region",2);Rs=Jn([P(vr)],Rs);const ne={registration:{[vr]:{class:Rs,singleton:!0}},type:vr,factory:le.Singleton.create(vr)},$r=({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},ei=(t,e,s)=>{const{model:r}=Pe(ne.type);if(!r)throw new Error("RegionInfo model not found");if(!Sr(r))throw new Error("RegionInfo model not ready");const o={system:r.defaultUnitSystem},n=$r({source:e}),i=$r({source:s||o,defaultMeasure:r.getUnitMeasure(n.unit||"")});return r.convert(t,n,i)};function fa(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 Zy=(t,e,s,r)=>{const o=ei(t,e,s),n=$r({source:e}),{model:i}=Pe(ne.type);if(!i)throw new Error("RegionInfo model not found");const a=i.getUnitMeasure(n.unit||""),c={system:i.defaultUnitSystem},u=$r({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:fa(o,d||n.unit||"",{...f,mode:"long"}),shortDisplay:fa(o,d||n.unit||"",{...f,mode:"short"})}};var Xy=Object.defineProperty,Jy=Object.getOwnPropertyDescriptor,Eu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Jy(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Xy(e,s,o),o};const Mu="browser-router-model",eb="kos.http.request",tb="kos.http.response";let Cr=class{constructor(t,e,s){l(this,"_id");l(this,"logger");l(this,"router");this._id=t,this.logger=s.logger,this.router=new nh}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),_l({msg:d,options:{responseId:i,destinationAddress:s,type:tb,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}`)}};Eu([B({topic:eb})],Cr.prototype,"handleRequest",1);Cr=Eu([P(Mu)],Cr);const ti=new Ce({class:Cr,type:Mu});function pa({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 ga({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:ho(s)?ei(Number(s),t,e):s,sb=(t,e,s,r)=>{if((t==null?void 0:t.type)==="enum"||!(t!=null&&t.options))return[];if(t.options.type==="rangeCount")return pa(t.options).map(Ot(s,r));if(t.options.type==="rangeInterval")return ga(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 pa(t.options.unitSystems[e]).map(Ot(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return ga(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[]},rb=(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 ob=Object.defineProperty,nb=Object.getOwnPropertyDescriptor,si=(t,e,s,r)=>{for(var o=r>1?void 0:r?nb(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&&ob(e,s,o),o};function ib(t){return(t==null?void 0:t.type)==="enum"}function ab(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 cb(t,e){const s=new Date;s.setHours(0,0,0,0);const r=new Date(s.getTime()+t*1e3);return Ze.format(r,e)}const wr="config-bean-prop-model",It=m.createLogger({name:"config-bean-prop-model"}),lb=yt("path"),ub=yt("serviceBasePath");let Ps=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 cu(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?ab(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:sb(r,s,e==null?void 0:e.from,e==null?void 0:e.to),n=o.length>0?o.map(a=>({label:a,value:a})):[];return this.optionsExpander?typeof this.optionsExpander=="function"?this.optionsExpander(s,o):this.optionsExpander:n}convertUnit(t,e,s){const r=(t==null?void 0:t.measure)||s,o=(t==null?void 0:t.system)||e,n=t==null?void 0:t.unit;return{measure:r,system:o,unit:n}}getConverterUnits(){const t=this.regionInfo.defaultUnitSystem,e=this.getConverter();if(!e)throw Error("No converter defined");const s=e.measure,r=this.convertUnit(e.from,"si",s),o=this.convertUnit(e.to,t,s);return{backend:r,display:o}}set value(t){this.updateProperty(t)}get value(){return this.getValue(!0)}get rawValue(){return this.bean.props[this.attribute]}get significantValue(){var o,n;const t=this.value,e=this.regionInfo.defaultUnitSystem,s=this.getConverter(),r=(s==null?void 0:s.measure)||((o=s==null?void 0:s.to)==null?void 0:o.measure);if(!isNaN(t)&&s&&r){const i=this.getDefaultUnitDecimalPlaces(r,e,(n=s==null?void 0:s.to)==null?void 0:n.unit);try{const c=this.getFormatterOptions(s);if(c){let u=String(t);return u=c.formatToParts(Number(t))[0].value,Number(u)}}catch(c){It.info(`error formatting value ${t}`,c)}return Number(t).toFixed(i)}return t}get previousValue(){return this.getValue(!1)}getValue(t){const e=this.bean[t?"props":"prevProps"][this.attribute];if(typeof e=="boolean")return e;if(this.getConverter()&&!isNaN(e)){const{backend:r,display:o}=this.getConverterUnits();return this.regionInfo.convert(Number(e),r,o)}return e||""}async activate(){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 cb(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 rb(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;const{unit:t,measure:e}=this.getConverterFromFormat(),s=t==="drt"?"second":t;if(this.converter){const g=(r=this.converter)==null?void 0:r.measure,v=(n=(o=this.converter)==null?void 0:o.to)==null?void 0:n.measure,E=(a=(i=this.converter)==null?void 0:i.from)==null?void 0:a.measure,_=g||v||E||e,k=((u=(c=this.converter)==null?void 0:c.to)==null?void 0:u.unit)||this.regionInfo.getDefaultUnitForMeasure(_,((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.system)??this.regionInfo.defaultUnitSystem),S=((p=(f=this.converter)==null?void 0:f.to)==null?void 0:p.system)??this.regionInfo.getUnitSystem(k),O=this.schemaFormat==="drt"?"second":this.schemaFormat||s;return{...this.converter,from:{unit:O,...this.converter.from},to:{...this.converter.to,unit:k,system:S},measure:_}}if(s&&e){const g=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),v=this.regionInfo.getUnitSystem(s),E=this.regionInfo.getUnitSystem(g);return{measure:e,to:{unit:v===E?s:g}}}}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)}};si([Jt({modelType:ne.type})],Ps.prototype,"regionInfo",2);si([fo({path:lb,serviceBasePath:ub})],Ps.prototype,"bean",2);Ps=si([P(wr)],Ps);const wt={registration:{[wr]:{class:Ps,singleton:!1}},type:wr,factory:le.Factory.create(wr)},Tu="future-container-model",tt=es(Tu),_u=t=>Wn(ss)(t),db=t=>{const e=_u(t);return tt.build(tt.type,{}).addFutureModel(e),e},hb=t=>tt.build(tt.type,{}).getFuture(String(t)),gt={buildFutureModel:_u,initiateFuture:db,getFuture:hb};var fb=Object.defineProperty,pb=Object.getOwnPropertyDescriptor,ri=(t,e,s,r)=>{for(var o=r>1?void 0:r?pb(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&&fb(e,s,o),o};const cr=m.getLogger(tt.type);let ks=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=eu,addFuture:o=tu}=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){cr.error("error deleting a Future"),cr.error(e)}}async createFuture(t){try{const e=await this._addFuture(t),s=e==null?void 0:e.data;if(s){const r=Wn(ss)(s);return this.addFutureModel(r),r}}catch(e){throw cr.error("error creating a Future"),cr.error(e),e}}handleFutureUpdated(t,e){const s=gt.buildFutureModel(t);this.addFutureModel(s);const r=`kos.future/${t.tracker||t.id}`;this.logger.debug(`publishing future update to ${r}`),K(r,e.body,e.headers)}};ri([Le],ks.prototype,"_futures",2);ri([B({topic:"kos.future"})],ks.prototype,"handleFutureUpdated",1);ks=ri([P(tt.type)],ks);const Su=ks,{URL:Qs}=ue(),{getOne:gb,postModel:mb,deleteModel:Ou}=ie.build({basePath:`${Qs}/api/keyVal`}),en=m.createLogger({name:"key-value-service",group:"Services"}),Iu=async(t,e)=>{await Ou({urlOverride:`${Qs}/api/keyVal/${t}/${e}`,id:e})},$u=async(t,e,s)=>{const r=await mb({urlOverride:`${Qs}/api/keyVal/${t}/${e}`,model:s.toString()});if((r==null?void 0:r.status)!==200)throw en.error("Failed to update key-value data",r),new Error(`Failed to update key-value data for namespace ${t}`);return r.data},Cu=async(t="studio")=>{en.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await gb({urlOverride:`${Qs}/api/keyVal/${t}`});if((e==null?void 0:e.status)!==200)throw en.error("Failed to retrieve key-value data",e),new Error(`Failed to retrieve key-value data for namespace ${t}`);return e.data},yb=async t=>{await Ou({urlOverride:`${Qs}/api/keyVal/${t}`,id:""})},bb=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Iu,deleteKeyValueNamespace:yb,getKeyValue:Cu,updateKeyValue:$u},Symbol.toStringTag,{value:"Module"}));var vb=Object.defineProperty,wb=Object.getOwnPropertyDescriptor,oi=(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&&vb(e,s,o),o};const Du="key-value-model";let Ls=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=Re(),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 $u(this.namespace,t,e),this.data[t]=e):(await Iu(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await Cu(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)}};oi([B({topic:"/keyVal/set"})],Ls.prototype,"handleStateUpdate",1);oi([B({topic:"/keyVal/remove"})],Ls.prototype,"handleStateDelete",1);Ls=oi([P(Du)],Ls);const ni=new ve({class:Ls,type:Du});var me="INUMBER",rs="IOP1",os="IOP2",ns="IOP3",Ke="IVAR",mt="IVARNAME",jt="IFUNCALL",po="IFUNDEF",ce="IEXPR",ii="IEXPREVAL",Et="IMEMBER",go="IENDSTATEMENT",Bt="IARRAY";function L(t,e){this.type=t,this.value=e??0}L.prototype.toString=function(){switch(this.type){case me:case rs:case os:case ns:case Ke:case mt:case go:return this.value;case jt:return"CALL "+this.value;case po:return"DEF "+this.value;case Bt:return"ARRAY "+this.value;case Et:return"."+this.value;default:return"Invalid Instruction"}};function mo(t){return new L(rs,t)}function We(t){return new L(os,t)}function Au(t){return new L(ns,t)}function tn(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===me||p===mt)Array.isArray(f.value)?n.push.apply(n,tn(f.value.map(function(g){return new L(me,g)}).concat(new L(Bt,f.value.length)),e,s,r,o)):n.push(f);else if(p===Ke&&o.hasOwnProperty(f.value))f=new L(me,o[f.value]),n.push(f);else if(p===os&&n.length>1)c=n.pop(),a=n.pop(),d=s[f.value],f=new L(me,d(a.value,c.value)),n.push(f);else if(p===ns&&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 L(me,d(a.value,c.value,u.value)),n.push(f));else if(p===rs&&n.length>0)a=n.pop(),d=e[f.value],f=new L(me,d(a.value)),n.push(f);else if(p===ce){for(;n.length>0;)i.push(n.shift());i.push(new L(ce,tn(f.value,e,s,r,o)))}else if(p===Et&&n.length>0)a=n.pop(),n.push(new L(me,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===Ke&&n.value===e)for(var a=0;a<s.tokens.length;a++){var c=s.tokens[a],u;c.type===rs?u=mo(c.value):c.type===os?u=We(c.value):c.type===ns?u=Au(c.value):u=new L(c.type,c.value),r.push(u)}else i===ce?r.push(new L(ce,xu(n.value,e,s))):r.push(n)}return r}function dt(t,e,s){var r=[],o,n,i,a,c,u;if(ai(t))return Ue(t,s);for(var d=t.length,h=0;h<d;h++){var f=t[h],p=f.type;if(p===me||p===mt)r.push(f.value);else if(p===os)n=r.pop(),o=r.pop(),f.value==="and"?r.push(o?!!dt(n,e,s):!1):f.value==="or"?r.push(o?!0:!!dt(n,e,s)):f.value==="="?(a=e.binaryOps[f.value],r.push(a(o,dt(n,e,s),s))):(a=e.binaryOps[f.value],r.push(a(Ue(o,s),Ue(n,s))));else if(p===ns)i=r.pop(),n=r.pop(),o=r.pop(),f.value==="?"?r.push(dt(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===Ke)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 g=s[f.value];if(g!==void 0)r.push(g);else throw new Error("undefined variable: "+f.value)}else if(p===rs)o=r.pop(),a=e.unaryOps[f.value],r.push(a(Ue(o,s)));else if(p===jt){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===po)r.push(function(){for(var v=r.pop(),E=[],_=f.value;_-- >0;)E.unshift(r.pop());var k=r.pop(),S=function(){for(var O=Object.assign({},s),N=0,ee=E.length;N<ee;N++)O[E[N]]=arguments[N];return dt(v,e,O)};return Object.defineProperty(S,"name",{value:k,writable:!1}),s[k]=S,S}());else if(p===ce)r.push(Eb(f,e));else if(p===ii)r.push(f);else if(p===Et)o=r.pop(),r.push(o[f.value]);else if(p===go)r.pop();else if(p===Bt){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 Eb(t,e,s){return ai(t)?t:{type:ii,value:function(r){return dt(t.value,e,r)}}}function ai(t){return t&&t.type===ii}function Ue(t,e){return ai(t)?t.value(e):t}function ci(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===me)typeof d.value=="number"&&d.value<0?s.push("("+d.value+")"):Array.isArray(d.value)?s.push("["+d.value.map(ma).join(", ")+"]"):s.push(ma(d.value));else if(h===os)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===ns)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===Ke||h===mt)s.push(d.value);else if(h===rs)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===jt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());i=s.pop(),s.push(i+"("+a.join(", ")+")")}else if(h===po){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===Et)r=s.pop(),s.push(r+"."+d.value);else if(h===Bt){for(c=d.value,a=[];c-- >0;)a.unshift(s.pop());s.push("["+a.join(", ")+"]")}else if(h===ce)s.push("("+ci(d.value,e)+")");else if(h!==go)throw new Error("invalid Expression")}return s.length>1&&(e?s=[s.join(",")]:s=[s.join(";")]),String(s[0])}function ma(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 li(t,e,s){s=s||{};for(var r=!!s.withMembers,o=null,n=0;n<t.length;n++){var i=t[n];i.type===Ke||i.type===mt?!r&&!At(e,i.value)?e.push(i.value):(o!==null&&(At(e,o)||e.push(o)),o=i.value):i.type===Et&&r&&o!==null?o+="."+i.value:i.type===ce?li(i.value,e,s):o!==null&&(At(e,o)||e.push(o),o=null)}o!==null&&!At(e,o)&&e.push(o)}function Oe(t,e){this.tokens=t,this.parser=e,this.unaryOps=e.unaryOps,this.binaryOps=e.binaryOps,this.ternaryOps=e.ternaryOps,this.functions=e.functions}Oe.prototype.simplify=function(t){return t=t||{},new Oe(tn(this.tokens,this.unaryOps,this.binaryOps,this.ternaryOps,t),this.parser)};Oe.prototype.substitute=function(t,e){return e instanceof Oe||(e=this.parser.parse(String(e))),new Oe(xu(this.tokens,t,e),this.parser)};Oe.prototype.evaluate=function(t){return t=t||{},dt(this.tokens,this,t)};Oe.prototype.toString=function(){return ci(this.tokens,!1)};Oe.prototype.symbols=function(t){t=t||{};var e=[];return li(this.tokens,e,t),e};Oe.prototype.variables=function(t){t=t||{};var e=[];li(this.tokens,e,t);var s=this.functions;return e.filter(function(r){return!(r in s)})};Oe.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 "+ci(this.simplify(e).tokens,!0)+"; }");return function(){return r.apply(s,arguments)}};var Fs="TEOF",j="TOP",yo="TNUMBER",Ru="TSTRING",qe="TPAREN",Ht="TBRACKET",bo="TCOMMA",ui="TNAME",di="TSEMICOLON";function Pu(t,e,s){this.type=t,this.value=e,this.index=s}Pu.prototype.toString=function(){return this.type+": "+this.value};function G(t,e){this.pos=0,this.current=null,this.unaryOps=t.unaryOps,this.binaryOps=t.binaryOps,this.ternaryOps=t.ternaryOps,this.consts=t.consts,this.expression=e,this.savedPosition=0,this.savedCurrent=null,this.options=t.options,this.parser=t}G.prototype.newToken=function(t,e,s){return new Pu(t,e,s??this.pos)};G.prototype.save=function(){this.savedPosition=this.pos,this.savedCurrent=this.current};G.prototype.restore=function(){this.pos=this.savedPosition,this.current=this.savedCurrent};G.prototype.next=function(){if(this.pos>=this.expression.length)return this.newToken(Fs,"EOF");if(this.isWhitespace()||this.isComment())return this.next();if(this.isRadixInteger()||this.isNumber()||this.isOperator()||this.isString()||this.isParen()||this.isBracket()||this.isComma()||this.isSemicolon()||this.isNamedOp()||this.isConst()||this.isName())return this.current;this.parseError('Unknown character "'+this.expression.charAt(this.pos)+'"')};G.prototype.isString=function(){var t=!1,e=this.pos,s=this.expression.charAt(e);if(s==="'"||s==='"')for(var r=this.expression.indexOf(s,e+1);r>=0&&this.pos<this.expression.length;){if(this.pos=r+1,this.expression.charAt(r-1)!=="\\"){var o=this.expression.substring(e+1,r);this.current=this.newToken(Ru,this.unescape(o),e),t=!0;break}r=this.expression.indexOf(s,r+1)}return t};G.prototype.isParen=function(){var t=this.expression.charAt(this.pos);return t==="("||t===")"?(this.current=this.newToken(qe,t),this.pos++,!0):!1};G.prototype.isBracket=function(){var t=this.expression.charAt(this.pos);return(t==="["||t==="]")&&this.isOperatorEnabled("[")?(this.current=this.newToken(Ht,t),this.pos++,!0):!1};G.prototype.isComma=function(){var t=this.expression.charAt(this.pos);return t===","?(this.current=this.newToken(bo,","),this.pos++,!0):!1};G.prototype.isSemicolon=function(){var t=this.expression.charAt(this.pos);return t===";"?(this.current=this.newToken(di,";"),this.pos++,!0):!1};G.prototype.isConst=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&s!=="."&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(r in this.consts)return this.current=this.newToken(yo,this.consts[r]),this.pos+=r.length,!0}return!1};G.prototype.isNamedOp=function(){for(var t=this.pos,e=t;e<this.expression.length;e++){var s=this.expression.charAt(e);if(s.toUpperCase()===s.toLowerCase()&&(e===this.pos||s!=="_"&&(s<"0"||s>"9")))break}if(e>t){var r=this.expression.substring(t,e);if(this.isOperatorEnabled(r)&&(r in this.binaryOps||r in this.unaryOps||r in this.ternaryOps))return this.current=this.newToken(j,r),this.pos+=r.length,!0}return!1};G.prototype.isName=function(){for(var t=this.pos,e=t,s=!1;e<this.expression.length;e++){var r=this.expression.charAt(e);if(r.toUpperCase()===r.toLowerCase()){if(e===this.pos&&(r==="$"||r==="_")){r==="_"&&(s=!0);continue}else if(e===this.pos||!s||r!=="_"&&(r<"0"||r>"9"))break}else s=!0}if(s){var o=this.expression.substring(t,e);return this.current=this.newToken(ui,o),this.pos+=o.length,!0}return!1};G.prototype.isWhitespace=function(){for(var t=!1,e=this.expression.charAt(this.pos);(e===" "||e===" "||e===`
108
- `||e==="\r")&&(t=!0,this.pos++,!(this.pos>=this.expression.length));)e=this.expression.charAt(this.pos);return t};var Mb=/^[0-9a-f]{4}$/i;G.prototype.unescape=function(t){var e=t.indexOf("\\");if(e<0)return t;for(var s=t.substring(0,e);e>=0;){var r=t.charAt(++e);switch(r){case"'":s+="'";break;case'"':s+='"';break;case"\\":s+="\\";break;case"/":s+="/";break;case"b":s+="\b";break;case"f":s+="\f";break;case"n":s+=`
109
- `;break;case"r":s+="\r";break;case"t":s+=" ";break;case"u":var o=t.substring(e+1,e+5);Mb.test(o)||this.parseError("Illegal escape sequence: \\u"+o),s+=String.fromCharCode(parseInt(o,16)),e+=4;break;default:throw this.parseError('Illegal escape sequence: "\\'+r+'"')}++e;var n=t.indexOf("\\",e);s+=t.substring(e,n<0?t.length:n),e=n}return s};G.prototype.isComment=function(){var t=this.expression.charAt(this.pos);return t==="/"&&this.expression.charAt(this.pos+1)==="*"?(this.pos=this.expression.indexOf("*/",this.pos)+2,this.pos===1&&(this.pos=this.expression.length),!0):!1};G.prototype.isRadixInteger=function(){var t=this.pos;if(t>=this.expression.length-2||this.expression.charAt(t)!=="0")return!1;++t;var e,s;if(this.expression.charAt(t)==="x")e=16,s=/^[0-9a-f]$/i,++t;else if(this.expression.charAt(t)==="b")e=2,s=/^[01]$/i,++t;else return!1;for(var r=!1,o=t;t<this.expression.length;){var n=this.expression.charAt(t);if(s.test(n))t++,r=!0;else break}return r&&(this.current=this.newToken(yo,parseInt(this.expression.substring(o,t),e)),this.pos=t),r};G.prototype.isNumber=function(){for(var t=!1,e=this.pos,s=e,r=e,o=!1,n=!1,i;e<this.expression.length&&(i=this.expression.charAt(e),i>="0"&&i<="9"||!o&&i===".");)i==="."?o=!0:n=!0,e++,t=n;if(t&&(r=e),i==="e"||i==="E"){e++;for(var a=!0,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(yo,parseFloat(this.expression.substring(s,e))),this.pos=e):this.pos=r,t};G.prototype.isOperator=function(){var t=this.pos,e=this.expression.charAt(this.pos);if(e==="+"||e==="-"||e==="*"||e==="/"||e==="%"||e==="^"||e==="?"||e===":"||e===".")this.current=this.newToken(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)};G.prototype.isOperatorEnabled=function(t){return this.parser.isOperatorEnabled(t)};G.prototype.getCoordinates=function(){var t=0,e,s=-1;do t++,e=this.pos-s,s=this.expression.indexOf(`
110
- `,s+1);while(s>=0&&s<this.pos);return{line:t,column:e}};G.prototype.parseError=function(t){var e=this.getCoordinates();throw new Error("parse error ["+e.line+":"+e.column+"]: "+t)};function 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(ui)||this.accept(j,s))t.push(new L(Ke,this.current.value));else if(this.accept(yo))t.push(new L(me,this.current.value));else if(this.accept(Ru))t.push(new L(me,this.current.value));else if(this.accept(qe,"("))this.parseExpression(t),this.expect(qe,")");else if(this.accept(Ht,"["))if(this.accept(Ht,"]"))t.push(new L(Bt,0));else{var r=this.parseArrayList(t);t.push(new L(Bt,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(di)?(this.nextToken&&this.nextToken.type!==Fs&&!(this.nextToken.type===qe&&this.nextToken.value===")")&&e.push(new L(go)),this.nextToken.type!==Fs&&this.parseExpression(e),t.push(new L(ce,e)),!0):!1};q.prototype.parseArrayList=function(t){for(var e=0;!this.accept(Ht,"]");)for(this.parseExpression(t),++e;this.accept(bo);)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===jt){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===Ke&&(t[i]=new L(mt,t[i].value))}this.parseVariableAssignmentExpression(s),t.push(new L(ce,s)),t.push(new L(po,e.value));continue}if(e.type!==Ke&&e.type!==Et)throw new Error("expected variable for assignment");this.parseVariableAssignmentExpression(s),t.push(new L(mt,e.value)),t.push(new L(ce,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 L(ce,e)),t.push(new L(ce,s)),t.push(Au("?"))}};q.prototype.parseOrExpression=function(t){for(this.parseAndExpression(t);this.accept(j,"or");){var e=[];this.parseAndExpression(e),t.push(new L(ce,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 L(ce,e)),t.push(We("and"))}};var Tb=["==","!=","<","<=",">=",">","in"];q.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,Tb);){var e=this.current;this.parseAddSub(t),t.push(We(e.value))}};var _b=["+","-","||"];q.prototype.parseAddSub=function(t){for(this.parseTerm(t);this.accept(j,_b);){var e=this.current;this.parseTerm(t),t.push(We(e.value))}};var Sb=["*","/","%"];q.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,Sb);){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===di||this.nextToken.type===bo||this.nextToken.type===Fs||this.nextToken.type===qe&&this.nextToken.value===")"){this.restore(),this.parseAtom(t);return}}var r=this.current;this.parseFactor(t),t.push(mo(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(mo("!"))};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(mo(r.value))}else for(this.parseMemberExpression(t);this.accept(qe,"(");)if(this.accept(qe,")"))t.push(new L(jt,0));else{var o=this.parseArgumentList(t);t.push(new L(jt,o))}};q.prototype.parseArgumentList=function(t){for(var e=0;!this.accept(qe,")");)for(this.parseExpression(t),++e;this.accept(bo);)this.parseExpression(t),++e;return e};q.prototype.parseMemberExpression=function(t){for(this.parseAtom(t);this.accept(j,".")||this.accept(Ht,"[");){var e=this.current;if(e.value==="."){if(!this.allowMemberAccess)throw new Error('unexpected ".", member access is not permitted');this.expect(ui),t.push(new L(Et,this.current.value))}else if(e.value==="["){if(!this.tokens.isOperatorEnabled("["))throw new Error('unexpected "[]", arrays are disabled');this.parseExpression(t),this.expect(Ht,"]"),t.push(We("["))}else throw new Error("unexpected symbol: "+e.value)}};function Ob(t,e){return Number(t)+Number(e)}function Ib(t,e){return t-e}function $b(t,e){return t*e}function Cb(t,e){return t/e}function Db(t,e){return t%e}function Ab(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+t+e}function xb(t,e){return t===e}function Rb(t,e){return t!==e}function Pb(t,e){return t>e}function kb(t,e){return t<e}function Lb(t,e){return t>=e}function Fb(t,e){return t<=e}function Nb(t,e){return!!(t&&e)}function Ub(t,e){return!!(t||e)}function jb(t,e){return At(e,t)}function Bb(t){return(Math.exp(t)-Math.exp(-t))/2}function Hb(t){return(Math.exp(t)+Math.exp(-t))/2}function Kb(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function qb(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function zb(t){return Math.log(t+Math.sqrt(t*t-1))}function Vb(t){return Math.log((1+t)/(1-t))/2}function ya(t){return Math.log(t)*Math.LOG10E}function Gb(t){return-t}function Yb(t){return!t}function Wb(t){return t<0?Math.ceil(t):Math.floor(t)}function Qb(t){return Math.random()*(t||1)}function ba(t){return hi(t+1)}function Zb(t){return isFinite(t)&&t===Math.round(t)}var Xb=4.7421875,Uo=[.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 hi(t){var e,s;if(Zb(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)*hi(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=Uo[0];for(var u=1;u<Uo.length;++u)s+=Uo[u]/(t+u);return e=t+Xb+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function Jb(t){return Array.isArray(t)?t.length:String(t).length}function va(){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 wa(t,e,s){return t?e:s}function ev(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 tv(t,e,s){return s&&(s[t]=e),e}function sv(t,e){return t[e|0]}function rv(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function ov(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function nv(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 iv(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 av(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 cv(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 lv(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function uv(t){return(t>0)-(t<0)||+t}var Ea=1/3;function dv(t){return t<0?-Math.pow(-t,Ea):Math.pow(t,Ea)}function hv(t){return Math.exp(t)-1}function fv(t){return Math.log(1+t)}function pv(t){return Math.log(t)/Math.LN2}function Mt(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||Bb,cosh:Math.cosh||Hb,tanh:Math.tanh||Kb,asinh:Math.asinh||qb,acosh:Math.acosh||zb,atanh:Math.atanh||Vb,sqrt:Math.sqrt,cbrt:Math.cbrt||dv,log:Math.log,log2:Math.log2||pv,ln:Math.log,lg:Math.log10||ya,log10:Math.log10||ya,expm1:Math.expm1||hv,log1p:Math.log1p||fv,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||Wb,"-":Gb,"+":Number,exp:Math.exp,not:Yb,length:Jb,"!":ba,sign:Math.sign||uv},this.binaryOps={"+":Ob,"-":Ib,"*":$b,"/":Cb,"%":Db,"^":Math.pow,"||":Ab,"==":xb,"!=":Rb,">":Pb,"<":kb,">=":Lb,"<=":Fb,and:Nb,or:Ub,in:jb,"=":tv,"[":sv},this.ternaryOps={"?":wa},this.functions={random:Qb,fac:ba,min:ov,max:rv,hypot:Math.hypot||va,pyt:Math.hypot||va,pow:Math.pow,atan2:Math.atan2,if:wa,gamma:hi,roundTo:ev,map:nv,fold:iv,filter:av,indexOf:cv,join:lv},this.consts={E:Math.E,PI:Math.PI,true:!0,false:!1}}Mt.prototype.parse=function(t){var e=[],s=new q(this,new G(this,t),{allowMemberAccess:this.options.allowMemberAccess});return s.parseExpression(e),s.expect(Fs,"EOF"),new Oe(e,this)};Mt.prototype.evaluate=function(t,e){return this.parse(t).evaluate(e)};var ku=new Mt;Mt.parse=function(t){return ku.parse(t)};Mt.evaluate=function(t,e){return ku.parse(t).evaluate(e)};var Ma={"+":"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 gv(t){return Ma.hasOwnProperty(t)?Ma[t]:t}Mt.prototype.isOperatorEnabled=function(t){var e=gv(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var mv=Object.defineProperty,yv=Object.getOwnPropertyDescriptor,bv=(t,e,s)=>e in t?mv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,vv=(t,e,s,r)=>{for(var o=r>1?void 0:r?yv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},wv=(t,e,s)=>(bv(t,e+"",s),s);const Ev="kos-expression-evaluator-model";class Mv{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 Dr=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=Re(),this._results=Re(),this.parser=new Mt,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 Mv(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=vt();return this.addExpression(e,t),e}};wv(Dr,"Registration");Dr=vv([P({modelTypeId:Ev,singleton:!1})],Dr);const Lu=Dr.Registration,Tv=m.createLogger({name:"kos-log-manager-service",group:"Services"}),_v="/api/kos/logs/overrides",Fu=async()=>(Tv.debug("sending GET for kos-log-manager"),await Ne.get(_v)),Sv=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:Fu},Symbol.toStringTag,{value:"Module"}));var Ov=Object.defineProperty,Iv=Object.getOwnPropertyDescriptor,vo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Iv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Ov(e,s,o),o};const Nu="kos-log-manager-model",$v="/kos/logs/override/add/*",Cv="/kos/logs/override/remove/*",Dv=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 Kt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_overrides");this.id=t,this.logger=s.logger,this._overrides=new pi}updateModel(t){}resolveLoggers(){const t=m.getLoggers(),s=Object.entries(t).map(([r,o])=>({name:r,level:Dv(o.getLevel())})).reduce((r,{name:o,level:n})=>(r[o]={name:o,level:n},r),{});return this.logger.debug("Resolved loggers",s),s}async getAllLoggers(t,e){const s=Object.values(this.resolveLoggers());return e==null||e.send(s),s}setLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=m.getLoggers()[r.name];if(!o){this.logger.debug(`Logger ${r.name} not found`);return}o.setLevel(t.level)});const s=m.getLoggers()[t.name];if(!s){this.logger.debug(`Logger ${t.name} not found`);return}s.setLevel(t.level),globalThis.kos.logOverrides=this._overrides.data}resetLogLevels(t){Object.values(this.resolveLoggers()).filter(r=>r.name.startsWith(t.name)).forEach(r=>{const o=m.getLoggers()[r.name];o||this.logger.debug(`Logger ${r.name} not found`),o==null||o.resetLevel()});const s=m.getLoggers()[t.name];s||this.logger.debug(`Logger ${t.name} not found`),s==null||s.resetLevel(),globalThis.kos.logOverrides=this._overrides.data}handleOverrideAdded(t,e){var s;this.logger.debug(`Override received for node type ${((s=e.wildcardCapture)==null?void 0:s.nodeType)??"unknown"}`),this._overrides.addModel({...t,id:t.name}),this.setLogLevels(t)}handleOverrideRemoved(t){this._overrides.removeModel(t.name),this.resetLogLevels(t)}async init(){this.logger.debug(`initializing kos-log-manager ${this.id}`)}async load(){this.logger.debug(`loading kos-log-manager ${this.id}`),this.resolveLoggers();const[t,e]=await Fu();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)})}};vo([xc("/api/kos/ui/loggers")],Kt.prototype,"getAllLoggers",1);vo([B({topic:$v,websocket:!0,wildcardName:"nodeType"})],Kt.prototype,"handleOverrideAdded",1);vo([B({topic:Cv,websocket:!0,wildcardName:"nodeType"})],Kt.prototype,"handleOverrideRemoved",1);Kt=vo([P(Nu)],Kt);const Uu=new Ce({class:Kt,type:Nu}),{URL:Zs}=ue(),{postModel:fi,getOne:Av}=ie.build({basePath:`${Zs}/api/kos-time`});m.createLogger({name:"kos-time-service",group:"Services"});const ju=async t=>{const e=await fi({model:t,urlOverride:`${Zs}/api/kos/time/time`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Bu=async t=>{const e=await fi({model:t,urlOverride:`${Zs}/api/kos/time/date`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set time");return e.data},Hu=async t=>{const e=await fi({model:{},urlOverride:`${Zs}/api/kos/time/timezone?tz=${t}`});if((e==null?void 0:e.status)!==200)throw Error("Failed to set timezone");return e.data},Ku=async()=>{const t=await Av({urlOverride:`${Zs}/api/kos/time/timezone`});if((t==null?void 0:t.status)!==200)throw Error("Failed to set timezone");return t.data.timeZone},xv=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:Ku,setDate:Bu,setTime:ju,setTimezone:Hu},Symbol.toStringTag,{value:"Module"}));var Rv=Object.defineProperty,Pv=Object.getOwnPropertyDescriptor,wo=(t,e,s,r)=>{for(var o=r>1?void 0:r?Pv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Rv(e,s,o),o};const hs="kos-time-model",kv="/kos/time/time",Lv="/kos/time/day",Fv="/kos/time/timezone";let qt=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 ju(t)}async updateSystemDate(t){await Bu(t)}async updateSystemTimezone(t){await Hu(t)}handleTimeChange(){K($s.TIME_CHANGE,{})}handleDayChange(){K($s.DAY_CHANGE,{})}async handleTimeZoneChange(){await this.retrieveTimezone(),K($s.TIMEZONE_CHANGE,{})}async init(){this.logger.debug(`initializing kos-time ${this.id}`)}async retrieveTimezone(){const t=await Ku();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};wo([B({topic:kv,websocket:!0})],qt.prototype,"handleTimeChange",1);wo([B({topic:Lv,websocket:!0})],qt.prototype,"handleDayChange",1);wo([B({topic:Fv,websocket:!0})],qt.prototype,"handleTimeZoneChange",1);qt=wo([P(hs)],qt);const Ar={registration:{[hs]:{class:qt,singleton:!0}},type:hs,predicate:$e(hs),factory:le.Singleton.create(hs)};var Nv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,qu=(t,e,s,r)=>{for(var o=r>1?void 0:r?Uv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Nv(e,s,o),o};const zu="log-block-container-model";let xr=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}`)}};qu([Le],xr.prototype,"_models",2);xr=qu([P(zu)],xr);const jv=m.createLogger({name:"log-stream-container-service",group:"Services"}),Vu=()=>{var r;const t=be(),s=(t==null?void 0:t.connId)||((r=window==null?void 0:window.kosBridge)==null?void 0:r.call(window,"connId"));return m.error(`getKosConnectionId: ${s}`),s},is=Vu(),Bv="/api/kos/logs/node/{nodeId}/streams",Gu=async()=>(jv.debug("sending GET for log-stream-container"),await Ne.get(Bv,{path:{nodeId:"primary"}},{destinationAddress:is})),Yu=async(t,e="primary")=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:is})},Wu=async t=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:is})},Hv=async()=>{await Ne.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:is})},Qu=async t=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:is}),Zu=async(t,e)=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:is}),Kv=Object.freeze(Object.defineProperty({__proto__:null,createOverride:Hv,getKosConnectionId:Vu,getLogStreamBlock:Zu,getLogStreamBlocks:Qu,getLogStreams:Gu,subscribeToLogStream:Yu,unsubscribeFromLogStream:Wu},Symbol.toStringTag,{value:"Module"}));var qv=Object.getOwnPropertyDescriptor,zv=(t,e,s,r)=>{for(var o=r>1?void 0:r?qv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Xu="log-block-model";let sn=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 Zu(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}`)}};sn=zv([P(Xu)],sn);const Ns=new ve({class:sn,type:Xu}),Eo=new ve({class:xr,type:zu});Eo.addRelatedModel(Ns);var Vv=Object.defineProperty,Gv=Object.getOwnPropertyDescriptor,Ju=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Vv(e,s,o),o};const ed="log-stream-model";let Rr=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=Eo.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=Ns.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=Ns.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 Yu(this.name)}async unsubscribe(){await Wu(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 Qu(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=ch(()=>{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()}}};Ju([Le],Rr.prototype,"_blocks",2);Rr=Ju([P(ed)],Rr);const Cs=new ve({class:Rr,type:ed});var Yv=Object.defineProperty,Wv=Object.getOwnPropertyDescriptor,Tt=(t,e,s,r)=>{for(var o=r>1?void 0:r?Wv(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&&Yv(e,s,o),o};const td="log-stream-container-model",Qv="/kos/logs/subscription/addBlock/*",Zv="/kos/logs/subscription/updateBlock/*",Xv="/kos/logs/subscription/removeBlock/*",Jv="/kos/logs/subscription/lines/*",sd="/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: ${sd}`);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 Gu();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([Le],ze.prototype,"_models",2);Tt([B({topic:[sd],websocket:!0})],ze.prototype,"handleStreamAdded",1);Tt([B({topic:[Qv],websocket:!0})],ze.prototype,"handleAddBlock",1);Tt([B({topic:[Xv],websocket:!0})],ze.prototype,"handleRemoveBlock",1);Tt([B({topic:[Zv],websocket:!0})],ze.prototype,"handleUpdateBlock",1);Tt([B({topic:[Jv],websocket:!0})],ze.prototype,"handleLogLine",1);ze=Tt([P(td)],ze);const Xs=new Ce({class:ze,type:td});Xs.addRelatedModel(Cs);Xs.addRelatedModel(Eo);Xs.addRelatedModel(Ns);const at=m.createLogger({name:"kos-data-container"});class pi{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=M.observable.map(new Map),this._sortKey=e==null?void 0:e.sortKey,this._revision=1,this._optionsMap=(e==null?void 0:e.indexMap)||{};const s=e!=null&&e.indexMap?Object.keys(e.indexMap).reduce((r,o)=>(r[o]=void 0,r),{}):{};this._index=M.observable.map(s),this.idx=Re(),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=M.observable.map(new Map)),M.makeAutoObservable(this,{}),this.init()}init(){Object.keys(this._optionsMap).forEach(e=>{const s=this._optionsMap[e],r=new kn({container:this,key:s});this._index.set(e,r),this.idx[e]=r.data})}[Symbol.iterator](){return this.data[Symbol.iterator]()}get index(){return this._index}get indexKeys(){return Array.from(this.index.keys()).reduce((e,s)=>{var r;return e[s]=(r=this.index.get(s))==null?void 0:r.keys,e},{})}get revision(){return this._revision}addAll(e){M.runInAction(()=>{e.forEach(s=>this.addModel(s))})}removeAll(e){M.runInAction(()=>{e.forEach(s=>this.removeModel(s))})}sortFn(e,s){const r=this._sortKey;return r?String(e[r]).localeCompare(String(s[r]),void 0,{numeric:!0}):0}get data(){const e=Array.from(this._data.values());return this._sortKey&&e.sort(this.sortFn.bind(this)),e}increment(){M.runInAction(()=>{this._revision=this._revision+1})}addModel(e,s){const r=this._ensureObservable(e);this._cleanupExistingDisposer(e.id),this._persistData(r),this._trackDataMetadata(r),this._enforceCapacityLimits(),this._configureDataMonitoring(r),s||this.increment()}_ensureObservable(e){return M.isObservable(e)?e:M.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=M.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=M.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??[]:(at.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):(at.info(`key ${s} not found in ${e} index: ${Array.from(r.index.keys())}`),[])}else return at.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){at.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):(at.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);at.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){at.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}))}}}const ew=t=>t.rank!==void 0,tw=t=>t.visibleRole!==void 0,sw=t=>t.color!==void 0,rw=t=>{const e=t.info??{};return ew(e)?e.rank:0},ow=t=>{const e=t.info??{};return sw(e)?e.color:"orange"},nw=t=>{const e=t.info??{};return tw(e)?e.visibleRole:"TECHNICIAN"},{URL:Mo}=ue(),{getAll:iw,postModel:rd}=ie.build({basePath:`${Mo}/api/kos/troubles`}),od=async t=>await iw({urlOverride:`${Mo}${t}`}),nd=async(t,e="/api/kos/troubles",s)=>{try{const r=await rd({model:{},urlOverride:`${Mo}${e}/resolve/${t}`,tracker:s});return r!=null&&r.data&&gt.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:et.Fail,tracker:s,reason:"Failed to resolve trouble"};return gt.initiateFuture(o),o}},aw=async(t,e="/api/kos/troubles",s)=>{try{const r=await rd({model:t,urlOverride:`${Mo}${e}/resolve/`,tracker:s});return r!=null&&r.data&&gt.initiateFuture(r.data),r.data}catch{const o={id:s||"",endState:et.Fail,tracker:s,reason:"Failed to resolve troubles"};return gt.initiateFuture(o),o}},cw=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:aw,getTroubles:od,resolveTrouble:nd},Symbol.toStringTag,{value:"Module"})),Pr="troubleDataMapper",lr=new Map;Ys(Pr,{register:(t,e)=>{var s;lr.has(t)||lr.set(t,[]),(s=lr.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=lr.get(t);if(!s)return{...e.data};const r=s.map(i=>i(e));return(await Promise.allSettled(r)).reduce((i,a)=>(a.status==="fulfilled"?i={...i,...a.value}:m.info(`Trouble mapper ${t} failed: ${a.reason}`),i),{...e.data})}});const Js="troubleMapper",ur=new Map;Ys(Js,{register:(t,e)=>{var s;ur.has(t)||ur.set(t,[]),(s=ur.get(t))==null||s.push(e)},execute:async(t,e)=>{const s=ur.get(t);if(!s)return[];const r=s.map(i=>i(e)),n=(await Promise.allSettled(r)).map(i=>i.status==="fulfilled"?i.value:(m.info(`Trouble mapper ${t} failed: ${i.reason}`),[])).flat();return Array.from(new Set(n))}});$[Js].register("nozzle",async t=>[t.data.nozzlePath]);$[Js].register("path",async t=>[t.data.path]);const lw=async t=>{const e=new Set,s=t.ifaces,r=s==null?void 0:s.map(n=>$[Js].execute(n,t));return(await Promise.allSettled(r)).forEach(n=>{n.status==="fulfilled"&&n.value.forEach(i=>e.add(i))}),Array.from(e)},id=async t=>{const e=t.ifaces,s=e==null?void 0:e.map(i=>$[Pr].execute(i,t)),r=$[Pr].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 uw{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class dw{constructor(){l(this,"type","BlockPumpTrouble");l(this,"title","Block Pump Trouble");l(this,"subtitle","Trouble")}}class $t{static getHandler(e){switch(e){case"ResolvableTrouble":return new uw;case"BlockPumpTrouble":return new dw;default:return}}}var hw=Object.defineProperty,fw=Object.getOwnPropertyDescriptor,ad=(t,e,s,r)=>{for(var o=r>1?void 0:r?fw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&hw(e,s,o),o};const fs="trouble-model";function dr(t){return typeof t.shouldDefer=="boolean"}let kr=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,...g},v){l(this,"id");l(this,"logger");l(this,"_troubleId");l(this,"_resolvable");l(this,"type");l(this,"futureHandler");l(this,"ifaces");l(this,"clientData");l(this,"info");l(this,"role");l(this,"color");l(this,"tags");l(this,"data");l(this,"rank");l(this,"servicePath");l(this,"group");l(this,"createTime");l(this,"_mapped",{});this.id=t,this.logger=v.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.servicePath=p??"/api/kos/troubles",this.createTime=d,this.clientData=n,this.data={},Object.assign(this.data,g),this.futureHandler=new lo(this)}getTitleWithContext(t){var s,r;const e=t?(r=(s=$t.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:$t.getHandler(this.type);return(e==null?void 0:e.title)||"Trouble"}getSubtitleWithContext(t){var s,r;const e=t?(r=(s=$t.getHandler(this.type))==null?void 0:s.context)==null?void 0:r[t]:$t.getHandler(this.type);return(e==null?void 0:e.subtitle)||"Trouble"}get rawId(){return this._troubleId}get title(){var t;return((t=$t.getHandler(this.type))==null?void 0:t.title)||"Trouble"}get subtitle(){var t;return((t=$t.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 id(this)}get deferredCompanion(){const t=Yo(this.id,e=>dr(e));if(t&&dr(t.modelData))return t.modelData}get deferred(){return this.deferredCompanion?this.deferredCompanion.deferred:!1}get shouldDefer(){const t=Yo(this.id,e=>dr(e));return t&&dr(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 nd(this._troubleId,this.servicePath,t)}};ad([Ri()],kr.prototype,"resolve",1);kr=ad([P(fs)],kr);const Us={registration:{[fs]:{class:kr,singleton:!1}},type:fs,predicate:$e(fs),factory:le.Factory.create(fs)};var cd=Object.defineProperty,pw=Object.getOwnPropertyDescriptor,gw=(t,e,s)=>e in t?cd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,gi=(t,e,s,r)=>{for(var o=r>1?void 0:r?pw(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},mw=(t,e,s)=>(gw(t,e+"",s),s);function Ta(t){return $.propertyMapper.hasMapper(Se.TroubleRank)?$.propertyMapper.executeMapper(Se.TroubleRank,t):rw(t)}function _a(t){return($.propertyMapper.hasMapper(Se.TroubleColor)?$.propertyMapper.executeMapper(Se.TroubleColor,t):ow(t)).toLowerCase()}function Sa(t){return($.propertyMapper.hasMapper(Se.TroubleRole)?$.propertyMapper.executeMapper(Se.TroubleRole,t):nw(t)).toLowerCase()}const yw="trouble-container-model";class ye{}l(ye,"INDEX_TROUBLES_BY_IFACE","byIface"),l(ye,"INDEX_TROUBLES_BY_TYPE","byType"),l(ye,"INDEX_TROUBLES_BY_GROUP","byGroup"),l(ye,"INDEX_TROUBLES_BY_DEFERRED","byDeferred"),l(ye,"SORT_KEY_RANK","rank"),l(ye,"TROUBLES_DEFERRED","true");let zt=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");const t=await od(this.servicePath);try{t==null||t.data.forEach(e=>{const s={...e,servicePath:this.servicePath,rank:Ta(e),color:_a(e),role:Sa(e),id:String(e.id)},r=Us.factory(`trouble-${e.id}`)(s);this.troubles.addModel(r)})}catch(e){throw this.logger.error(e),e}}handleTroubleRemoved(t){const e=`trouble-${t}`,s=this.troubles.getModel(e);this.troubles.removeModel(e),s&&Ae(s)}handleTroubleAdded(t){const e={...t,servicePath:this.servicePath,rank:Ta(t),color:_a(t),role:Sa(t),id:String(t.id)};if(e.role==="NONE")return;const s=Us.factory(`trouble-${t.id}`)(e);this.troubles.addModel(s)}};mw(zt,"Registration");gi([B({topic:"/kos/trouble/remove",websocket:!0,lifecycle:D.INIT})],zt.prototype,"handleTroubleRemoved",1);gi([B({topic:"/kos/trouble/add",websocket:!0})],zt.prototype,"handleTroubleAdded",1);zt=gi([P({modelTypeId:yw,singleton:!0}),kc(),Ac({containerProperty:"troubles",containerOptions:{indexMap:{[ye.INDEX_TROUBLES_BY_IFACE]:lw,[ye.INDEX_TROUBLES_BY_TYPE]:"type",[ye.INDEX_TROUBLES_BY_GROUP]:"group",[ye.INDEX_TROUBLES_BY_DEFERRED]:"deferred"},sortKey:ye.SORT_KEY_RANK}})],zt);const Vt=zt.Registration,{URL:ld}=ue(),{getAll:bw}=ie.build({basePath:`${ld}/api/kos/ota`}),Oa=m.createLogger({name:"ota-service",group:"Services"}),vw=async()=>{Oa.debug("sending GET request to /api/kos/ota/artifacts");const t=await bw({urlOverride:`${ld}/api/kos/ota/artifacts`});return Oa.debug("getArtifacts - response:",t),t==null?void 0:t.data};var ww=Object.defineProperty,Ew=Object.getOwnPropertyDescriptor,To=(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=(r?i(e,s,o):i(o))||o);return r&&o&&ww(e,s,o),o};const ud="ota-model",Mw=t=>{let e=null;for(const s in t){const r=t[s],o=r.lastUpdateTime;(!e||e.lastUpdateTime<o)&&(e=r)}return e},jo=t=>{const e=t.artifactInfo,s=Mw(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 Gt=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"data",new pi);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 vw();t&&t.forEach(e=>{const s=jo(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=jo(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=jo(e);s&&this.data.updateModel(s)})}catch(e){this.logger.error(`handleChangedArtifacts ${this.id} - error:`,e)}}};To([Jt({modelType:Vt.type})],Gt.prototype,"troubleContainer",2);To([B({topic:"/kos/ota/artifacts/all",websocket:!0})],Gt.prototype,"handleAllArtifacts",1);To([B({topic:"/kos/ota/artifacts/changed",websocket:!0})],Gt.prototype,"handleChangedArtifacts",1);Gt=To([P(ud)],Gt);const Lr=new Ce({class:Gt,type:ud});function Tw(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 Bo=m.createLogger({name:"software-info-service",group:"Services"}),mi=async t=>{Bo.debug("sending GET for software-info");const[e,s]=await iu.get("/api/kos/manifest/info",void 0,{signal:t});if(!s)throw t!=null&&t.aborted?(Bo.debug("Request was aborted"),new z("Request was aborted")):(Bo.error("Failed to fetch software-info",e),new z("Failed to fetch software-info"));return s},_w=Tw(mi),Sw=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:mi,getSoftwareInfosWithCancel:_w},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 ps="software-info-model";let rn=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 mi(),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)}}};rn=Iw([P(ps)],rn);const Fr={registration:{[ps]:{class:rn,singleton:!1}},type:ps,predicate:$e(ps),factory:le.Factory.create(ps)},{URL:dd}=ue(),{getOne:$w}=ie.build({basePath:`${dd}/api/kos/state`}),Cw=m.createLogger({name:"state-bean-service",group:"Services"}),hd=async({path:t})=>(Cw.debug("sending GET for state-bean"),await $w({urlOverride:`${dd}/api/kos/state/${t}`})),Dw=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:hd},Symbol.toStringTag,{value:"Module"}));var Aw=Object.defineProperty,xw=Object.getOwnPropertyDescriptor,fd=(t,e,s,r)=>{for(var o=r>1?void 0:r?xw(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 gs="state-bean-model",Rw=yt("path");let Nr=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=Li.map(new Map),Jo(e,this)}updateModel(t){Jo(t,this)}handleConfigBeanUpdated(t){Object.entries(t).forEach(([e,s])=>{let r=s;typeof r=="string"&&Zn(r)&&(r=r.toLowerCase()=="true"),typeof r=="string"&&ho(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 hd({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};fd([B({topic:`/kos/state/${Rw}`,websocket:!0})],Nr.prototype,"handleConfigBeanUpdated",1);Nr=fd([P(gs)],Nr);const js={registration:{[gs]:{class:Nr,singleton:!1}},type:gs,predicate:$e(gs),factory:le.Factory.create(gs)};var Pw=Object.defineProperty,kw=Object.getOwnPropertyDescriptor,pd=(t,e,s,r)=>{for(var o=r>1?void 0:r?kw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Pw(e,s,o),o};const ms="state-prop-model",Ia=yt("path");let Ur=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())??""}};pd([Jt({modelType:js.type,id:`state-bean-${Ia}`,options:{path:Ia}})],Ur.prototype,"stateBean",2);Ur=pd([P(ms)],Ur);const yi={registration:{[ms]:{class:Ur,singleton:!1}},type:ms,predicate:$e(ms),factory:le.Factory.create(ms)},{URL:Lw}=ue(),{getAll:Fw}=ie.build({basePath:`${Lw}/api/state-prop`}),Nw=m.createLogger({name:"state-prop-service",group:"Services"}),Uw=async()=>(Nw.debug("sending GET for state-prop"),await Fw({})),jw=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:Uw},Symbol.toStringTag,{value:"Module"})),{URL:bi}=ue(),{getOne:gd}=ie.build({basePath:`${bi}/api/translation`}),Ds=m.createLogger({name:"translation-service",group:"Services"}),Bw=()=>{const t=window.location.origin,e=be();return(e==null?void 0:e.host)||t},md=async(t,e)=>{Ds.debug(`Loading translations from: ${t}`);const s=e??Bw();try{const r=await fetch(`${s}${t}`);return r.status!==200?(Ds.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw Ds.error("Error fetching translations",r),r}},Hw=async()=>{Ds.debug("Getting system localization descriptor");const t=await gd({urlOverride:`${bi}/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},yd=t=>async()=>{Ds.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await gd({urlOverride:`${bi}/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]},bd="langResolver";var Kw=Object.getOwnPropertyDescriptor,qw=(t,e,s,r)=>{for(var o=r>1?void 0:r?Kw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const ys="translation-model";function zw(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 vd(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=vd(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function wd(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]=wd(t[r],e[r]):s[r]=e[r]);return s}const on=(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)?on(r,e):r},hr=(t,e,s)=>{const r=/{{(.*?)}}/g,n=on(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 on(n,e)},$a=(t,e)=>{if(e.includes(":")){const[s,r]=e.split(":");return{namespace:s,key:r}}else return{namespace:t,key:e}};let nn=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(bd),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=W.getContext(this.id);return this.bundleResolver(this.namespace,r,o)}try{const o=this.resolver(this.namespace,r);return md(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=wd(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=vd(r)})}async init(){this.logger.debug(`initializing translation ${this.id}`)}exists(t){const{namespace:e,key:s}=$a(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}=zw(e),{namespace:n,key:i}=$a(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=>hr(u,this.data,o)):hr(this.data[a],this.data,o)}if(this.data[i]){const c=this.data[i];return Array.isArray(c)?c.map(u=>hr(u,this.data,o)):hr(this.data[i],this.data,o)}return s??i}unload(){this.logger.debug(`unloading translation ${this.id}`),this.disposer&&this.disposer()}async load(){this.logger.debug(`loading translation ${this.id}`),await this.loadTranslations()}async ready(){this.logger.debug(`ready translation ${this.id}`),this.disposer=M.reaction(()=>this.currentLocale,(t,e)=>{this.logger.info(`translation langs for namespace ${this.id} changed from ${e} to ${t}`),this.loadTranslations()})}};nn=qw([io(),P(ys)],nn);const jr={registration:{[ys]:{class:nn,singleton:!1}},type:ys,predicate:$e(ys),factory:le.Factory.create(ys)};var Vw=Object.defineProperty,Gw=Object.getOwnPropertyDescriptor,Ed=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Vw(e,s,o),o};const bs="translation-container-model",Yw=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function Ww(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 Yw([r,o])}let Br=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||Ww.bind(this),s.kosContext.set(bd,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 pe(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=jr.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=jr.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)}};Ed([Le],Br.prototype,"_models",2);Br=Ed([P(bs)],Br);const Ve={registration:{[bs]:{class:Br,singleton:!0}},type:bs,predicate:$e(bs),factory:le.Singleton.create(bs)},Qw={set(t,e){const s=W.getContext(Ve.type);s&&s.set(t,e)},get(t){const e=W.getContext(Ve.type);return e==null?void 0:e.get(t)}},Md={async init(t){const e=Ve.factory(t);return await pe(e),{translations:e}}};function Zw(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 Td="kos-ws-event",vi=es(Td);var Xw=Object.defineProperty,Jw=Object.getOwnPropertyDescriptor,wi=(t,e,s,r)=>{for(var o=r>1?void 0:r?Jw(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 eE=({headers:t,body:e})=>Object.entries(t).map(([r,o])=>`${r}:${o}`).join("\\n")+"\\n\\n"+e;exports.WsEventModel=class{constructor(e){l(this,"id");l(this,"events");l(this,"_topicMap");this.id=e,this.events=M.observable.map(new Map),this._topicMap=new Map}get websocketEvents(){return Array.from(this.events.values())}handleSendEvent(e,s){this.processEvent(s,!0)}handleReceiveEvent(e,s){this.processEvent(s)}processEvent(e,s=!1){m.debug("kos event received");const{body:r,headers:o}=e.body,n=o["request-id"]||o["response-id"],i=o["request-id"]||o["response-id"]||o.topic||o.type;if(i){let a=i;if(n)a=`${a}-${s?"send":"receive"}`;else{const u=this._topicMap.get(i)||0;a=`${a}-${u+1}`,this._topicMap.set(i,u+1)}const c={msgId:a,content:r,headers:o,timestamp:Date.now(),raw:eE({headers:o,body:r}),direction:s?"send":"receive",mocked:!!o.mocked};this.events.set(a,c),m.debug(`logged ${this.events.size} events`)}}};wi([B({topic:[zs.SEND]})],exports.WsEventModel.prototype,"handleSendEvent",1);wi([B({topic:[zs.RECEIVED]})],exports.WsEventModel.prototype,"handleReceiveEvent",1);exports.WsEventModel=wi([P(vi.type)],exports.WsEventModel);const Ca=be(),tE=Ca.debug==="true"||Ca.debug===!0,sE="/api/system/canvas",_d=async(t,e)=>{const s=e||sE,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:tE?"false":"true"},body:t})},rE=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:_d},Symbol.toStringTag,{value:"Module"}));function Da(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var oE=Object.defineProperty,nE=Object.getOwnPropertyDescriptor,Sd=(t,e,s,r)=>{for(var o=r>1?void 0:r?nE(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&&oE(e,s,o),o};const Od="canvas-renderer-model";function Ho(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){_d(t,e)}checkStreaming(){if(this.isOneShotDone()||!this.isStreaming){requestAnimationFrame(()=>{const t=this.isOneShotDone();this.stopStreaming(!t)});return}}handleFrame(t){var s;const e=Da(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=Da(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 Ho(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=Ho(this._renderer);Ho(this._renderer)&&this._renderer.onDone(()=>{var c,u,d;this.logger.debug(`Renderer completed for ${this.id}`),K("/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"})})}};Sd([Jt({modelType:ti.type})],Hr.prototype,"router",2);Hr=Sd([P(Od)],Hr);const Ei=new ve({class:Hr,type:Od});class Id{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 iE{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 aE extends iE{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 ey{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||!hl(e))return null;const o=((n=s==null?void 0:s.headers)==null?void 0:n.topic)||"";return dl(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 Vm(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 Ot(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 ty(t){return!!(t!=null&&t[Be])&&Object.keys(t[Be]).length>0}function sy(t){return!!(t!=null&&t[Z])&&Object.keys(t[Z]).length>0}function ry(t){return!!(t!=null&&t[Ke])&&t[Ke].length>0}function oy(t){const e=Object.getPrototypeOf(t);return!!(e!=null&&e[gt])&&Object.keys(e[gt]).length>0}function ny(t){return t.retention===ie.TTL&&t.extendOnRefresh===!0&&t.ttl!==void 0}function iy(t,e){return t.has(e)}function ay(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 cy{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(!ny(s)||!iy(this.responses,e))return!1;const r=this.responses.get(e);return ay(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 ly{static createAll(e){const{modelId:s,modelTypeName:r,modelData:o}=e,n=Hn.create({modelId:s,modelTypeName:r}),i=new dm(e,Ot(n,"fsm")),a=new fm(Ot(n,"offline-queue")),c=new rm(e),u=new sm(e),d=new cy;o.serviceResponses=d;const h={fsm:i,offlineQueue:a,serviceResponseStore:d,companionManager:c,childResolver:u};if(ty(o)&&(h.effectManager=new om(r,s,o,Ot(n,"effect"))),sy(o)){const f=Ot(n,"subscription");h.subscriptionManager=new ey(e,o,s,a,f),h.onlineLifecycleManager=new pm(e,Ot(n,"online"))}return ry(o)&&(h.httpRouteManager=new Yn(o,Ot(n,"http-routes"))),oy(o)&&(h.serviceRequestManager=new qm(o,d)),h}}const N=x.getLogger("kos-model"),uy="kos.extension.model.loader";class zl{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=ly.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}),em(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 Ol(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(yl(this.modelTypeName,this.modelId),i),H(bl(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=`${uy}.${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&&Kc(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 dy{constructor(e,s){l(this,"companionInstantiator");this.registry=e,this.cache=s,this.companionInstantiator=new Gg(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 zl({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 hy=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 Vl=10,ya=g.createLogger({name:"kos-model-manager"});class Gl{constructor(){l(this,"cache");l(this,"instantiator");l(this,"dependencies");l(this,"_registry");globalThis.kos=globalThis.kos||{},this.dependencies=new qg,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 hy(e),r.cache=new zg(e.preloadModels),r.instantiator=new dy(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),gl.addToDeletionQueue(e.id,setTimeout(()=>this.destroyModel(s),Vl)))}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 fy=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=>x.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=>x.debug(n.machine.current)),online:s}},W=g.createLogger({name:"kos-core"}),py=()=>{const t=de(),e=t==null?void 0:t.alias,s=process.env.KOS_CONNECTION_ALIAS;return e||s||void 0},gy=()=>{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://")},my=()=>{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},yy=()=>{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},by=(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",vy=t=>typeof t.unload=="function";var Yl=(t=>(t.LOGGED_IN="logged_in",t.LOGGED_OUT="logged_out",t))(Yl||{});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=my(),o=yy(),n=gy();s.host=r,s.port=Number.parseInt(o),s.protocol=n,process.env.KOS_ALLOW_ANONYMOUS==="true"&&(s.authorized=!0);const i=py()??e;i&&(s.alias=i.replace("{{TIMESTAMP}}",Date.now().toString())),this._transport=s.init(),this.fsmService=fy(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)vy(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}=by(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=Gl.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 wy=g.createLogger({name:"kos-model-visitor",group:"kos-ui-core"});class Wl{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)){wy.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 Ey extends Wl{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 My(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 _y(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))},Ql=t=>t,Xn=t=>t,Ty=({container:t,onAddItem:e,onUpdateItem:s,onRemoveItem:r=Ql,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)},Sy=({container:t,onAddItem:e,onRemoveItem:s=Ql,idMapper:r=Xn})=>o=>{const n=o.map(r);Qn(n,t.models).forEach(s),n.forEach(e)},Oy=({items:t,onAddItem:e,onRemoveItem:s,idMapper:r=Xn})=>o=>{const n=o.map(r);Qn(n,t).forEach(s),n.forEach(e)},$y=(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 Xl(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],Zl=(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},Jl=(t,e)=>{const s=new Date(t);return s.setDate(s.getDate()+e),s},Ft="en-US",eu={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"}},tu={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"}},su=(t,{dateStyle:e="short",locales:s=Ft}={dateStyle:"short",locales:Ft})=>{const r=e==="short"?eu.short:{dateStyle:e};return new Intl.DateTimeFormat(s,r).format(t)},ru=(t,{locales:e=Ft,timeStyle:s="short"}={locales:Ft,timeStyle:"short"})=>{const r=tu[s];return new Intl.DateTimeFormat(e,r).format(t)},ou=(t,{dateStyle:e="short",locales:s=Ft,timeStyle:r="short"}={dateStyle:"short",locales:Ft,timeStyle:"short"})=>{const o={...e&&eu[e],...r&&tu[r]};return new Intl.DateTimeFormat(s,o).format(t)},Iy=Object.freeze(Object.defineProperty({__proto__:null,addDaysToDate:Jl,addMonthsToDate:Zl,formatDate:su,formatDateSince:Xl,formatDateTime:ou,formatTime:ru,getDaysInMonth:Jn,isLeapYear:Zn},Symbol.toStringTag,{value:"Module"})),nu="featureFlagResolver",cr=new Map;Zt(nu,{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 au.updateFlags(i),Object.keys(i)}});const Cy="kos.loader.featureFlag";class iu{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 iu;const au=window.KosFeatureFlags,cu=(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)}`},lu=t=>{const s=new RegExp("hsl\\((\\d+),\\s+(\\d+)\\%,\\s+(\\d+)\\%\\)").exec(t);if(!s)throw Error("Invalid HSL string");return cu(parseInt(s[1]),parseInt(s[2]),parseInt(s[3]))},uu=(t,e)=>getComputedStyle(t).getPropertyValue(e),Dy=(t,e)=>lu(uu(t,e)),Ay=(t,e)=>{const s={...t};return s.id&&delete s.id,s},on=(t,e,s=Ay)=>{const r=s(t,e);E.runInAction(()=>{Object.assign(e,r)})};class du{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 xy=async(t,e)=>{const s=new du;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}}),Ry=t=>{S.getInstance().modelManager.registerModel(t)},Py=(t,e)=>{S.getInstance().modelManager.registerCompanionModel(t,e)},Ea="/kos/ui/internal/heartbeat/",ky=({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(()=>{Ul({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}},hu=(...t)=>e=>t.reduce((s,r)=>r(s),e),Ly={maxAttempts:5,baseDelayMs:100,backoffFactor:1.5};async function Fy(t,e){let s=1;const r={...Ly,...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 Ny=g.createLogger({name:"kos-service-request"}),fe=t=>({isMock:!1,URL:exports.BASE_URL}),Uy=(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),jy=(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}},By=(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;Ny.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}},Ky=(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 O;try{O=await v.json()}catch{}throw new z(`There was a problem modifying the model; returned status ${v.status}`,O??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:jy(t,s||e,c),getModelById:Ky(t,r||e,c),getOne:By(t,r||e,c),addModel:Ma(t,n||e,c),deleteModel:Uy(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 Hy(t,e,s="get"){const r=t.serviceResponses;if(r)return r.getByPath(e,s)}function qy(t,e,s="get"){const r=t.serviceResponses;return r?r.has(`${s.toUpperCase()}:${e}`):!1}function zy(t,e,s="get"){const r=t.serviceResponses;r&&r.delete(`${s.toUpperCase()}:${e}`)}function Vy(t,e){const s=t.serviceResponses;s&&s.clearPath(e)}function Gy(t){const e=t.serviceResponses;e&&e.clear()}const Yy=wt(),fu=()=>`kos-${Yy}`,Wy=t=>!!t&&!t.includes("VM_SERVICE")&&t.startsWith(fu()),ei=async(t,e=6e4)=>new Promise((s,r)=>{const{unsubscribe:o}=C(t,i=>{x.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)}),Qy=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)},Xy=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};var sc;const pu=new Set(((sc=process.env.KOS_TOOL_ACCESS_WHITELIST)==null?void 0:sc.split(","))||[]),Zy=()=>pu,Jy=(t=[])=>(Array.isArray(t)?t:[t]).some(s=>pu.has(s)),be=new Map;class gu{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?il(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 gu(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 eb=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 tb{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 sb{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 mu{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 yu{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 bu=g.createLogger({name:"intent-service"}),rb=t=>{$n(`/kos/intent/${t.type}`)?H(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):bu.info(`No subscribers for intent ${t.type}. Intent not sent.`)},ob=async t=>new Promise(e=>{const{type:s,options:r}=t;if($n(`/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 bu.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 vu(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 nb(t,e={}){return vu([t],e)}async function ib(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 ab(){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,wu=E.reaction,ri=E.observable,oi="Not Assigned",cb="kos.trouble.added",lb="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 Eu=g.createLogger({name:"config-bean-service",group:"Services"}),ni=exports.BASE_URL,Mu=t=>(t==null?void 0:t.decimals)!==void 0,{postModel:ub,getOne:db}=ce.build({destinationAddress:"",basePath:`${ni}/kos/config/`}),_u=async(t,e,s="/api/kos/config")=>(Eu.debug(`sending modify request for ConfigBean: ${t}`),ub({model:e,urlOverride:`${ni}${s}/${t}`})),Tu=async(t,e="/api/kos/config")=>(Eu.debug(`sending get request for ConfigBean: ${t}`),await db({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 Su(t=[]){return t.reverse().reduce((e,s)=>{const{overrides:r}=s;return r&&(e={...e,...r}),e},{})}function Ou(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])?Ou(t[r],o,s):s[o]=t[r]}return s}const $u=(t,e)=>{const s=t.details[0].bean||Su(t.details[0].scopes),r=Ou(s);E.runInAction(()=>{const o={...r};e.props.setValues(o)})},Iu=(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})})},Cu=t=>Object.fromEntries(t.props.entries),hb=t=>e=>s=>t.build(e,s);var fb=Object.defineProperty,pb=Object.getOwnPropertyDescriptor,Du=(t,e,s,r)=>{for(var o=r>1?void 0:r?pb(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&&fb(e,s,o),o};function gb(t,e){for(const s of t)if(new RegExp(`^${s}$`).test(e))return s}const ai="config-bean-model",lr=g.getLogger(ai),mb=vt("path");function yb(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||yb(this);const{modifyConfigBean:s=_u,getConfigBean:r=Tu}=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;$u(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=gb(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=Cu(this);await this._modifyConfigBean(this.path,t,this.serviceBasePath)}handleConfigBeanUpdated(t){Iu(t,this)}};Du([B({topic:`/kos/config/${mb}`,websocket:!0})],Dr.prototype,"handleConfigBeanUpdated",1);Dr=Du([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:bb,getAll:vb}=ce.build({basePath:`${ci}/api/kos/regions/info`}),Au=async t=>{try{return await bb({urlOverride:`${ci}${t}/info`})}catch{return}},xu=async t=>{try{return await vb({urlOverride:`${ci}${t}`})}catch{return}},wb=Object.freeze(Object.defineProperty({__proto__:null,getRegionInfo:Au,getRegions:xu},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 Ru={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 Eb(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},{...Ru});return{...t,...r}}function Mb(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]:{...Ru}}});return Object.keys(r).forEach(o=>{t[o]={...t[o],...r[o]}}),t}function _b(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 Tb=Object.defineProperty,Sb=Object.getOwnPropertyDescriptor,li=(t,e,s,r)=>{for(var o=r>1?void 0:r?Sb(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&&Tb(e,s,o),o};const Er="region-info-model",cs=g.createLogger({name:"region-info-model"});function Ob(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=Ob(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 xu(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 Au(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(Eb,{}),this.measureMap=e.data.unitSystems.reduce(Mb,{}),this.defaultMeasureMap=e.data.unitSystems.reduce(_b,{}),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)},Ar=({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=Ar({source:e}),i=Ar({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=Ar({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=Ar({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 Oa({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 $t=(t,e)=>s=>!t||!e?s:go(s)?ui(Number(s),t,e):s,Ib=(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($t(s,r));if(t.options.type==="rangeInterval")return Oa(t.options).map($t(s,r));if(t.options.type==="list"){const{list:o}=t.options;return o.map($t(s,r))}else{if(t.options.type==="unitSystemRangeCount"&&e)return Sa(t.options.unitSystems[e]).map($t(s,r));if(t.options.type==="unitSystemRangeInterval"&&e)return Oa(t.options.unitSystems[e]).map($t(s,r));if(t.options.type==="unitSystemList"&&e){const{list:o}=t.options.unitSystems[e];return o.map($t(s,r))}}return[]},Cb=(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 Db=Object.defineProperty,Ab=Object.getOwnPropertyDescriptor,di=(t,e,s,r)=>{for(var o=r>1?void 0:r?Ab(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&&Db(e,s,o),o};function xb(t){return(t==null?void 0:t.type)==="enum"}function Rb(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 Pb(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"}),kb=vt("path"),Lb=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 Mu(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?Rb(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=xb(r)?r.values:Ib(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 Pb(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 Cb(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();if(this.schemaFormat==="drt")return;const s=t==="drt"?"second":t;if(this.converter){const M=(r=this.converter)==null?void 0:r.measure,O=(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,A=(u=(c=this.converter)==null?void 0:c.to)!=null&&u.unit?this.regionInfo.getUnitMeasure(this.converter.to.unit):void 0,$=M||O||U||A||e,P=((h=(d=this.converter)==null?void 0:d.to)==null?void 0:h.unit)||this.regionInfo.getDefaultUnitForMeasure($,((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:$}}if(s&&e){const M=this.regionInfo.getDefaultUnitForMeasure(e,this.regionInfo.defaultUnitSystem),O=this.regionInfo.getUnitSystem(s),U=this.regionInfo.getUnitSystem(M);return{measure:e,to:{unit:O===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:kb,serviceBasePath:Lb})],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 Fb(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]})})}))},Pu=t=>e=>s=>t.build(String(e),s),pi=t=>e=>hu(hi,Pu(t)(e.tracker||e.id))(e),yo=g.createLogger({name:"future-service",group:"Services"}),{isMock:Nb,URL:Zs}=fe();var tt=(t=>(t.Success="SUCCESS",t.Fail="FAIL",t.Aborted="ABORT",t.Canceled="CANCEL",t))(tt||{});const{getAll:Ub,modifyModel:jb,addModel:Bb,deleteModel:Kb,postModel:Hb}=ce.build({destinationAddress:"",basePath:`${Zs}/api/future`,mock:Nb}),qb=async()=>await Ub({}),ku=async(t,e="/api/kos/future")=>(yo.info(`sending delete request for Future: ${t}`),await Kb({id:t,urlOverride:`${Zs}${e}/${t}`})),Lu=async(t,e="/api/kos/future")=>(yo.info("sending add request for Future"),await Bb({model:t,urlOverride:`${Zs}${e}`})),zb=async(t,e,s="/api/kos/future")=>(yo.info(`sending modify request for Future: ${t}`),jb({model:e,id:t,urlOverride:`${Zs}${s}/${t}`})),Fu=async(t,e="/api/kos/future")=>(yo.info(`sending cancel request for Future: ${t}`),Hb({urlOverride:`${Zs}${e}/${t}/cancel`,ordered:!0,model:{}})),Nu="future-model",ts=Jt(Nu),Uu="future-container-model",st=Jt(Uu),ju=t=>pi(ts)(t),Vb=t=>{const e=ju(t);return st.build(st.type,{}).addFutureModel(e),e},Gb=t=>st.build(st.type,{}).getFuture(String(t)),mt={buildFutureModel:ju,initiateFuture:Vb,getFuture:Gb},Yb=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 O={[ho]:!0,$tracker:c};p.push(O)}}else p.push(c);const y=await t.apply(this,p);g.debug(`received future response for ${c}`,y);const v=Yb(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(sl,{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:Bu}=fe(),{getOne:Wb}=ce.build({basePath:`${Bu}/api/kos/state`}),Qb=g.createLogger({name:"state-bean-service",group:"Services"}),Ku=async({path:t})=>(Qb.debug("sending GET for state-bean"),await Wb({urlOverride:`${Bu}/api/kos/state/${t}`})),Xb=Object.freeze(Object.defineProperty({__proto__:null,getStateBeanData:Ku},Symbol.toStringTag,{value:"Module"}));var Zb=Object.defineProperty,Jb=Object.getOwnPropertyDescriptor,Hu=(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 us="state-bean-model",ev=vt("path");let xr=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 Ku({path:this.path});t!=null&&t.data&&this.updateProps(t.data)}};Hu([B({topic:`/kos/state/${ev}`,websocket:!0})],xr.prototype,"handleConfigBeanUpdated",1);xr=Hu([D(us)],xr);const Ls={registration:{[us]:{class:xr,singleton:!1}},type:us,predicate:Ie(us),factory:he.Factory.create(us)},tv=({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 sv=Object.defineProperty,rv=Object.getOwnPropertyDescriptor,qu=(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 ds="state-prop-model",$a=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())??""}};qu([Xt({modelType:Ls.type,id:`state-bean-${$a}`,options:{path:$a}})],Rr.prototype,"stateBean",2);Rr=qu([D(ds)],Rr);const mi={registration:{[ds]:{class:Rr,singleton:!1}},type:ds,predicate:Ie(ds),factory:he.Factory.create(ds)},{URL:ov}=fe(),{getAll:nv}=ce.build({basePath:`${ov}/api/state-prop`}),iv=g.createLogger({name:"state-prop-service",group:"Services"}),av=async()=>(iv.debug("sending GET for state-prop"),await nv({})),cv=Object.freeze(Object.defineProperty({__proto__:null,getStateProps:av},Symbol.toStringTag,{value:"Module"}));function lv(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 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 Vu="browser-router-model",hv="kos.http.request",fv="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 yu}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),jl({msg:d,options:{responseId:i,destinationAddress:s,type:fv,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}`)}};zu([B({topic:hv})],Pr.prototype,"handleRequest",1);Pr=zu([D(Vu)],Pr);const yi=new Ce({class:Pr,type:Vu});var pv=Object.defineProperty,gv=Object.getOwnPropertyDescriptor,Gu=(t,e,s,r)=>{for(var o=r>1?void 0:r?gv(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&pv(e,s,o),o};const 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=Fu,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)}};Gu([B({topic:`kos.future/${Tr}`})],kr.prototype,"handleFutureUpdated",1);kr=Gu([D(ts.type)],kr);const Yu=kr;var mv=Object.defineProperty,yv=Object.getOwnPropertyDescriptor,bi=(t,e,s,r)=>{for(var o=r>1?void 0:r?yv(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&&mv(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=ku,addFuture:o=Lu}=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([$e],Fs.prototype,"_futures",2);bi([B({topic:"kos.future"})],Fs.prototype,"handleFutureUpdated",1);Fs=bi([D(st.type)],Fs);const Wu=Fs,{URL:Js}=fe(),{getOne:bv,postModel:vv,deleteModel:Qu}=ce.build({basePath:`${Js}/api/keyVal`}),an=g.createLogger({name:"key-value-service",group:"Services"}),Xu=async(t,e)=>{await Qu({urlOverride:`${Js}/api/keyVal/${t}/${e}`,id:e})},Zu=async(t,e,s)=>{const r=await vv({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},Ju=async(t="studio")=>{an.debug(`Retrieving all key-value data for namespace: ${t}`);const e=await bv({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},wv=async t=>{await Qu({urlOverride:`${Js}/api/keyVal/${t}`,id:""})},Ev=Object.freeze(Object.defineProperty({__proto__:null,deleteKeyValue:Xu,deleteKeyValueNamespace:wv,getKeyValue:Ju,updateKeyValue:Zu},Symbol.toStringTag,{value:"Module"}));var Mv=Object.defineProperty,_v=Object.getOwnPropertyDescriptor,vi=(t,e,s,r)=>{for(var o=r>1?void 0:r?_v(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&&Mv(e,s,o),o};const ed="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 Zu(this.namespace,t,e),this.data[t]=e):(await Xu(this.namespace,t),this.data[t]=void 0)}async load(){this.logger.debug(`loading studio-state ${this.id}`);const t=await Ju(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(ed)],Ns);const wi=new Ee({class:Ns,type:ed});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 td(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 sd(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=td(c.value):u=new k(c.type,c.value),r.push(u)}else i===ue?r.push(new k(ue,sd(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=[],O=f.value;O-- >0;)M.unshift(r.pop());var U=r.pop(),A=function(){for(var $=Object.assign({},s),P=0,V=M.length;P<V;P++)$[M[P]]=arguments[P];return ht(v,e,$)};return Object.defineProperty(A,"name",{value:U,writable:!1}),s[U]=A,A}());else if(p===ue)r.push(Tv(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 Tv(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 xt(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&&!xt(e,i.value)?e.push(i.value):(o!==null&&(xt(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&&(xt(e,o)||e.push(o),o=null)}o!==null&&!xt(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(sd(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",rd="TSTRING",qe="TPAREN",jt="TBRACKET",_o="TCOMMA",Si="TNAME",Oi="TSEMICOLON";function od(t,e,s){this.type=t,this.value=e,this.index=s}od.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 od(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(rd,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(Oi,";"),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 Sv=/^[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);Sv.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)?xt(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(rd))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(Oi)?(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(td("?"))}};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 Ov=["==","!=","<","<=",">=",">","in"];q.prototype.parseComparison=function(t){for(this.parseAddSub(t);this.accept(j,Ov);){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 Iv=["*","/","%"];q.prototype.parseTerm=function(t){for(this.parseFactor(t);this.accept(j,Iv);){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===Oi||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 Cv(t,e){return Number(t)+Number(e)}function Dv(t,e){return t-e}function Av(t,e){return t*e}function xv(t,e){return t/e}function Rv(t,e){return t%e}function Pv(t,e){return Array.isArray(t)&&Array.isArray(e)?t.concat(e):""+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 t>=e}function jv(t,e){return t<=e}function Bv(t,e){return!!(t&&e)}function Kv(t,e){return!!(t||e)}function Hv(t,e){return xt(e,t)}function qv(t){return(Math.exp(t)-Math.exp(-t))/2}function zv(t){return(Math.exp(t)+Math.exp(-t))/2}function Vv(t){return t===1/0?1:t===-1/0?-1:(Math.exp(t)-Math.exp(-t))/(Math.exp(t)+Math.exp(-t))}function Gv(t){return t===-1/0?t:Math.log(t+Math.sqrt(t*t+1))}function Yv(t){return Math.log(t+Math.sqrt(t*t-1))}function Wv(t){return Math.log((1+t)/(1-t))/2}function Ca(t){return Math.log(t)*Math.LOG10E}function Qv(t){return-t}function Xv(t){return!t}function Zv(t){return t<0?Math.ceil(t):Math.floor(t)}function Jv(t){return Math.random()*(t||1)}function Da(t){return $i(t+1)}function ew(t){return isFinite(t)&&t===Math.round(t)}var tw=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 $i(t){var e,s;if(ew(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)*$i(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+tw+.5,Math.sqrt(2*Math.PI)*Math.pow(e,t+.5)*Math.exp(-e)*s}function sw(t){return Array.isArray(t)?t.length:String(t).length}function Aa(){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 rw(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 ow(t,e,s){return s&&(s[t]=e),e}function nw(t,e){return t[e|0]}function iw(t){return arguments.length===1&&Array.isArray(t)?Math.max.apply(Math,t):Math.max.apply(Math,arguments)}function aw(t){return arguments.length===1&&Array.isArray(t)?Math.min.apply(Math,t):Math.min.apply(Math,arguments)}function cw(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 lw(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 uw(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 dw(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 hw(t,e){if(!Array.isArray(e))throw new Error("Second argument to join is not an array");return e.join(t)}function fw(t){return(t>0)-(t<0)||+t}var Ra=1/3;function pw(t){return t<0?-Math.pow(-t,Ra):Math.pow(t,Ra)}function gw(t){return Math.exp(t)-1}function mw(t){return Math.log(1+t)}function yw(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||qv,cosh:Math.cosh||zv,tanh:Math.tanh||Vv,asinh:Math.asinh||Gv,acosh:Math.acosh||Yv,atanh:Math.atanh||Wv,sqrt:Math.sqrt,cbrt:Math.cbrt||pw,log:Math.log,log2:Math.log2||yw,ln:Math.log,lg:Math.log10||Ca,log10:Math.log10||Ca,expm1:Math.expm1||gw,log1p:Math.log1p||mw,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc||Zv,"-":Qv,"+":Number,exp:Math.exp,not:Xv,length:sw,"!":Da,sign:Math.sign||fw},this.binaryOps={"+":Cv,"-":Dv,"*":Av,"/":xv,"%":Rv,"^":Math.pow,"||":Pv,"==":kv,"!=":Lv,">":Fv,"<":Nv,">=":Uv,"<=":jv,and:Bv,or:Kv,in:Hv,"=":ow,"[":nw},this.ternaryOps={"?":xa},this.functions={random:Jv,fac:Da,min:aw,max:iw,hypot:Math.hypot||Aa,pyt:Math.hypot||Aa,pow:Math.pow,atan2:Math.atan2,if:xa,gamma:$i,roundTo:rw,map:cw,fold:lw,filter:uw,indexOf:dw,join:hw},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 nd=new _t;_t.parse=function(t){return nd.parse(t)};_t.evaluate=function(t,e){return nd.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 bw(t){return Pa.hasOwnProperty(t)?Pa[t]:t}_t.prototype.isOperatorEnabled=function(t){var e=bw(t),s=this.options.operators||{};return!(e in s)||!!s[e]};var vw=Object.defineProperty,ww=Object.getOwnPropertyDescriptor,Ew=(t,e,s)=>e in t?vw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Mw=(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=i(o)||o);return o},_w=(t,e,s)=>(Ew(t,e+"",s),s);const Tw="kos-expression-evaluator-model";class Sw{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 Sw(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}};_w(Lr,"Registration");Lr=Mw([D({modelTypeId:Tw,singleton:!1})],Lr);const id=Lr.Registration,Ow=g.createLogger({name:"kos-log-manager-service",group:"Services"}),$w="/api/kos/logs/overrides",ad=async()=>(Ow.debug("sending GET for kos-log-manager"),await Ne.get($w)),Iw=Object.freeze(Object.defineProperty({__proto__:null,getLogOverrides:ad},Symbol.toStringTag,{value:"Module"}));var Cw=Object.defineProperty,Dw=Object.getOwnPropertyDescriptor,To=(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 cd="kos-log-manager-model",Aw="/kos/logs/override/add/*",xw="/kos/logs/override/remove/*",Rw=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:Rw(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 ad();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([qc("/api/kos/ui/loggers")],Bt.prototype,"getAllLoggers",1);To([B({topic:Aw,websocket:!0,wildcardName:"nodeType"})],Bt.prototype,"handleOverrideAdded",1);To([B({topic:xw,websocket:!0,wildcardName:"nodeType"})],Bt.prototype,"handleOverrideRemoved",1);Bt=To([D(cd)],Bt);const ld=new Ce({class:Bt,type:cd}),{URL:er}=fe(),{postModel:Ii,getOne:Pw}=ce.build({basePath:`${er}/api/kos-time`});g.createLogger({name:"kos-time-service",group:"Services"});const ud=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},dd=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},hd=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},fd=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},kw=Object.freeze(Object.defineProperty({__proto__:null,getTimezone:fd,setDate:dd,setTime:ud,setTimezone:hd},Symbol.toStringTag,{value:"Module"}));var Lw=Object.defineProperty,Fw=Object.getOwnPropertyDescriptor,So=(t,e,s,r)=>{for(var o=r>1?void 0:r?Fw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Lw(e,s,o),o};const hs="kos-time-model",Nw="/kos/time/time",Uw="/kos/time/day",jw="/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 ud(t)}async updateSystemDate(t){await dd(t)}async updateSystemTimezone(t){await hd(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 fd();this.setTimezone(t)}setTimezone(t){this.timezone=t}async load(){this.logger.debug(`loading kos-time ${this.id}`),this.retrieveTimezone()}};So([B({topic:Nw,websocket:!0})],Kt.prototype,"handleTimeChange",1);So([B({topic:Uw,websocket:!0})],Kt.prototype,"handleDayChange",1);So([B({topic:jw,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 Bw=Object.defineProperty,Kw=Object.getOwnPropertyDescriptor,pd=(t,e,s,r)=>{for(var o=r>1?void 0:r?Kw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Bw(e,s,o),o};const gd="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}`)}};pd([$e],Nr.prototype,"_models",2);Nr=pd([D(gd)],Nr);const Hw=g.createLogger({name:"log-stream-container-service",group:"Services"}),md=()=>{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=md(),qw="/api/kos/logs/node/{nodeId}/streams",yd=async()=>(Hw.debug("sending GET for log-stream-container"),await Ne.get(qw,{path:{nodeId:"primary"}},{destinationAddress:ns})),bd=async(t,e="primary")=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/subscribe",{path:{nodeId:e,stream:t}},void 0,{destinationAddress:ns})},vd=async t=>{await Ne.post("/api/kos/logs/node/{nodeId}/{stream}/unsubscribe",{path:{nodeId:"primary",stream:t}},void 0,{destinationAddress:ns})},zw=async()=>{await Ne.post("/api/kos/logs/overrides",{},{level:"WARN",name:"com.example",nodeType:"java",type:"package"},{destinationAddress:ns})},wd=async t=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks",{path:{nodeId:"primary",stream:t}},{destinationAddress:ns}),Ed=async(t,e)=>await Ne.get("/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}",{path:{nodeId:"primary",stream:t,blockId:e}},{destinationAddress:ns}),Vw=Object.freeze(Object.defineProperty({__proto__:null,createOverride:zw,getKosConnectionId:md,getLogStreamBlock:Ed,getLogStreamBlocks:wd,getLogStreams:yd,subscribeToLogStream:bd,unsubscribeFromLogStream:vd},Symbol.toStringTag,{value:"Module"}));var Gw=Object.getOwnPropertyDescriptor,Yw=(t,e,s,r)=>{for(var o=r>1?void 0:r?Gw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Md="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 Ed(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=Yw([D(Md)],ln);const js=new Ee({class:ln,type:Md}),Oo=new Ee({class:Nr,type:gd});Oo.addRelatedModel(js);var Ww=Object.defineProperty,Qw=Object.getOwnPropertyDescriptor,_d=(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&&Ww(e,s,o),o};const Td="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=Oo.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 bd(this.name)}async unsubscribe(){await vd(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 wd(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=wu(()=>{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()}}};_d([$e],Ur.prototype,"_blocks",2);Ur=_d([D(Td)],Ur);const Cs=new Ee({class:Ur,type:Td});var Xw=Object.defineProperty,Zw=Object.getOwnPropertyDescriptor,Tt=(t,e,s,r)=>{for(var o=r>1?void 0:r?Zw(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&Xw(e,s,o),o};const Sd="log-stream-container-model",Jw="/kos/logs/subscription/addBlock/*",eE="/kos/logs/subscription/updateBlock/*",tE="/kos/logs/subscription/removeBlock/*",sE="/kos/logs/subscription/lines/*",Od="/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: ${Od}`);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 yd();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([$e],ze.prototype,"_models",2);Tt([B({topic:[Od],websocket:!0})],ze.prototype,"handleStreamAdded",1);Tt([B({topic:[Jw],websocket:!0})],ze.prototype,"handleAddBlock",1);Tt([B({topic:[tE],websocket:!0})],ze.prototype,"handleRemoveBlock",1);Tt([B({topic:[eE],websocket:!0})],ze.prototype,"handleUpdateBlock",1);Tt([B({topic:[sE],websocket:!0})],ze.prototype,"handleLogLine",1);ze=Tt([D(Sd)],ze);const tr=new Ce({class:ze,type:Sd});tr.addRelatedModel(Cs);tr.addRelatedModel(Oo);tr.addRelatedModel(js);const rE=t=>(t==null?void 0:t.rank)!==void 0,oE=t=>(t==null?void 0:t.visibleRole)!==void 0,nE=t=>(t==null?void 0:t.color)!==void 0,iE=t=>{const e=t.info??{};return rE(e)?e.rank:0},aE=t=>{const e=t.info??{};return nE(e)?e.color:"orange"},cE=t=>{const e=t.info??{};return oE(e)?e.visibleRole:"TECHNICIAN"},{URL:$o}=fe(),{getAll:lE,postModel:$d}=ce.build({basePath:`${$o}/api/kos/troubles`}),Ds=g.createLogger({name:"trouble-services"}),Id=()=>{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=Id();Ds.info(`Destination address for trouble services: ${Bs}`);const Cd=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 lE({urlOverride:`${$o}${t}`,destinationAddress:e?Bs:void 0})},Dd=async(t,e="/api/kos/troubles",s)=>{try{const r=e.includes("/kos/troubles"),o=await $d({model:{},urlOverride:`${$o}${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}},Ad=async(t,e="/api/kos/troubles",s)=>{try{const r=await $d({model:t,urlOverride:`${$o}${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}},uE=Object.freeze(Object.defineProperty({__proto__:null,bulkResolveTroubles:Ad,getKosConnectionId:Id,getTroubles:Cd,resolveTrouble:Dd},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 dE=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)},xd=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 hE{constructor(){l(this,"type","ResolvableTrouble");l(this,"title","Resolvable Trouble");l(this,"subtitle","Trouble")}}class fE{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 hE;case"BlockPumpTrouble":return new fE;default:return}}}var pE=Object.defineProperty,gE=Object.getOwnPropertyDescriptor,Rd=(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="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 xd(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 Dd(this._troubleId,this.servicePath,t)}};Rd([bo()],Br.prototype,"resolve",1);Br=Rd([D(fs)],Br);const Ks={registration:{[fs]:{class:Br,singleton:!1}},type:fs,predicate:Ie(fs),factory:he.Factory.create(fs)};var Pd=Object.defineProperty,mE=Object.getOwnPropertyDescriptor,yE=(t,e,s)=>e in t?Pd(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?mE(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&&Pd(e,s,o),o},bE=(t,e,s)=>(yE(t,e+"",s),s);function ka(t){return T.propertyMapper.hasMapper(se.TroubleRank)?T.propertyMapper.executeMapper(se.TroubleRank,t):iE(t)}function La(t){return(T.propertyMapper.hasMapper(se.TroubleColor)?T.propertyMapper.executeMapper(se.TroubleColor,t):aE(t)).toLowerCase()}function Fa(t){return(T.propertyMapper.hasMapper(se.TroubleRole)?T.propertyMapper.executeMapper(se.TroubleRole,t):cE(t)).toLowerCase()}const vE="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 Cd(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 Ad(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)}};bE(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:vE,singleton:!0}),Qt(),Hc(),uo({containerProperty:"troubles",containerOptions:{indexMap:{[we.INDEX_TROUBLES_BY_IFACE]:dE,[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:kd}=fe(),{getAll:wE}=ce.build({basePath:`${kd}/api/kos/ota`}),Na=g.createLogger({name:"ota-service",group:"Services"}),EE=async()=>{Na.debug("sending GET request to /api/kos/ota/artifacts");const t=await wE({urlOverride:`${kd}/api/kos/ota/artifacts`});return Na.debug("getArtifacts - response:",t),t==null?void 0:t.data};var ME=Object.defineProperty,_E=Object.getOwnPropertyDescriptor,Co=(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=(r?i(e,s,o):i(o))||o);return r&&o&&ME(e,s,o),o};const Ld="ota-model",TE=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=TE(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 EE();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(Ld)],qt);const Kr=new Ce({class:qt,type:Ld}),Fd=De(),Ua=de(),SE=Ua.debug==="true"||Ua.debug===!0,OE="/api/system/canvas",Nd=async(t,e)=>{const s=e||OE,r=`${exports.BASE_URL}${s}`;await exports.kosFetch(r,{method:"POST",headers:{hide:SE?"false":"true"},body:t})},$E=Object.freeze(Object.defineProperty({__proto__:null,sendCanvasData:Nd},Symbol.toStringTag,{value:"Module"}));function ja(t,e,s){{const r=t.filter((o,n)=>n%4!==3);return btoa(String.fromCharCode(...r))}}var IE=Object.defineProperty,CE=Object.getOwnPropertyDescriptor,Ud=(t,e,s,r)=>{for(var o=r>1?void 0:r?CE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&IE(e,s,o),o};const jd="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){Nd(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"})})}};Ud([Xt({modelType:yi.type})],Hr.prototype,"router",2);Hr=Ud([D(jd)],Hr);const Ci=new Ee({class:Hr,type:jd});class Bd{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 DE{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 AE extends DE{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 @@ ${u}topics:${e}
141
141
  vec3 rgb = hslToRgb(hue, 1.0, 0.5);
142
142
  gl_FragColor = vec4(rgb, 1.0);
143
143
  }
144
- `,i=this.compileShader(r.VERTEX_SHADER,o),a=this.compileShader(r.FRAGMENT_SHADER,n);this.program=this.createProgram(i,a),this.posBuffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,this.posBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW),this.aPosition=r.getAttribLocation(this.program,"a_position"),this.uMinHue=r.getUniformLocation(this.program,"minHue"),this.uMaxHue=r.getUniformLocation(this.program,"maxHue"),this.uHueOffset=r.getUniformLocation(this.program,"hueOffset"),this.uGridHeight=r.getUniformLocation(this.program,"gridHeight")}reset(){this.hueOffset=0,this.lastUpdate=performance.now()}renderFrame(s,r){const o=this.gl;if(this.canvas.width=s,this.canvas.height=r,this.shouldStep(50)){const n=this.speedPx/r;this.hueOffset=(this.hueOffset+n)%1}o.viewport(0,0,s,r),o.clear(o.COLOR_BUFFER_BIT),o.useProgram(this.program),o.enableVertexAttribArray(this.aPosition),o.bindBuffer(o.ARRAY_BUFFER,this.posBuffer),o.vertexAttribPointer(this.aPosition,2,o.FLOAT,!1,0,0),o.uniform1f(this.uMinHue,this.minHue/360),o.uniform1f(this.uMaxHue,this.maxHue/360),o.uniform1f(this.uHueOffset,this.hueOffset),o.uniform1f(this.uGridHeight,r),o.drawArrays(o.TRIANGLES,0,6)}compileShader(s,r){const o=this.gl.createShader(s);if(this.gl.shaderSource(o,r),this.gl.compileShader(o),!this.gl.getShaderParameter(o,this.gl.COMPILE_STATUS))throw new Error(this.gl.getShaderInfoLog(o)||"Shader compile failed");return o}createProgram(s,r){const o=this.gl.createProgram();if(this.gl.attachShader(o,s),this.gl.attachShader(o,r),this.gl.linkProgram(o),!this.gl.getProgramParameter(o,this.gl.LINK_STATUS))throw new Error("Program linking failed");return o}}class _t{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 Mi(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 cE=Mi(_t);class lE extends cE{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 uE=Mi(_t);class $d extends uE{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 dE extends Id{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 hE(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 Cd(t){return typeof t=="string"?hE(t):t}function Kr(t){const e=Cd(t);return`rgb(${e.r},${e.g},${e.b})`}class fE extends _t{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=Cd(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 g=this.trailColors[p];u=g.r,d=g.g,h=g.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 Dd extends _t{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,g,v,E,_,k,S;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=((g=this.scrollConfig)==null?void 0:g.width)||s,c=((v=this.scrollConfig)==null?void 0:v.height)||r);let u,d;switch(o==="left"||o==="right"?(u=0,((E=this.scrollConfig)==null?void 0:E.offsetY)==="center"||((_=this.scrollConfig)==null?void 0:_.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((k=this.scrollConfig)==null?void 0:k.offsetX)==="center"||((S=this.scrollConfig)==null?void 0:S.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 N=O+a+n;N<s&&this.ctx.drawImage(this.img,N,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 N=O-a-n;N<s&&this.ctx.drawImage(this.img,N,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 N=O+c+n;N>-c&&this.ctx.drawImage(this.img,u,N,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 N=O-c-n;N<r&&this.ctx.drawImage(this.img,u,N,a,c)}break}}}checkScrollCompletion(s,r,o,n){var h,f,p,g,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=((g=this.scrollConfig)==null?void 0:g.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=Kr(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 gE extends _t{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=Kr(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 mE{constructor(e){l(this,"patterns");l(this,"currentPatternIndex",0);l(this,"currentRenderer",null);l(this,"loopConfig");l(this,"currentLoopCount",0);l(this,"transitionDuration");l(this,"patternOverrides");l(this,"completionCallback",null);l(this,"patternStore");l(this,"canvas");l(this,"ctx");l(this,"width",0);l(this,"height",0);this.patterns=e.patterns,this.loopConfig=e.loop??!1,this.transitionDuration=e.transitionDuration??0,this.patternOverrides=e.patternOverrides??{},this.patternStore=e.patternStore??new Map,this.canvas=document.createElement("canvas");const s=this.canvas.getContext("2d");if(!s)throw new Error("2D canvas not supported");if(this.ctx=s,this.patterns.length===0)throw new Error("SequenceRenderer requires at least one pattern");this.loadCurrentPattern()}loadCurrentPattern(){var n,i,a,c;const e=this.patterns[this.currentPatternIndex],s=this.patternStore.get(e);if(!s){console.warn(`Pattern "${e}" not found in store, skipping`),this.moveToNextPattern();return}this.currentRenderer&&((i=(n=this.currentRenderer).dispose)==null||i.call(n));const r=this.patternOverrides[e]??{},o={...s.data,...r};try{this.currentRenderer=qr({mode:s.type,data:o}),this.currentRenderer&&this.isDoneAware(this.currentRenderer)&&this.currentRenderer.onDone(()=>{this.handlePatternComplete()}),this.currentRenderer&&(this.currentRenderer.reset(),(c=(a=this.currentRenderer).play)==null||c.call(a),this.width>0&&this.height>0&&this.currentRenderer.renderFrame(this.width,this.height))}catch(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 yE=Mi(_t);class bE extends yE{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=Kr(r)}setColor(s){this.color=Kr(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 vE extends _t{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 Aa=new Map;Ys(re,{register(t,e){Aa.set(t,e)},execute(t,e){const s=Aa.get(t);return s?new s(e):null}});$.canvas.registerRenderer("video",dE);$.canvas.registerRenderer("video-basic",Id);$[re].register("image-static",$d);$[re].register("image-scrolling",Dd);const wE=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new Dd(t):new $d(t)}};$[re].register("image",wE);$[re].register("color",bE);$[re].register("matrix",fE);$[re].register("sweep",vE);$[re].register("gradient",lE);$[re].register("drop",aE);$[re].register("sequence",mE);$[re].register("text",gE);const EE=class{constructor(t){const e=(s,r)=>{const o=qr({mode:s,data:r});if(!o)throw new Error(`Failed to create renderer of type: ${s}`);return o};return new pE(t,e)}};$[re].register("overlay",EE);const qr=({mode:t,data:e})=>{const s=$[re].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var ME=Object.defineProperty,TE=Object.getOwnPropertyDescriptor,as=(t,e,s,r)=>{for(var o=r>1?void 0:r?TE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&ME(e,s,o),o};const Ad="canvas-dispatcher-model";function _E(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 st=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=Ei.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=qr({mode:i,data:c}),o.setClearOnComplete(n.clearOnComplete),o.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleColorApplication(t,e){var u,d,h;const s=t.params.color,r=_E(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=qr({mode:"color",data:{r:i,g:c,b:a}}),n.startStreaming(),(h=e.status)==null||h.call(e,200).send({status:"OK"})}async handleEndpointCreation(t,e){var r,o;const s=t.body;if(!s.apiPath||!s.id){(r=e.status)==null||r.call(e,400).send({error:"Name and path are required"});return}this.addNamedEndpoint(s.id,s),(o=e.status)==null||o.call(e,200).send({status:"OK"})}async load(t){var s;const e=t==null?void 0:t.get(Yt.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)}))}};as([Le],st.prototype,"_endpointRenderers",2);as([Gs("/api/ui/canvas/patterns")],st.prototype,"handlePatternsPost",1);as([Gs("/api/ui/canvas/pattern/:endpoint/:pattern")],st.prototype,"handlePatternApplication",1);as([Gs("/api/ui/canvas/color/:endpoint/:color")],st.prototype,"handleColorApplication",1);as([Gs("/api/ui/canvas/endpoint")],st.prototype,"handleEndpointCreation",1);st=as([P(Ad)],st);const Yt=new Ce({class:st,type:Ad}),{URL:Ti}=ue(),{getOne:xd}=ie.build({basePath:`${Ti}/api/device`}),zr=m.createLogger({name:"device-service",group:"Services"}),Rd=async()=>{zr.debug("sending GET for device serial number");try{const t=await xd({urlOverride:`${Ti}/api/kos/device/serialNumber`});return[void 0,t==null?void 0:t.data.serialNumber]}catch(t){if(t instanceof z)return zr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},Pd=async()=>{zr.debug("sending GET for device details");try{const t=await xd({urlOverride:`${Ti}/api/kos/device`});return t?[void 0,t.data]:["unknownError",void 0]}catch(t){if(t instanceof z)return zr.error(`Error fetching device serial number: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},SE=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Pd,getSerialNumber:Rd},Symbol.toStringTag,{value:"Module"}));var OE=Object.defineProperty,IE=Object.getOwnPropertyDescriptor,kd=(t,e,s,r)=>{for(var o=r>1?void 0:r?IE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&OE(e,s,o),o};const Ld="device-model",$E="/kos/criticalData/changed",CE="/kos/criticalData/available";let Vr=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 Pd();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 Rd();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()}};kd([B({topic:[$E,CE],websocket:!0})],Vr.prototype,"handleCriticalDataChanged",1);Vr=kd([P(Ld)],Vr);const Gr=new Ce({class:Vr,type:Ld});var DE=Object.getOwnPropertyDescriptor,AE=(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=i(o)||o);return o};const Fd="network-interface-model";let an=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}`)}};an=AE([P(Fd)],an);const _i=new ve({class:an,type:Fd}),{URL:xE}=ue(),{getAll:RE}=ie.build({basePath:`${xE}/api/kos/network/interfaces`}),xa=m.createLogger({name:"network-interface-service",group:"Services"}),Nd=async()=>{xa.debug("sending GET for copy-logs");try{const t=await RE({});return[void 0,t==null?void 0:t.data]}catch(t){if(t instanceof z)return xa.error(`Error fetching log file size: ${t.payload.error}`),[t.payload.error,void 0]}return["unknownError",void 0]},PE=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Nd},Symbol.toStringTag,{value:"Module"}));var kE=Object.defineProperty,LE=Object.getOwnPropertyDescriptor,Ud=(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 jd="network-interface-container-model";let Yr=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 Nd();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=_i.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Ud([Le],Yr.prototype,"_models",2);Yr=Ud([P(jd)],Yr);const Bs=new Ce({class:Yr,type:jd});Bs.addRelatedModel(_i);const{URL:FE}=ue(),{getAll:NE}=ie.build({basePath:`${FE}/api/kos/storage/devices`}),Ra=m.createLogger({name:"storage-device-service",group:"Services"}),Bd=async()=>{Ra.debug("sending GET for storage-device");const t=await NE({});return!(t!=null&&t.data)||t.status!==200?(Ra.error("Failed to retrieve storage-device data",t),[]):t.data},UE=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:Bd},Symbol.toStringTag,{value:"Module"}));var jE=Object.getOwnPropertyDescriptor,BE=(t,e,s,r)=>{for(var o=r>1?void 0:r?jE(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const Hd="storage-device-model";let cn=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}`)}};cn=BE([io(),P(Hd)],cn);const Wr=new ve({class:cn,type:Hd});var HE=Object.defineProperty,KE=Object.getOwnPropertyDescriptor,Si=(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&&HE(e,s,o),o};const Kd="storage-device-container-model",qE="/kos/storage";let Hs=class{constructor(t,e,s){l(this,"id");l(this,"logger");l(this,"_models");this.id=t,this.logger=s.logger,this._models=new 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=Wr.instance(s.id).options(o).build();this.addModel(n)}})}async load(){this.logger.debug(`loading storage-device-container container ${this.id}`),(await Bd()).forEach(e=>{if(e.deviceType!=="disk"){const s={...e,kosParentId:this.id},r=Wr.instance(e.id).options(s).build();this.addModel(r)}})}};Si([Le],Hs.prototype,"_models",2);Si([B({topic:qE,websocket:!0})],Hs.prototype,"handleStorageAvailability",1);Hs=Si([P(Kd)],Hs);const Wt=new Ce({class:Hs,type:Kd});Wt.addRelatedModel(Wr);const{URL:Oi}=ue(),{getAll:zE,postModel:VE}=ie.build({basePath:`${Oi}/api/kos/update/available`}),Pa=m.createLogger({name:"usb-update-service",group:"Services"}),qd=async()=>{Pa.debug("sending GET for usb-update");const t=await zE({urlOverride:`${Oi}/api/kos/update/available`});return!(t!=null&&t.data)||(t==null?void 0:t.status)!==200?(Pa.error("Failed to retrieve usb-update data",t),[]):t.data},zd=async(t,e,s)=>{const r=await VE({model:{manifestId:t,deviceId:e},tracker:s,urlOverride:`${Oi}/api/kos/update/install`});if(!(r!=null&&r.data))throw new Error("No response from server");return r.data},GE=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:qd,installUpdate:zd},Symbol.toStringTag,{value:"Module"}));var YE=Object.defineProperty,WE=Object.getOwnPropertyDescriptor,Vd=(t,e,s,r)=>{for(var o=r>1?void 0:r?WE(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 Gd="usb-update-model";let Qr=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 lo(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}`),zd(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}`)}};Vd([Ri()],Qr.prototype,"install",1);Qr=Vd([P(Gd)],Qr);const Ii=new ve({class:Qr,type:Gd});var QE=Object.defineProperty,ZE=Object.getOwnPropertyDescriptor,_o=(t,e,s,r)=>{for(var o=r>1?void 0:r?ZE(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&&QE(e,s,o),o};const Yd="usb-update-container-model";let Qt=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 qd();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=Ii.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}`)}};_o([Jt({modelType:Wt.type})],Qt.prototype,"storageService",2);_o([Le],Qt.prototype,"_models",2);_o([Lc({dependencies:t=>[t.isUsbInserted]})],Qt.prototype,"usbInsertedEffect",1);Qt=_o([P(Yd)],Qt);const Ks=new Ce({class:Qt,type:Yd});Ks.addRelatedModel(Ii);const XE=()=>({...{[ss.type]:{class:nu},[tt.type]:{class:Su,singleton:!0},...ne.registration,...wt.registration,...Vt.registration,...jr.registration,...Ve.registration,[vi.type]:{class:exports.WsEventModel,singleton:!0},...js.registration,...yi.registration,...Ar.registration}}),$i=XE(),JE={models:$i,preloadModels:[]},ka=!0,Wd=t=>()=>{const e=$i;return Gc(ln)(Us).model(Vt).model(Wt).model(Ks).model(Gr).model(Lr).model(xs).model(Fr).model(ni).model(Bs).model(Yt).model(Ei).model(Lu).model(ti,ka).model(Xs).model(Uu,ka),Object.keys(e).forEach(s=>{const r=e[s];Vc(ln)(s,r)}),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t)}},Ie={};Ie.core={models:Wd(Ie)};Ie.preload=R.model.preloadModel(Ie);Ie.model=R.model.register(Ie);Ie.companion=R.companion.register(Ie);Ie.legacy=R.model.registerLegacyModel(Ie);const ln=Ie;class eM{registerTroubleRankMapper(e,s){return $.propertyMapper.registerPropertyMapper(Se.TroubleRank,e,s),this}registerTroubleRoleMapper(e,s){return $.propertyMapper.registerPropertyMapper(Se.TroubleRole,e,s),this}registerTroubleColorMapper(e,s){return $.propertyMapper.registerPropertyMapper(Se.TroubleColor,e,s),this}registerModelLoader(e,s,r){$.loader.registerLoader(e,s,r)}registerCanvasPatternLoader(e,s){$.loader.registerLoader(Yt.loader,e,s)}}const tM=async(t,e)=>{const s=ni.instance(t).options({}).build(),r=e?`${e}-`:"";return await pe(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:()=>{Ae(s)}}},Qd="kos:service:region",Zd="regionId",sM=`${Qd}-${Zd}`,Xd=async t=>{const e=wt.factory(sM)({path:Qd,attribute:Zd});await pe(e),e.updateProperty(t)};function rM(t){return bt(t)}const La=Ye(),oM=Object.freeze(Object.defineProperty({__proto__:null,api:La,default:La,kosServiceRequest:rM},Symbol.toStringTag,{value:"Module"}));function nM(t){return bt(t)}const Fa=Ye(),iM=Object.freeze(Object.defineProperty({__proto__:null,api:Fa,default:Fa,kosServiceRequest:nM},Symbol.toStringTag,{value:"Module"}));function aM(t){return bt(t)}const Na=Ye(),cM=Object.freeze(Object.defineProperty({__proto__:null,api:Na,default:Na,kosServiceRequest:aM},Symbol.toStringTag,{value:"Module"}));function lM(t){return bt(t)}const Ua=Ye(),uM=Object.freeze(Object.defineProperty({__proto__:null,api:Ua,default:Ua,kosServiceRequest:lM},Symbol.toStringTag,{value:"Module"}));function dM(t){return bt(t)}const ja=Ye(),hM=Object.freeze(Object.defineProperty({__proto__:null,api:ja,default:ja,kosServiceRequest:dM},Symbol.toStringTag,{value:"Module"}));function fM(t){return bt(t)}const Ba=Ye(),pM=Object.freeze(Object.defineProperty({__proto__:null,api:Ba,default:Ba,kosServiceRequest:fM},Symbol.toStringTag,{value:"Module"})),Ci="/kos-timer-event",Di="/kos-timer-event/tick",Ai="defaultTimerEnd",vs=m.createLogger({name:"timer-manager"}),gM=t=>t.updateProperty!==void 0;class Jd{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,gM(s)&&Q(()=>{m.info(`Updating config value timer ${e} with new timeout value ${s.value}`);const n=s.value||60;this.updateTimeout(n)}),this.addTimeoutAction({name:Ai}),r&&r.forEach(n=>{this.addTimeoutAction(n)})}get id(){return this.name}start(){if(this.state==="active"){vs.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&&(vs.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;vs.debug(`Executing timer action ${s.name} at ${e}`),(r=s.action)==null||r.call(s,s.name,e),this.notifyTimeoutAction(s),s.singleUse&&(vs.info(`${this.name} Removing single-use action ${s.name}`),this.removeTimeoutAction(s.name))}),this.notifyTick()}notifyTick(){K(`${Di}/${this.name}`,{name:this.name,remainingTime:this.remainingTime})}notifyTimeoutAction(e){K(Ci,{name:this.name,action:e.name,remainingTime:this.remainingTime})}}const ws=new Map,Ct=(t,e)=>{const s=ws.get(t);if(!s){vs.error(`Timer ${t} not found`);return}e(s)},eh={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(ws.has(t))return ws.get(t);const r=new Jd(t,e,s);return ws.set(t,r),r},getTimer(t){return ws.get(t)},clearTimer(t){Ct(t,e=>e.pause())},restartTimer(t){Ct(t,e=>e.restart())},resetTimer(t){Ct(t,e=>e.reset())},addTimeoutAction(t,e){Ct(t,s=>s.addTimeoutAction(e))},removeTimeoutAction(t,e){Ct(t,s=>s.removeTimeoutAction(e))},startTimer(t){Ct(t,e=>e.start())}},th="kos:service:region:settings",sh="timeZone",mM=`${th}-${sh}`,un=async t=>{const e=wt.factory(mM)({path:th,attribute:sh});await pe(e),e.updateProperty(t)},yM=t=>!t||!t.data;function xi(t,e,s={}){const{alias:r,namespace:o,abortController:n=!1,trackerPolicy:i="id"}=s;return async function(...a){const c=vt();m.debug(`Calling future service ${e} with tracker ${c}`);let u,d;n&&(u=new AbortController);const h=gt.initiateFuture({tracker:c,id:Vn});o&&(h.namespace=o),m.debug(`waiting for future ${h.id} to be ready`),await pe(h),m.debug(`future ${h.id} is ready`),te(()=>{m.debug(`Adding future ${h.id} to futureHandler`),this.futureHandler.addFuture(h,r)}),n&&u&&(d=Q(()=>{(h.status==="CANCELLED"||h.endState===et.Canceled)&&(m.debug(`Future ${h.id} cancelled, aborting request`),u==null||u.abort())}),u.signal.addEventListener("abort",async()=>{if(h.status!=="CANCELLED"&&h.endState!==et.Canceled&&!h.endState){m.debug(`AbortController aborted, cancelling future ${h.id}`);try{await h.cancelFuture()}catch(p){m.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 E=p[p.length-1];E&&typeof E=="object"&&"aborted"in E?p[p.length-1]=u.signal:p.push(u.signal)}if(i==="context"){const E=p[p.length-1];if(Rn(E))E.$tracker=c;else{const _={[ao]:!0,$tracker:c};p.push(_)}}else p.push(c);const g=await t.apply(this,p);m.debug(`received future response for ${c}`,g);const v=yM(g)?g:g==null?void 0:g.data;return v?(v.progress=1,m.debug("mapping future response to future model"),h.endState?m.debug(`future ${h.id} has already completed. Not updating the model`):Yn(v,h)):this.futureHandler.removeFuture(r),f(),v}catch(p){if(f(),n&&(u!=null&&u.signal.aborted)){const g=new Error("Operation cancelled");throw m.debug(`Operation ${e} was cancelled`),g}throw m.error(p),p}}}function Ri(t={}){const{alias:e}=t;return(s,r,o)=>{s[xt]=s[xt]||{},e&&(s[Pt]=s[Pt]||new Map,s[Pt].set(r,e));const n=o.value,i=xi(n,r,t);s[xt][r]={handler:i}}}const ft=class ft{constructor(){l(this,"bindings",new Map)}static getInstance(){return ft._instance||(ft._instance=new ft),ft._instance}register(e,s){this.bindings.has(e)&&console.warn(`[declarative-model] Overwriting existing bindings for model type "${e}"`),this.bindings.set(e,s)}get(e){return this.bindings.get(e)}has(e){return this.bindings.has(e)}remove(e){return this.bindings.delete(e)}clear(){this.bindings.clear()}};l(ft,"_instance");let dn=ft;const cs=dn.getInstance(),bM={IMMEDIATE:Z.IMMEDIATE,SINGLE:Z.SINGLE,TTL:Z.TTL,PERMANENT:Z.PERMANENT};function vM(t,e,s,r,o){var g,v,E;const n=s.service,i=s.handler,a=(n.method||"GET").toUpperCase();let c;if(i&&((g=r==null?void 0:r.serviceHandlers)!=null&&g[i])){const _=r.serviceHandlers[i],k=`__svc_${i}`;t[k]=function(S,O){_(this,S,O)},c=t[k]}else{const _=`__svc_merge_${e}`;t[_]=function(k,S){S&&typeof S=="object"&&!Array.isArray(S)&&Object.assign(this,S)},c=t[_]}let u;if(i&&((v=r==null?void 0:r.serviceTransforms)!=null&&v[i]))u=r.serviceTransforms[i];else if(n.transform){const _=n.transform;u=k=>_.split(".").reduce((S,O)=>S==null?void 0:S[O],k)}let d;i&&((E=r==null?void 0:r.serviceConditions)!=null&&E[i])&&(d=r.serviceConditions[i]);let h;n.cache&&(h={retention:bM[n.cache.retention]??Z.SINGLE,ttl:n.cache.ttl});let f;n.errorHandler&&(f={strategy:n.errorHandler.strategy,defaultValue:n.errorHandler.defaultValue});const p=`${a}:${n.path}`;o[p]={path:n.path,method:n.method,lifecycle:s.lifecycle?Pi(s.lifecycle):void 0,handlerMethod:`__svc_${i||e}`,originalHandler:c,transform:u,condition:d,errorHandler:f,cache:h,iterateOver:n.iterateOver,pathParams:n.pathParams,queryParams:n.queryParams,body:n.body,requestOptions:n.requestOptions}}function wM(t,e,s,r,o,n,i){var h,f;const a=s.future,c=s.handler,u=c?(f=(h=r==null?void 0:r.futureHandlers)==null?void 0:h.handlers)==null?void 0:f[c]:void 0;if(!u){console.warn(`[declarative-model] Future action "${e}" on "${i}" references handler "${c}" but no binding was found. Skipping.`);return}t[e]=function(...p){return u(this,...p)};const d=xi(t[e],e,{alias:a.alias,namespace:a.namespace,abortController:a.abortController??!1,trackerPolicy:a.trackerPolicy??"id"});o[e]={handler:d},a.alias&&n.set(e,a.alias)}function EM(t,e){var a;if(!e.actions)return;const s=cs.get(e.model.modelTypeId),r=t[He]??{},o={},n=new Map;let i=0;for(const[c,u]of Object.entries(e.actions))u.service&&vM(t,c,u,s,r),u.future&&(wM(t,c,u,s,o,n,e.model.modelTypeId),i++);if(Object.keys(r).length>0&&(t[He]=r),Object.keys(o).length>0&&(t[xt]=o),n.size>0&&(t[Pt]=n),i>0){const c={mode:"full",handlerProperty:"futureHandler"};if(i>1?t[ro]=c:t[so]=c,(a=s==null?void 0:s.futureHandlers)!=null&&a.onFutureUpdate){const u=s.futureHandlers.onFutureUpdate;t.onFutureUpdate=function(d,h){u(this,d,h)}}}}const Ko={INIT:"init",LOAD:"load",READY:"ready",ACTIVATE:"activate",ONLINE:"online"};function Pi(t){return t?Ko[t]??Ko.INIT:Ko.INIT}const MM={string:"",number:0,boolean:!1,object:null,array:[]};function TM(t){return t.default!==void 0?t.default:MM[t.type]??null}function _M(t){var i,a;const{model:e}=t,s=e.properties??{},r=cs.get(e.modelTypeId),o=function(c,u={}){this.id=c;for(const[d,h]of Object.entries(s))if((u==null?void 0:u[d])!==void 0)this[d]=u[d];else{const f=TM(h);Array.isArray(f)?this[d]=[...f]:f!==null&&typeof f=="object"?this[d]={...f}:this[d]=f}if(u&&typeof u=="object")for(const[d,h]of Object.entries(u))!(d in s)&&d!=="parentId"&&(this[d]=h)};o.prototype.modelTypeId=e.modelTypeId;const n=["init","load","ready","activate","online","offline","unload","deactivate"];for(const c of n){const u=(i=t.lifecycle)==null?void 0:i[c],d=(u==null?void 0:u.handler)??c,h=(a=r==null?void 0:r.lifecycle)==null?void 0:a[d];h?o.prototype[c]=async function(f){return h(this,f)}:u&&console.warn(`[declarative-model] Lifecycle "${c}" declared on "${e.modelTypeId}" but no binding handler "${d}" was found.`)}if(r!=null&&r.computed)for(const[c,u]of Object.entries(r.computed))Object.defineProperty(o.prototype,c,{get(){return u(this)},enumerable:!0,configurable:!0});if(r!=null&&r.actions)for(const[c,u]of Object.entries(r.actions))o.prototype[c]=function(...d){return u(this,...d)};return o}function SM(t,e){var o,n,i;if(!e.topics)return;const s=t[X]??{},r=cs.get(e.model.modelTypeId);for(const[a,c]of Object.entries(e.topics)){const u=c.handler;let d;if(u&&((o=r==null?void 0:r.topicHandlers)!=null&&o[u])){const p=r.topicHandlers[u],g=`__topic_${u}`;t[g]=function(v,E){p(this,v,E)},d=t[g]}else{const p=`__topic_merge_${a.replace(/[^a-zA-Z0-9]/g,"_")}`;t[p]=function(g){g&&typeof g=="object"&&Object.assign(this,g)},d=t[p]}(c.debounce||c.throttle||c.once)&&(d=Fn(d,{debounce:c.debounce,throttle:c.throttle,once:c.once}));const h=u&&((n=r==null?void 0:r.topicConditions)!=null&&n[u])?r.topicConditions[u]:()=>!0,f=u&&((i=r==null?void 0:r.topicTransforms)!=null&&i[u])?r.topicTransforms[u]:p=>p;s[a]={websocket:c.websocket??!0,fos:c.fos??!1,bridge:c.bridge??!1,handler:d,lifecycle:Pi(c.lifecycle),condition:h,transform:f,once:c.once,destinationAddress:c.destinationAddress,wildcardName:c.wildcardName}}t[X]=s}function OM(t,e){if(!e.dependencies)return;const s=t[x]??{};for(const[r,o]of Object.entries(e.dependencies)){const n=(o.resolutionPolicy??"CREATE").toLowerCase();s[r]={modelType:o.modelType,id:o.id,options:o.options??{},lifecycle:Pi(o.lifecycle),resolutionPolicy:n}}t[x]=s}function IM(t,e){var o;if(!e.configProperties)return;const s=t[x]??{},r=cs.get(e.model.modelTypeId);for(const[n,i]of Object.entries(e.configProperties)){const a=i.converter?{...i.converter}:void 0;a&&(typeof a.from=="string"&&(a.from={unit:a.from}),typeof a.to=="string"&&(a.to={unit:a.to}));let c;i.optionsExpander&&((o=r==null?void 0:r.configPropertyExpanders)!=null&&o[i.optionsExpander])&&(c=r.configPropertyExpanders[i.optionsExpander]),s[n]={modelType:"config-bean-prop-model",id:`${i.path}-${i.attribute}`,options:{path:i.path,attribute:i.attribute,serviceBasePath:i.serviceBasePath,converter:a,formatter:i.formatter,optionsExpander:c},lifecycle:"init",lazy:i.lazy}}t[x]=s}function $M(t,e){if(!e.stateProperties)return;const s=t[x]??{};for(const[r,o]of Object.entries(e.stateProperties))s[r]={modelType:"state-prop-model",id:`${o.path}-${o.attribute}`,options:{path:o.path,attribute:o.attribute},lifecycle:"init"};t[x]=s}function CM(t,e){e.container&&(t[no]={containerProperty:e.container.containerProperty||"container",includeMethods:e.container.includeMethods!==!1,includeGetters:e.container.includeGetters!==!1,modelsProperty:e.container.modelsProperty||"models",containerOptions:e.container.containerOptions??{},childModelType:e.container.childModelType})}function DM(t,e){var o;if(!e.effects)return;const s={},r=cs.get(e.model.modelTypeId);for(const[n,i]of Object.entries(e.effects)){const a=i.handler,c=(o=r==null?void 0:r.effectHandlers)==null?void 0:o[a];if(!c){console.warn(`[declarative-model] Effect "${n}" on "${e.model.modelTypeId}" references handler "${a}" but no binding was found. Skipping.`);continue}const u=typeof c=="function"?c:c.handler,d=typeof c=="object"?c.dependencies:void 0,h=function(){u(this)},f=i.dependencies,p=d??(f?g=>f.map(v=>v.split(".").reduce((E,_)=>E==null?void 0:E[_],g)):void 0);s[n]={dependencies:p,value:h,options:{fireImmediately:i.fireImmediately??!1}}}Object.keys(s).length>0&&(t[xe]=s)}function AM(t,e){const s=e.model.modelTypeId;t[oo]={loggerProperty:"logger"};let r;Object.defineProperty(t,"logger",{get(){return r||(r=Pn.create({modelTypeName:s,component:"kos-model"})),r},enumerable:!1,configurable:!0})}function xM(t,e){var s;(s=e.logging)!=null&&s.group&&(t[Rt]={group:e.logging.group})}const Es=new Map,RM={get(t){return Es.get(t)},has(t){return Es.has(t)},remove(t){return Es.delete(t)},clear(){Es.clear()}};function rh(t){var n;const{model:e}=t;if(!(e!=null&&e.modelTypeId))throw new Error("[declarative-model] model.modelTypeId is required in declarative config");const s=_M(t);AM(s.prototype,t),SM(s.prototype,t),IM(s.prototype,t),$M(s.prototype,t),OM(s.prototype,t),CM(s.prototype,t),EM(s.prototype,t),DM(s.prototype,t),xM(s,t),(n=s.prototype)[_e]??(n[_e]={});const o=P({modelTypeId:e.modelTypeId,singleton:e.singleton??!1,optionsRequired:e.optionsRequired})(s);return Es.set(e.modelTypeId,o),o}function PM(t){return typeof t=="function"&&typeof t.keys=="function"}function Ha(t){if(PM(t)){const e={};for(const s of t.keys())e[s]=t(s);return e}return t}function kM(t){let e=0,s=0;for(const[r,o]of Object.entries(t)){if(!o||typeof o!="object")continue;const n=o.default&&typeof o.default=="object"?o.default:o;for(const[i,a]of Object.entries(n))if(typeof a=="function"&&i.startsWith("register")&&i.endsWith("Bindings"))try{a(),e++}catch(c){s++,console.warn(`[declarative-model-discovery] Error executing ${i} from ${r}:`,c)}}s>0&&console.warn(`[declarative-model-discovery] Registered ${e} bindings with ${s} errors`)}function LM(t){var r;let e=0,s=0;for(const[o,n]of Object.entries(t))try{const i=(n==null?void 0:n.default)??n;if(!((r=i==null?void 0:i.model)!=null&&r.modelTypeId)){console.warn(`[declarative-model-discovery] Skipping ${o}: missing model.modelTypeId`);continue}const a=rh(i);a.Registration&&(a.Registration.register(),e++)}catch(i){s++,console.warn(`[declarative-model-discovery] Error processing ${o}:`,i)}s>0&&console.warn(`[declarative-model-discovery] Registered ${e} models with ${s} errors`)}function FM(t){const e=t.bindings?Ha(t.bindings):{},s=Ha(t.models);kM(e),LM(s)}class NM{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 le.Factory.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!1,factory:this.factory},...this.childRegistration}}get predicate(){return $e(this.type)}}class UM{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 le.Singleton.create(this.type)}get registration(){return{[this.type]:{class:this.model,singleton:!0,factory:this.factory},...this.childRegistration}}get predicate(){return $e(this.type)}}class oh{constructor(){l(this,"_token");M.makeAutoObservable(this),C("token",e=>{this.token=e==null?void 0:e.body})}get token(){return this._token}set token(e){this._token=e}}class nh{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 ih=m.createLogger({name:"intent-service"}),jM=t=>{Mn(`/kos/intent/${t.type}`)?K(`/kos/intent/${t.type}`,t.options,{"kos.intent.type":t.type}):ih.info(`No subscribers for intent ${t.type}. Intent not sent.`)},BM=async t=>new Promise(e=>{const{type:s,options:r}=t;if(Mn(`/kos/intent/${t.type}`)){const o=vt(),{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);K(`/kos/intent/${s}`,r,{"kos.intent.type":s,sync:o})}else ih.info(`No subscribers for intent ${t.type}. Intent not sent.`),e([null,{body:void 0,payload:void 0}])}),je=m.createLogger({name:"app-startup-service"});async function ah(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 Sn(n,{getCurrentState:async()=>{try{const{default:c}=await Promise.resolve().then(()=>Ol),[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 HM(t,e={}){return ah([t],e)}async function KM(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 qM(){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 hn=M.when,ki=M.computed,te=M.runInAction,Q=M.autorun,ch=M.reaction,Li=M.observable;function zM(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[x]=u[x]||{},u[x][d]={modelType:wt.type,id:`${e}-${s}`,options:{path:e,attribute:s,serviceBasePath:a,converter:c,formatter:o,optionsExpander:i},lifecycle:D.INIT,lazy:n}}}const VM=({path:t})=>(e,s)=>{e[x]=e[x]||{},e[x][s]={modelType:js.type,id:`${js.type}-${t}`,options:{path:t},lifecycle:D.INIT}};function GM(t){const{path:e,attribute:s}=t;return(r,o)=>{r[x]=r[x]||{},r[x][o]={modelType:yi.type,id:`${e}-${s}`,options:{path:e,attribute:s},lifecycle:D.INIT}}}const Ft=m.createLogger({name:"services",group:"Services"}),YM=async(t,e)=>lh(t,e,`${exports.BASE_URL}/api/server/login`),lh=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()},WM=async t=>uh(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),uh=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()},QM=async(t,e)=>dh(t,e,`${exports.BASE_URL}/api/server/resetPassword`),dh=async(t,e,s=`${exports.BASE_URL}/api/resetPassword`)=>{Ft.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(Ft.debug(`password reset returned status ${r.status}`),!r.ok){Ft.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()},ZM=async(t,e,s)=>hh(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),hh=async(t,e,s,r=`${exports.BASE_URL}/api/server/acceptInvite`)=>{Ft.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(Ft.debug(`invitation accept returned status ${o.status}`),!o.ok){Ft.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 XM(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 g;return c&&typeof c=="object"&&(g=M.autorun(()=>{const v=c.progress||0,E=c.status||"PENDING",_=!c.endState;(v!==d||E!==h||_!==f)&&(d=v,h=E,f=_,p.forEach(k=>{try{k(d,h)}catch(S){console.warn("Progress callback error:",S)}}))})),n.finally(()=>{f=!1,i!=null&&i.signal.aborted||(h="COMPLETED",p.forEach(v=>{try{v(d,h)}catch(E){console.warn("Progress callback error:",E)}})),g&&g(),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(E){console.warn("Progress callback error:",E)}}),g&&g()},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}const JM=ut.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 xE=Di(St);class RE extends xE{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 PE=Di(St);class Kd extends PE{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 kE extends Bd{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 LE(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 Hd(t){return typeof t=="string"?LE(t):t}function qr(t){const e=Hd(t);return`rgb(${e.r},${e.g},${e.b})`}class FE 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=Hd(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 NE{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 qd 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,O,U,A;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"||((O=this.scrollConfig)==null?void 0:O.offsetY)===void 0?d=(r-c)/2:d=this.scrollConfig.offsetY):(((U=this.scrollConfig)==null?void 0:U.offsetX)==="center"||((A=this.scrollConfig)==null?void 0:A.offsetX)===void 0?u=(s-a)/2:u=this.scrollConfig.offsetX,d=0),o){case"left":{const $=s-this.position;if($<s&&$>-a&&this.ctx.drawImage(this.img,$,d,a,c),this.loopConfig&&this.pauseDuration===0&&this.position>n){const P=$+a+n;P<s&&this.ctx.drawImage(this.img,P,d,a,c)}break}case"right":{const $=-a+this.position;if($>-a&&$<s&&this.ctx.drawImage(this.img,$,d,a,c),this.loopConfig&&this.pauseDuration===0&&$-n-a>-a){const P=$-a-n;P<s&&this.ctx.drawImage(this.img,P,d,a,c)}break}case"up":{const $=r-this.position;if($>-c&&$<r&&this.ctx.drawImage(this.img,u,$,a,c),this.loopConfig&&this.pauseDuration===0&&$+c+n<r){const P=$+c+n;P>-c&&this.ctx.drawImage(this.img,u,P,a,c)}break}case"down":{const $=-c+this.position;if($>-c&&$<r&&this.ctx.drawImage(this.img,u,$,a,c),this.loopConfig&&this.pauseDuration===0&&$-n-c>-c){const P=$-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 UE 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 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=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 BE=Di(St);class KE extends BE{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 HE 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",kE);T.canvas.registerRenderer("video-basic",Bd);T[oe].register("image-static",Kd);T[oe].register("image-scrolling",qd);const qE=class{constructor(t){var e;return(e=t.scroll)!=null&&e.enabled?new qd(t):new Kd(t)}};T[oe].register("image",qE);T[oe].register("color",KE);T[oe].register("matrix",FE);T[oe].register("sweep",HE);T[oe].register("gradient",RE);T[oe].register("drop",AE);T[oe].register("sequence",jE);T[oe].register("text",UE);const zE=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 NE(t,e)}};T[oe].register("overlay",zE);const zr=({mode:t,data:e})=>{const s=T[oe].execute(t,e);if(s)return s;throw new Error(`Unknown mode: ${t}`)};var VE=Object.defineProperty,GE=Object.getOwnPropertyDescriptor,is=(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 zd="canvas-dispatcher-model";function YE(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=YE(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([$e],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:Ai}=fe(),{getOne:Vd}=ce.build({basePath:`${Ai}/api/device`}),Vr=g.createLogger({name:"device-service",group:"Services"}),Gd=async()=>{Vr.debug("sending GET for device serial number");try{const t=await Vd({urlOverride:`${Ai}/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]},Yd=async()=>{Vr.debug("sending GET for device details");try{const t=await Vd({urlOverride:`${Ai}/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]},WE=Object.freeze(Object.defineProperty({__proto__:null,getDeviceDetails:Yd,getSerialNumber:Gd},Symbol.toStringTag,{value:"Module"}));var QE=Object.defineProperty,XE=Object.getOwnPropertyDescriptor,Wd=(t,e,s,r)=>{for(var o=r>1?void 0:r?XE(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&&QE(e,s,o),o};const Qd="device-model",ZE="/kos/criticalData/changed",JE="/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 Yd();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 Gd();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()}};Wd([B({topic:[ZE,JE],websocket:!0})],Gr.prototype,"handleCriticalDataChanged",1);Gr=Wd([D(Qd)],Gr);const Yr=new Ce({class:Gr,type:Qd});var eM=Object.getOwnPropertyDescriptor,tM=(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 Xd="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=tM([D(Xd)],un);const xi=new Ee({class:un,type:Xd}),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:sM}=fe(),{getAll:rM}=ce.build({basePath:`${sM}/api/kos/network/interfaces`}),oM=Ri(),Ka=g.createLogger({name:"network-interface-service",group:"Services"}),Zd=async()=>{Ka.debug("sending GET for copy-logs");try{const t=await rM({destinationAddress:oM});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]},nM=Object.freeze(Object.defineProperty({__proto__:null,getNetworkInterfaces:Zd},Symbol.toStringTag,{value:"Module"}));var iM=Object.defineProperty,aM=Object.getOwnPropertyDescriptor,Jd=(t,e,s,r)=>{for(var o=r>1?void 0:r?aM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&iM(e,s,o),o};const eh="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 Zd();if(t){this.logger.error(`Error loading network interfaces: ${t}`);return}e&&e.forEach(s=>{const r=xi.instance(s.name).forceUpdate.options(s).build();this.addModel(r)})}async load(){this.logger.debug(`loading network-interface-container container ${this.id}`),this.refreshInterfaces()}};Jd([$e],Wr.prototype,"_models",2);Wr=Jd([D(eh)],Wr);const Hs=new Ce({class:Wr,type:eh});Hs.addRelatedModel(xi);const{URL:cM}=fe(),{getAll:lM}=ce.build({basePath:`${cM}/api/kos/storage/devices`}),Ha=g.createLogger({name:"storage-device-service",group:"Services"}),th=async()=>{Ha.debug("sending GET for storage-device");const t=await lM({});return!(t!=null&&t.data)||t.status!==200?(Ha.error("Failed to retrieve storage-device data",t),[]):t.data},uM=Object.freeze(Object.defineProperty({__proto__:null,getStorageDevices:th},Symbol.toStringTag,{value:"Module"}));var dM=Object.getOwnPropertyDescriptor,hM=(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=i(o)||o);return o};const sh="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=hM([lo(),D(sh)],dn);const Qr=new Ee({class:dn,type:sh});var fM=Object.defineProperty,pM=Object.getOwnPropertyDescriptor,Pi=(t,e,s,r)=>{for(var o=r>1?void 0:r?pM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&fM(e,s,o),o};const rh="storage-device-container-model",gM="/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 th()).forEach(e=>{if(e.deviceType!=="disk"){const s={...e,kosParentId:this.id},r=Qr.instance(e.id).options(s).build();this.addModel(r)}})}};Pi([$e],qs.prototype,"_models",2);Pi([B({topic:gM,websocket:!0})],qs.prototype,"handleStorageAvailability",1);qs=Pi([D(rh)],qs);const Vt=new Ce({class:qs,type:rh});Vt.addRelatedModel(Qr);const{URL:ki}=fe(),{getAll:mM,postModel:yM}=ce.build({basePath:`${ki}/api/kos/update/available`}),qa=g.createLogger({name:"usb-update-service",group:"Services"}),oh=async()=>{qa.debug("sending GET for usb-update");const t=await mM({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},nh=async(t,e,s)=>{const r=await yM({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},bM=Object.freeze(Object.defineProperty({__proto__:null,getAvailableUpdates:oh,installUpdate: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="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}`),nh(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}`)}};ih([bo()],Xr.prototype,"install",1);Xr=ih([D(ah)],Xr);const Li=new Ee({class:Xr,type:ah});var EM=Object.defineProperty,MM=Object.getOwnPropertyDescriptor,Do=(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&&EM(e,s,o),o};const ch="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 oh();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([$e],Gt.prototype,"_models",2);Do([Gc({dependencies:t=>[t.isUsbInserted]})],Gt.prototype,"usbInsertedEffect",1);Gt=Do([D(ch)],Gt);const zs=new Ce({class:Gt,type:ch});zs.addRelatedModel(Li);const{URL:Fi}=fe(),{getOne:lh}=ce.build({basePath:`${Fi}/api/translation`}),As=g.createLogger({name:"translation-service",group:"Services"}),_M=()=>{const t=window.location.origin,e=de();return(e==null?void 0:e.host)||t},uh=async(t,e)=>{As.debug(`Loading translations from: ${t}`);const s=e??_M();try{const r=await fetch(`${s}${t}`);return r.status!==200?(As.warn(`Failed to fetch translations at ${t}: ${r.status}`),{}):await r.json()}catch(r){throw As.error("Error fetching translations",r),r}},TM=async()=>{As.debug("Getting system localization descriptor");const t=await lh({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},dh=t=>async()=>{As.debug(`Getting KOS localization descriptor for context: ${t}`);const e=await lh({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]},hh="langResolver";var SM=Object.getOwnPropertyDescriptor,OM=(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=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 fh(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=fh(t[r],o);return{...s,...n}}else return{...s,[o]:t[r]}},{})}function ph(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]=ph(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(hh),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 uh(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=ph(o,n.value))):this.logger.error(`failed to load translation ${this.id} for ${t[i]}`),o),{});this.data=fh(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=OM([lo(),D(ps)],fn);const Zr={registration:{[ps]:{class:fn,singleton:!1}},type:ps,predicate:Ie(ps),factory:he.Factory.create(ps)};var IM=Object.defineProperty,CM=Object.getOwnPropertyDescriptor,gh=(t,e,s,r)=>{for(var o=r>1?void 0:r?CM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&IM(e,s,o),o};const gs="translation-container-model",DM=(t,e="/")=>t.join(e).replace(new RegExp(e+"{1,}","g"),e);function AM(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 DM([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||AM.bind(this),s.kosContext.set(hh,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)}};gh([$e],Jr.prototype,"_models",2);Jr=gh([D(gs)],Jr);const Ve={registration:{[gs]:{class:Jr,singleton:!0}},type:gs,predicate:Ie(gs),factory:he.Singleton.create(gs)},xM={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)}},mh={async init(t){const e=Ve.factory(t);return await ye(e),{translations:e}}},yh="kos-ws-event",Ni=Jt(yh);var RM=Object.defineProperty,PM=Object.getOwnPropertyDescriptor,Ui=(t,e,s,r)=>{for(var o=r>1?void 0:r?PM(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=(r?i(e,s,o):i(o))||o);return r&&o&&RM(e,s,o),o};const kM=({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:kM({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 LM=()=>({...{[ts.type]:{class:Yu},[st.type]:{class:Wu,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=LM(),FM={models:ji,preloadModels:[]},NM=!0,bh=t=>()=>{const e=ji;return cl(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(id).model(yi,NM).model(tr).model(ld),Object.keys(e).forEach(s=>{const r=e[s];al(pn)(s,r)}),{preload:R.model.preloadModel(t),model:R.model.register(t),companion:R.companion.register(t),legacy:R.model.registerLegacyModel(t)}},Oe={};Oe.core={models:bh(Oe)};Oe.preload=R.model.preloadModel(Oe);Oe.model=R.model.register(Oe);Oe.companion=R.companion.register(Oe);Oe.legacy=R.model.registerLegacyModel(Oe);const pn=Oe;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=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)}}},vh="kos:service:region",wh="regionId",BM=`${vh}-${wh}`,Eh=async t=>{const e=Et.factory(BM)({path:vh,attribute:wh});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 Mh(t){return Ye(t)}const gn=De(),GM=Object.freeze(Object.defineProperty({__proto__:null,api:gn,default:gn,kosServiceRequest:Mh},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",ms=g.createLogger({name:"timer-manager"}),o_=t=>t.updateProperty!==void 0;class _h{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"){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)},Th={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 _h(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())}},Sh="kos:service:region:settings",Oh="timeZone",n_=`${Sh}-${Oh}`,mn=async t=>{const e=Et.factory(n_)({path:Sh,attribute:Oh});await ye(e),e.updateProperty(t)};function i_(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"}),a_=Ri(),qi=async t=>{Yo.debug("sending GET for software-info");const[e,s]=await Fd.get("/api/kos/manifest/info",void 0,{signal:t,destinationAddress:a_});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},c_=i_(qi),l_=Object.freeze(Object.defineProperty({__proto__:null,getSoftwareInfos:qi,getSoftwareInfosWithCancel:c_},Symbol.toStringTag,{value:"Module"}));var u_=Object.getOwnPropertyDescriptor,d_=(t,e,s,r)=>{for(var o=r>1?void 0:r?u_(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=d_([D(bs)],yn);const eo={registration:{[bs]:{class:yn,singleton:!1}},type:bs,predicate:Ie(bs),factory:he.Factory.create(bs)};function h_(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"}),f_=async(t,e)=>$h(t,e,`${exports.BASE_URL}/api/server/login`),$h=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()},p_=async t=>Ih(t,`${exports.BASE_URL}/api/server/startPasswordReset`,""),Ih=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()},g_=async(t,e)=>Ch(t,e,`${exports.BASE_URL}/api/server/resetPassword`),Ch=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()},m_=async(t,e,s)=>Dh(t,e,s,`${exports.BASE_URL}/api/server/acceptInvite`),Dh=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 y_(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",O=!c.endState;(v!==d||M!==h||O!==f)&&(d=v,h=M,f=O,p.forEach(U=>{try{U(d,h)}catch(A){console.warn("Progress callback error:",A)}}))})),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 b_=Object.defineProperty,v_=Object.getOwnPropertyDescriptor,w_=(t,e,s)=>e in t?b_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,E_=(t,e,s,r)=>{for(var o=r>1?void 0:r?v_(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},M_=(t,e,s)=>(w_(t,e+"",s),s);const __="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}`)}};M_(to,"Registration");to=E_([D({modelTypeId:__,singleton:!1}),Qt()],to);const zi=to.Registration;var T_=Object.defineProperty,S_=Object.getOwnPropertyDescriptor,O_=(t,e,s)=>e in t?T_(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?S_(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o},I_=(t,e,s)=>(O_(t,e+"",s),s);const C_="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}`)}};I_(so,"Registration");so=$_([D({modelTypeId:C_,singleton:!1}),uo({containerOptions:{sortKey:"pinNum"}}),Qt()],so);const Vi=so.Registration;Vi.addRelatedModel(zi);var Ah=Object.defineProperty,D_=Object.getOwnPropertyDescriptor,A_=(t,e,s)=>e in t?Ah(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xh=(t,e,s,r)=>{for(var o=r>1?void 0:r?D_(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&&Ah(e,s,o),o},x_=(t,e,s)=>(A_(t,e+"",s),s);const R_="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}`)}};x_(Vs,"Registration");xh([$e],Vs.prototype,"_pins",2);Vs=xh([D({modelTypeId:R_,singleton:!1}),Qt()],Vs);const ro=Vs.Registration;g.createLogger({name:"gpio-chip-container-service",group:"Services"});const Rh="/api/kos/gpio/chips",P_="/api/kos/gpio/pins",Ph=Mh,kh=gn,k_=Object.freeze(Object.defineProperty({__proto__:null,GPIO_CHIP_PATH:Rh,GPIO_PIN_PATH:P_,gpioApi:kh,gpioServiceRequest:Ph},Symbol.toStringTag,{value:"Module"}));var Lh=Object.defineProperty,L_=Object.getOwnPropertyDescriptor,F_=(t,e,s)=>e in t?Lh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Fh=(t,e,s,r)=>{for(var o=r>1?void 0:r?L_(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&&Lh(e,s,o),o},N_=(t,e,s)=>(F_(t,e+"",s),s);const U_="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 kh.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}`)}};N_(Gs,"Registration");Fh([Ph({path:Rh,method:"get",errorHandler:{strategy:"log",defaultValue:[]},lifecycle:I.INIT,requestOptions:t=>({destinationAddress:t.destinationAddress})})],Gs.prototype,"handleGpioChipInit",1);Gs=Fh([D({modelTypeId:U_,singleton:!0}),uo({containerOptions:{sortKey:"num"}}),Qt()],Gs);const Nh=Gs.Registration;Nh.addRelatedModel(ro);const Ja=g.createLogger({name:"studio-properties-service",group:"Services"}),j_="/api/kos/studio/properties",Uh=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(j_,{},{destinationAddress:t,timeout:500})},B_=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:Uh},Symbol.toStringTag,{value:"Module"}));var K_=Object.getOwnPropertyDescriptor,H_=(t,e,s,r)=>{for(var o=r>1?void 0:r?K_(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const jh="studio-properties-model",q_="/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:q_,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await Uh(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=H_([D(jh)],bn);const z_=new Ee({class:bn,type:jh}),V_=dt.keyframes`
146
146
  0% {
147
147
  left: -90px;
148
148
  color: #eee;
@@ -154,13 +154,13 @@ ${u}topics:${e}
154
154
  left: 90px;
155
155
  color: #eee;
156
156
  }
157
- `,eT=ut.css`
157
+ `,G_=dt.css`
158
158
  font-size: 100px;
159
159
  margin-top: -80px;
160
160
  position: relative;
161
- animation: ${JM} ease-in-out infinite alternate;
161
+ animation: ${V_} ease-in-out infinite alternate;
162
162
  animation-duration: 1.2s;
163
- `,tT=({children:t})=>Va.createPortal(t,document.body);function fh({message:t="Wait a moment while we load your app.",theme:e="light"}){return T.jsx(tT,{children:T.jsxs(sT,{theme:e,children:[t,T.jsx("div",{css:eT,children:"."})]})})}const sT=mn.div`
163
+ `,Y_=({children:t})=>rc.createPortal(t,document.body);function Bh({message:t="Wait a moment while we load your app.",theme:e="light"}){return _.jsx(Y_,{children:_.jsxs(W_,{theme:e,children:[t,_.jsx("div",{css:G_,children:"."})]})})}const W_=En.div`
164
164
  padding-inline: 20px;
165
165
  width: 100%;
166
166
  height: 100vh;
@@ -174,31 +174,31 @@ ${u}topics:${e}
174
174
  left: 0;
175
175
  color: ${({theme:t})=>t==="light"?"black":"white"};
176
176
  z-index: 10000;
177
- `;class ph extends y.Component{constructor(e){super(e),this.state={error:null,errorInfo:null}}componentDidCatch(e,s){this.setState({error:e,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||T.jsxs("div",{children:[T.jsx("h2",{children:"Something went wrong."}),T.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),T.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const rT={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},oT=({value:t=0,title:e,status:s="normal",subtitle:r})=>{const o=ut.css`
177
+ `;class Kh extends m.Component{constructor(e){super(e),this.state={error:null,errorInfo:null}}componentDidCatch(e,s){this.setState({error:e,errorInfo:s})}render(){return this.state.errorInfo?this.props.fallback||_.jsxs("div",{children:[_.jsx("h2",{children:"Something went wrong."}),_.jsxs("details",{style:{whiteSpace:"pre-wrap"},children:[this.state.error&&this.state.error.toString(),_.jsx("br",{}),this.state.errorInfo.componentStack]})]}):this.props.children}}const Q_={normal:"#B5F7F6",warn:"#F3D78A",error:"#FC8486"},X_=({value:t=0,title:e,status:s="normal",subtitle:r})=>{const o=dt.css`
178
178
  display: flex;
179
179
  flex-direction: column;
180
- `,n=ut.css`
180
+ `,n=dt.css`
181
181
  position: relative;
182
182
  height: 18px;
183
183
  width: 100%;
184
184
  background-color: #ddd;
185
185
  border-radius: 5px;
186
186
  overflow: hidden;
187
- `,i=ut.css`
187
+ `,i=dt.css`
188
188
  position: absolute;
189
189
  top: 50%; /* position the top edge of the element at the middle of the parent */
190
190
  left: 50%; /* position the left edge of the element at the middle of the parent */
191
191
  z-index: 5;
192
192
  transform: translate(-50%, -50%);
193
193
  font-size: smaller;
194
- `,a=ut.css`
194
+ `,a=dt.css`
195
195
  width: ${t}%;
196
196
  height: 35px;
197
- background-color: ${rT[s]};
197
+ background-color: ${Q_[s]};
198
198
  text-align: center;
199
199
  line-height: 32px;
200
200
  color: black;
201
- `,c=ut.css`
201
+ `,c=dt.css`
202
202
  animation: indeterminateAnimation 1s infinite linear;
203
203
  transform-origin: 0% 50%;
204
204
  @keyframes indeterminateAnimation {
@@ -212,7 +212,7 @@ ${u}topics:${e}
212
212
  transform: translateX(100%) scaleX(0.5);
213
213
  }
214
214
  }
215
- `;return T.jsxs("div",{css:o,children:[T.jsxs("div",{css:n,children:[T.jsx("div",{css:i,children:e}),T.jsx("div",{css:[a,t<0?c:""]})]}),T.jsx("div",{children:r})]})},nT={setModel:()=>!1},So=y.createContext(nT),iT=()=>{const t=y.useContext(So);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},gh=({children:t})=>{const[e,s]=y.useState(),r=y.useCallback(o=>(s(o),!0),[s]);return T.jsx(So.Provider,{value:{model:e,setModel:r},children:t})},mh=m.createLogger({name:"kos-model-hierarchy-context"}),aT={models:[],addModel:()=>{mh.debug("Default implementation being used. Do Nothing.")}},Oo=y.createContext(aT),cT=({children:t})=>{const[e,s]=y.useState([]),r=y.useCallback(o=>{e.includes(o)||(mh.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[e]);return T.jsx(Oo.Provider,{value:{models:e,addModel:r},children:t})},lT=()=>!0,yh=t=>{const e=y.useContext(Oo);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||lT;return y.useMemo(()=>e.models.filter(s),[e.models,s])},uT=t=>yh({filter:s=>{const r=Pe(s.id);return(r==null?void 0:r.type)===t}})[0],dT=m.createLogger({name:"kos-model-loader"}),hT=()=>T.jsx("div",{}),bh=({fallback:t,children:e,...s})=>T.jsx(gh,{children:T.jsx(ph,{fallback:t,children:T.jsx(y.Suspense,{children:T.jsx(vh,{...s,children:e})})})}),vh=t=>{const[e,s]=y.useState(),[r,o]=y.useState(!1),{setModel:n}=y.useContext(So),i=y.useContext(Oo);if(y.useEffect(()=>{t.model&&(s(t.model),n(t.model),o(!0),i&&i.addModel(t.model))},[i,t.model,n]),t.error)throw dT.error(t.error),new Error(t.error);const a=t.loading||T.jsx(hT,{});return T.jsx(T.Fragment,{children:e&&r?t.children:a})},Er={header:{title:"Model",createLabel:"Create new Model",deleteLabel:"Delete"},createModal:{okText:"OK",cancelText:"Cancel",title:"Create New Model"}},wh=y.createContext(Er),fT=({translations:t=Er,children:e})=>{const s={header:{...Er.header,...t.header},createModal:{...Er.createModal,...t.createModal}};return T.jsx(wh.Provider,{value:s,children:e})};function pT(t,e){const s=I.create(t,!1,e),r=s.whenReady().then(()=>s);return On(r)}const Eh=y.createContext(void 0),gT=(t={models:{},preloadModels:[]},e)=>{const s=pT(t,e),r=({children:o})=>{const n=s.read(),[i,a]=y.useState(n.isOnline);return y.useEffect(()=>{const c=Q(()=>{a(n.isOnline)});return()=>{c()}},[n]),T.jsx(Eh.Provider,{value:{kosCore:n,online:i},children:o})};return{KosCoreContextProvider:yn.observer(r)}},Mh=()=>{const t=y.useContext(Eh);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},mT=8,yT=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),ht=new Map;function bT(t,e){if(ht.has(t)){const s=ht.get(t);if(s.status==="finished"){const r=I.getInstance().modelManager.getModelById(t);return{kosModel:r,model:r==null?void 0:r.modelData}}else throw s.promise}else{const s=e().then(()=>{ht.set(t,{status:"finished",key:t})},o=>{throw ht.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw ht.set(t,r),s}}function vT(t,e){return bT(t,e)}async function wT(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>mT)throw Error(`KOS Model ${s} has not been found`);await yT(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=Mh(),[i,a]=y.useState(!1),[c,u]=y.useState(),{kosModel:d,model:h}=vT(e||s||"",()=>wT(n.kosCore,t));return y.useEffect(()=>{t.forceUpdate&&h&&Ln(h)&&h.updateModel(t.options||{})},[h]),y.useEffect(()=>{async function f(){try{return await n.kosCore.whenReady(),r&&await(d==null?void 0:d.fsm.transitionTo(F.GO_ACTIVE,w.ACTIVE)),a(!0),d}catch(g){throw u(g.message),g}}let p;return n.kosCore&&e&&f().then(g=>{p=Q(()=>{const v=(g==null?void 0:g.status)===w.READY;a(v)})}).catch(g=>{console.error(g)}),()=>{if(r){if(h!=null&&h.id){const g=n.kosCore.modelManager.getModelById(h.id);g==null||g.fsm.transitionTo(F.GO_INACTIVE,w.INACTIVE).then(()=>{if(o){const v=h.id;Ae(h).then(()=>{ht.delete(v),p==null||p()})}})}}else o&&h&&Ae(h).then(()=>{ht.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:bh}},Fi=()=>{const t=Ar.type;return J({modelId:t,modelType:Ar.type,options:{}})},Ni=y.createContext(void 0),ET=({children:t})=>{const{model:e,ready:s}=Fi(),r=y.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(Ni.Provider,{value:r,children:t})},MT=()=>{const t=y.useContext(Ni);if(!t)throw new Error("useKosTimeContext must be used within a KosTimeProvider");return t},Ui=()=>{const t=Fr.type;return J({modelId:t,modelType:Fr.type,options:{}})};function TT(t){return()=>e=>{const{model:s,status:r,KosModelLoader:o}=Ui();return T.jsx(o,{...r,children:T.jsx(t,{...e,softwareInfo:s})})}}const ji=y.createContext(void 0),_T=({children:t})=>{const{model:e,ready:s}=Ui(),r=y.useMemo(()=>s&&e?{model:e}:{},[s,e]);return T.jsx(ji.Provider,{value:r,children:t})},ST=()=>{const t=y.useContext(ji);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Th=new oh,_h=y.createContext(Th);function OT({children:t}){return T.jsx(_h.Provider,{value:Th,children:t})}const Bi=y.createContext(void 0),IT=()=>{const t=window.location.origin,e=be();return(e==null?void 0:e.host)||t},$T=({children:t,appContext:e,locale:s="en",resolver:r,rootUrl:o,descriptorResolver:n})=>{const[i,a]=y.useState(!1),[c,u]=y.useState(),[d,h]=y.useState(),f=o||IT(),p=y.useMemo(()=>e??"app/system",[e]);y.useEffect(()=>{async function E(){const k=(Array.isArray(p)?p:[p]).map(ee=>(n||yd(ee))()),N=(await Promise.allSettled(k)).map(ee=>{if(ee.status==="rejected"){m.warn("Failed to load localization descriptor",ee.reason);return}return ee.value}).filter(ee=>!!ee).reverse().reduce((ee,we)=>{const H=we.path;return Object.keys(we.namespaces).forEach(ls=>{const se=we.namespaces[ls];se.basePath=H}),{...ee,namespaces:{...ee.namespaces,...we.namespaces}}},{});u(N)}E()},[p,n]),y.useEffect(()=>{async function E(){if(c){const _=f,{translations:k}=await Md.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:_});h(k),a(!0)}}E()},[s,c,r,f]);const g=y.useMemo(()=>i?{setLocale:E=>{d&&(d.currentLocale=E)}}:{setLocale:()=>{throw new Error("Translations not ready")}},[i,d]),v=i?t:null;return T.jsx(Bi.Provider,{value:g,children:v})},CT=()=>{const t=y.useContext(Bi);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},DT=()=>{const t=Yt.type;return J({modelId:t,modelType:Yt.type,options:{}})};function AT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=DT();return T.jsx(o,{...r,children:T.jsx(t,{...e,canvasDispatcher:s})})}}const xT=(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 RT({ctx:t,format:e,dataString:s,width:r,height:o,pixelSize:n}){const i=xT(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 PT=m.createLogger({name:"canvas-streamer"});PT.debug("main-view component loaded");const qo=10,Sh=yn.observer(({canvasDispatcher:t,height:e=30,width:s=50,defaultFps:r=10,showPreview:o=!1,name:n,apiPath:i="/api/system/canvas"})=>{const a=y.useRef(null),[c,u]=y.useState();y.useEffect(()=>{const h=t.addNamedEndpoint(n,{apiPath:i,fps:r,width:s,height:e,id:n});u(h)},[t]);const d=y.useCallback(h=>{if(a.current&&o){const f=a.current.getContext("2d");f&&RT({ctx:f,format:"base64",dataString:h,height:e,width:s,pixelSize:qo})}},[s,e,o]);return y.useEffect(()=>{c&&(c.onFrame=d,c.width=s,c.height=e,c.fps=r)},[c,d,s,e,r]),o&&Va.createPortal(T.jsx(LT,{children:T.jsx(FT,{children:T.jsx("canvas",{ref:a,width:s*qo,height:e*qo,style:{border:"1px solid black"}})})}),document.body)}),kT=AT(Sh),LT=mn.div`
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})]})},Z_={setModel:()=>!1},Ao=m.createContext(Z_),J_=()=>{const t=m.useContext(Ao);if(t==null)throw new Error("useModels must be used within a KosModelProvider");return t.model},Hh=({children:t})=>{const[e,s]=m.useState(),r=m.useCallback(o=>(s(o),!0),[s]);return _.jsx(Ao.Provider,{value:{model:e,setModel:r},children:t})},qh=g.createLogger({name:"kos-model-hierarchy-context"}),eT={models:[],addModel:()=>{qh.debug("Default implementation being used. Do Nothing.")}},xo=m.createContext(eT),tT=({children:t})=>{const[e,s]=m.useState([]),r=m.useCallback(o=>{e.includes(o)||(qh.debug("adding to hierarchy context",o.id),s(n=>[...n,o]))},[e]);return _.jsx(xo.Provider,{value:{models:e,addModel:r},children:t})},sT=()=>!0,zh=t=>{const e=m.useContext(xo);if(!e)throw new Error("useContextModelHierarchy must be used within a KosModelCollectionProvider");const s=(t==null?void 0:t.filter)||sT;return m.useMemo(()=>e.models.filter(s),[e.models,s])},rT=t=>zh({filter:s=>{const r=ke(s.id);return(r==null?void 0:r.type)===t}})[0],oT=g.createLogger({name:"kos-model-loader"}),nT=()=>_.jsx("div",{}),Vh=({fallback:t,children:e,...s})=>_.jsx(Hh,{children:_.jsx(Kh,{fallback:t,children:_.jsx(m.Suspense,{children:_.jsx(Gh,{...s,children:e})})})}),Gh=t=>{const[e,s]=m.useState(),[r,o]=m.useState(!1),{setModel:n}=m.useContext(Ao),i=m.useContext(xo);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 oT.error(t.error),new Error(t.error);const a=t.loading||_.jsx(nT,{});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"}},Yh=m.createContext(_r),iT=({translations:t=_r,children:e})=>{const s={header:{..._r.header,...t.header},createModal:{..._r.createModal,...t.createModal}};return _.jsx(Yh.Provider,{value:s,children:e})};function aT(t,e){const s=S.create(t,!1,e),r=s.whenReady().then(()=>s);return An(r)}const Wh=m.createContext(void 0),cT=(t={models:{},preloadModels:[]},e)=>{const s=aT(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(Wh.Provider,{value:{kosCore:n,online:i},children:o})};return{KosCoreContextProvider:Mn.observer(r)}},Qh=()=>{const t=m.useContext(Wh);if(t===void 0)throw new Error("useKosCore must be used within a KosCoreContextProvider");return t},lT=8,uT=(t=0)=>new Promise(e=>{setTimeout(()=>{e(!0)},2**t*10)}),ft=new Map;function dT(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 hT(t,e){return dT(t,e)}async function fT(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>lT)throw Error(`KOS Model ${s} has not been found`);await uT(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=Qh(),[i,a]=m.useState(!1),[c,u]=m.useState(),{kosModel:d,model:h}=hT(e||s||"",()=>fT(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:Vh}},Gi=()=>{const t=Fr.type;return J({modelId:t,modelType:Fr.type,options:{}})},Yi=m.createContext(void 0),pT=({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})},gT=()=>{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 mT(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),yT=({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})},bT=()=>{const t=m.useContext(Qi);if(!t)throw new Error("useSoftwareInfoContext must be used within a SoftwareInfoProvider");return t},Xh=new mu,Zh=m.createContext(Xh);function vT({children:t}){return _.jsx(Zh.Provider,{value:Xh,children:t})}const Xi=m.createContext(void 0),wT=()=>{const t=window.location.origin,e=de();return(e==null?void 0:e.host)||t},ET=({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||wT(),p=m.useMemo(()=>e??"app/system",[e]);m.useEffect(()=>{async function M(){const U=(Array.isArray(p)?p:[p]).map(V=>(n||dh(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 O=f,{translations:U}=await mh.init({lang:s,descriptor:c,defaultNamespace:"common",resolver:r,rootUrl:O});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})},MT=()=>{const t=m.useContext(Xi);if(!t)throw new Error("useTranslationContainerContext must be used within a TranslationContainerProvider");return t},_T=()=>{const t=zt.type;return J({modelId:t,modelType:zt.type,options:{}})};function TT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=_T();return _.jsx(o,{...r,children:_.jsx(t,{...e,canvasDispatcher:s})})}}const ST=(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 OT({ctx:t,format:e,dataString:s,width:r,height:o,pixelSize:n}){const i=ST(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,Jh=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&&OT({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&&rc.createPortal(_.jsx(CT,{children:_.jsx(DT,{children:_.jsx("canvas",{ref:a,width:s*Wo,height:e*Wo,style:{border:"1px solid black"}})})}),document.body)}),IT=TT(Jh),CT=En.div`
216
216
  display: flex;
217
217
  flex-direction: column;
218
218
  gap: 8px;
@@ -220,9 +220,9 @@ ${u}topics:${e}
220
220
  width: 100%;
221
221
  justify-content: space-between;
222
222
  align-items: center;
223
- `,FT=mn.div`
223
+ `,DT=En.div`
224
224
  display: flex;
225
225
  flex-direction: column;
226
226
  align-items: center;
227
- `,Oh=()=>{const t=Gr.type;return J({modelId:t,modelType:Gr.type,options:{}})};function NT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Oh();return T.jsx(o,{...r,children:T.jsx(t,{...e,device:s})})}}function UT(t,e,s){const r=new Promise(o=>{I.getInstance().whenReady().then(()=>{const{model:n}=I.getInstance().modelManager.createModelInstance(t,e??t,s);return n.whenReady().then(()=>{o(n.modelData)})})});return On(r)}function jT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Fi();return T.jsx(o,{...r,children:T.jsx(t,{...e,kosTime:s})})}}const Ih=()=>{const t=Bs.type;return J({modelId:t,modelType:Bs.type,options:{}})};function BT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Ih();return T.jsx(o,{...r,children:T.jsx(t,{...e,networkInterfaceContainer:s})})}}const $h=()=>{const t=Lr.type;return J({modelId:t,modelType:Lr.type,options:{}})};function HT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=$h();return T.jsx(o,{...r,children:T.jsx(t,{...e,oTA:s})})}}function KT(t,e){y.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 qT(t){const e=y.useRef(null),s=t.onAlert;return KT(e,s),T.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const zT=t=>{var u;const{stateProp:e}=t,[s,r]=y.useState((u=t.stateProp)==null?void 0:u.value),[o,n]=y.useState(!1),[i,a]=y.useState(void 0);return y.useEffect(()=>{async function d(h){try{h&&(await pe(h),n(!0))}catch(f){a(f.message)}}d(e)},[e]),y.useEffect(()=>{const d=Q(()=>{e&&o&&r(e.value)});return()=>{d()}},[o,e]),[s,{ready:o,error:i}]},Ch=()=>{const[t,e]=y.useState(!1),[s,r]=y.useState([]),o=Wt.type,n=J({modelId:o,modelType:Wt.type,options:{}});return y.useEffect(()=>{const i=Q(()=>{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 VT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Ch();return T.jsx(o,{...r,children:T.jsx(t,{...e,storageDeviceContainer:s})})}}const zo=m.createLogger({name:"use-timer"}),GT=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=eh.getTimer(t);y.useEffect(()=>{if(!n){console.warn(`Timer with name ${t} does not exist.`);return}const u=C(Ci,d=>{const{name:h,action:f,remainingTime:p}=d==null?void 0:d.body;h===t&&(f===Ai?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]),y.useEffect(()=>{if(!n||!s)return;const u=`${Di}/${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=y.useCallback(()=>{n?n.start():zo.warn(`Timer with name ${t} does not exist.`)},[n,t]),a=y.useCallback(()=>{n?n.reset():zo.warn(`Timer with name ${t} does not exist.`)},[n,t]),c=y.useCallback(()=>{n?n.pause():zo.warn(`Timer with name ${t} does not exist.`)},[n,t]);return{timer:n,start:i,reset:a,pause:c}},YT=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},WT=t=>t instanceof RegExp,QT=t=>typeof t=="string",ZT=(t,e,s)=>{if(t===""||e==="")return t;let r=e;WT(r)||(r=new RegExp("("+YT(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},Dh=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>QT(o)?ZT(o,e,s):o)};function XT(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=Dh(s,n,(i,a)=>o.type==="br"?T.jsx("br",{}):y.cloneElement(o,{key:`${r}-${a}`},i))}),s}const JT=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=XT(a,o||{});return T.jsx("span",{className:t.className,children:c})},Dt=new Map;function e_(t,e){if(Dt.has(t)){const s=Dt.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{Dt.set(t,{status:"finished",result:o})},o=>{throw Dt.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw Dt.set(t,r),s}}function fn(t,e){return e_(t,e)}const t_=async()=>{const t=await Kc(Ve.type);return await pe(t.model),t.model},s_=async(t,e,s)=>{const r=t.resolveNamespace(e);await pe(r);for(const o of s){const n=t.resolveNamespace(o);await pe(n),Dt.set(o,{status:"finished",result:n})}return r},r_=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=fn(Ve.type,t_),i=s.join("__"),a=fn(i,()=>s_(n,r,o)),c=y.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:y.useCallback((d,h)=>{const f=e!=null&&e.keyPrefix?`${e.keyPrefix}.${d}`:d;return a?a.resolveKey(f,h):(m.debug(`Translation model ${t} not ready for key: ${f}`),f)},[e==null?void 0:e.keyPrefix,t,a]),i18n:c}},Ah=()=>{const t=Ve.type;return J({modelId:t,modelType:Ve.type,options:{}})};function o_(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Ah();return T.jsx(o,{...r,children:T.jsx(t,{...e,translationContainer:s})})}}const n_=t=>J({modelId:t,modelType:Us.type}),Hi=()=>J({modelId:Vt.type,modelType:Vt.type,options:{}}),i_=({troubleType:t,condition:e})=>{const{model:s}=Hi(),[r,o]=y.useState(!1),[n,i]=y.useState([]),a=y.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 y.useEffect(()=>Q(()=>{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 a_(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Hi();return T.jsx(o,{...r,children:T.jsx(t,{...e,troubleContainer:s})})}}const xh=()=>{const t=Ks.type,e=J({modelId:t,modelType:Ks.type,options:{},activate:!0,destroyOnUnmount:!0}),[s,r]=y.useState(!1),[o,n]=y.useState(!1),[i,a]=y.useState([]);return y.useEffect(()=>{const c=Q(()=>{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 c_(t){return e=>{const{model:s,status:r,KosModelLoader:o}=xh();return T.jsx(o,{...r,children:T.jsx(t,{...e,usbUpdateContainer:s})})}}const l_=({path:t,propKey:e})=>{const{status:s}=J({modelType:xs.type,modelId:t,options:{path:t}}),[r,o]=y.useState(!1),[n,i]=y.useState(),[a,c]=y.useState(""),[u,d]=y.useState(),h=f=>{n&&e&&n.updateProperty(e,f)};return y.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]),y.useEffect(()=>{e&&M.autorun(()=>{const f=n==null?void 0:n.props[e];c(f||"")})},[n,e]),{config:n,ready:r,value:a,error:u,updateValue:h}},u_=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},Rh=({configProperty:t,optionsTransformer:e})=>{const[s,r]=y.useState(!1),[o,n]=y.useState(""),[i,a]=y.useReducer(u_,{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=y.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 y.useEffect(()=>{async function u(d){try{d&&(await pe(d),r(!0))}catch(h){n(h.message)}}u(t)},[t]),y.useEffect(()=>{const u=Q(()=>{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 d_(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 h_(t,e){return new Date(t,e,0).getDate()}function Ph(t,e){const s=d_(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function kh(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function Lh(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function Fh(t,e=[2018,2028]){const s=Lh(e);return t==="long"?s:s.map(r=>Number(r.toString().substring(2)))}function Ki(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 f_({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 Me(t){return t.toString().length===2?new Date(Date.parse(`01 Jan 20${t}`)).getFullYear():t}function p_(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function Nh(t,e,s){const r=Me(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 Ms(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 Ts(t,e){return new Date(t,e,0).getDate()}function Uh(t="en-US",e="short"){const s=new Intl.DateTimeFormat(t,{weekday:e}).format;return[...Array(7).keys()].map(r=>s(new Date(Date.UTC(2021,5,r))))}function jh({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=qi(n,r),u=Bh(n,r,t),d=Hh(i,t),h=Kh(i,t),f=zi(e,s),p=qh(e,s,t,o),g=Gh(s,e,p),v=zh(t,a);return{daysArray:f,monthsArray:d,yearsArray:c,yearsOptionsArray:u,monthsOptionsArray:h,daysOptionsArray:p,calendarDayArray:g,dayNamesArray:v}}function qi(t="long",e=[2018,2028]){return y.useMemo(()=>Fh(t,e),[t,e])}function Bh(t="long",e=[2018,2028],s="en-US"){const r=qi(t,e);return y.useMemo(()=>r.map(n=>({label:n.toLocaleString(s).replace(",",""),value:n})),[s,r])}function Hh(t,e="en-US"){return y.useMemo(()=>Ki(t,e),[t,e])}function Kh(t,e="en-US"){const s=y.useMemo(()=>kh(),[]),r=y.useMemo(()=>Ki(t,e),[t,e]);return y.useMemo(()=>[...Array(12).keys()].map(n=>({label:r[n],value:Number(s[n])})),[r,s])}function zi(t,e){const s=Me(t);return y.useMemo(()=>Ph(s,e),[e,s])}const g_=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function qh(t,e,s="en-US",r=[]){const o=zi(t,e);return y.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:g_(t,e,i,r)})),[r,s,e,o,t])}function zh(t="en-US",e="short"){return y.useMemo(()=>Uh(t,e),[t,e])}function Vh({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:Ze.format(n,r)}}function Gh(t,e,s){return y.useMemo(()=>Nh(t,e,s),[t,e,s])}var Yh=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(Yh||{});function m_({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]=y.useState(e),[f,p]=y.useState(c),[g,v]=y.useState(s),[E,_]=y.useState(r);y.useEffect(()=>{h(e)},[e]),y.useEffect(()=>{v(s)},[s]),y.useEffect(()=>{_(r)},[r]);const{yearsArray:k,yearsOptionsArray:S,monthsArray:O,monthsOptionsArray:N,daysArray:ee,daysOptionsArray:we,calendarDayArray:H,dayNamesArray:ls}=jh({locale:t,year:d,yearRange:f,month:g,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:se}=Vh({year:d,month:g,day:E,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:v,setDay:_,nextMonth:()=>{const oe=g<11?Me(d):Me(d+1),de=g<11?g+1:0;if(!Ms(oe,de,E)){const ot=Ts(oe,de);_(ot)}de===0&&h(oe),v(de)},previousMonth:()=>{const oe=Me(g===0?d-1:d),de=g===0?11:g-1;if(!Ms(oe,de,E)){const ot=Ts(oe,de);_(ot)}de===11&&h(oe),v(de)},nextYear:()=>{const oe=d<f[1]?d+1:f[0],de=Me(oe);if(Ms(de,g,E))h(oe);else{const ot=Ts(Me(d+1),g);_(ot),h(oe)}},previousYear:()=>{const oe=d>f[0]?d-1:f[0],de=Me(oe);if(Ms(de,g,E))h(oe);else{const ot=Ts(Me(d-1),g);_(ot),h(oe)}}},dateState:{year:d,yearRange:f,month:g,day:E,yearsArray:k,yearsOptionsArray:S,monthsArray:O,monthsOptionsArray:N,daysArray:ee,daysOptionsArray:we,calendarDayNames:ls,calendarDayArray:H,formattedDate:se}}}function Wh({date:t=new Date,dateFormat:e,timeFormat:s,options:r={}}){const[o,n]=y.useState("Formatting Time..."),[i,a]=y.useState("Formatting Date..."),c=!!r.ignoreDateFormat,{model:u,ready:d}=J({modelId:ne.type,modelType:ne.type,options:{}}),h=typeof t=="string"?Ze.parseISO(t):t;return y.useEffect(()=>{c?a(""):e?a(Ze.format(h,e)):d&&a(Ze.format(h,u!=null&&u.selectedDateFormat?u==null?void 0:u.selectedDateFormat:""))},[c,t,e,h,u,d]),y.useEffect(()=>{s?n(Ze.format(h,s)):d&&n(Ze.format(h,u!=null&&u.selectedTimeFormat?u==null?void 0:u.selectedTimeFormat:""))},[t,s,h,u,d]),{formattedDate:i,formattedTime:o}}const Qh=({secondsFromMidnight:t=0})=>{const[e,s]=y.useState(0),[r,o]=y.useState(0),[n,i]=y.useState(0),[a,c]=y.useState(new Date),{formattedTime:u}=Wh({date:a,options:{ignoreDateFormat:!0}});return y.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 g=new Date;g.setHours(0,0,0,0);const v=new Date(g.getTime()+d*1e3);c(new Date(v))},[t]),{hours:e,minutes:r,seconds:n,formattedTime:u,timeActions:{setHours:s,setMinutes:o,setSeconds:i}}},y_=({configProperty:t})=>{const{value:e}=Rh({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=Qh({secondsFromMidnight:s}),c=y.useRef();return y.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 b_(t,e={}){const{intervalMs:s=5*60*1e3,immediate:r=!0}=e;y.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 v_=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),w_=(t=v_)=>{const[e,s]=y.useState([]),[r,o]=y.useState(),{model:n,ready:i}=J({modelType:ne.type,modelId:ne.type,options:{}});y.useEffect(()=>{const c=Q(()=>{s((n==null?void 0:n.dateFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),y.useEffect(()=>{const c=Q(()=>{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=y.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}}},E_=t=>T.jsx("option",{title:t,value:t,children:t},t),Zh="kos:service:region:settings",Xh="timeZone",M_=`${Zh}-${Xh}`,T_=(t=E_)=>{const[e,s]=y.useState([]),[r,o]=y.useState(""),{model:n,ready:i}=J({modelType:ne.type,modelId:ne.type,options:{}}),a=wt.factory(M_)({path:Zh,attribute:Xh});y.useEffect(()=>{const u=Q(()=>{s((n==null?void 0:n.timeZones.map(t))||[]),n!=null&&n.timeZones.length&&un(n==null?void 0:n.timeZones[0])});return()=>{u()}},[n,i,t]),y.useEffect(()=>{const u=Q(()=>{o(a.value||"")});return()=>{u()}},[a.value]);const c=y.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&&un(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}}},Jh="kos:service:region",ef="regionId",__=`${Jh}-${ef}`,S_=t=>T.jsx("option",{title:t,value:t,children:t},t),tf=(t=S_)=>{const[e,s]=y.useState([]),[r,o]=y.useState("factory"),{model:n,ready:i}=J({modelType:ne.type,modelId:ne.type,options:{}}),a=wt.factory(__)({path:Jh,attribute:ef});y.useEffect(()=>{const u=Q(()=>{s((n==null?void 0:n.availableRegions.map(t))||[])});return()=>{u()}},[n,i,t]),y.useEffect(()=>{const u=Q(()=>{o(a.value||"factory")});return()=>{u()}},[a.value]);const c=y.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&&Xd(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}}},O_=t=>T.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),I_=(t=O_)=>{const[e,s]=y.useState([]),[r,o]=y.useState(),{model:n,ready:i}=J({modelType:ne.type,modelId:ne.type,options:{}});y.useEffect(()=>{const c=Q(()=>{s((n==null?void 0:n.timeFormatOptions.map(t))||[])});return()=>{c()}},[n,i,t]),y.useEffect(()=>{const c=Q(()=>{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=y.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}}},$_=(t,e)=>y.useMemo(()=>ki(t),e),C_={config:{attributes:!0,childList:!0,subtree:!0}};function D_(t,e,s=C_){const[r,o]=y.useState(null);y.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]),y.useEffect(()=>{if(!r)return()=>{};if(!t)throw new Error("A valid DOM element is required");const{config:n}=s;try{r.observe(t,n)}catch(i){m.error(i)}return()=>{r&&r.disconnect()}},[r,t,s])}const sf={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}},Vo=m.createLogger({name:"usePressGesture",group:"kos-hooks"});function A_({onPressed:t,onRelease:e,intersectionStrategy:s=sf}){const r=y.useRef(!1),o=pf.useGesture({onDragStart:c=>{Vo.info("onDragStart",c.type),s.validateStart(c)&&(t&&t(),r.current=!0)},onDrag:c=>{Vo.info("onDrag",c.type),r.current&&s.validateStop(c)&&(e&&e(),r.current=!1)},onDragEnd:c=>{Vo.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 rf=()=>{const[t,e]=y.useState(!1),s=I.getInstance();return y.useEffect(()=>{const r=Q(()=>{s&&s.reloading!==t&&e(s.reloading)});return()=>{r()}},[s,t]),[t]};function of(t=!1,e="2-digit"){return y.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 pn(t,e="2-digit",s=0,r=0){return y.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 nf(t="en-US"){return y.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 af({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=of(t,e),i=pn(60,s),a=pn(60,r),c=nf(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function cf(t,e){return Ze.format(t,e)}function lf({formatOptions:t,initialDate:e=new Date,locale:s="en-US",format:r="HH:mm"}){const[o,n]=y.useState(e),i=y.useCallback(v=>{n(E=>{const _=new Date(E);return _.setHours(Number(v)),_})},[]),a=y.useCallback(v=>{n(E=>{const _=new Date(E);return _.setMinutes(Number(v)),_})},[]),c=y.useCallback(v=>{n(E=>{const _=new Date(E);return _.setSeconds(Number(v)),_})},[]),u=y.useCallback(v=>{const E=new Date(v);n(E)},[]),d=cf(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:g}=af({formatOptions:t,locale:s});return{amPmOptions:g,formattedTime:d,hourOptions:h,minuteOptions:f,secondOptions:p,setHours:i,setMinutes:a,setSeconds:c,setTime:u,time:new Date(o)}}const x_=t=>{const{regionModel:e}=tf(),s=y.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return lf({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function R_(t,e,s={}){const{disposeOnUnmount:r=!0}=s,[o,n]=y.useState(!1),[i,a]=y.useState(void 0),c=y.useRef(null),u=y.useRef(!0),d=y.useRef(!1),h=y.useMemo(()=>{if(!u.current&&c.current&&r&&gr(c.current)){const p=c.current;Promise.resolve().then(()=>{gr(p)&&p.dispose()})}u.current=!1,d.current=!1;const f=t();return c.current=f,f},e);return y.useEffect(()=>{d.current||(Xc(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]),y.useEffect(()=>()=>{r&&c.current&&gr(c.current)&&c.current.dispose(),c.current=null},[r]),{viewModel:h,ready:o,error:i}}function P_(t){return e=>{const[s]=rf();return s?T.jsx(fh,{message:"Wait a moment while your project reloads..."}):T.jsx(t,{...e})}}const Ka=m.createLogger({name:"studio-properties-service",group:"Services"}),k_="/api/kos/studio/properties",uf=async t=>{if(Ka.debug("sending GET for studio-properties"),!t)throw Ka.error("connectionId is undefined"),new Error("connectionId is undefined");return await Ne.get(k_,{},{destinationAddress:t,timeout:500})},L_=Object.freeze(Object.defineProperty({__proto__:null,getStudioProperties:uf},Symbol.toStringTag,{value:"Module"}));var F_=Object.getOwnPropertyDescriptor,N_=(t,e,s,r)=>{for(var o=r>1?void 0:r?F_(e,s):e,n=t.length-1,i;n>=0;n--)(i=t[n])&&(o=i(o)||o);return o};const df="studio-properties-model",U_="/kos/studio/properties",qa={"kos.studio.tool.legacy":1};let gn=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=Re(),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=Nt.getInstance().subscribeTopic({topic:U_,destinationAddress:this.connectionId,callback:s=>{this.logger.error(`Received studio-properties message for connection ${this.connectionId}: ${JSON.stringify(s)}`)}});const[t,e]=await uf(this.connectionId);if(t){this.logger.error(`Error loading studio-properties: ${t}`),this.data.setValues(qa);return}if(e){const s=Object.keys(e).reduce((r,o)=>(r[o]=e[o]??o,r),{});this.data.setValues(s??qa),m.ifDebug(()=>this.logger.debug(`studio-properties loaded: ${JSON.stringify(s)}`))}}get(t){return this.data[t]}createObservableProperty(t){return ki(()=>this.get(t))}};gn=N_([P(df)],gn);const j_=new ve({class:gn,type:df});Object.defineProperty(exports,"makeAutoObservable",{enumerable:!0,get:()=>M.makeAutoObservable});Object.defineProperty(exports,"makeObservable",{enumerable:!0,get:()=>M.makeObservable});Object.defineProperty(exports,"kosComponent",{enumerable:!0,get:()=>yn.observer});exports.AncestorPathVisitor=Vm;exports.AuthState=xl;exports.BrowserKosRouter=nh;exports.BrowserRouter=ti;exports.CanvasDispatcher=Yt;exports.CanvasDispatcherServices=rE;exports.CanvasRenderer=Ei;exports.CanvasStreamer=kT;exports.CanvasStreamerBase=Sh;exports.ChildModels=_e;exports.CompanionParentModel=Je;exports.ConfigBean=xs;exports.ContainerAwareSetup=no;exports.CoreExtensionManager=eM;exports.CoreModels=$i;exports.CreateModelTranslationsContext=wh;exports.CreateModelTranslationsProvider=fT;exports.DateDisplayFormat=Yh;exports.DateHelpers=Jm;exports.DependencyLifecycle=D;exports.DependencyModels=x;exports.DependencyResolutionPolicy=Xe;exports.Device=Gr;exports.DeviceServices=SE;exports.DomIntersectionStrategy=sf;exports.EVENT_KOS_MODEL_READY=En;exports.EVENT_TROUBLE_ADDED=_y;exports.EVENT_TROUBLE_REMOVED=Sy;exports.EXTENSION_CANVAS_RENDERER=re;exports.EXTENSION_FEATURE_FLAG_RESOLVER=Kl;exports.EXTENSION_TROUBLE_DATA_MAPPER=Pr;exports.EXTENSION_TROUBLE_MAPPER=Js;exports.ErrorBoundaryWithFallback=ph;exports.EventBus=bf;exports.EventBusFunctional=wf;exports.EventBusState=Mf;exports.ExtensionException=pr;exports.ExtensionManager=$;exports.FUTURE_CONTAINER_MODEL_TYPE=Tu;exports.FUTURE_MODEL_TYPE=Jl;exports.FUTURE_NOT_ASSIGNED=Vn;exports.FeatureFlagService=ql;exports.FetchError=z;exports.FutureAliases=Pt;exports.FutureContainerFactory=tt;exports.FutureContainerModel=Su;exports.FutureContainerSetup=so;exports.FutureEndState=et;exports.FutureFactory=ss;exports.FutureHandler=lo;exports.FutureManager=gt;exports.FutureModel=nu;exports.FutureService=xt;exports.HEADER_CACHE_CONTROL=Qa;exports.HEADER_CONTENT_TYPE=Wa;exports.HEADER_DESTINATION_ADDR=Ge;exports.HEADER_FOS_REQUEST_ID=Za;exports.HEADER_METHOD=Zr;exports.HEADER_ORDERED=vn;exports.HEADER_REQUEST_ID=qs;exports.HEADER_REQUEST_TYPE=ke;exports.HEADER_RESPONSE_ID=Xr;exports.HEADER_SOURCE_ADDR=Ya;exports.HEADER_TOPIC=Ga;exports.HEADER_URL=Zt;exports.HEADER_WORK_TRACKER=wn;exports.HttpRouteHandlers=Be;exports.KOS_EXECUTION_CONTEXT=ao;exports.KOS_MODEL_ID=Mr;exports.KOS_SERVICE=cM;exports.KOS_SERVICE_1_6_5=oM;exports.KOS_SERVICE_1_8_1=iM;exports.KeyValue=ni;exports.KeyValueServices=bb;exports.Kos=le;exports.KosConfigPropertySpec=wt;exports.KosContainerIndex=kn;exports.KosContextBean=Xl;exports.KosContextManager=W;exports.KosCore=I;exports.KosCoreModelPropertyMapper=Se;exports.KosDataContainer=pi;exports.KosDependencyTypes=cp;exports.KosExpressionEvaluator=Lu;exports.KosExtensionUtils=Op;exports.KosFeatureFlags=zl;exports.KosFetchMethods=Fc;exports.KosGlobalConfig=In;exports.KosHttpRouteManager=jn;exports.KosLog=m;exports.KosLogManager=Uu;exports.KosLogManagerServices=Sv;exports.KosMockEvents=ec;exports.KosModel=Cl;exports.KosModelCollectionProvider=cT;exports.KosModelContainer=Fe;exports.KosModelContext=So;exports.KosModelEvents=F;exports.KosModelFactory=Os;exports.KosModelLoader=bh;exports.KosModelLoaderDisplay=vh;exports.KosModelManager=Al;exports.KosModelProvider=gh;exports.KosModelRegistrationFactory=ve;exports.KosModelRegistry=ln;exports.KosModelState=w;exports.KosModelSymbol=$n;exports.KosModelVisitor=Rl;exports.KosObservableData=jc;exports.KosRegistration=NM;exports.KosSingletonRegistration=UM;exports.KosTime=Ar;exports.KosTimeContext=Ni;exports.KosTimeProvider=ET;exports.KosTimeServices=xv;exports.KosTimer=Jd;exports.KosToken=oh;exports.KosTranslationProvider=$T;exports.KosTranslations=Md;exports.KosViewModelSymbol=$c;exports.KosWSTransportStatus=$l;exports.KosWsEvents=zs;exports.LOADER_FEATURE_FLAG=ey;exports.LOGIN_HOST=Xa;exports.LOGIN_URL=gf;exports.LoadingMessage=fh;exports.LogBlock=Ns;exports.LogBlockContainer=Eo;exports.LogConfig=Rt;exports.LogStream=Cs;exports.LogStreamContainer=Xs;exports.LogStreamServices=Kv;exports.LoggerSetup=oo;exports.MODEL_DELETION_DELAY=Dl;exports.MiddlewareChain=Wl;exports.ModelEffects=xe;exports.ModelError=ol;exports.MultipleFutureContainerSetup=ro;exports.MultipleFutureHandler=Nc;exports.NestedModelContext=Oo;exports.NetworkInterface=_i;exports.NetworkInterfaceContainer=Bs;exports.NetworkInterfaceServices=PE;exports.ObservableData=Re;exports.OptionsRequired=Vs;exports.Ota=Lr;exports.OutsideAlerter=qT;exports.PLUGIN_EXTENSION_NAME=Ip;exports.PORT=Ja;exports.PROFILE_ENABLE_RELEASES=_f;exports.PROFILE_LOG_DEBUG=bc;exports.PROFILE_LOG_INFO=vc;exports.PROFILE_RELAX_STORE_VALIDATION=Sf;exports.PROFILE_TOOLS_PREVIEW=yc;exports.ParentModel=_s;exports.PluginExtensionManager=$p;exports.ProgressBar=oT;exports.ReferenceConfig=fr;exports.RegionInfo=ne;exports.RegionServices=zy;exports.RegistrationManager=R;exports.Registry=JE;exports.ReloadAwareSetup=Cc;exports.ReplayStrategy=pt;exports.ResponseRetention=Z;exports.STATUS=bn;exports.ServiceFactory=ie;exports.ServiceRequestHandlers=He;exports.SingletonKosModelRegistrationFactory=Ce;exports.SoftwareInfo=Fr;exports.SoftwareInfoContext=ji;exports.SoftwareInfoProvider=_T;exports.SoftwareInfoServices=Sw;exports.StateActionHandlers=Pf;exports.StateBean=js;exports.StateBeanServices=Dw;exports.StateEntryHandlers=kt;exports.StateExitHandlers=Ss;exports.StateMachineSetup=Xt;exports.StateProp=yi;exports.StatePropServices=jw;exports.StorageDevice=Wr;exports.StorageDeviceContainer=Wt;exports.StorageDeviceServices=UE;exports.StudioProperties=j_;exports.StudioPropertiesServices=L_;exports.SubscriptionHandlers=X;exports.TIMER_END=Ai;exports.TIMER_EVENT=Ci;exports.TOPIC_TIMER_TICK_EVENT=Di;exports.TimerManager=eh;exports.TokenContext=_h;exports.TokenProvider=OT;exports.Topics=$s;exports.Trans=JT;exports.TransitionMap=yr;exports.Transitions=Nn;exports.Translation=jr;exports.TranslationContainer=Ve;exports.TranslationContainerContext=Bi;exports.TranslationContext=Qw;exports.TransportFactory=Xo;exports.Trouble=Us;exports.TroubleAwareSetup=Cn;exports.TroubleContainer=Vt;exports.TroubleServices=cw;exports.Troubles=ye;exports.UsbUpdate=Ii;exports.UsbUpdateContainer=Ks;exports.UsbUpdateServices=GE;exports.VFS_SERVICE=pM;exports.VFS_SERVICE_1_6_5=uM;exports.VFS_SERVICE_1_8_1=hM;exports.ViewModelConfig=Dn;exports.WS_EVENT_TYPE=Td;exports.WebSocketEvents=Te;exports.WebSocketTransport=Nt;exports.WsEventFactory=vi;exports.acceptOrgInvitation=hh;exports.addDaysToDate=Fl;exports.addFuture=tu;exports.addMonthsToDate=Ll;exports.api=iu;exports.applyFunctionalEnhancements=Fn;exports.applyMixins=Gm;exports.arraysEqual=Ym;exports.buildConfigBeanModel=Ny;exports.buildFuture=Wn;exports.buildFutureModel=ru;exports.cancelFuture=su;exports.checkAppsStarted=KM;exports.checkWildcardPattern=Zc;exports.clearAllServiceResponses=by;exports.clearPath=yy;exports.clearServiceResponse=my;exports.convert=ei;exports.convertFileSizeRaw=Tf;exports.convertWithUnits=Zy;exports.createBaseMessage=pl;exports.createBroadcastMessageResponse=wl;exports.createCancellablePromise=XM;exports.createClient=Ye;exports.createFosBaseMessage=fl;exports.createHeaders=gl;exports.createKosHtpMessageResponse=El;exports.createKosMessage=bl;exports.createKosMessageResponse=Ml;exports.createMessageBody=rt;exports.createModelDependency=al;exports.createOptionKey=sp;exports.createPropKey=yt;exports.createReadableStream=ml;exports.createStudioMessage=hl;exports.createStudioMessageRequest=yl;exports.createStudioMessageResponse=vl;exports.debounce=Wc;exports.declarativeModel=rh;exports.declarativeModelRegistry=RM;exports.del=Rc;exports.deleteFuture=eu;exports.destroyKosModel=Ae;exports.discoverAndRegisterModels=FM;exports.evaluateScopes=du;exports.executeChildrenModelLifecycle=ul;exports.executeDependentModelLifecycle=ds;exports.executeListLifecycle=ll;exports.fetchModel=UT;exports.findModel=Pp;exports.findModels=qc;exports.formatDate=jl;exports.formatDateSince=kl;exports.formatDateTime=Hl;exports.formatTime=Bl;exports.get=xc;exports.getAllKosCompanionModels=zc;exports.getCalendarMonthArray=Nh;exports.getConfigBean=uu;exports.getDayStrings=Uh;exports.getDays=h_;exports.getDaysArray=Ph;exports.getDaysInMonth=qn;exports.getDependenciesByLifecycle=cl;exports.getFormattedDate=f_;exports.getFormattedMonth=p_;exports.getFormattedMonthsArray=Ki;exports.getFormattedYear=Me;exports.getFormattedYearsArray=Fh;exports.getFutures=xy;exports.getHttpRouteHandlers=Pc;exports.getKosCompanionModel=kp;exports.getKosLocalizationDescriptor=yd;exports.getKosMessageLogging=Tc;exports.getKosModel=Kc;exports.getKosModelSync=Pe;exports.getKosModelType=Rp;exports.getKosSessionKey=Zl;exports.getLastDayOfMonth=Ts;exports.getLocalizationDescriptor=Hw;exports.getLogLevel=Mc;exports.getLogMessageToStudio=_c;exports.getMessageBody=Zo;exports.getMonthsArray=kh;exports.getObservableCompanions=Lp;exports.getQueryParams=be;exports.getServiceResponse=py;exports.getStartedApps=qM;exports.getTranslations=md;exports.getYearsArray=Lh;exports.hasCachedResponse=gy;exports.hasDecimals=cu;exports.hasHttpRouteHandlers=_r;exports.hasKosProfile=Go;exports.hasReadyHook=Xc;exports.hslStringToHex=Gl;exports.hslToHex=Vl;exports.httpDelete=up;exports.initKosProvider=gT;exports.initializeStateMachine=Dc;exports.injectStateMachineSupport=xn;exports.isBoolean=Zn;exports.isDisposable=gr;exports.isKosCompanionTypeFactory=el;exports.isKosDataModel=Is;exports.isKosExecutionContext=Rn;exports.isKosLoggingEnabled=$f;exports.isKosModel=$e;exports.isKosModelContainer=Un;exports.isKosModelReady=Sr;exports.isLeapYear=Kn;exports.isLocalRefId=wy;exports.isNumber=ho;exports.isPrintable=$g;exports.isTroubleAware=Zw;exports.isValidDate=Ms;exports.kosAction=te;exports.kosAutoEffect=Q;exports.kosChild=Le;exports.kosCompanion=op;exports.kosComputed=ki;exports.kosConfigBean=fo;exports.kosConfigProperty=zM;exports.kosContainerAware=Ac;exports.kosContext=np;exports.kosDependency=Jt;exports.kosEffect=ch;exports.kosFuture=Ri;exports.kosFutureAware=ip;exports.kosLogger=dp;exports.kosLoggerAware=kc;exports.kosModel=P;exports.kosModelEffect=Lc;exports.kosMultipleFutureAware=ap;exports.kosObservable=Li;exports.kosParentAware=io;exports.kosReference=hp;exports.kosServiceRequest=bt;exports.kosStateBean=VM;exports.kosStateEntry=bp;exports.kosStateExit=vp;exports.kosStateGuard=wp;exports.kosStateMachine=yp;exports.kosStateProp=GM;exports.kosSubscribe=Zp;exports.kosTopicHandler=B;exports.kosTroubleAware=Ep;exports.kosViewModel=yg;exports.kosWhen=hn;exports.login=lh;exports.mapConfigBeanModelToDto=gu;exports.mapDataToModel=Jo;exports.mapDtoToConfigBeanModel=fu;exports.mapDtoToFutureModel=Yn;exports.mapDtoToFutureOptions=Gn;exports.mapUpdateDtoToConfigBeanModel=pu;exports.modelBindings=cs;exports.modelEventTopicFactory=tl;exports.modelFactory=es;exports.modelTypeEventTopicFactory=sl;exports.modifyConfigBean=lu;exports.modifyFuture=Ry;exports.pairedClientHeartbeat=iy;exports.parseWildcardSegment=Qc;exports.pipe=Ql;exports.post=Gs;exports.preloadKosModel=Up;exports.processId=Xm;exports.processMiddleware=ry;exports.put=lp;exports.registerCompanionModel=Np;exports.registerCoreModels=Wd;exports.registerExtensionPoint=Ys;exports.registerHttpRoutes=Bg;exports.registerKosModel=Gc;exports.registerLegacyModel=Vc;exports.resetKosModel=xp;exports.resetPassword=dh;exports.resolveBaseUrl=Sl;exports.resolveChild=il;exports.resolveContainerDeltas=Wm;exports.resolveItemListDeltas=Zm;exports.resolveKosCompanion=Yo;exports.resolveKosContext=Ty;exports.resolveKosProfiles=Ec;exports.resolveListDeltas=Qm;exports.resolveServiceUrl=ue;exports.resolveVariable=Yl;exports.retryWithExponentialBackoff=cy;exports.sendAsyncIntent=BM;exports.sendBroadcastMessage=Jg;exports.sendIntent=jM;exports.sendKosHttpMessageResponse=_l;exports.sendKosMessage=Qg;exports.sendKosMessageResponse=Tl;exports.sendRequest=Ey;exports.sendStudioMessage=Xg;exports.sendStudioMessageRequest=Zg;exports.startPasswordReset=uh;exports.stringComponentInsert=Dh;exports.studioAcceptOrgInvitation=ZM;exports.studioLogin=YM;exports.studioResetPassword=QM;exports.studioStartPasswordReset=WM;exports.subscribeStore=tM;exports.syncPublish=My;exports.troubleByTypeReducer=Uc;exports.troubleDataFactory=id;exports.unloadKosModel=Ap;exports.updateCompanionModelRegistration=ny;exports.updateModelRegistration=oy;exports.updateRegion=Xd;exports.updateTimeZone=un;exports.useAmPmValues=nf;exports.useCalendarDayArray=Gh;exports.useConfigBean=l_;exports.useConfigProperty=Rh;exports.useContextModel=iT;exports.useContextModelHierarchy=yh;exports.useDateArrays=jh;exports.useDateProps=m_;exports.useDateRelativeConfig=y_;exports.useDateRelativeData=Qh;exports.useDayNames=zh;exports.useDayOptions=qh;exports.useDays=zi;exports.useDevice=Oh;exports.useFormattedDate=Vh;exports.useFormattedTime=cf;exports.useFunctionWarmup=b_;exports.useHourValues=of;exports.useKosCore=Mh;exports.useKosDateFormats=w_;exports.useKosModel=J;exports.useKosRegions=tf;exports.useKosTime=Fi;exports.useKosTimeContext=MT;exports.useKosTimeFormats=I_;exports.useKosTimeZones=T_;exports.useKosTranslation=r_;exports.useKosTranslationContext=CT;exports.useLocalComputed=$_;exports.useModelFromHierarchy=uT;exports.useMonths=Hh;exports.useMonthsOptions=Kh;exports.useMutationObserver=D_;exports.useNetworkInterfaceContainer=Ih;exports.useOta=$h;exports.usePressGesture=A_;exports.useProjectReload=rf;exports.useRegionTimeProps=x_;exports.useRegionalTimeDate=Wh;exports.useSoftwareInfo=Ui;exports.useSoftwareInfoContext=ST;exports.useStateProperty=zT;exports.useStorageDeviceContainer=Ch;exports.useSuspenseData=fn;exports.useTimeOptions=af;exports.useTimeProps=lf;exports.useTimeValues=pn;exports.useTimer=GT;exports.useTranslationContainer=Ah;exports.useTroubleContainerModel=Hi;exports.useTroubleModel=n_;exports.useTroublePresence=i_;exports.useUsbUpdateContainer=xh;exports.useViewModel=R_;exports.useYears=qi;exports.useYearsOptions=Bh;exports.uuid=vt;exports.variableToHex=ty;exports.waitForAppToStart=HM;exports.waitForAppsToStart=ah;exports.waitForRequest=zn;exports.whenReady=pe;exports.withDevice=NT;exports.withKosTime=jT;exports.withNetworkInterfaceContainer=BT;exports.withOta=HT;exports.withProjectReloading=P_;exports.withSoftwareInfo=TT;exports.withStorageDeviceContainer=VT;exports.withTranslationContainer=o_;exports.withTroubleContainer=a_;exports.withUsbUpdateContainer=c_;exports.wrapPromise=On;exports.wrapWithFutureLifecycle=xi;
227
+ `,ef=()=>{const t=Yr.type;return J({modelId:t,modelType:Yr.type,options:{}})};function AT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=ef();return _.jsx(o,{...r,children:_.jsx(t,{...e,device:s})})}}function xT(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 An(r)}function RT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Gi();return _.jsx(o,{...r,children:_.jsx(t,{...e,kosTime:s})})}}const tf=()=>{const t=Hs.type;return J({modelId:t,modelType:Hs.type,options:{}})};function PT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=tf();return _.jsx(o,{...r,children:_.jsx(t,{...e,networkInterfaceContainer:s})})}}const sf=()=>{const t=Kr.type;return J({modelId:t,modelType:Kr.type,options:{}})};function kT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=sf();return _.jsx(o,{...r,children:_.jsx(t,{...e,oTA:s})})}}function LT(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 FT(t){const e=m.useRef(null),s=t.onAlert;return LT(e,s),_.jsx("div",{ref:e,style:{width:"100%"},children:t.children})}const NT=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}]},rf=()=>{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 UT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=rf();return _.jsx(o,{...r,children:_.jsx(t,{...e,storageDeviceContainer:s})})}}const Qo=g.createLogger({name:"use-timer"}),jT=({timerName:t,onTimerExpired:e,onTimerTick:s,timerEventActions:r,autoStart:o})=>{const n=Th.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}},BT=t=>{const e=/[\\^$.*+?()[\]{}|]/g;return RegExp(e.source).test(t)?t.replace(e,"\\$&"):t},KT=t=>t instanceof RegExp,HT=t=>typeof t=="string",qT=(t,e,s)=>{if(t===""||e==="")return t;let r=e;KT(r)||(r=new RegExp("("+BT(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},of=(t,e,s)=>{let r=t;return Array.isArray(r)||(r=[r]),r.flatMap(o=>HT(o)?qT(o,e,s):o)};function zT(t,e){let s=t;return Object.entries(e).forEach(([r,o])=>{const n=new RegExp(`<${r}>(.*?)</${r}>|<${r}/>`,"g");s=of(s,n,(i,a)=>o.type==="br"?_.jsx("br",{}):m.cloneElement(o,{key:`${r}-${a}`},i))}),s}const VT=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=zT(a,o||{});return _.jsx("span",{className:t.className,children:c})},At=new Map;function GT(t,e){if(At.has(t)){const s=At.get(t);if(s.status==="finished")return s.result;throw s.promise}else{const s=e().then(o=>{At.set(t,{status:"finished",result:o})},o=>{throw At.set(t,{status:"error",error:o}),o}),r={status:"pending",promise:s};throw At.set(t,r),s}}function vn(t,e){return GT(t,e)}const YT=async()=>{const t=await ol(Ve.type);return await ye(t.model),t.model},WT=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),At.set(o,{status:"finished",result:n})}return r},QT=(t,e)=>{const s=[t].flat(),[r,...o]=s,n=vn(Ve.type,YT),i=s.join("__"),a=vn(i,()=>WT(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}},nf=()=>{const t=Ve.type;return J({modelId:t,modelType:Ve.type,options:{}})};function XT(t){return e=>{const{model:s,status:r,KosModelLoader:o}=nf();return _.jsx(o,{...r,children:_.jsx(t,{...e,translationContainer:s})})}}const ZT=t=>J({modelId:t,modelType:Ks.type}),Zi=()=>J({modelId:Ht.type,modelType:Ht.type,options:{}}),JT=({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 eS(t){return e=>{const{model:s,status:r,KosModelLoader:o}=Zi();return _.jsx(o,{...r,children:_.jsx(t,{...e,troubleContainer:s})})}}const af=()=>{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 tS(t){return e=>{const{model:s,status:r,KosModelLoader:o}=af();return _.jsx(o,{...r,children:_.jsx(t,{...e,usbUpdateContainer:s})})}}const sS=({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}},rS=(t,e)=>{switch(e.type){case"UPDATE":return e.payload;default:return t}},cf=({configProperty:t,optionsTransformer:e})=>{const[s,r]=m.useState(!1),[o,n]=m.useState(""),[i,a]=m.useReducer(rS,{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 oS(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 nS(t,e){return new Date(t,e,0).getDate()}function lf(t,e){const s=oS(e,t),r=[];for(let o=1;o<=s;o++)r.push(o);return r}function uf(){return[...Array(12).keys()].map(e=>new Date(0,e).getMonth())}function df(t=[2018,2028]){const e=[];for(let s=t[0];s<=t[1];s++)e.push(s);return e}function hf(t,e=[2018,2028]){const s=df(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 iS({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 aS(t){return typeof t=="string"?new Date(Date.parse(`01 ${t.substring(0,3)} 2023`)).getMonth()+1:t}function ff(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 pf(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 gf({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=mf(n,r,t),d=yf(i,t),h=bf(i,t),f=ta(e,s),p=vf(e,s,t,o),y=Mf(s,e,p),v=wf(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(()=>hf(t,e),[t,e])}function mf(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 yf(t,e="en-US"){return m.useMemo(()=>Ji(t,e),[t,e])}function bf(t,e="en-US"){const s=m.useMemo(()=>uf(),[]),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(()=>lf(s,e),[e,s])}const cS=(t,e,s,r=[])=>{const o=new Date(t,e,s).getDay();return r.length>0&&r.includes(o)};function vf(t,e,s="en-US",r=[]){const o=ta(t,e);return m.useMemo(()=>o.map(i=>({label:i.toLocaleString(s),value:i,disabled:cS(t,e,i,r)})),[r,s,e,o,t])}function wf(t="en-US",e="short"){return m.useMemo(()=>pf(t,e),[t,e])}function Ef({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 Mf(t,e,s){return m.useMemo(()=>ff(t,e,s),[t,e,s])}var _f=(t=>(t.MMDDYY="MMDDYY",t.DDMMYY="DDMMYY",t.YYMMDD="YYMMDD",t.YYDDMM="YYDDMM",t))(_f||{});function lS({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,O]=m.useState(r);m.useEffect(()=>{h(e)},[e]),m.useEffect(()=>{v(s)},[s]),m.useEffect(()=>{O(r)},[r]);const{yearsArray:U,yearsOptionsArray:A,monthsArray:$,monthsOptionsArray:P,daysArray:V,daysOptionsArray:ee,calendarDayArray:K,dayNamesArray:as}=gf({locale:t,year:d,yearRange:f,month:y,formatOptions:{yearFormat:o,monthFormat:n,dayFormat:i},daysOfWeekFilter:u}),{formattedDate:re}=Ef({year:d,month:y,day:M,formatString:a});return{dateActions:{setYear:h,setYearRange:p,setMonth:v,setDay:O,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);O(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);O(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);O(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);O(nt),h(ne)}}},dateState:{year:d,yearRange:f,month:y,day:M,yearsArray:U,yearsOptionsArray:A,monthsArray:$,monthsOptionsArray:P,daysArray:V,daysOptionsArray:ee,calendarDayNames:as,calendarDayArray:K,formattedDate:re}}}function Tf({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 Sf=({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}=Tf({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}}},uS=({configProperty:t})=>{const{value:e}=cf({configProperty:t}),s=parseInt(e||"0",10),{hours:r,minutes:o,seconds:n,formattedTime:i,timeActions:a}=Sf({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 dS(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 hS=t=>_.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),fS=(t=hS)=>{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}}},pS=t=>_.jsx("option",{title:t,value:t,children:t},t),Of="kos:service:region:settings",$f="timeZone",gS=`${Of}-${$f}`,mS=(t=pS)=>{const[e,s]=m.useState([]),[r,o]=m.useState(""),{model:n,ready:i}=J({modelType:ae.type,modelId:ae.type,options:{}}),a=Et.factory(gS)({path:Of,attribute:$f});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}}},If="kos:service:region",Cf="regionId",yS=`${If}-${Cf}`,bS=t=>_.jsx("option",{title:t,value:t,children:t},t),Df=(t=bS)=>{const[e,s]=m.useState([]),[r,o]=m.useState("factory"),{model:n,ready:i}=J({modelType:ae.type,modelId:ae.type}),a=Et.factory(yS)({path:If,attribute:Cf});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&&Eh(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}}},vS=t=>_.jsx("option",{title:t.id,value:t.format,children:t.format},t.id),wS=(t=vS)=>{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}}},ES=(t,e)=>m.useMemo(()=>si(t),e),MS={config:{attributes:!0,childList:!0,subtree:!0}};function _S(t,e,s=MS){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 Af={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 TS({onPressed:t,onRelease:e,intersectionStrategy:s=Af}){const r=m.useRef(!1),o=jf.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 xf=()=>{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 Rf(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 Pf(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 kf({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=Rf(t,e),i=wn(60,s),a=wn(60,r),c=Pf(o);return{hourOptions:n,minuteOptions:i,secondOptions:a,amPmOptions:c}}function Lf(t,e){return Xe.format(t,e)}function Ff({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 O=new Date(M);return O.setHours(Number(v)),O})},[]),a=m.useCallback(v=>{n(M=>{const O=new Date(M);return O.setMinutes(Number(v)),O})},[]),c=m.useCallback(v=>{n(M=>{const O=new Date(M);return O.setSeconds(Number(v)),O})},[]),u=m.useCallback(v=>{const M=new Date(v);n(M)},[]),d=Lf(o,r),{hourOptions:h,minuteOptions:f,secondOptions:p,amPmOptions:y}=kf({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 SS=t=>{const{regionModel:e}=Df(),s=m.useMemo(()=>({hour12:e==null?void 0:e.is12HourTimeFormat}),[e==null?void 0:e.is12HourTimeFormat]);return Ff({...t,locale:e==null?void 0:e.regionId,format:e==null?void 0:e.selectedTimeFormat,formatOptions:s})};function OS(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||(pl(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]=xf();return s?_.jsx(Bh,{message:"Wait a moment while your project reloads..."}):_.jsx(t,{...e})}}Kf({"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=Ey;exports.AuthState=Yl;exports.BrowserKosRouter=yu;exports.BrowserRouter=yi;exports.CanvasDispatcher=zt;exports.CanvasDispatcherServices=$E;exports.CanvasRenderer=Ci;exports.CanvasStreamer=IT;exports.CanvasStreamerBase=Jh;exports.ChildModels=Je;exports.CompanionParentModel=et;exports.ConfigBean=Rs;exports.ContainerAwareSetup=Nn;exports.CoreExtensionManager=UM;exports.CoreModels=ji;exports.CreateModelTranslationsContext=Yh;exports.CreateModelTranslationsProvider=iT;exports.DateDisplayFormat=_f;exports.DateHelpers=Iy;exports.DependencyLifecycle=I;exports.DependencyModels=F;exports.DependencyResolutionPolicy=Ze;exports.Device=Yr;exports.DeviceServices=WE;exports.DomIntersectionStrategy=Af;exports.EVENT_KOS_MODEL_READY=On;exports.EVENT_TROUBLE_ADDED=cb;exports.EVENT_TROUBLE_REMOVED=lb;exports.EXTENSION_CANVAS_RENDERER=oe;exports.EXTENSION_FEATURE_FLAG_RESOLVER=nu;exports.EXTENSION_FUTURE_LIFECYCLE_WRAPPER=sl;exports.EXTENSION_TROUBLE_DATA_MAPPER=jr;exports.EXTENSION_TROUBLE_MAPPER=sr;exports.ErrorBoundaryWithFallback=Kh;exports.EventBus=Vf;exports.EventBusFunctional=Yf;exports.EventBusState=Qf;exports.ExtensionException=mr;exports.ExtensionManager=T;exports.FUTURE_CONTAINER_MODEL_TYPE=Uu;exports.FUTURE_MODEL_TYPE=Nu;exports.FUTURE_NOT_ASSIGNED=oi;exports.FeatureFlagService=iu;exports.FetchError=z;exports.FutureAliases=Ts;exports.FutureContainerFactory=st;exports.FutureContainerModel=Wu;exports.FutureContainerSetup=Pn;exports.FutureEndState=tt;exports.FutureFactory=ts;exports.FutureHandler=po;exports.FutureManager=mt;exports.FutureModel=Yu;exports.FutureService=Es;exports.GpioChip=ro;exports.GpioChipContainer=Nh;exports.GpioChipServices=k_;exports.GpioPin=zi;exports.GpioPinContainer=Vi;exports.HEADER_CACHE_CONTROL=cc;exports.HEADER_CONTENT_TYPE=ac;exports.HEADER_DESTINATION_ADDR=Ge;exports.HEADER_FOS_REQUEST_ID=lc;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=ic;exports.HEADER_TOPIC=nc;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=wi;exports.KeyValueServices=Ev;exports.Kos=he;exports.KosConfigPropertySpec=Et;exports.KosContainerIndex=qn;exports.KosContextBean=gu;exports.KosContextManager=Q;exports.KosCore=S;exports.KosCoreModelPropertyMapper=se;exports.KosDataContainer=ti;exports.KosDependencyTypes=kp;exports.KosExpressionEvaluator=id;exports.KosExtensionUtils=Xp;exports.KosFeatureFlags=au;exports.KosFetchMethods=Xc;exports.KosGlobalConfig=xn;exports.KosHttpRouteManager=Yn;exports.KosLog=g;exports.KosLogManager=ld;exports.KosLogManagerServices=Iw;exports.KosLoggerFactory=Hn;exports.KosMockEvents=hc;exports.KosModel=zl;exports.KosModelCollectionProvider=tT;exports.KosModelContainer=Fe;exports.KosModelContext=Ao;exports.KosModelEvents=L;exports.KosModelFactory=Os;exports.KosModelLoader=Vh;exports.KosModelLoaderDisplay=Gh;exports.KosModelManager=Gl;exports.KosModelProvider=Hh;exports.KosModelRegistrationFactory=Ee;exports.KosModelRegistry=pn;exports.KosModelState=w;exports.KosModelSymbol=Rn;exports.KosModelVisitor=Wl;exports.KosObservableData=el;exports.KosRegistration=tb;exports.KosSingletonRegistration=sb;exports.KosTime=Fr;exports.KosTimeContext=Yi;exports.KosTimeProvider=pT;exports.KosTimeServices=kw;exports.KosTimer=_h;exports.KosToken=mu;exports.KosTranslationProvider=ET;exports.KosTranslations=mh;exports.KosViewModelSymbol=jc;exports.KosWSTransportStatus=ql;exports.KosWsEvents=Ws;exports.LOADER_FEATURE_FLAG=Cy;exports.LOGIN_HOST=uc;exports.LOGIN_URL=Hf;exports.LoadingMessage=Bh;exports.LogBlock=js;exports.LogBlockContainer=Oo;exports.LogConfig=_s;exports.LogStream=Cs;exports.LogStreamContainer=tr;exports.LogStreamServices=Vw;exports.LoggerSetup=Fn;exports.MODEL_DELETION_DELAY=Vl;exports.MiddlewareChain=du;exports.ModelEffects=Be;exports.ModelError=wl;exports.MultipleFutureContainerSetup=kn;exports.MultipleFutureHandler=Zc;exports.NestedModelContext=xo;exports.NetworkInterface=xi;exports.NetworkInterfaceContainer=Hs;exports.NetworkInterfaceServices=nM;exports.ObservableData=Pe;exports.OptionsRequired=Qs;exports.Ota=Kr;exports.OutsideAlerter=FT;exports.PLUGIN_EXTENSION_NAME=Zp;exports.PORT=dc;exports.PROFILE_ENABLE_RELEASES=Zf;exports.PROFILE_LOG_DEBUG=Dc;exports.PROFILE_LOG_INFO=Ac;exports.PROFILE_RELAX_STORE_VALIDATION=Jf;exports.PROFILE_TOOLS_PREVIEW=Cc;exports.ParentModel=Ms;exports.PluginExtensionManager=Jp;exports.ProgressBar=X_;exports.ReferenceConfig=gr;exports.RegionInfo=ae;exports.RegionServices=wb;exports.RegistrationManager=R;exports.Registry=FM;exports.ReloadAwareSetup=Bc;exports.ReplayStrategy=pt;exports.ResponseRetention=ie;exports.STATUS=_n;exports.ServiceFactory=ce;exports.ServiceRequestError=$r;exports.ServiceRequestHandlers=gt;exports.SingletonKosModelRegistrationFactory=Ce;exports.SoftwareInfo=eo;exports.SoftwareInfoContext=Qi;exports.SoftwareInfoProvider=yT;exports.SoftwareInfoServices=l_;exports.StateActionHandlers=cp;exports.StateBean=Ls;exports.StateBeanServices=Xb;exports.StateEntryHandlers=Rt;exports.StateExitHandlers=Ss;exports.StateMachineSetup=Wt;exports.StateProp=mi;exports.StatePropServices=cv;exports.StorageDevice=Qr;exports.StorageDeviceContainer=Vt;exports.StorageDeviceServices=uM;exports.StudioProperties=z_;exports.StudioPropertiesServices=B_;exports.SubscriptionHandlers=Z;exports.TIMER_END=Hi;exports.TIMER_EVENT=Bi;exports.TOPIC_TIMER_TICK_EVENT=Ki;exports.TimerManager=Th;exports.TokenContext=Zh;exports.TokenProvider=vT;exports.Topics=Is;exports.Trans=VT;exports.TransitionMap=vr;exports.Transitions=Vn;exports.Translation=Zr;exports.TranslationContainer=Ve;exports.TranslationContainerContext=Xi;exports.TranslationContext=xM;exports.TransportFactory=rn;exports.Trouble=Ks;exports.TroubleAwareSetup=Ln;exports.TroubleContainer=Ht;exports.TroubleServices=uE;exports.Troubles=we;exports.UsbUpdate=Li;exports.UsbUpdateContainer=zs;exports.UsbUpdateServices=bM;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=yh;exports.WebSocketEvents=Te;exports.WebSocketTransport=Lt;exports.WsEventFactory=Ni;exports.acceptOrgInvitation=Dh;exports.addDaysToDate=Jl;exports.addFuture=Lu;exports.addMonthsToDate=Zl;exports.api=Fd;exports.applyFunctionalEnhancements=fl;exports.applyMixins=My;exports.arraysEqual=_y;exports.buildConfigBeanModel=hb;exports.buildFuture=pi;exports.buildFutureModel=Pu;exports.cancelFuture=Fu;exports.checkAppsStarted=ib;exports.checkOrgAuthorization=Jy;exports.checkWildcardPattern=hl;exports.clearAllServiceResponses=Gy;exports.clearPath=Vy;exports.clearServiceResponse=zy;exports.convert=ui;exports.convertFileSizeRaw=Xf;exports.convertWithUnits=$b;exports.createBaseMessage=Dl;exports.createBroadcastMessageResponse=Ll;exports.createCancellablePromise=y_;exports.createClient=De;exports.createFosBaseMessage=Cl;exports.createHeaders=Al;exports.createKosHtpMessageResponse=Fl;exports.createKosMessage=Pl;exports.createKosMessageResponse=Nl;exports.createMessageBody=ot;exports.createModelDependency=_l;exports.createOptionKey=Dp;exports.createPropKey=vt;exports.createReadableStream=xl;exports.createStudioMessage=Il;exports.createStudioMessageRequest=Rl;exports.createStudioMessageResponse=kl;exports.debounce=ul;exports.del=zc;exports.deleteFuture=ku;exports.destroyKosModel=Re;exports.evaluateScopes=Su;exports.executeApiMethod=Wc;exports.executeChildrenModelLifecycle=Ol;exports.executeDependentModelLifecycle=ls;exports.executeListLifecycle=Sl;exports.fetchModel=xT;exports.findModel=ng;exports.findModels=nl;exports.formatDate=su;exports.formatDateSince=Xl;exports.formatDateTime=ou;exports.formatTime=ru;exports.get=qc;exports.getAllKosCompanionModels=il;exports.getCalendarMonthArray=ff;exports.getConfigBean=Tu;exports.getDayStrings=pf;exports.getDays=nS;exports.getDaysArray=lf;exports.getDaysInMonth=Jn;exports.getDependenciesByLifecycle=Tl;exports.getFormattedDate=iS;exports.getFormattedMonth=aS;exports.getFormattedMonthsArray=Ji;exports.getFormattedYear=_e;exports.getFormattedYearsArray=hf;exports.getFutures=qb;exports.getHttpRouteHandlers=Vc;exports.getKosCompanionModel=ig;exports.getKosConnectionId=Ri;exports.getKosLocalizationDescriptor=dh;exports.getKosMessageLogging=kc;exports.getKosModel=ol;exports.getKosModelSync=ke;exports.getKosModelType=og;exports.getKosServiceApi=KM;exports.getKosSessionKey=fu;exports.getLastDayOfMonth=ws;exports.getLocalizationDescriptor=TM;exports.getLogLevel=Pc;exports.getLogMessageToStudio=Lc;exports.getMessageBody=sn;exports.getMonthsArray=uf;exports.getObservableCompanions=ag;exports.getQueryParams=de;exports.getServiceResponse=Hy;exports.getStartedApps=ab;exports.getTranslations=uh;exports.getWhitelistedOrgs=Zy;exports.getYearsArray=df;exports.handleServiceRequestError=Qc;exports.hasCachedResponse=qy;exports.hasDecimals=Mu;exports.hasHttpRouteHandlers=Or;exports.hasKosProfile=Zo;exports.hasReadyHook=pl;exports.hslStringToHex=lu;exports.hslToHex=cu;exports.httpDelete=Fp;exports.initKosProvider=cT;exports.initializeStateMachine=Kc;exports.injectStateMachineSupport=Bn;exports.isBoolean=ii;exports.isDisposable=yr;exports.isKosCompanionTypeFactory=ml;exports.isKosDataModel=$s;exports.isKosExecutionContext=Kn;exports.isKosLoggingEnabled=sp;exports.isKosModel=Ie;exports.isKosModelContainer=Gn;exports.isKosModelReady=Ir;exports.isLeapYear=Zn;exports.isLocalRefId=Wy;exports.isNumber=go;exports.isPrintable=Jg;exports.isTroubleAware=h_;exports.isValidDate=vs;exports.kosAction=te;exports.kosAutoEffect=X;exports.kosChild=$e;exports.kosCompanion=xp;exports.kosComputed=si;exports.kosConfigBean=mo;exports.kosConfigProperty=Fb;exports.kosContainerAware=uo;exports.kosContext=Rp;exports.kosDependency=Xt;exports.kosEffect=wu;exports.kosFuture=bo;exports.kosFutureAware=Hc;exports.kosLogger=Np;exports.kosLoggerAware=Qt;exports.kosModel=D;exports.kosModelEffect=Gc;exports.kosMultipleFutureAware=Pp;exports.kosObservable=ri;exports.kosParentAware=lo;exports.kosReference=Up;exports.kosServiceRequest=Ye;exports.kosStateBean=tv;exports.kosStateEntry=Hp;exports.kosStateExit=qp;exports.kosStateGuard=zp;exports.kosStateMachine=Kp;exports.kosStateProp=lv;exports.kosSubscribe=Mg;exports.kosTopicHandler=B;exports.kosTroubleAware=Vp;exports.kosViewModel=Kg;exports.kosWhen=nn;exports.login=$h;exports.mapConfigBeanModelToDto=Cu;exports.mapDataToModel=on;exports.mapDtoToConfigBeanModel=$u;exports.mapDtoToFutureModel=fi;exports.mapDtoToFutureOptions=hi;exports.mapUpdateDtoToConfigBeanModel=Iu;exports.modelEventTopicFactory=yl;exports.modelFactory=Jt;exports.modelTypeEventTopicFactory=bl;exports.modifyConfigBean=_u;exports.modifyFuture=zb;exports.pairedClientHeartbeat=ky;exports.parseWildcardSegment=dl;exports.pipe=hu;exports.post=Xs;exports.preloadKosModel=ug;exports.processId=$y;exports.processMiddleware=xy;exports.put=Lp;exports.registerCompanionModel=lg;exports.registerCoreModels=bh;exports.registerExtensionPoint=Zt;exports.registerHttpRoutes=hm;exports.registerKosModel=cl;exports.registerLegacyModel=al;exports.resetKosModel=rg;exports.resetPassword=Ch;exports.resolveBaseUrl=Bl;exports.resolveChild=Ml;exports.resolveContainerDeltas=Ty;exports.resolveItemListDeltas=Oy;exports.resolveKosCompanion=Jo;exports.resolveKosContext=eb;exports.resolveKosProfiles=Rc;exports.resolveListDeltas=Sy;exports.resolveServiceRequestParameters=Yc;exports.resolveServiceUrl=fe;exports.resolveVariable=uu;exports.retryWithExponentialBackoff=Fy;exports.sendAsyncIntent=ob;exports.sendBroadcastMessage=Tm;exports.sendIntent=rb;exports.sendKosHttpMessageResponse=jl;exports.sendKosMessage=Em;exports.sendKosMessageResponse=Ul;exports.sendRequest=Qy;exports.sendStudioMessage=_m;exports.sendStudioMessageRequest=Mm;exports.startPasswordReset=Ih;exports.stringComponentInsert=of;exports.studioAcceptOrgInvitation=m_;exports.studioLogin=f_;exports.studioResetPassword=g_;exports.studioStartPasswordReset=p_;exports.subscribeStore=jM;exports.syncPublish=Xy;exports.troubleByTypeReducer=Jc;exports.troubleDataFactory=xd;exports.unloadKosModel=sg;exports.updateCompanionModelRegistration=Py;exports.updateModelRegistration=Ry;exports.updateRegion=Eh;exports.updateTimeZone=mn;exports.useAmPmValues=Pf;exports.useCalendarDayArray=Mf;exports.useConfigBean=sS;exports.useConfigProperty=cf;exports.useContextModel=J_;exports.useContextModelHierarchy=zh;exports.useDateArrays=gf;exports.useDateProps=lS;exports.useDateRelativeConfig=uS;exports.useDateRelativeData=Sf;exports.useDayNames=wf;exports.useDayOptions=vf;exports.useDays=ta;exports.useDevice=ef;exports.useFormattedDate=Ef;exports.useFormattedTime=Lf;exports.useFunctionWarmup=dS;exports.useHourValues=Rf;exports.useKosCore=Qh;exports.useKosDateFormats=fS;exports.useKosModel=J;exports.useKosRegions=Df;exports.useKosTime=Gi;exports.useKosTimeContext=gT;exports.useKosTimeFormats=wS;exports.useKosTimeZones=mS;exports.useKosTranslation=QT;exports.useKosTranslationContext=MT;exports.useLocalComputed=ES;exports.useModelFromHierarchy=rT;exports.useMonths=yf;exports.useMonthsOptions=bf;exports.useMutationObserver=_S;exports.useNetworkInterfaceContainer=tf;exports.useOta=sf;exports.usePressGesture=TS;exports.useProjectReload=xf;exports.useRegionTimeProps=SS;exports.useRegionalTimeDate=Tf;exports.useSoftwareInfo=Wi;exports.useSoftwareInfoContext=bT;exports.useStateProperty=NT;exports.useStorageDeviceContainer=rf;exports.useSuspenseData=vn;exports.useTimeOptions=kf;exports.useTimeProps=Ff;exports.useTimeValues=wn;exports.useTimer=jT;exports.useTranslationContainer=nf;exports.useTroubleContainerModel=Zi;exports.useTroubleModel=ZT;exports.useTroublePresence=JT;exports.useUsbUpdateContainer=af;exports.useViewModel=OS;exports.useYears=ea;exports.useYearsOptions=mf;exports.uuid=wt;exports.variableToHex=Dy;exports.waitForAppToStart=nb;exports.waitForAppsToStart=vu;exports.waitForRequest=ei;exports.whenReady=ye;exports.withDevice=AT;exports.withKosTime=RT;exports.withNetworkInterfaceContainer=PT;exports.withOta=kT;exports.withProjectReloading=$S;exports.withSoftwareInfo=mT;exports.withStorageDeviceContainer=UT;exports.withTranslationContainer=XT;exports.withTroubleContainer=eS;exports.withUsbUpdateContainer=tS;exports.wrapPromise=An;exports.wrapWithFutureLifecycle=gi;
228
228
  //# sourceMappingURL=index.cjs.map