@kosdev-code/kos-ui-sdk 2.0.2

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 (764) hide show
  1. package/common/constants/index.d.ts +26 -0
  2. package/common/constants/index.d.ts.map +1 -0
  3. package/common/events/eventBus.d.ts +18 -0
  4. package/common/events/eventBus.d.ts.map +1 -0
  5. package/common/events/index.d.ts +15 -0
  6. package/common/events/index.d.ts.map +1 -0
  7. package/common/file-utils.d.ts +9 -0
  8. package/common/file-utils.d.ts.map +1 -0
  9. package/common/index.d.ts +4 -0
  10. package/common/index.d.ts.map +1 -0
  11. package/common/types/global.d.ts +19 -0
  12. package/core/core/api/index.d.ts +2 -0
  13. package/core/core/api/index.d.ts.map +1 -0
  14. package/core/core/api/wrapPromise.d.ts +14 -0
  15. package/core/core/api/wrapPromise.d.ts.map +1 -0
  16. package/core/core/context/index.d.ts +2 -0
  17. package/core/core/context/index.d.ts.map +1 -0
  18. package/core/core/context/kos-context-manager.d.ts +30 -0
  19. package/core/core/context/kos-context-manager.d.ts.map +1 -0
  20. package/core/core/decorators/index.d.ts +13 -0
  21. package/core/core/decorators/index.d.ts.map +1 -0
  22. package/core/core/decorators/kos-child.d.ts +19 -0
  23. package/core/core/decorators/kos-child.d.ts.map +1 -0
  24. package/core/core/decorators/kos-companion.d.ts +11 -0
  25. package/core/core/decorators/kos-companion.d.ts.map +1 -0
  26. package/core/core/decorators/kos-context.d.ts +2 -0
  27. package/core/core/decorators/kos-context.d.ts.map +1 -0
  28. package/core/core/decorators/kos-log.d.ts +11 -0
  29. package/core/core/decorators/kos-log.d.ts.map +1 -0
  30. package/core/core/decorators/kos-model-effect.d.ts +25 -0
  31. package/core/core/decorators/kos-model-effect.d.ts.map +1 -0
  32. package/core/core/decorators/kos-parent.d.ts +11 -0
  33. package/core/core/decorators/kos-parent.d.ts.map +1 -0
  34. package/core/core/decorators/kos-reference.d.ts +6 -0
  35. package/core/core/decorators/kos-reference.d.ts.map +1 -0
  36. package/core/core/decorators/kosDependency.d.ts +16 -0
  37. package/core/core/decorators/kosDependency.d.ts.map +1 -0
  38. package/core/core/decorators/kosModel.d.ts +23 -0
  39. package/core/core/decorators/kosModel.d.ts.map +1 -0
  40. package/core/core/decorators/kosSubscribe.d.ts +9 -0
  41. package/core/core/decorators/kosSubscribe.d.ts.map +1 -0
  42. package/core/core/decorators/kosTopicHandler.d.ts +78 -0
  43. package/core/core/decorators/kosTopicHandler.d.ts.map +1 -0
  44. package/core/core/decorators/propKeys.d.ts +13 -0
  45. package/core/core/decorators/propKeys.d.ts.map +1 -0
  46. package/core/core/decorators/resolve-parameters.d.ts +8 -0
  47. package/core/core/decorators/resolve-parameters.d.ts.map +1 -0
  48. package/core/core/extension/extension-manager.d.ts +40 -0
  49. package/core/core/extension/extension-manager.d.ts.map +1 -0
  50. package/core/core/extension/index.d.ts +4 -0
  51. package/core/core/extension/index.d.ts.map +1 -0
  52. package/core/core/extension/initialize-extension.d.ts +45 -0
  53. package/core/core/extension/initialize-extension.d.ts.map +1 -0
  54. package/core/core/extension/plugin-extension-manager.d.ts +23 -0
  55. package/core/core/extension/plugin-extension-manager.d.ts.map +1 -0
  56. package/core/core/kos-container-index.d.ts +34 -0
  57. package/core/core/kos-container-index.d.ts.map +1 -0
  58. package/core/core/kos-container-model.d.ts +69 -0
  59. package/core/core/kos-container-model.d.ts.map +1 -0
  60. package/core/core/kos-data-container.d.ts +48 -0
  61. package/core/core/kos-data-container.d.ts.map +1 -0
  62. package/core/core/kos-deletion-manager.d.ts +5 -0
  63. package/core/core/kos-deletion-manager.d.ts.map +1 -0
  64. package/core/core/kos-model-factory.d.ts +19 -0
  65. package/core/core/kos-model-factory.d.ts.map +1 -0
  66. package/core/core/kos-registration.d.ts +26 -0
  67. package/core/core/kos-registration.d.ts.map +1 -0
  68. package/core/core/kos-singleton-registration.d.ts +25 -0
  69. package/core/core/kos-singleton-registration.d.ts.map +1 -0
  70. package/core/core/kosCore.d.ts +80 -0
  71. package/core/core/kosCore.d.ts.map +1 -0
  72. package/core/core/kosModel.d.ts +150 -0
  73. package/core/core/kosModel.d.ts.map +1 -0
  74. package/core/core/kosModelManager.d.ts +58 -0
  75. package/core/core/kosModelManager.d.ts.map +1 -0
  76. package/core/core/lifecycle/constants.d.ts +37 -0
  77. package/core/core/lifecycle/constants.d.ts.map +1 -0
  78. package/core/core/lifecycle/index.d.ts +2 -0
  79. package/core/core/lifecycle/index.d.ts.map +1 -0
  80. package/core/core/lifecycle/kosCoreLifecycle.d.ts +86 -0
  81. package/core/core/lifecycle/kosCoreLifecycle.d.ts.map +1 -0
  82. package/core/core/lifecycle/kosModelLifecycle.d.ts +57 -0
  83. package/core/core/lifecycle/kosModelLifecycle.d.ts.map +1 -0
  84. package/core/core/lifecycle/model-active-machine.d.ts +31 -0
  85. package/core/core/lifecycle/model-active-machine.d.ts.map +1 -0
  86. package/core/core/lifecycle/model-machine.d.ts +28 -0
  87. package/core/core/lifecycle/model-machine.d.ts.map +1 -0
  88. package/core/core/lifecycle/model-online-machine.d.ts +19 -0
  89. package/core/core/lifecycle/model-online-machine.d.ts.map +1 -0
  90. package/core/core/log/index.d.ts +2 -0
  91. package/core/core/log/index.d.ts.map +1 -0
  92. package/core/core/log/log.d.ts +36 -0
  93. package/core/core/log/log.d.ts.map +1 -0
  94. package/core/core/models/index.d.ts +2 -0
  95. package/core/core/models/index.d.ts.map +1 -0
  96. package/core/core/models/kos-core/index.d.ts +12 -0
  97. package/core/core/models/kos-core/index.d.ts.map +1 -0
  98. package/core/core/models/kos-token/index.d.ts +11 -0
  99. package/core/core/models/kos-token/index.d.ts.map +1 -0
  100. package/core/core/registration/base-kos-model-registration.d.ts +10 -0
  101. package/core/core/registration/base-kos-model-registration.d.ts.map +1 -0
  102. package/core/core/registration/index.d.ts +4 -0
  103. package/core/core/registration/index.d.ts.map +1 -0
  104. package/core/core/registration/model-registration.d.ts +44 -0
  105. package/core/core/registration/model-registration.d.ts.map +1 -0
  106. package/core/core/registration/registration-manager.d.ts +41 -0
  107. package/core/core/registration/registration-manager.d.ts.map +1 -0
  108. package/core/core/registration/singleton-kos-model-registration-factory.d.ts +10 -0
  109. package/core/core/registration/singleton-kos-model-registration-factory.d.ts.map +1 -0
  110. package/core/core/services/browser-router.d.ts +46 -0
  111. package/core/core/services/browser-router.d.ts.map +1 -0
  112. package/core/core/services/index.d.ts +3 -0
  113. package/core/core/services/index.d.ts.map +1 -0
  114. package/core/core/services/intent-service.d.ts +8 -0
  115. package/core/core/services/intent-service.d.ts.map +1 -0
  116. package/core/core/transport/base-message-transport.d.ts +53 -0
  117. package/core/core/transport/base-message-transport.d.ts.map +1 -0
  118. package/core/core/transport/bridge-message-transport.d.ts +7 -0
  119. package/core/core/transport/bridge-message-transport.d.ts.map +1 -0
  120. package/core/core/transport/bridge-transport.d.ts +29 -0
  121. package/core/core/transport/bridge-transport.d.ts.map +1 -0
  122. package/core/core/transport/detect-wakeup.d.ts +2 -0
  123. package/core/core/transport/detect-wakeup.d.ts.map +1 -0
  124. package/core/core/transport/fos-message-transport.d.ts +7 -0
  125. package/core/core/transport/fos-message-transport.d.ts.map +1 -0
  126. package/core/core/transport/index.d.ts +3 -0
  127. package/core/core/transport/index.d.ts.map +1 -0
  128. package/core/core/transport/kos-message-transport.d.ts +7 -0
  129. package/core/core/transport/kos-message-transport.d.ts.map +1 -0
  130. package/core/core/transport/transport-factory.d.ts +27 -0
  131. package/core/core/transport/transport-factory.d.ts.map +1 -0
  132. package/core/core/transport/transport.d.ts +12 -0
  133. package/core/core/transport/transport.d.ts.map +1 -0
  134. package/core/core/transport/web-socket-transport-adapter.d.ts +6 -0
  135. package/core/core/transport/web-socket-transport-adapter.d.ts.map +1 -0
  136. package/core/core/transport/webSocketTransport.d.ts +83 -0
  137. package/core/core/transport/webSocketTransport.d.ts.map +1 -0
  138. package/core/core/types/index.d.ts +4 -0
  139. package/core/core/types/index.d.ts.map +1 -0
  140. package/core/core/types/kos-model-manager-types.d.ts +33 -0
  141. package/core/core/types/kos-model-manager-types.d.ts.map +1 -0
  142. package/core/core/types/model.d.ts +26 -0
  143. package/core/core/types/model.d.ts.map +1 -0
  144. package/core/core/types/registration.d.ts +54 -0
  145. package/core/core/types/registration.d.ts.map +1 -0
  146. package/core/core/types/serviceTypes.d.ts +9 -0
  147. package/core/core/types/serviceTypes.d.ts.map +1 -0
  148. package/core/index.d.ts +61 -0
  149. package/core/index.d.ts.map +1 -0
  150. package/core/lib/kos-ui-core.d.ts +2 -0
  151. package/core/lib/kos-ui-core.d.ts.map +1 -0
  152. package/core/mocks/browser.d.ts +3 -0
  153. package/core/mocks/browser.d.ts.map +1 -0
  154. package/core/mocks/handlers.d.ts +3 -0
  155. package/core/mocks/handlers.d.ts.map +1 -0
  156. package/core/mocks/server.d.ts +3 -0
  157. package/core/mocks/server.d.ts.map +1 -0
  158. package/core/types/global.d.ts +68 -0
  159. package/core/types/index.d.ts +4 -0
  160. package/core/types/index.d.ts.map +1 -0
  161. package/core/types/kos-dependency.d.ts +21 -0
  162. package/core/types/kos-dependency.d.ts.map +1 -0
  163. package/core/types/model.d.ts +100 -0
  164. package/core/types/model.d.ts.map +1 -0
  165. package/core/types/utils/kos-fetch.d.ts +124 -0
  166. package/core/types/utils/kos-fetch.d.ts.map +1 -0
  167. package/core/util/api-request-id.d.ts +2 -0
  168. package/core/util/api-request-id.d.ts.map +1 -0
  169. package/core/util/apply-mixins.d.ts +2 -0
  170. package/core/util/apply-mixins.d.ts.map +1 -0
  171. package/core/util/container-utils.d.ts +26 -0
  172. package/core/util/container-utils.d.ts.map +1 -0
  173. package/core/util/cycle-detection.d.ts +12 -0
  174. package/core/util/cycle-detection.d.ts.map +1 -0
  175. package/core/util/date-utils.d.ts +2 -0
  176. package/core/util/date-utils.d.ts.map +1 -0
  177. package/core/util/debounce.d.ts +19 -0
  178. package/core/util/debounce.d.ts.map +1 -0
  179. package/core/util/feature-flags.d.ts +13 -0
  180. package/core/util/feature-flags.d.ts.map +1 -0
  181. package/core/util/get-query-params.d.ts +2 -0
  182. package/core/util/get-query-params.d.ts.map +1 -0
  183. package/core/util/hsl-to-hex.d.ts +5 -0
  184. package/core/util/hsl-to-hex.d.ts.map +1 -0
  185. package/core/util/index.d.ts +30 -0
  186. package/core/util/index.d.ts.map +1 -0
  187. package/core/util/kos-config-init.d.ts +15 -0
  188. package/core/util/kos-config-init.d.ts.map +1 -0
  189. package/core/util/kos-core-utils.d.ts +4 -0
  190. package/core/util/kos-core-utils.d.ts.map +1 -0
  191. package/core/util/kos-data-mapper-utils.d.ts +14 -0
  192. package/core/util/kos-data-mapper-utils.d.ts.map +1 -0
  193. package/core/util/kos-fetch.d.ts +18 -0
  194. package/core/util/kos-fetch.d.ts.map +1 -0
  195. package/core/util/kos-message-utils.d.ts +34 -0
  196. package/core/util/kos-message-utils.d.ts.map +1 -0
  197. package/core/util/kos-model-formatter.d.ts +21 -0
  198. package/core/util/kos-model-formatter.d.ts.map +1 -0
  199. package/core/util/kos-model-utils.d.ts +100 -0
  200. package/core/util/kos-model-utils.d.ts.map +1 -0
  201. package/core/util/kos-model-visitor.d.ts +41 -0
  202. package/core/util/kos-model-visitor.d.ts.map +1 -0
  203. package/core/util/kos-service-request.d.ts +65 -0
  204. package/core/util/kos-service-request.d.ts.map +1 -0
  205. package/core/util/log-utils.d.ts +6 -0
  206. package/core/util/log-utils.d.ts.map +1 -0
  207. package/core/util/logger-plugin.d.ts +2 -0
  208. package/core/util/logger-plugin.d.ts.map +1 -0
  209. package/core/util/middleware.d.ts +14 -0
  210. package/core/util/middleware.d.ts.map +1 -0
  211. package/core/util/model-attribute-utils.d.ts +37 -0
  212. package/core/util/model-attribute-utils.d.ts.map +1 -0
  213. package/core/util/model-factory.d.ts +5 -0
  214. package/core/util/model-factory.d.ts.map +1 -0
  215. package/core/util/model-registration-utils.d.ts +6 -0
  216. package/core/util/model-registration-utils.d.ts.map +1 -0
  217. package/core/util/model-utils.d.ts +42 -0
  218. package/core/util/model-utils.d.ts.map +1 -0
  219. package/core/util/observable-proxy-map.d.ts +10 -0
  220. package/core/util/observable-proxy-map.d.ts.map +1 -0
  221. package/core/util/paired-client-heartbeat.d.ts +18 -0
  222. package/core/util/paired-client-heartbeat.d.ts.map +1 -0
  223. package/core/util/pipe.d.ts +4 -0
  224. package/core/util/pipe.d.ts.map +1 -0
  225. package/core/util/reference-cache.d.ts +17 -0
  226. package/core/util/reference-cache.d.ts.map +1 -0
  227. package/core/util/retry-with-exponential-backoff.d.ts +18 -0
  228. package/core/util/retry-with-exponential-backoff.d.ts.map +1 -0
  229. package/core/util/service-factory.d.ts +177 -0
  230. package/core/util/service-factory.d.ts.map +1 -0
  231. package/core/util/session-utils.d.ts +3 -0
  232. package/core/util/session-utils.d.ts.map +1 -0
  233. package/core/util/setRandomInterval.d.ts +5 -0
  234. package/core/util/setRandomInterval.d.ts.map +1 -0
  235. package/core/util/wait-for-request.d.ts +15 -0
  236. package/core/util/wait-for-request.d.ts.map +1 -0
  237. package/core/util/when-ready.d.ts +21 -0
  238. package/core/util/when-ready.d.ts.map +1 -0
  239. package/index.cjs +146 -0
  240. package/index.cjs.map +1 -0
  241. package/index.d.cts +6 -0
  242. package/index.d.ts +6 -0
  243. package/index.d.ts.map +1 -0
  244. package/index.js +10456 -0
  245. package/index.js.map +1 -0
  246. package/models/constants/index.d.ts +18 -0
  247. package/models/constants/index.d.ts.map +1 -0
  248. package/models/decorators/future-service.d.ts +7 -0
  249. package/models/decorators/future-service.d.ts.map +1 -0
  250. package/models/decorators/index.d.ts +6 -0
  251. package/models/decorators/index.d.ts.map +1 -0
  252. package/models/decorators/kos-config-bean-prop.d.ts +42 -0
  253. package/models/decorators/kos-config-bean-prop.d.ts.map +1 -0
  254. package/models/decorators/kos-config-bean.d.ts +8 -0
  255. package/models/decorators/kos-config-bean.d.ts.map +1 -0
  256. package/models/decorators/kos-state-bean.d.ts +6 -0
  257. package/models/decorators/kos-state-bean.d.ts.map +1 -0
  258. package/models/decorators/kos-state-prop.d.ts +10 -0
  259. package/models/decorators/kos-state-prop.d.ts.map +1 -0
  260. package/models/index.d.ts +11 -0
  261. package/models/index.d.ts.map +1 -0
  262. package/models/model.d.ts +7 -0
  263. package/models/models/browser-router/browser-router-model.d.ts +17 -0
  264. package/models/models/browser-router/browser-router-model.d.ts.map +1 -0
  265. package/models/models/browser-router/browser-router-registration.d.ts +89 -0
  266. package/models/models/browser-router/browser-router-registration.d.ts.map +1 -0
  267. package/models/models/browser-router/index.d.ts +4 -0
  268. package/models/models/browser-router/index.d.ts.map +1 -0
  269. package/models/models/browser-router/types/index.d.ts +1 -0
  270. package/models/models/browser-router/utils/index.d.ts +2 -0
  271. package/models/models/browser-router/utils/index.d.ts.map +1 -0
  272. package/models/models/browser-router/utils/init-kos-browser-router.d.ts +2 -0
  273. package/models/models/browser-router/utils/init-kos-browser-router.d.ts.map +1 -0
  274. package/models/models/config-bean/config-bean-model-builder.d.ts +57 -0
  275. package/models/models/config-bean/config-bean-model-builder.d.ts.map +1 -0
  276. package/models/models/config-bean/config-bean-model.d.ts +75 -0
  277. package/models/models/config-bean/config-bean-model.d.ts.map +1 -0
  278. package/models/models/config-bean/config-bean-types.d.ts +66 -0
  279. package/models/models/config-bean/config-bean-types.d.ts.map +1 -0
  280. package/models/models/config-bean/index.d.ts +4 -0
  281. package/models/models/config-bean/index.d.ts.map +1 -0
  282. package/models/models/config-bean-prop/config-bean-prop-model.d.ts +86 -0
  283. package/models/models/config-bean-prop/config-bean-prop-model.d.ts.map +1 -0
  284. package/models/models/config-bean-prop/config-options-factory.d.ts +6 -0
  285. package/models/models/config-bean-prop/config-options-factory.d.ts.map +1 -0
  286. package/models/models/config-bean-prop/index.d.ts +3 -0
  287. package/models/models/config-bean-prop/index.d.ts.map +1 -0
  288. package/models/models/config-bean-prop/types/index.d.ts +76 -0
  289. package/models/models/device/device-model.d.ts +48 -0
  290. package/models/models/device/device-model.d.ts.map +1 -0
  291. package/models/models/device/device-registration.d.ts +89 -0
  292. package/models/models/device/device-registration.d.ts.map +1 -0
  293. package/models/models/device/index.d.ts +5 -0
  294. package/models/models/device/index.d.ts.map +1 -0
  295. package/models/models/device/services/device-services.d.ts +21 -0
  296. package/models/models/device/services/device-services.d.ts.map +1 -0
  297. package/models/models/device/services/index.d.ts +2 -0
  298. package/models/models/device/services/index.d.ts.map +1 -0
  299. package/models/models/device/types/index.d.ts +5 -0
  300. package/models/models/future/future-aware.d.ts +32 -0
  301. package/models/models/future/future-aware.d.ts.map +1 -0
  302. package/models/models/future/future-factory.d.ts +5 -0
  303. package/models/models/future/future-factory.d.ts.map +1 -0
  304. package/models/models/future/future-model-builder.d.ts +76 -0
  305. package/models/models/future/future-model-builder.d.ts.map +1 -0
  306. package/models/models/future/future-model.d.ts +66 -0
  307. package/models/models/future/future-model.d.ts.map +1 -0
  308. package/models/models/future/future-types.d.ts +83 -0
  309. package/models/models/future/future-types.d.ts.map +1 -0
  310. package/models/models/future/index.d.ts +6 -0
  311. package/models/models/future/index.d.ts.map +1 -0
  312. package/models/models/future-container/future-container-factory.d.ts +5 -0
  313. package/models/models/future-container/future-container-factory.d.ts.map +1 -0
  314. package/models/models/future-container/future-container-model.d.ts +124 -0
  315. package/models/models/future-container/future-container-model.d.ts.map +1 -0
  316. package/models/models/future-container/future-container-types.d.ts +109 -0
  317. package/models/models/future-container/future-container-types.d.ts.map +1 -0
  318. package/models/models/future-container/index.d.ts +4 -0
  319. package/models/models/future-container/index.d.ts.map +1 -0
  320. package/models/models/index.d.ts +20 -0
  321. package/models/models/index.d.ts.map +1 -0
  322. package/models/models/key-value/index.d.ts +5 -0
  323. package/models/models/key-value/index.d.ts.map +1 -0
  324. package/models/models/key-value/key-value-model.d.ts +19 -0
  325. package/models/models/key-value/key-value-model.d.ts.map +1 -0
  326. package/models/models/key-value/key-value-registration.d.ts +89 -0
  327. package/models/models/key-value/key-value-registration.d.ts.map +1 -0
  328. package/models/models/key-value/services/index.d.ts +2 -0
  329. package/models/models/key-value/services/index.d.ts.map +1 -0
  330. package/models/models/key-value/services/key-value-services.d.ts +18 -0
  331. package/models/models/key-value/services/key-value-services.d.ts.map +1 -0
  332. package/models/models/key-value/types/index.d.ts +3 -0
  333. package/models/models/kos-core/index.d.ts +11 -0
  334. package/models/models/kos-core/index.d.ts.map +1 -0
  335. package/models/models/kos-time/index.d.ts +5 -0
  336. package/models/models/kos-time/index.d.ts.map +1 -0
  337. package/models/models/kos-time/kos-time-model.d.ts +36 -0
  338. package/models/models/kos-time/kos-time-model.d.ts.map +1 -0
  339. package/models/models/kos-time/kos-time-registration.d.ts +87 -0
  340. package/models/models/kos-time/kos-time-registration.d.ts.map +1 -0
  341. package/models/models/kos-time/services/index.d.ts +2 -0
  342. package/models/models/kos-time/services/index.d.ts.map +1 -0
  343. package/models/models/kos-time/services/kos-time-services.d.ts +16 -0
  344. package/models/models/kos-time/services/kos-time-services.d.ts.map +1 -0
  345. package/models/models/kos-time/types/index.d.ts +13 -0
  346. package/models/models/kos-token/index.d.ts +11 -0
  347. package/models/models/kos-token/index.d.ts.map +1 -0
  348. package/models/models/log-block/index.d.ts +6 -0
  349. package/models/models/log-block/index.d.ts.map +1 -0
  350. package/models/models/log-block/log-block-container-model.d.ts +23 -0
  351. package/models/models/log-block/log-block-container-model.d.ts.map +1 -0
  352. package/models/models/log-block/log-block-container-registration.d.ts +87 -0
  353. package/models/models/log-block/log-block-container-registration.d.ts.map +1 -0
  354. package/models/models/log-block/log-block-model.d.ts +28 -0
  355. package/models/models/log-block/log-block-model.d.ts.map +1 -0
  356. package/models/models/log-block/log-block-registration.d.ts +87 -0
  357. package/models/models/log-block/log-block-registration.d.ts.map +1 -0
  358. package/models/models/log-block/types/index.d.ts +38 -0
  359. package/models/models/log-stream/index.d.ts +7 -0
  360. package/models/models/log-stream/index.d.ts.map +1 -0
  361. package/models/models/log-stream/log-stream-container-model.d.ts +35 -0
  362. package/models/models/log-stream/log-stream-container-model.d.ts.map +1 -0
  363. package/models/models/log-stream/log-stream-container-registration.d.ts +87 -0
  364. package/models/models/log-stream/log-stream-container-registration.d.ts.map +1 -0
  365. package/models/models/log-stream/log-stream-model.d.ts +38 -0
  366. package/models/models/log-stream/log-stream-model.d.ts.map +1 -0
  367. package/models/models/log-stream/log-stream-registration.d.ts +87 -0
  368. package/models/models/log-stream/log-stream-registration.d.ts.map +1 -0
  369. package/models/models/log-stream/services/index.d.ts +2 -0
  370. package/models/models/log-stream/services/index.d.ts.map +1 -0
  371. package/models/models/log-stream/services/log-stream-services.d.ts +22 -0
  372. package/models/models/log-stream/services/log-stream-services.d.ts.map +1 -0
  373. package/models/models/log-stream/types/index.d.ts +9 -0
  374. package/models/models/network-interface/index.d.ts +7 -0
  375. package/models/models/network-interface/index.d.ts.map +1 -0
  376. package/models/models/network-interface/network-interface-container-model.d.ts +21 -0
  377. package/models/models/network-interface/network-interface-container-model.d.ts.map +1 -0
  378. package/models/models/network-interface/network-interface-container-registration.d.ts +86 -0
  379. package/models/models/network-interface/network-interface-container-registration.d.ts.map +1 -0
  380. package/models/models/network-interface/network-interface-model.d.ts +25 -0
  381. package/models/models/network-interface/network-interface-model.d.ts.map +1 -0
  382. package/models/models/network-interface/network-interface-registration.d.ts +86 -0
  383. package/models/models/network-interface/network-interface-registration.d.ts.map +1 -0
  384. package/models/models/network-interface/services/index.d.ts +2 -0
  385. package/models/models/network-interface/services/index.d.ts.map +1 -0
  386. package/models/models/network-interface/services/network-interface-services.d.ts +46 -0
  387. package/models/models/network-interface/services/network-interface-services.d.ts.map +1 -0
  388. package/models/models/network-interface/types/index.d.ts +10 -0
  389. package/models/models/ota/index.d.ts +4 -0
  390. package/models/models/ota/index.d.ts.map +1 -0
  391. package/models/models/ota/ota-model.d.ts +26 -0
  392. package/models/models/ota/ota-model.d.ts.map +1 -0
  393. package/models/models/ota/ota-registration.d.ts +89 -0
  394. package/models/models/ota/ota-registration.d.ts.map +1 -0
  395. package/models/models/ota/services/index.d.ts +2 -0
  396. package/models/models/ota/services/index.d.ts.map +1 -0
  397. package/models/models/ota/services/ota-services.d.ts +8 -0
  398. package/models/models/ota/services/ota-services.d.ts.map +1 -0
  399. package/models/models/ota/types/index.d.ts +56 -0
  400. package/models/models/region-info/index.d.ts +5 -0
  401. package/models/models/region-info/index.d.ts.map +1 -0
  402. package/models/models/region-info/region-info-model.d.ts +95 -0
  403. package/models/models/region-info/region-info-model.d.ts.map +1 -0
  404. package/models/models/region-info/services/index.d.ts +2 -0
  405. package/models/models/region-info/services/index.d.ts.map +1 -0
  406. package/models/models/region-info/services/region-info-services.d.ts +48 -0
  407. package/models/models/region-info/services/region-info-services.d.ts.map +1 -0
  408. package/models/models/region-info/types/index.d.ts +168 -0
  409. package/models/models/region-info/types/index.d.ts.map +1 -0
  410. package/models/models/region-info/utils/unit-system-utils.d.ts +4 -0
  411. package/models/models/region-info/utils/unit-system-utils.d.ts.map +1 -0
  412. package/models/models/software-info/index.d.ts +4 -0
  413. package/models/models/software-info/index.d.ts.map +1 -0
  414. package/models/models/software-info/services/index.d.ts +2 -0
  415. package/models/models/software-info/services/index.d.ts.map +1 -0
  416. package/models/models/software-info/services/software-info-services.d.ts +22 -0
  417. package/models/models/software-info/services/software-info-services.d.ts.map +1 -0
  418. package/models/models/software-info/software-info-model.d.ts +14 -0
  419. package/models/models/software-info/software-info-model.d.ts.map +1 -0
  420. package/models/models/software-info/software-info-registration.d.ts +84 -0
  421. package/models/models/software-info/software-info-registration.d.ts.map +1 -0
  422. package/models/models/software-info/types/index.d.ts +35 -0
  423. package/models/models/state-bean/index.d.ts +4 -0
  424. package/models/models/state-bean/index.d.ts.map +1 -0
  425. package/models/models/state-bean/services/index.d.ts +2 -0
  426. package/models/models/state-bean/services/index.d.ts.map +1 -0
  427. package/models/models/state-bean/services/state-bean-services.d.ts +14 -0
  428. package/models/models/state-bean/services/state-bean-services.d.ts.map +1 -0
  429. package/models/models/state-bean/state-bean-model.d.ts +29 -0
  430. package/models/models/state-bean/state-bean-model.d.ts.map +1 -0
  431. package/models/models/state-bean/state-bean-registration.d.ts +84 -0
  432. package/models/models/state-bean/state-bean-registration.d.ts.map +1 -0
  433. package/models/models/state-bean/types/index.d.ts +24 -0
  434. package/models/models/state-prop/index.d.ts +4 -0
  435. package/models/models/state-prop/index.d.ts.map +1 -0
  436. package/models/models/state-prop/services/index.d.ts +2 -0
  437. package/models/models/state-prop/services/index.d.ts.map +1 -0
  438. package/models/models/state-prop/services/state-prop-services.d.ts +11 -0
  439. package/models/models/state-prop/services/state-prop-services.d.ts.map +1 -0
  440. package/models/models/state-prop/state-prop-model.d.ts +19 -0
  441. package/models/models/state-prop/state-prop-model.d.ts.map +1 -0
  442. package/models/models/state-prop/state-prop-registration.d.ts +84 -0
  443. package/models/models/state-prop/state-prop-registration.d.ts.map +1 -0
  444. package/models/models/state-prop/types/index.d.ts +20 -0
  445. package/models/models/storage-device/index.d.ts +7 -0
  446. package/models/models/storage-device/index.d.ts.map +1 -0
  447. package/models/models/storage-device/services/index.d.ts +2 -0
  448. package/models/models/storage-device/services/index.d.ts.map +1 -0
  449. package/models/models/storage-device/services/storage-device-services.d.ts +22 -0
  450. package/models/models/storage-device/services/storage-device-services.d.ts.map +1 -0
  451. package/models/models/storage-device/storage-device-container-model.d.ts +31 -0
  452. package/models/models/storage-device/storage-device-container-model.d.ts.map +1 -0
  453. package/models/models/storage-device/storage-device-container-registration.d.ts +86 -0
  454. package/models/models/storage-device/storage-device-container-registration.d.ts.map +1 -0
  455. package/models/models/storage-device/storage-device-model.d.ts +27 -0
  456. package/models/models/storage-device/storage-device-model.d.ts.map +1 -0
  457. package/models/models/storage-device/storage-device-registration.d.ts +87 -0
  458. package/models/models/storage-device/storage-device-registration.d.ts.map +1 -0
  459. package/models/models/storage-device/types/index.d.ts +20 -0
  460. package/models/models/translation/constants.d.ts +2 -0
  461. package/models/models/translation/constants.d.ts.map +1 -0
  462. package/models/models/translation/index.d.ts +9 -0
  463. package/models/models/translation/index.d.ts.map +1 -0
  464. package/models/models/translation/services/index.d.ts +2 -0
  465. package/models/models/translation/services/index.d.ts.map +1 -0
  466. package/models/models/translation/services/translation-services.d.ts +25 -0
  467. package/models/models/translation/services/translation-services.d.ts.map +1 -0
  468. package/models/models/translation/translation-container-model.d.ts +36 -0
  469. package/models/models/translation/translation-container-model.d.ts.map +1 -0
  470. package/models/models/translation/translation-container-registration.d.ts +87 -0
  471. package/models/models/translation/translation-container-registration.d.ts.map +1 -0
  472. package/models/models/translation/translation-context.d.ts +27 -0
  473. package/models/models/translation/translation-context.d.ts.map +1 -0
  474. package/models/models/translation/translation-model.d.ts +42 -0
  475. package/models/models/translation/translation-model.d.ts.map +1 -0
  476. package/models/models/translation/translation-registration.d.ts +85 -0
  477. package/models/models/translation/translation-registration.d.ts.map +1 -0
  478. package/models/models/translation/types/index.d.ts +43 -0
  479. package/models/models/trouble/handlers/resolvable-trouble-handler.d.ts +16 -0
  480. package/models/models/trouble/handlers/resolvable-trouble-handler.d.ts.map +1 -0
  481. package/models/models/trouble/index.d.ts +8 -0
  482. package/models/models/trouble/index.d.ts.map +1 -0
  483. package/models/models/trouble/services/index.d.ts +2 -0
  484. package/models/models/trouble/services/index.d.ts.map +1 -0
  485. package/models/models/trouble/services/trouble-services.d.ts +23 -0
  486. package/models/models/trouble/services/trouble-services.d.ts.map +1 -0
  487. package/models/models/trouble/trouble-model.d.ts +42 -0
  488. package/models/models/trouble/trouble-model.d.ts.map +1 -0
  489. package/models/models/trouble/trouble-registration.d.ts +84 -0
  490. package/models/models/trouble/trouble-registration.d.ts.map +1 -0
  491. package/models/models/trouble/types/index.d.ts +100 -0
  492. package/models/models/trouble/utils/trouble-data-extension.d.ts +5 -0
  493. package/models/models/trouble/utils/trouble-data-extension.d.ts.map +1 -0
  494. package/models/models/trouble/utils/trouble-extension.d.ts +5 -0
  495. package/models/models/trouble/utils/trouble-extension.d.ts.map +1 -0
  496. package/models/models/trouble/utils/trouble-reducer.d.ts +4 -0
  497. package/models/models/trouble/utils/trouble-reducer.d.ts.map +1 -0
  498. package/models/models/trouble-container/index.d.ts +4 -0
  499. package/models/models/trouble-container/index.d.ts.map +1 -0
  500. package/models/models/trouble-container/trouble-container-model.d.ts +23 -0
  501. package/models/models/trouble-container/trouble-container-model.d.ts.map +1 -0
  502. package/models/models/trouble-container/trouble-container-registration.d.ts +5 -0
  503. package/models/models/trouble-container/trouble-container-registration.d.ts.map +1 -0
  504. package/models/models/trouble-container/trouble-utils.d.ts +5 -0
  505. package/models/models/trouble-container/trouble-utils.d.ts.map +1 -0
  506. package/models/models/trouble-container/types/index.d.ts +17 -0
  507. package/models/models/types/index.d.ts +3 -0
  508. package/models/models/types/index.d.ts.map +1 -0
  509. package/models/models/usb-update/index.d.ts +7 -0
  510. package/models/models/usb-update/index.d.ts.map +1 -0
  511. package/models/models/usb-update/services/index.d.ts +2 -0
  512. package/models/models/usb-update/services/index.d.ts.map +1 -0
  513. package/models/models/usb-update/services/usb-update-services.d.ts +22 -0
  514. package/models/models/usb-update/services/usb-update-services.d.ts.map +1 -0
  515. package/models/models/usb-update/types/index.d.ts +14 -0
  516. package/models/models/usb-update/usb-update-container-model.d.ts +34 -0
  517. package/models/models/usb-update/usb-update-container-model.d.ts.map +1 -0
  518. package/models/models/usb-update/usb-update-container-registration.d.ts +87 -0
  519. package/models/models/usb-update/usb-update-container-registration.d.ts.map +1 -0
  520. package/models/models/usb-update/usb-update-model.d.ts +30 -0
  521. package/models/models/usb-update/usb-update-model.d.ts.map +1 -0
  522. package/models/models/usb-update/usb-update-registration.d.ts +87 -0
  523. package/models/models/usb-update/usb-update-registration.d.ts.map +1 -0
  524. package/models/models/ws-event/index.d.ts +4 -0
  525. package/models/models/ws-event/index.d.ts.map +1 -0
  526. package/models/models/ws-event/types/index.d.ts +25 -0
  527. package/models/models/ws-event/types/index.d.ts.map +1 -0
  528. package/models/models/ws-event/ws-event-factory.d.ts +5 -0
  529. package/models/models/ws-event/ws-event-factory.d.ts.map +1 -0
  530. package/models/models/ws-event/ws-event-model.d.ts +15 -0
  531. package/models/models/ws-event/ws-event-model.d.ts.map +1 -0
  532. package/models/registration.d.ts +7 -0
  533. package/models/registration.d.ts.map +1 -0
  534. package/models/services/config-bean/index.d.ts +144 -0
  535. package/models/services/config-bean/index.d.ts.map +1 -0
  536. package/models/services/future/index.d.ts +98 -0
  537. package/models/services/future/index.d.ts.map +1 -0
  538. package/models/services/index.d.ts +4 -0
  539. package/models/services/index.d.ts.map +1 -0
  540. package/models/services/login/index.d.ts +78 -0
  541. package/models/services/login/index.d.ts.map +1 -0
  542. package/models/services/trouble/index.d.ts +59 -0
  543. package/models/services/trouble/index.d.ts.map +1 -0
  544. package/models/types/global.d.ts +19 -0
  545. package/models/utils/client.d.ts +63 -0
  546. package/models/utils/client.d.ts.map +1 -0
  547. package/models/utils/conversion-utils.d.ts +41 -0
  548. package/models/utils/conversion-utils.d.ts.map +1 -0
  549. package/models/utils/core-registration-manager.d.ts +21 -0
  550. package/models/utils/core-registration-manager.d.ts.map +1 -0
  551. package/models/utils/extension-manager.d.ts +21 -0
  552. package/models/utils/extension-manager.d.ts.map +1 -0
  553. package/models/utils/future-manager/index.d.ts +9 -0
  554. package/models/utils/future-manager/index.d.ts.map +1 -0
  555. package/models/utils/index.d.ts +11 -0
  556. package/models/utils/index.d.ts.map +1 -0
  557. package/models/utils/openapi.d.ts +9493 -0
  558. package/models/utils/persistence-store.d.ts +58 -0
  559. package/models/utils/persistence-store.d.ts.map +1 -0
  560. package/models/utils/prop-utils.d.ts +3 -0
  561. package/models/utils/prop-utils.d.ts.map +1 -0
  562. package/models/utils/region-utils.d.ts +2 -0
  563. package/models/utils/region-utils.d.ts.map +1 -0
  564. package/models/utils/service.d.ts +70 -0
  565. package/models/utils/service.d.ts.map +1 -0
  566. package/models/utils/timer-manager.d.ts +153 -0
  567. package/models/utils/timer-manager.d.ts.map +1 -0
  568. package/models/utils/timezone-utils.d.ts +2 -0
  569. package/models/utils/timezone-utils.d.ts.map +1 -0
  570. package/models/utils/trouble-utils.d.ts +6 -0
  571. package/models/utils/trouble-utils.d.ts.map +1 -0
  572. package/models/utils/types.d.ts +9637 -0
  573. package/models/utils/types.d.ts.map +1 -0
  574. package/package.json +42 -0
  575. package/ui/components/error-boundary/error-boundary.d.ts +16 -0
  576. package/ui/components/error-boundary/error-boundary.d.ts.map +1 -0
  577. package/ui/components/error-boundary/index.d.ts +2 -0
  578. package/ui/components/error-boundary/index.d.ts.map +1 -0
  579. package/ui/components/index.d.ts +5 -0
  580. package/ui/components/index.d.ts.map +1 -0
  581. package/ui/components/kos-model-loader/contexts/kos-model-context.d.ts +12 -0
  582. package/ui/components/kos-model-loader/contexts/kos-model-context.d.ts.map +1 -0
  583. package/ui/components/kos-model-loader/contexts/kos-model-hierarchy-context.d.ts +16 -0
  584. package/ui/components/kos-model-loader/contexts/kos-model-hierarchy-context.d.ts.map +1 -0
  585. package/ui/components/kos-model-loader/index.d.ts +4 -0
  586. package/ui/components/kos-model-loader/index.d.ts.map +1 -0
  587. package/ui/components/kos-model-loader/kos-model-loader.d.ts +13 -0
  588. package/ui/components/kos-model-loader/kos-model-loader.d.ts.map +1 -0
  589. package/ui/components/loading-message/index.d.ts +11 -0
  590. package/ui/components/loading-message/index.d.ts.map +1 -0
  591. package/ui/components/loading-message/loading-message-styles.d.ts +3 -0
  592. package/ui/components/loading-message/loading-message-styles.d.ts.map +1 -0
  593. package/ui/components/progress-bar/index.d.ts +2 -0
  594. package/ui/components/progress-bar/index.d.ts.map +1 -0
  595. package/ui/components/progress-bar/progress-bar.d.ts +11 -0
  596. package/ui/components/progress-bar/progress-bar.d.ts.map +1 -0
  597. package/ui/constants/index.d.ts +2 -0
  598. package/ui/constants/index.d.ts.map +1 -0
  599. package/ui/contexts/create-model-context.d.ts +28 -0
  600. package/ui/contexts/create-model-context.d.ts.map +1 -0
  601. package/ui/contexts/fetch-kos-core.d.ts +6 -0
  602. package/ui/contexts/fetch-kos-core.d.ts.map +1 -0
  603. package/ui/contexts/index.d.ts +7 -0
  604. package/ui/contexts/index.d.ts.map +1 -0
  605. package/ui/contexts/kos-core-context.d.ts +16 -0
  606. package/ui/contexts/kos-core-context.d.ts.map +1 -0
  607. package/ui/contexts/kos-model-context.d.ts +10 -0
  608. package/ui/contexts/kos-model-context.d.ts.map +1 -0
  609. package/ui/contexts/kos-time/index.d.ts +2 -0
  610. package/ui/contexts/kos-time/index.d.ts.map +1 -0
  611. package/ui/contexts/kos-time/kos-time-provider.d.ts +13 -0
  612. package/ui/contexts/kos-time/kos-time-provider.d.ts.map +1 -0
  613. package/ui/contexts/modal-context.d.ts +13 -0
  614. package/ui/contexts/modal-context.d.ts.map +1 -0
  615. package/ui/contexts/software-info/index.d.ts +2 -0
  616. package/ui/contexts/software-info/index.d.ts.map +1 -0
  617. package/ui/contexts/software-info/software-info-provider.d.ts +14 -0
  618. package/ui/contexts/software-info/software-info-provider.d.ts.map +1 -0
  619. package/ui/contexts/state-bean/index.d.ts +2 -0
  620. package/ui/contexts/state-bean/index.d.ts.map +1 -0
  621. package/ui/contexts/state-bean/state-bean-provider.d.ts +14 -0
  622. package/ui/contexts/state-bean/state-bean-provider.d.ts.map +1 -0
  623. package/ui/contexts/token-context.d.ts +9 -0
  624. package/ui/contexts/token-context.d.ts.map +1 -0
  625. package/ui/contexts/translation-container/index.d.ts +2 -0
  626. package/ui/contexts/translation-container/index.d.ts.map +1 -0
  627. package/ui/contexts/translation-container/kos-translations-provider.d.ts +18 -0
  628. package/ui/contexts/translation-container/kos-translations-provider.d.ts.map +1 -0
  629. package/ui/hooks/device/index.d.ts +3 -0
  630. package/ui/hooks/device/index.d.ts.map +1 -0
  631. package/ui/hooks/device/use-device.d.ts +14 -0
  632. package/ui/hooks/device/use-device.d.ts.map +1 -0
  633. package/ui/hooks/device/with-device.d.ts +9 -0
  634. package/ui/hooks/device/with-device.d.ts.map +1 -0
  635. package/ui/hooks/fetch-model.d.ts +6 -0
  636. package/ui/hooks/fetch-model.d.ts.map +1 -0
  637. package/ui/hooks/index.d.ts +30 -0
  638. package/ui/hooks/index.d.ts.map +1 -0
  639. package/ui/hooks/kos-time/index.d.ts +3 -0
  640. package/ui/hooks/kos-time/index.d.ts.map +1 -0
  641. package/ui/hooks/kos-time/use-kos-time.d.ts +14 -0
  642. package/ui/hooks/kos-time/use-kos-time.d.ts.map +1 -0
  643. package/ui/hooks/kos-time/with-kos-time.d.ts +8 -0
  644. package/ui/hooks/kos-time/with-kos-time.d.ts.map +1 -0
  645. package/ui/hooks/network-interface-container/index.d.ts +3 -0
  646. package/ui/hooks/network-interface-container/index.d.ts.map +1 -0
  647. package/ui/hooks/network-interface-container/use-network-interface-container.d.ts +14 -0
  648. package/ui/hooks/network-interface-container/use-network-interface-container.d.ts.map +1 -0
  649. package/ui/hooks/network-interface-container/with-network-interface-container.d.ts +9 -0
  650. package/ui/hooks/network-interface-container/with-network-interface-container.d.ts.map +1 -0
  651. package/ui/hooks/ota/index.d.ts +3 -0
  652. package/ui/hooks/ota/index.d.ts.map +1 -0
  653. package/ui/hooks/ota/use-ota.d.ts +14 -0
  654. package/ui/hooks/ota/use-ota.d.ts.map +1 -0
  655. package/ui/hooks/ota/with-ota.d.ts +9 -0
  656. package/ui/hooks/ota/with-ota.d.ts.map +1 -0
  657. package/ui/hooks/outside-alerter.d.ts +11 -0
  658. package/ui/hooks/outside-alerter.d.ts.map +1 -0
  659. package/ui/hooks/software-info/index.d.ts +3 -0
  660. package/ui/hooks/software-info/index.d.ts.map +1 -0
  661. package/ui/hooks/software-info/use-software-info.d.ts +14 -0
  662. package/ui/hooks/software-info/use-software-info.d.ts.map +1 -0
  663. package/ui/hooks/software-info/with-software-info.d.ts +8 -0
  664. package/ui/hooks/software-info/with-software-info.d.ts.map +1 -0
  665. package/ui/hooks/state-bean/use-state-bean.d.ts +14 -0
  666. package/ui/hooks/state-bean/use-state-bean.d.ts.map +1 -0
  667. package/ui/hooks/state-bean/with-state-bean.d.ts +8 -0
  668. package/ui/hooks/state-bean/with-state-bean.d.ts.map +1 -0
  669. package/ui/hooks/state-prop/index.d.ts +2 -0
  670. package/ui/hooks/state-prop/index.d.ts.map +1 -0
  671. package/ui/hooks/state-prop/use-state-prop.d.ts +15 -0
  672. package/ui/hooks/state-prop/use-state-prop.d.ts.map +1 -0
  673. package/ui/hooks/storage-device-container/index.d.ts +3 -0
  674. package/ui/hooks/storage-device-container/index.d.ts.map +1 -0
  675. package/ui/hooks/storage-device-container/use-storage-device-container.d.ts +16 -0
  676. package/ui/hooks/storage-device-container/use-storage-device-container.d.ts.map +1 -0
  677. package/ui/hooks/storage-device-container/with-storage-device-container.d.ts +9 -0
  678. package/ui/hooks/storage-device-container/with-storage-device-container.d.ts.map +1 -0
  679. package/ui/hooks/timer/index.d.ts +2 -0
  680. package/ui/hooks/timer/index.d.ts.map +1 -0
  681. package/ui/hooks/timer/use-timer.d.ts +19 -0
  682. package/ui/hooks/timer/use-timer.d.ts.map +1 -0
  683. package/ui/hooks/translation-container/index.d.ts +6 -0
  684. package/ui/hooks/translation-container/index.d.ts.map +1 -0
  685. package/ui/hooks/translation-container/trans.d.ts +21 -0
  686. package/ui/hooks/translation-container/trans.d.ts.map +1 -0
  687. package/ui/hooks/translation-container/use-translation-container.d.ts +43 -0
  688. package/ui/hooks/translation-container/use-translation-container.d.ts.map +1 -0
  689. package/ui/hooks/translation-container/use-translation.d.ts +14 -0
  690. package/ui/hooks/translation-container/use-translation.d.ts.map +1 -0
  691. package/ui/hooks/translation-container/with-translation-container.d.ts +9 -0
  692. package/ui/hooks/translation-container/with-translation-container.d.ts.map +1 -0
  693. package/ui/hooks/trouble/index.d.ts +5 -0
  694. package/ui/hooks/trouble/index.d.ts.map +1 -0
  695. package/ui/hooks/trouble/use-trouble-container.d.ts +14 -0
  696. package/ui/hooks/trouble/use-trouble-container.d.ts.map +1 -0
  697. package/ui/hooks/trouble/use-trouble-visibility.d.ts +16 -0
  698. package/ui/hooks/trouble/use-trouble-visibility.d.ts.map +1 -0
  699. package/ui/hooks/trouble/use-trouble.d.ts +14 -0
  700. package/ui/hooks/trouble/use-trouble.d.ts.map +1 -0
  701. package/ui/hooks/trouble/with-trouble-container.d.ts +8 -0
  702. package/ui/hooks/trouble/with-trouble-container.d.ts.map +1 -0
  703. package/ui/hooks/usb-update-container/index.d.ts +3 -0
  704. package/ui/hooks/usb-update-container/index.d.ts.map +1 -0
  705. package/ui/hooks/usb-update-container/use-usb-update-container.d.ts +17 -0
  706. package/ui/hooks/usb-update-container/use-usb-update-container.d.ts.map +1 -0
  707. package/ui/hooks/usb-update-container/with-usb-update-container.d.ts +9 -0
  708. package/ui/hooks/usb-update-container/with-usb-update-container.d.ts.map +1 -0
  709. package/ui/hooks/use-config-bean.d.ts +15 -0
  710. package/ui/hooks/use-config-bean.d.ts.map +1 -0
  711. package/ui/hooks/use-config-property.d.ts +29 -0
  712. package/ui/hooks/use-config-property.d.ts.map +1 -0
  713. package/ui/hooks/use-date-props.d.ts +169 -0
  714. package/ui/hooks/use-date-props.d.ts.map +1 -0
  715. package/ui/hooks/use-date-relative-prop.d.ts +49 -0
  716. package/ui/hooks/use-date-relative-prop.d.ts.map +1 -0
  717. package/ui/hooks/use-kos-date-formats.d.ts +57 -0
  718. package/ui/hooks/use-kos-date-formats.d.ts.map +1 -0
  719. package/ui/hooks/use-kos-model.d.ts +23 -0
  720. package/ui/hooks/use-kos-model.d.ts.map +1 -0
  721. package/ui/hooks/use-kos-region-timezones.d.ts +89 -0
  722. package/ui/hooks/use-kos-region-timezones.d.ts.map +1 -0
  723. package/ui/hooks/use-kos-regions.d.ts +59 -0
  724. package/ui/hooks/use-kos-regions.d.ts.map +1 -0
  725. package/ui/hooks/use-kos-time-formats.d.ts +58 -0
  726. package/ui/hooks/use-kos-time-formats.d.ts.map +1 -0
  727. package/ui/hooks/use-kos-token.d.ts +5 -0
  728. package/ui/hooks/use-kos-token.d.ts.map +1 -0
  729. package/ui/hooks/use-kos-unit-systems.d.ts +56 -0
  730. package/ui/hooks/use-kos-unit-systems.d.ts.map +1 -0
  731. package/ui/hooks/use-local-computed.d.ts +7 -0
  732. package/ui/hooks/use-local-computed.d.ts.map +1 -0
  733. package/ui/hooks/use-mutation-observer.d.ts +13 -0
  734. package/ui/hooks/use-mutation-observer.d.ts.map +1 -0
  735. package/ui/hooks/use-press-gesture/index.d.ts +4 -0
  736. package/ui/hooks/use-press-gesture/index.d.ts.map +1 -0
  737. package/ui/hooks/use-press-gesture/strategy/dom-intersection-strategy.d.ts +4 -0
  738. package/ui/hooks/use-press-gesture/strategy/dom-intersection-strategy.d.ts.map +1 -0
  739. package/ui/hooks/use-press-gesture/strategy/intersection-strategy.d.ts +9 -0
  740. package/ui/hooks/use-press-gesture/strategy/intersection-strategy.d.ts.map +1 -0
  741. package/ui/hooks/use-press-gesture/use-press-gesture.d.ts +17 -0
  742. package/ui/hooks/use-press-gesture/use-press-gesture.d.ts.map +1 -0
  743. package/ui/hooks/use-project-reloading.d.ts +2 -0
  744. package/ui/hooks/use-project-reloading.d.ts.map +1 -0
  745. package/ui/hooks/use-region-time-props.d.ts +27 -0
  746. package/ui/hooks/use-region-time-props.d.ts.map +1 -0
  747. package/ui/hooks/use-time-props.d.ts +68 -0
  748. package/ui/hooks/use-time-props.d.ts.map +1 -0
  749. package/ui/hooks/with-project-reload.d.ts +7 -0
  750. package/ui/hooks/with-project-reload.d.ts.map +1 -0
  751. package/ui/i18n/config.d.ts +11 -0
  752. package/ui/i18n/config.d.ts.map +1 -0
  753. package/ui/index.d.ts +6 -0
  754. package/ui/index.d.ts.map +1 -0
  755. package/ui/mocks/browser.d.ts +3 -0
  756. package/ui/mocks/browser.d.ts.map +1 -0
  757. package/ui/mocks/handlers.d.ts +3 -0
  758. package/ui/mocks/handlers.d.ts.map +1 -0
  759. package/ui/utils/date-utils.d.ts +34 -0
  760. package/ui/utils/date-utils.d.ts.map +1 -0
  761. package/ui/utils/date.d.ts +31 -0
  762. package/ui/utils/date.d.ts.map +1 -0
  763. package/ui/utils/index.d.ts +2 -0
  764. package/ui/utils/index.d.ts.map +1 -0
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../../packages/sdk/kos-ui-sdk/src/common/constants/index.ts","../../../../packages/sdk/kos-ui-sdk/src/common/events/eventBus.ts","../../../../packages/sdk/kos-ui-sdk/src/common/file-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/api/wrapPromise.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/api-request-id.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/apply-mixins.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/container-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/date-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/debounce.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/feature-flags.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/get-query-params.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/hsl-to-hex.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-config-init.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-data-mapper-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-deletion-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/propKeys.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/extension/extension-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/types/kos-dependency.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/log-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/log/log.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-message-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-child.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/model-attribute-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-parent.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/resolve-parameters.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kosModel.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-companion.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-context.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-log.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-model-effect.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-reference.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kosDependency.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kosSubscribe.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kosTopicHandler.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/constants.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/model-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/model-active-machine.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/model-online-machine.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/model-machine.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/kosModelLifecycle.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/web-socket-transport-adapter.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/base-message-transport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/bridge-transport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/bridge-message-transport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/fos-message-transport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/kos-message-transport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/transport-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/webSocketTransport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kosModel.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/types/registration.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kosModelManager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/extension/initialize-extension.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/extension/plugin-extension-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/kosCoreLifecycle.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/when-ready.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-model-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-model-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/registration/registration-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/registration/model-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/registration/base-kos-model-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/registration/singleton-kos-model-registration-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kosCore.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-fetch.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-model-visitor.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-service-request.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/middleware.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/model-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/model-registration-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/observable-proxy-map.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/paired-client-heartbeat.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/pipe.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/retry-with-exponential-backoff.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/service-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/session-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/wait-for-request.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/context/kos-context-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-container-index.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-data-container.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-singleton-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/models/kos-token/index.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/services/browser-router.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/services/intent-service.ts","../../../../packages/sdk/kos-ui-sdk/src/core/types/utils/kos-fetch.ts","../../../../packages/sdk/kos-ui-sdk/src/core/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/constants/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/services/config-bean/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/prop-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/config-bean/config-bean-model-builder.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/config-bean/config-bean-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/decorators/kos-config-bean.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/region-info/services/region-info-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/region-info/types/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/region-info/utils/unit-system-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/region-info/region-info-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/conversion-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/config-bean-prop/config-options-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/config-bean-prop/config-bean-prop-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/decorators/kos-config-bean-prop.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future/future-aware.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future/future-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/models/services/future/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future/future-model-builder.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future/future-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/client.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/browser-router/browser-router-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/browser-router/browser-router-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future-container/future-container-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/future-manager/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future-container/future-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/key-value/services/key-value-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/key-value/key-value-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/key-value/key-value-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/kos-time/services/kos-time-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/kos-time/kos-time-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/kos-time/kos-time-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-block/log-block-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/service.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-stream/services/log-stream-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-block/log-block-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-block/log-block-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-block/log-block-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-stream/log-stream-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-stream/log-stream-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-stream/log-stream-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-stream/log-stream-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/trouble-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/services/trouble-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/utils/trouble-data-extension.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/utils/trouble-extension.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble-container/trouble-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/handlers/resolvable-trouble-handler.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/trouble-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/trouble-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble-container/trouble-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble-container/trouble-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/ota/services/ota-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/ota/ota-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/ota/ota-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/software-info/services/software-info-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/software-info/software-info-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/software-info/software-info-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-bean/services/state-bean-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-bean/state-bean-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-bean/state-bean-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-prop/state-prop-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-prop/state-prop-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-prop/services/state-prop-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/services/translation-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/constants.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/translation-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/translation-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/translation-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/translation-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/translation-context.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/utils/trouble-reducer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/ws-event/ws-event-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/ws-event/ws-event-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/device/services/device-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/device/device-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/device/device-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/network-interface/network-interface-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/network-interface/network-interface-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/network-interface/services/network-interface-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/network-interface/network-interface-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/network-interface/network-interface-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/storage-device/services/storage-device-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/storage-device/storage-device-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/storage-device/storage-device-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/storage-device/storage-device-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/storage-device/storage-device-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/usb-update/services/usb-update-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/usb-update/usb-update-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/usb-update/usb-update-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/usb-update/usb-update-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/usb-update/usb-update-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/core-registration-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/extension-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/persistence-store.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/region-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/timer-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/timezone-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/decorators/future-service.ts","../../../../packages/sdk/kos-ui-sdk/src/models/decorators/kos-state-bean.ts","../../../../packages/sdk/kos-ui-sdk/src/models/decorators/kos-state-prop.ts","../../../../packages/sdk/kos-ui-sdk/src/models/services/login/index.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/components/loading-message/loading-message-styles.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/components/loading-message/index.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/components/error-boundary/error-boundary.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/components/progress-bar/progress-bar.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-context.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-hierarchy-context.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/components/kos-model-loader/kos-model-loader.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/create-model-context.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/fetch-kos-core.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/kos-core-context.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-kos-model.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/kos-time/use-kos-time.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/kos-time/kos-time-provider.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/software-info/use-software-info.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/software-info/with-software-info.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/software-info/software-info-provider.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/token-context.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/translation-container/kos-translations-provider.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/device/use-device.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/device/with-device.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/fetch-model.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/kos-time/with-kos-time.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/network-interface-container/use-network-interface-container.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/network-interface-container/with-network-interface-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/ota/use-ota.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/ota/with-ota.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/outside-alerter.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/state-prop/use-state-prop.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/storage-device-container/use-storage-device-container.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/storage-device-container/with-storage-device-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/timer/use-timer.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/translation-container/trans.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/translation-container/use-translation.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/translation-container/use-translation-container.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/translation-container/with-translation-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/trouble/use-trouble.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-visibility.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/trouble/with-trouble-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/usb-update-container/use-usb-update-container.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/usb-update-container/with-usb-update-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-config-bean.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-config-property.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/utils/date.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/utils/date-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-date-props.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-date-relative-prop.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-kos-date-formats.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-kos-region-timezones.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-kos-regions.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-kos-time-formats.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-local-computed.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-mutation-observer.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-press-gesture/strategy/dom-intersection-strategy.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-press-gesture/use-press-gesture.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-project-reloading.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-time-props.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-region-time-props.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/with-project-reload.tsx"],"sourcesContent":["export const HEADER_METHOD = `method`;\nexport const HEADER_TOPIC = `topic`;\nexport const HEADER_URL = `url`;\nexport const HEADER_REQUEST_ID = `request-id`;\nexport const HEADER_RESPONSE_ID = `response-id`;\nexport const STATUS = `status`;\nexport const HEADER_DESTINATION_ADDR = `dst-addr`;\nexport const HEADER_SOURCE_ADDR = `src-addr`;\nexport const HEADER_REQUEST_TYPE = `type`;\nexport const HEADER_ORDERED = `ordered`;\nexport const HEADER_WORK_TRACKER = `tracker`;\nexport const HEADER_CONTENT_TYPE = `Content-Type`;\nexport const HEADER_CACHE_CONTROL = `Cache-Control`;\n\nexport const HEADER_FOS_REQUEST_ID = `requestId`;\nexport const LOGIN_HOST = process.env.KOS_LOGIN_URL || \"http://localhost\";\nexport const PORT = process.env.KOS_APP_PORT || \"8080\";\n\nexport const LOGIN_URL = `${LOGIN_HOST}:${PORT}`;\n\nexport const KOS_MODEL_ID = `{MODEL_ID}`;\n\nexport enum KosWsEvents {\n SEND = \"/ws/log/msg/send\",\n RECEIVED = \"/ws/log/msg/receive\",\n}\n\nexport enum KosMockEvents {\n MSG_RECEIVE = \"/mock/msg/receive\",\n}\n","import log from \"loglevel\";\nlog.info(\"Initializing event bus\");\nglobalThis.kos = globalThis.kos || {};\nglobalThis.kos.subscriptions = globalThis.kos.subscriptions || {};\nconst subscriptions: Record<string, any> = globalThis.kos.subscriptions;\nconst getNextUniqueId = () => Symbol(`eventKey`);\n\nexport interface ApiCallback<T = string> {\n headers: Record<string, string>;\n body: T;\n}\nexport type EventCallback<T = ApiCallback> = (msg?: T) => void;\n\nexport interface PublishResponse {\n eventType: string;\n subscribers: number;\n}\n\nexport function subscribe<T = ApiCallback>(\n eventType: string,\n callback: EventCallback<T>\n) {\n const id = getNextUniqueId();\n if (!subscriptions[eventType]) {\n log.debug(`Initializing subscription for ${eventType}`);\n subscriptions[eventType] = {};\n }\n\n log.debug(`Subscribing to ${eventType} with id ${id.toString()}`);\n subscriptions[eventType][id] = callback;\n\n return {\n count: subscriptions[eventType]\n ? Object.getOwnPropertySymbols(subscriptions[eventType]).length\n : 0,\n unsubscribe: () => {\n log.debug(`Unsubscribing from ${eventType} with id ${id.toString()}`);\n\n if (subscriptions[eventType] && subscriptions[eventType][id]) {\n delete subscriptions[eventType][id];\n }\n\n if (\n subscriptions[eventType] &&\n Object.getOwnPropertySymbols(subscriptions[eventType]).length === 0\n ) {\n delete subscriptions[eventType];\n }\n return {\n count: subscriptions[eventType]\n ? Object.getOwnPropertySymbols(subscriptions[eventType]).length\n : 0,\n };\n },\n };\n}\n\nexport function publish(\n eventType: string,\n msg: unknown,\n headers: Record<string, string> = {}\n): PublishResponse {\n if (\n !subscriptions[eventType] ||\n Object.getOwnPropertySymbols(subscriptions[eventType]).length === 0\n ) {\n log.debug(`No subscriptions for ${eventType}. Not publishing.`);\n return {\n eventType,\n subscribers: 0,\n };\n }\n\n const count = Object.getOwnPropertySymbols(subscriptions[eventType]).length;\n // eslint-disable-next-line max-len\n Object.getOwnPropertySymbols(subscriptions[eventType]).forEach((id) => {\n if (headers[\"sync\"]) {\n // wait for the response and send it back if sync\n const responseId = headers[\"sync\"];\n log.debug(\n `Performing sync publish for ${eventType} with sync id ${responseId}`\n );\n subscriptions[eventType][id]({ body: msg, headers }).then(\n (response: any) => {\n log.debug(\n `Response recieved for ${responseId}, publishing back to source.`\n );\n publish(responseId, response);\n }\n );\n } else {\n // fire and forget if not sync\n log.debug(`Performing async publish for ${eventType}`);\n subscriptions[eventType][id]({ body: msg, headers });\n }\n });\n return {\n eventType,\n subscribers: count,\n };\n}\n\nexport function reset() {\n log.warn(\"Resetting event bus\");\n Object.keys(subscriptions).forEach((key) => delete subscriptions[key]);\n}\n","type Sizes = \"bytes\" | \"KB\" | \"MB\" | \"GB\" | \"TB\";\ninterface Convert {\n value: number;\n scale: Sizes;\n toString: () => string;\n}\nexport const convertFileSizeRaw = (bytes: number, decimals = 0): Convert => {\n if (!+bytes)\n return {\n value: 0,\n scale: \"bytes\",\n toString: () => `0 bytes`,\n };\n\n const k = 1024;\n const dm = decimals < 0 ? 0 : decimals;\n const sizes: Sizes[] = [\"bytes\", \"KB\", \"MB\", \"GB\", \"TB\"];\n\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n const value = parseFloat((bytes / Math.pow(k, i)).toFixed(dm));\n const scale = sizes[i];\n return {\n value,\n scale,\n toString: () => `${value} ${scale}`,\n };\n};\n","/**\n * Utility function that will wrap an arbitrary promise in order for it to\n * conform to the React Suspense API. By utilizing this higher order function\n * React components can participate in the Suspense workflow and enable the application\n * to display fallback behaviour while kOS data models or APIs are being fetched.\n *\n * @param promise The promise to be resolved\n * @returns an Object with a single `read` function that will be used to broadcast\n * status back to the React framework.\n */\nexport function wrapPromise<T>(promise: Promise<T>) {\n let status = `pending`;\n let response;\n\n const suspender = promise.then(\n (res) => {\n status = `success`;\n response = res;\n },\n (err) => {\n status = `error`;\n response = err;\n }\n );\n\n const read = (): T => {\n switch (status) {\n case `pending`:\n throw suspender;\n case `error`:\n throw response;\n default:\n return response;\n }\n };\n\n return { read };\n}\n","export function uuid() {\n return `xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx`.replace(/[xy]/g, function (c) {\n const r = (Math.random() * 16) | 0;\n const v = c == `x` ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n","export function applyMixins(derivedCtor: any, baseCtors: any[]) {\n baseCtors.forEach((baseCtor) => {\n Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {\n const descriptor = Object.getOwnPropertyDescriptor(\n baseCtor.prototype,\n name\n );\n Object.defineProperty(\n derivedCtor.prototype,\n name,\n <PropertyDescriptor & ThisType<any>>descriptor\n );\n });\n });\n}\n","import { IKosModelContainer } from \"../core/kos-container-model\";\nimport { IKosContainerModel } from \"../core/kosModel\";\n\ninterface Identifiable {\n id: string;\n}\n\n/**\n * Utility function to calculate the list of ids that should be removed from the\n * current state in order to remain in sync.\n *\n * @param projectedModels - the new list of models representing the next state\n * @param currentModels - the current list of models to be compared against\n * @returns the list of ids that should be removed from the current state\n */\nconst deltas = (\n projectedModels: Identifiable[],\n currentModels: Identifiable[]\n) => {\n const newIds = projectedModels.map((entity) => entity.id);\n const currentIds = currentModels.map((entity) => entity.id);\n const toRemove = currentIds.filter((modelId) => !newIds.includes(modelId));\n\n return toRemove;\n};\n\nexport type IdMapper = <D extends Identifiable = Identifiable>(entity: D) => D;\n\ntype Container = IKosContainerModel<any, any> | IKosModelContainer<any>;\ninterface ResolveParams<T extends Container, D> {\n container: T;\n onAddItem: (entity: D) => any;\n onRemoveItem: (id: string) => any;\n idMapper?: IdMapper;\n}\n\nexport const resolveContainerDeltas =\n <T extends IKosModelContainer<any>, D extends Identifiable>({\n container,\n onAddItem,\n onRemoveItem,\n idMapper = (entity) => entity,\n }: ResolveParams<T, D>) =>\n (entities: D[]) => {\n const mappedLayers = entities.map(idMapper);\n const toRemove = deltas(mappedLayers, container.data);\n const removedIds = toRemove.map(onRemoveItem).filter(Boolean);\n container.removeAll(removedIds);\n const toAdd = mappedLayers.map(onAddItem).filter(Boolean);\n container.addAll(toAdd);\n };\n\nexport const resolveListDeltas =\n <T extends IKosContainerModel<any, any>, D extends Identifiable>({\n container,\n onAddItem,\n onRemoveItem,\n idMapper = (entity) => entity,\n }: ResolveParams<T, D>) =>\n (entities: D[]) => {\n const mappedLayers = entities.map(idMapper);\n const toRemove = deltas(mappedLayers, container.models);\n toRemove.forEach(onRemoveItem);\n mappedLayers.forEach(onAddItem);\n };\n\ninterface ResolveItemsParams<T extends Identifiable, D> {\n items: T[];\n onAddItem: (entity: D) => void;\n onRemoveItem: (id: string) => void;\n idMapper?: IdMapper;\n}\nexport const resolveItemListDeltas =\n <T extends Identifiable, D extends Identifiable>({\n items,\n onAddItem,\n onRemoveItem,\n idMapper = (entity) => entity,\n }: ResolveItemsParams<T, D>) =>\n (entities: D[]) => {\n const mappedLayers = entities.map(idMapper);\n const toRemove = deltas(mappedLayers, items);\n toRemove.forEach(onRemoveItem);\n mappedLayers.forEach(onAddItem);\n };\n\nexport const processId = (id: string, prefix = \"parent-\") => {\n let _id = id;\n if (_id.startsWith(prefix)) {\n _id = _id.replace(prefix, \"\");\n }\n return _id;\n};\n","const formatter = new Intl.RelativeTimeFormat(undefined, {\n numeric: \"auto\",\n});\n\nconst DIVISIONS: { amount: number; name: Intl.RelativeTimeFormatUnit }[] = [\n { amount: 60, name: \"seconds\" },\n { amount: 60, name: \"minutes\" },\n { amount: 24, name: \"hours\" },\n { amount: 7, name: \"days\" },\n { amount: 4.34524, name: \"weeks\" },\n { amount: 12, name: \"months\" },\n { amount: Number.POSITIVE_INFINITY, name: \"years\" },\n];\n\nexport function formatDateSince(date: Date) {\n let duration = (date.getTime() - Date.now()) / 1000;\n\n for (let i = 0; i <= DIVISIONS.length; i++) {\n const division = DIVISIONS[i];\n if (Math.abs(duration) < division.amount) {\n return formatter.format(Math.round(duration), division.name);\n }\n duration /= division.amount;\n }\n return formatter.format(Math.round(duration), \"years\");\n}\n","/**\n * Debounces a function, ensuring it is called after a specified timeout\n * has passed since the last invocation.\n *\n * @param context - The context (this value) to be used when calling the debounced function.\n * @param func - The function to debounce.\n * @param timeout - The duration (in milliseconds) to wait after the last invocation before calling the function.\n * Defaults to 300 milliseconds.\n * @returns A debounced version of the provided function.\n *\n * @example\n * ```typescript\n * const debouncedFn = debounce(this, myFunction, 500);\n * debouncedFn(arg1, arg2);\n * ```\n */\nfunction debounce(context: any, func: Function, timeout = 300) {\n let timer: ReturnType<typeof setTimeout>;\n\n /**\n * Returns a debounced version of the provided function.\n *\n * @param args - The arguments to pass to the debounced function.\n */\n return (...args: any) => {\n /**\n * Clears the previous timer.\n */\n clearTimeout(timer);\n\n /**\n * Sets a new timer to call the provided function after the specified timeout.\n */\n timer = setTimeout(() => {\n func.apply(context, args);\n }, timeout);\n };\n}\n\nexport default debounce;\n","type FeatureFlags = Record<string, boolean>;\nexport class FeatureFlagService {\n private flags: Record<string, boolean> = {};\n\n constructor(initialFlags: FeatureFlags = {}) {\n this.flags = initialFlags;\n }\n\n // Check if a feature is enabled\n isFeatureEnabled(flag: string): boolean {\n return !!this.flags[flag];\n }\n\n // Enable a feature\n enableFeature(flag: string): void {\n this.flags[flag] = true;\n }\n\n // Disable a feature\n disableFeature(flag: string): void {\n this.flags[flag] = false;\n }\n\n // Toggle a feature\n toggleFeature(flag: string): void {\n this.flags[flag] = !this.flags[flag];\n }\n\n // Update multiple features at once\n updateFlags(newFlags: FeatureFlags): void {\n this.flags = { ...this.flags, ...newFlags };\n }\n}\n\nwindow.KosFeatureFlags = window.KosFeatureFlags ?? new FeatureFlagService();\n\nexport const KosFeatureFlags = window.KosFeatureFlags;\n","export const getQueryParams = (query = null) =>\n (query || window.location.search.replace(\"?\", \"\"))\n\n // get array of KeyValue pairs\n .split(\"&\")\n\n // Decode values\n .map((pair) => {\n const [key, val] = pair.split(\"=\");\n\n return [key, decodeURIComponent(val || \"\")];\n })\n\n // array to object\n .reduce((result, [key, val]) => {\n result[key] = val;\n return result;\n }, {});\n","export const hslToHex = (h: number, s: number, l: number) => {\n l /= 100;\n const a = (s * Math.min(l, 1 - l)) / 100;\n const f = (n) => {\n const k = (n + h / 30) % 12;\n const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n return Math.round(255 * color)\n .toString(16)\n .padStart(2, \"0\"); // convert to Hex and prefix \"0\" if needed\n };\n return `#${f(0)}${f(8)}${f(4)}`;\n};\n\nexport const hslStringToHex = (hsl: string) => {\n const reg = new RegExp(\"hsl\\\\((\\\\d+),\\\\s+(\\\\d+)\\\\%,\\\\s+(\\\\d+)\\\\%\\\\)\");\n const match = reg.exec(hsl);\n if (!match) {\n throw Error(\"Invalid HSL string\");\n }\n return hslToHex(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]));\n};\n\nexport const resolveVariable = (element: Element, variable: string) =>\n getComputedStyle(element).getPropertyValue(variable);\nexport const variableToHex = (element: Element, variable: string) =>\n hslStringToHex(resolveVariable(element, variable));\n","interface KosConfig {\n logging: boolean;\n profiles: string[];\n [key: string]: boolean | string[] | string | number | undefined;\n}\n\nexport const PROFILE_TOOLS_PREVIEW = \"studio.tools.preview\";\nexport const PROFILE_RELAX_STORE_VALIDATION = \"studio.relax.store.validation\";\nexport const PROFILE_LOG_DEBUG = \"studio.log.debug\";\nexport const PROFILE_LOG_INFO = \"studio.log.info\";\nconst defaultConfig = {\n profiles: [PROFILE_TOOLS_PREVIEW],\n};\nconst config = globalThis.getKosConfig?.() || JSON.stringify(defaultConfig);\n\nconst configObj = JSON.parse(config);\n\nglobalThis.kosConfig = configObj;\n\nexport const KosGlobalConfig: KosConfig = configObj;\n\nexport const resolveKosProfiles = () => KosGlobalConfig.profiles || [];\n\nexport const hasKosProfile = (profile: string) =>\n resolveKosProfiles().includes(profile);\n\nexport const isKosLoggingEnabled = () => KosGlobalConfig.logging || false;\n","import { runInAction as kosAction } from \"mobx\";\nimport { IKosDataModel } from \"../core/kosModel\";\n\nexport type KosDataMapper<\n D extends object = any,\n T extends IKosDataModel = IKosDataModel\n> = (data: D, model: T) => Partial<Omit<T, keyof IKosDataModel>>;\n\nexport type KosDataMapperUtils<\n D extends object,\n T extends IKosDataModel\n> = KosDataMapper<D, T>;\nconst defaultMapper = <D extends object, T extends IKosDataModel>(\n data: D,\n _model: T\n) => {\n const parsedData = { ...data };\n if ((parsedData as any).id) {\n delete (parsedData as any).id;\n }\n\n return parsedData;\n};\n\n/**\n * Utility function that can be used to map an arbitrary data object to a model.\n *\n * @param data - the input data for the mapping function\n * @param model - the target model to map the data to\n * @param mapper - a mapping function that takes the input data and the target model and returns a partial of the target model. The\n * results will be applied to the model.\n */\nexport const mapDataToModel = <D extends object, T extends IKosDataModel>(\n data: D,\n model: T,\n mapper: KosDataMapperUtils<D, T> = defaultMapper\n) => {\n const partial = mapper(data, model);\n kosAction(() => {\n Object.assign(model, partial);\n });\n};\n","const deletionMap = new Map<string, NodeJS.Timeout[]>();\nexport const KosDeletionManager = {\n addToDeletionQueue: (modelId: string, timeout: NodeJS.Timeout) => {\n const timeouts = deletionMap.get(modelId) || [];\n timeouts.push(timeout);\n deletionMap.set(modelId, timeouts);\n },\n\n cancelDeletion: (modelId: string) => {\n const timeouts = deletionMap.get(modelId);\n if (timeouts) {\n timeouts.forEach((timeout) => {\n clearTimeout(timeout);\n });\n }\n },\n};\n","/**\n * @internal\n */\nexport const SubscriptionHandlers = Symbol(`SubscriptionHandlers`);\nexport const DependencyModels = Symbol(`DependencyModels`);\nexport const FutureService = Symbol(`FutureService`);\nexport const ChildModels = Symbol(`ChildModels`);\nexport const ParentModel = Symbol(`ParentModel`);\nexport const LogConfig = Symbol(`LogConfig`);\nexport const ReferenceConfig = Symbol(`ReferenceConfig`);\nexport const KosModelSymbol = Symbol(`KosModelSymbol`);\nexport const ModelEffects = Symbol(`ModelEffects`);\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { IndexMapper } from \"../kos-container-index\";\nimport { IKosDataModel } from \"../kosModel\";\n\nexport type ExtensionType = number | string | boolean;\nexport type DataMapper<\n I extends object = any,\n O extends object = any,\n C extends object = any\n> = (input: I, context?: C) => Promise<O>;\n\nexport type PropertyMapper<\n I extends object = any,\n O extends ExtensionType = any,\n C extends object = any\n> = (input: I, context?: C) => O;\n\nexport type DataLoader<I extends object = any, O extends object = any> = (\n input: I\n) => Promise<O>;\n\nexport type IndexExtension<T extends IKosDataModel = any> = Record<\n string,\n keyof T | IndexMapper<any>\n>;\nconst dataMappers = new Map<string, DataMapper[]>();\nconst dataLoaders = new Map<string, DataLoader>();\nconst propertyMappers = new Map<string, PropertyMapper>();\nconst indexExtensions = new Map<string, IndexExtension>();\n\nexport interface ExtensionPoint<\n Data extends object = any,\n Output extends object = any,\n Context extends object = any\n> {\n register: (id: string, extension: any) => void;\n execute: (id: string, data: Data, context?: Context) => Output;\n}\nexport const registerExtensionPoint = (\n id: string,\n extensionPoint: ExtensionPoint\n) => {\n _ExtensionManager[id] = extensionPoint;\n};\n\nconst _ExtensionManager = {\n indexExtension: {\n registerIndexExtension: (id: string, extension: IndexExtension) => {\n const extensions = indexExtensions.get(id) || {};\n Object.assign(extensions, extension);\n indexExtensions.set(id, extension);\n },\n\n loadIndexExtensions: (id: string) => indexExtensions.get(id) || {},\n },\n loader: {\n registerLoader: (id: string, loader: DataLoader) => {\n dataLoaders.set(id, loader);\n },\n executeLoader: async <T extends object = any>(id: string, data: T) => {\n const loader = dataLoaders.get(id);\n if (!loader) {\n return undefined;\n }\n return await loader(data);\n },\n },\n propertyMapper: {\n registerPropertyMapper: (id: string, mapper: PropertyMapper) => {\n propertyMappers.set(id, mapper);\n },\n hasMapper: (id: string) => propertyMappers.has(id),\n executeMapper: <\n T extends object = any,\n O extends ExtensionType = any,\n C extends object = any\n >(\n id: string,\n data: T,\n context?: C\n ) => {\n const mapper = propertyMappers.get(id);\n if (!mapper) {\n return \"\" as O;\n }\n\n return mapper(data, context) as O;\n },\n },\n dataMapper: {\n registerDataMapper: (id: string, mapper: DataMapper) => {\n const mappers = dataMappers.get(id) || [];\n mappers.push(mapper);\n\n dataMappers.set(id, mappers);\n },\n executeMapper: async <\n T extends object = any,\n O extends object = any,\n C extends object = any\n >(\n id: string,\n data: T,\n context?: C\n ): Promise<O> => {\n const mappers = dataMappers.get(id);\n if (!mappers) {\n return {} as O;\n }\n\n const result = {};\n for (const mapper of mappers) {\n const _interim = await mapper(data, context);\n Object.assign(result, _interim);\n }\n\n return result as O;\n },\n },\n};\n\nexport interface IExtensionManager {}\ntype ExtensionManagerType = typeof _ExtensionManager &\n IExtensionManager & {\n [key: string]: ExtensionPoint;\n };\n\nexport const ExtensionManager = _ExtensionManager as ExtensionManagerType;\n","export enum DependencyLifecycle {\n INIT = \"init\",\n LOAD = \"load\",\n READY = \"ready\",\n ACTIVATE = \"activate\",\n ONLINE = \"online\",\n}\n\n/**\n * The parameters for the kosDependency decorator.\n * */\nexport interface KosDependencyParams<Options = unknown> {\n /** The type of the model to be injected. */\n modelType: string;\n /** The id of the model to be injected. */\n id?: string;\n /** The options to be passed to the model constructor. */\n options?: Options;\n /** The lifecycle at which the dependency should be injected. */\n lifecycle?: DependencyLifecycle;\n}\n","import { LogLevelDesc } from \"loglevel\";\nimport { getQueryParams } from \"../util/get-query-params\";\nimport {\n hasKosProfile,\n PROFILE_LOG_DEBUG,\n PROFILE_LOG_INFO,\n} from \"../util/kos-config-init\";\n\nconst resolveLogLevelProfile = (): LogLevelDesc | undefined => {\n const showDebugLogProfile = hasKosProfile(PROFILE_LOG_DEBUG);\n const showInfoLogProfile = hasKosProfile(PROFILE_LOG_INFO);\n return showDebugLogProfile\n ? \"DEBUG\"\n : showInfoLogProfile\n ? \"INFO\"\n : undefined;\n};\nexport const getLogLevel = (): LogLevelDesc => {\n const params = getQueryParams();\n\n const profileLogLevel = resolveLogLevelProfile();\n const logLevelParam = params[\"kosLogLevel\"];\n const logLevel =\n logLevelParam ??\n profileLogLevel ??\n window.kosLogLevel ??\n process.env.KOS_LOG_LEVEL;\n if (logLevel) {\n return logLevel as LogLevelDesc;\n }\n return \"WARN\";\n};\n\nexport const getKosMessageLogging = (): boolean => {\n const enableAll =\n window.kosMessageLogging || process.env.KOS_MESSAGE_LOGGING === \"true\";\n return enableAll;\n};\n\nexport const getLogMessageToStudio = (): boolean => {\n const enableAll =\n window.kosMessageStudioLogging ||\n process.env.KOS_MESSAGE_STUDIO_LOGGING === \"true\";\n return enableAll;\n};\n","import log, { LogLevel } from \"loglevel\";\nimport {\n getKosMessageLogging,\n getLogLevel,\n getLogMessageToStudio,\n} from \"../../util/log-utils\";\n\nconst WS_LOG = \"ws-log\";\nconst originalFactory = log.methodFactory;\n\nconst enableMessageLogging = getKosMessageLogging();\n\nconst enableStudioMessageLogging = getLogMessageToStudio();\nlog.methodFactory = function (methodName, logLevel, loggerName) {\n const rawMethod = originalFactory(methodName, logLevel, loggerName);\n\n return function (msg, style?) {\n rawMethod(msg, style || \"\");\n if (\n globalThis?.kosConfig?.logging &&\n globalThis.kosLog &&\n (loggerName !== WS_LOG ||\n (enableMessageLogging && enableStudioMessageLogging))\n ) {\n globalThis.kosLog(`UI: ${String(loggerName || \"Root\")} - ${msg}`);\n }\n };\n};\nlet level = getLogLevel();\nlog.setLevel(level);\n\nwindow.setKosLogLevel = (_level: log.LogLevelDesc) => {\n level = _level;\n log.setLevel(_level);\n};\nconst wsLog = log.getLogger(WS_LOG);\nwindow.enableKosMessageLog = () => {\n wsLog.setLevel(log.levels.INFO);\n};\n\nwindow.disableKosMessageLog = () => {\n wsLog.setLevel(log.levels.ERROR);\n};\n\nif (enableMessageLogging) {\n window.enableKosMessageLog();\n} else {\n window.disableKosMessageLog();\n}\nconst styles = [\n \"color: black\",\n \"display: block\",\n \"background-color: lightgreen\",\n\n \"padding: 4px\",\n \"margin: 0\",\n \"text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)\",\n \"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\",\n\n \"font-weight: bold\",\n].join(\";\");\n\nconst received = [\n \"color: black\",\n \"display: block\",\n\n \"padding: 4px\",\n \"background-color: yellow\",\n \"margin: 0\",\n \"text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)\",\n \"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\",\n\n \"font-weight: bold\",\n].join(\";\");\n\nconst conditionallyLog =\n (level: LogLevel[keyof LogLevel]) => (fn: VoidFunction) => {\n if (log.getLevel() <= level) {\n fn();\n }\n };\nexport const KosLog = {\n ...log,\n\n ifDebug: conditionallyLog(log.levels.DEBUG),\n ifInfo: conditionallyLog(log.levels.INFO),\n ifWarn: conditionallyLog(log.levels.WARN),\n ifError: conditionallyLog(log.levels.ERROR),\n getLogger: (name: string) => log.getLogger(`kos::${name}`),\n createLogger: ({ name, group }: { name: string; group?: string }) =>\n log.getLogger(`${group ? `${group}:` : \"kos\"}::${name}`),\n wsSend: (...msg: any[]) => {\n const str = String(msg).replace(/\\n/g, \"\\\\n\");\n wsLog.info(`%c⬆ ${str}`, styles);\n },\n wsReceive: (...msg: any[]) => {\n const str = String(msg).replace(/\\n/g, \"\\\\n\");\n wsLog.info(`%c⬇ ${str}`, received);\n },\n};\n","import {\n HEADER_CACHE_CONTROL,\n HEADER_CONTENT_TYPE,\n HEADER_DESTINATION_ADDR,\n HEADER_FOS_REQUEST_ID,\n HEADER_METHOD,\n HEADER_ORDERED,\n HEADER_REQUEST_ID,\n HEADER_REQUEST_TYPE,\n HEADER_RESPONSE_ID,\n HEADER_SOURCE_ADDR,\n HEADER_TOPIC,\n HEADER_URL,\n HEADER_WORK_TRACKER,\n STATUS,\n} from \"../../common\";\nimport { KosCore } from \"../core/kosCore\";\nimport { KosLog } from \"../core/log\";\nimport {\n KosBroadcastRequest,\n KosFetchReqeust,\n KosFetchResponseParams,\n KosMessageOptions,\n type KosHttpMessageOptions,\n type KosMessageRequest,\n} from \"../types\";\n\nexport const createStudioMessage = ({\n path,\n requestId,\n method,\n destinationAddress,\n}: KosFetchReqeust) => {\n let msg = `${HEADER_METHOD}:${method}\\n`;\n msg += `topic:${path}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_REQUEST_ID}:${requestId}\\n`;\n if (destinationAddress) {\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n }\n\n msg += `${HEADER_REQUEST_TYPE}:kos.studio.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const createFosBaseMessage = ({\n path,\n requestId,\n method,\n destinationAddress,\n ordered,\n tracker,\n}: KosFetchReqeust) => {\n let msg = `${HEADER_TOPIC}:/http${path}\\n`;\n msg += `${HEADER_METHOD}:${method}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_FOS_REQUEST_ID}:${requestId}\\n`;\n if (destinationAddress) {\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n }\n if (ordered) {\n msg += `${HEADER_ORDERED}:true\\n`;\n }\n if (tracker) {\n msg += `${HEADER_WORK_TRACKER}:${tracker}\\n`;\n }\n msg += `${HEADER_REQUEST_TYPE}:fos.http.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const createBaseMessage = ({\n path,\n requestId,\n method,\n destinationAddress,\n ordered,\n tracker,\n bridge,\n}: KosFetchReqeust) => {\n let msg = `${HEADER_METHOD}:${method}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_REQUEST_ID}:${requestId}\\n`;\n if (destinationAddress) {\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n }\n if (ordered) {\n msg += `${HEADER_ORDERED}:true\\n`;\n }\n if (tracker) {\n msg += `${HEADER_WORK_TRACKER}:${tracker}\\n`;\n }\n\n msg += `${HEADER_REQUEST_TYPE}:${bridge ? \"fos\" : \"kos\"}.http.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const createMessageBody = (msg: string, body?: string) => {\n let _msg = msg;\n if (body) {\n _msg += body;\n }\n return _msg;\n};\n\nexport function createHeaders(headers: Record<string, string>): Headers {\n const _headers = { ...headers };\n return {\n append(name: string, value: string) {\n _headers[name] = value;\n },\n delete(name: string) {\n delete _headers[name];\n },\n get(name: string) {\n return _headers[name];\n },\n forEach(callbackFn) {\n Object.keys(_headers).forEach((key) =>\n callbackFn(_headers[key], key, this)\n );\n },\n has(name) {\n return Object.hasOwn(_headers, name);\n },\n set(name: string, value: string) {\n _headers[name] = value;\n },\n keys() {\n return Object.keys(_headers);\n },\n values() {\n return Object.values(_headers);\n },\n entries() {\n return Object.entries(_headers);\n },\n } as unknown as Headers;\n}\n\nexport function createReadableStream(\n msg: string\n): ReadableStream<Uint8Array> | null {\n let sent = false;\n if (window.ReadableStream) {\n const stream = new ReadableStream({\n start(controller) {\n // The following function handles each data chunk\n function push() {\n // \"done\" is a Boolean and value a \"Uint8Array\"\n return Promise.resolve({ done: sent, value: msg }).then(\n ({ done, value }) => {\n // Is there no more data to read?\n if (done) {\n // Tell the browser that we have finished sending data\n controller.close();\n return;\n }\n\n // Get the data and send it to the browser via the controller\n controller.enqueue(value);\n sent = true;\n push();\n }\n );\n }\n\n push();\n },\n });\n return stream;\n }\n return msg as any;\n}\n\nexport const createStudioMessageRequest = ({\n path,\n requestId,\n destinationAddress,\n}: KosFetchReqeust) => {\n let msg = `topic:${path}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_REQUEST_ID}:${requestId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:kos.studio.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const createKosMessage = ({\n requestId,\n destinationAddress,\n requestType,\n headers,\n}: KosMessageRequest) => {\n let msg = `${HEADER_REQUEST_ID}:${requestId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:${requestType}\\n`;\n if (headers) {\n Object.keys(headers).forEach((key) => {\n msg += `${key}:${headers[key]}\\n`;\n });\n }\n msg += `\\n`;\n return msg;\n};\n\nexport const sendKosMessage = <T extends object>(\n msg: T,\n options: KosMessageRequest\n) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createKosMessage(options),\n typeof wrappedMsg === \"string\" ? wrappedMsg : JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n KosLog.debug(\"Sending message\", _msg);\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\nexport const createStudioMessageResponse = ({\n path,\n responseId,\n status,\n destinationAddress,\n}: KosFetchResponseParams) => {\n let msg = `topic:${path}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n if (responseId) msg += `${HEADER_RESPONSE_ID}:${responseId}\\n`;\n msg += `${STATUS}:${status}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n\n msg += `${HEADER_REQUEST_TYPE}:kos.studio.response\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const sendStudioMessageRequest = <T extends object>(\n msg: T,\n options: KosFetchReqeust\n) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createStudioMessageRequest(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\nexport const sendStudioMessage = <T extends object>(\n msg: T,\n options: KosFetchResponseParams\n) => {\n const wrappedMsg = options.responseId\n ? { status: options.status, data: msg }\n : msg;\n\n const _msg = createMessageBody(\n createStudioMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\nexport const createBroadcastMessageResponse = ({\n topic,\n}: KosBroadcastRequest) => {\n let msg = `topic:${topic}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:kos.broker.send\\n`;\n msg += `\\n`;\n return msg;\n};\nexport const createKosHtpMessageResponse = ({\n responseId,\n destinationAddress,\n type,\n sourceAddress,\n status,\n}: KosHttpMessageOptions) => {\n let msg = `${HEADER_RESPONSE_ID}:${responseId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_SOURCE_ADDR}:${sourceAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:${type ?? \"kos.message.request\"}\\n`;\n msg += `${STATUS}:${status}\\n`;\n msg += `${HEADER_CONTENT_TYPE}:application/json\\n`;\n msg += `${HEADER_CACHE_CONTROL}:no-cache\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const createKosMessageResponse = ({\n topic,\n responseId,\n destinationAddress,\n type,\n}: KosMessageOptions) => {\n let msg = `topic:${topic}\\n`;\n if (responseId) msg += `${HEADER_RESPONSE_ID}:${responseId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:${type ?? \"kos.message.request\"}\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport interface KosBroadcastRequestParams<T extends object> {\n msg: T;\n options: KosBroadcastRequest;\n}\nexport const sendBroadcastMessage = <T extends object>({\n msg,\n options,\n}: KosBroadcastRequestParams<T>) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createBroadcastMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\nexport interface KosMessageResponseParams<T extends object> {\n msg: T;\n options: KosMessageOptions;\n}\n\nexport interface KosHttpMessageResponseParams<T extends object> {\n msg: T;\n options: KosHttpMessageOptions;\n}\nexport const sendKosMessageResponse = <T extends object>({\n msg,\n options,\n}: KosMessageResponseParams<T>) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createKosMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\nexport const sendKosHttpMessageResponse = <T extends object>({\n msg,\n options,\n}: KosHttpMessageResponseParams<T>) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createKosHtpMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\nexport const getMessageBody = (payload, skipParse) => {\n try {\n return skipParse ? payload.body ?? payload : JSON.parse(payload.body);\n } catch {\n return payload.body || payload;\n }\n};\n","import { ChildModels } from \"./propKeys\";\n\n/**\n * Decorator for marking a property as a child model within a Kos Data Model class.\n *\n * If a property is marked as a child model, it will be automatically included in the model's\n * lifecycle management. This means that when the parent model will not transition to a ready state\n * until all of its child models are ready.\n *\n * Similarly, when the parent model is destroyed, all of its child models will be destroyed as well.\n *\n * If the property is a KosModelContainer then all of the underlying child models will be included in the\n * child model lifecycle management.\n *\n * @param target - The target object or class.\n * @param name - The name of the property to be marked as a child model.\n * @returns A decorator function that marks the property as a child model.\n * @category kOS Model Decorator\n */\nexport const kosChild = (target: {} | any, name: PropertyKey): any => {\n target[ChildModels] = target[ChildModels] || {};\n target[ChildModels][name] = true;\n};\n","import type { IKosDataModel } from \"../core/kosModel\";\n\n/**\n * Creates a property key string based on a given key from a Kos data model.\n *\n * Property keys are used by the kOS model framework to provide property expansion in model data.\n *\n * When create a model dependency or any model metadata that is derived from the existing model data,\n * a property key should be used to reference the data model key.\n *\n * For kos dependencies, propKeys can be used to resolve any dependency options that are derived from the data model.\n *\n * For topic handlers, the resolved topic can include propKey to allow for dynamic topic resolution based on the data model.\n *\n * @param key - The key from a Kos data model.\n * @returns A property key string enclosed in curly braces with a \"PROP_\" prefix.\n *\n * @example\n * // Create a property key for a data model key \"name\"\n * const propertyKey = createPropKey(\"name\");\n * // Result: \"{PROP_name}\"\n *\n * @example\n * // Create a property key for a data model key \"id\"\n * const propertyKey = createPropKey(\"id\");\n * // Result: \"{PROP_id}\"\n *\n * @example\n * The propKey can be used as part of dependency or topic listener to allow for models to\n * dynamically change the dependency or topic listener based on the data model.\n * ```typescript\n * @kosDependency({modelType: Ingredient.type, id: propertyKey})\n * ```\n */\nexport const createPropKey = <R extends IKosDataModel>(key: keyof R) =>\n `{PROP_${String(key)}}`;\n\nexport const createOptionKey = <R extends object>(key: keyof R) =>\n `{PROP_${String(key)}}`;\n","/* eslint-disable no-param-reassign */\nimport { createPropKey } from \"../../util/model-attribute-utils\";\nimport { IKosDataModel } from \"../kosModel\";\nimport { ParentModel } from \"./propKeys\";\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\nexport interface KosParentProps {\n parentId?: string;\n}\n\n/**\n * Decorator for declaring that a kOS model should be aware of it parent model.\n * This decorator will ensure that the parent model is available to the child model immediately after creation.\n * There is a slight performance overhead to this decorator, so it should only be used when necessary.\n *\n * @category kOS Model Decorator\n */\nconst DEFAULT_OPTION_KEY = createPropKey<any>(\"kosParentId\");\nexport const kosParentAware =\n <T extends IKosDataModel>(options?: KosParentProps) =>\n (constructor: DecoratedKosModel<T>): any => {\n constructor[ParentModel] = constructor[ParentModel] || {};\n const parentId = options?.parentId || DEFAULT_OPTION_KEY;\n constructor[ParentModel] = { parentId };\n };\n","import { KOS_MODEL_ID } from \"../../../common\";\n\ninterface ResolveParameterOptions {\n value: string | object;\n modelId: string;\n modelData: any;\n}\nexport const resolveParameters = ({\n value,\n modelId,\n modelData,\n}: ResolveParameterOptions) => {\n let _value = value;\n if (Array.isArray(_value)) {\n return [...(value as any)];\n } else if (typeof _value !== \"string\" && typeof _value !== \"object\") {\n return _value;\n } else if (typeof _value === \"object\") {\n _value = Object.keys(_value).reduce((acc, curr) => {\n acc[curr] = resolveParameters({\n value: _value[curr],\n modelId,\n modelData,\n });\n\n return acc;\n }, {});\n } else if (typeof _value === \"string\") {\n const propRegex = new RegExp(\".*({PROP_(.+)})\");\n let _depId: string | undefined = _value?.includes(KOS_MODEL_ID)\n ? _value.replace(KOS_MODEL_ID, modelId)\n : _value;\n const match = _depId.match(propRegex);\n if (match && modelData) {\n if (\n Object.getOwnPropertyNames(modelData).includes(match[2]) ||\n Object.getOwnPropertyNames(Object.getPrototypeOf(modelData)).includes(\n match[2]\n )\n ) {\n const prop = modelData[match[2]];\n _depId = prop ? _depId.replace(match[1], prop) : undefined;\n }\n }\n\n return _depId;\n } else {\n return _value;\n }\n\n return _value;\n};\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable max-len */\n/* eslint-disable no-param-reassign */\n/* eslint-disable max-classes-per-file */\nimport { makeAutoObservable } from \"mobx\";\nimport { KosCore } from \"../kosCore\";\nimport { IKosDataModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\n\nimport { KosContextManager } from \"../context/kos-context-manager\";\nimport {\n DependencyModels,\n FutureService,\n KosModelSymbol,\n LogConfig,\n ParentModel,\n SubscriptionHandlers,\n} from \"./propKeys\";\nimport { resolveParameters } from \"./resolve-parameters\";\n\nconst log = KosLog.createLogger({ name: \"kos-model\" });\n\nconst handler1 = {\n construct(target, args) {\n const kosContext = KosContextManager.createContext(args[0]);\n let parentId = target[ParentModel]?.parentId;\n if (parentId) {\n parentId = resolveParameters({\n value: parentId,\n modelData: args[1] || {},\n modelId: args[0],\n });\n\n KosContextManager.setParentContext(args[0], parentId);\n }\n const modelInstance = new target(...args, {\n logger: KosLog.createLogger({\n name: target.prototype.modelTypeId,\n group: target[LogConfig]?.group ?? \"kos-model\",\n }),\n kosContext,\n });\n\n // eslint-disable-next-line no-param-reassign\n try {\n Object.keys(modelInstance[FutureService] || {}).forEach((key) => {\n modelInstance[key] = modelInstance[FutureService][key].handler;\n });\n } catch (e) {\n log.error(`error while creating model instance`, e);\n }\n\n const dependencies = modelInstance[DependencyModels] || {};\n Object.keys(dependencies).forEach((key) => {\n const dependency = dependencies[key];\n const _id = resolveParameters({\n value: dependency.id || dependency.modelType,\n modelData: modelInstance,\n modelId: args[0],\n });\n const options = Object.keys(dependency?.options || {}).reduce(\n (acc, curr) => {\n const value = dependency.options[curr];\n acc[curr] = resolveParameters({\n value: value,\n modelData: modelInstance,\n modelId: args[0],\n });\n return acc;\n },\n {}\n );\n\n if (typeof _id === \"string\") {\n modelInstance[key] = !dependency.lazy\n ? KosCore.getInstance().modelManager.createModelInstance(\n dependency.modelType,\n _id,\n options || {}\n ).data\n : undefined;\n KosCore.getInstance().modelManager.addDependency(args[0], _id);\n }\n });\n\n let obs;\n try {\n obs = makeAutoObservable(modelInstance);\n } catch (e) {\n log.error(e);\n }\n\n return obs;\n },\n};\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\n/**\n * Decorator for defining a Kos Data Model class.\n *\n * The decorator will prepare the class instance to use as a kOS Data Model meaning:\n * 1. The properties on the class will be observable meaning that any changes to them will be tracked and trigger updates to any subscribers.\n * 2. Methods will be treated as kOS Actions meaning that they will encapsulate any model mutations and will result in atomic updates to the model.\n * 3. The class will be able to register topic handlers to receive messages from the backend and from other models.\n * 4. The model will participate in the model lifecycle and will be initialized, activated, and disposed at the appropriate times.\n *\n *\n * @param id - The unique identifier for the data model.\n * @returns A decorator function that defines a Kos Data Model class.\n *\n * @category kOS Model Decorator\n */\n\nexport const kosModel =\n <T extends IKosDataModel = any, O extends object = Record<string, any>>(\n id: string\n ) =>\n (constructor: DecoratedKosModel<T>) => {\n constructor.prototype.modelTypeId = id;\n constructor.prototype[KosModelSymbol] = true;\n constructor.prototype[SubscriptionHandlers] =\n constructor.prototype[SubscriptionHandlers] || {};\n constructor.prototype[DependencyModels] =\n constructor.prototype[DependencyModels] || {};\n\n // TODO: This is a temporary hack for backwards compatibility with the old model registration system\n const options: O = {} as O;\n KosLog.ifDebug(() => {\n KosLog.debug(`Registering model with options ${options}`);\n });\n return new Proxy(constructor, handler1);\n };\n","/**\n * @internal\n */\nimport { IKosDataModel } from \"../kosModel\";\nimport { kosParentAware } from \"./kos-parent\";\nimport { kosModel } from \"./kosModel\";\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\ntype KosCompantionOptions = { modelType: string };\nexport const kosCompanion =\n <T extends IKosDataModel>({ modelType }: KosCompantionOptions) =>\n (constructor: DecoratedKosModel<T>): any => {\n kosParentAware()(constructor);\n kosModel(modelType)(constructor);\n };\n","/**\n * @internal\n */\nimport { KosContextManager } from \"../context/kos-context-manager\";\n\nexport function kosContext(\n _target: any,\n _propertyKey: string,\n descriptor: PropertyDescriptor\n) {\n // store the original method\n const originalMethod = descriptor.value;\n\n // modify the descriptor value\n descriptor.value = function (...args: any[]) {\n // get the kos context\n const ctx = KosContextManager.getContext((this as any).id);\n // add the context as the last argument\n args.push(ctx);\n\n // apply the original method\n return originalMethod.apply(this, args);\n };\n}\n","/**\n * @internal\n */\nimport { IKosDataModel } from \"../kosModel\";\nimport { LogConfig } from \"./propKeys\";\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\ninterface LogConfigProps {\n group?: string;\n}\nexport const kosLogger =\n <T extends IKosDataModel>({ group }: LogConfigProps = { group: \"\" }) =>\n (constructor: DecoratedKosModel<T>): any => {\n constructor[LogConfig] = constructor[LogConfig] || {};\n constructor[LogConfig] = { group };\n };\n","/* eslint-disable no-param-reassign */\nimport { ModelEffects } from \"./propKeys\";\n\ninterface KosModelEffectProps<T = any> {\n dependencies: (model: T) => any[];\n}\n/**\n * Decorator for defining a Kos model effect function within a Kos Data Model class.\n *\n * @param props - An object containing configuration parameters for the topic handler.\n * @returns A decorator function.\n *\n * @example\n * ```typescript\n * class MyKosDataModel implements IKosDataModel {\n * // ...\n *\n * @kosModelEffect()\n * handleModelEffect() {\n * // Handle the received topic payload here.\n * }\n * }\n * ```\n * @category kOS Model Decorator\n */\nexport function kosModelEffect<T = any>(props?: KosModelEffectProps<T>) {\n return (target: T, _propertyKey: string, descriptor: PropertyDescriptor) => {\n target[ModelEffects] = target[ModelEffects] || {};\n\n target[ModelEffects][_propertyKey] = {\n dependencies: props?.dependencies,\n value: descriptor.value,\n };\n descriptor.value = function () {\n throw new Error(`Method ${_propertyKey} cannot be called directly.`);\n };\n };\n}\n","/**\n * @ignore\n * @deprecated\n */\nimport { ReferenceConfig } from \"./propKeys\";\n\ninterface ReferenceProps {\n modelType: string;\n}\n\nexport const kosReference =\n (props: ReferenceProps) =>\n (target: {} | any, name: PropertyKey): any => {\n target[ReferenceConfig] = target[ReferenceConfig] || {};\n target[ReferenceConfig][name] = props;\n };\n","/* eslint-disable no-param-reassign */\nimport {\n DependencyLifecycle,\n KosDependencyParams,\n} from \"../../types/kos-dependency\";\nimport { DependencyModels } from \"./propKeys\";\n\nexport * as KosDependencyTypes from \"../../types/kos-dependency\";\n\n/**\n * This decorator is used to define a dependency on a Kos model.\n *\n * @param params The parameters for the decorator.\n * @param params.modelType The type of the model to be injected.\n * @param params.id The id of the model to be injected.\n * @param params.options The options to be passed to the model constructor.\n * @param params.lifecycle The lifecycle at which the dependency should be injected.\n *\n * @category kOS Model Decorator\n * */\nexport const kosDependency =\n <Options = unknown>({\n /** The type of the model to be injected. */\n modelType,\n id,\n options,\n\n lifecycle,\n }: KosDependencyParams<Options>) =>\n (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType,\n id,\n options,\n lifecycle: lifecycle || DependencyLifecycle.INIT,\n };\n };\n","/**\n * @deprecated\n * @internal\n */\nimport { action } from \"mobx\";\nimport debounce from \"../../util/debounce\";\nimport { SubscriptionHandlers } from \"./propKeys\";\n\nexport interface IKosSubscriptionHandlerParams<T, M> {\n topic: string;\n condition?: (payload: T, model: M) => boolean;\n handler: Function;\n websocket?: boolean;\n skipParse?: boolean;\n}\n\nexport const kosSubscribe =\n <T = unknown, M = unknown>({\n topic,\n handler,\n websocket = false,\n condition = () => true,\n }: IKosSubscriptionHandlerParams<T, M>) =>\n (target: T) => {\n target[SubscriptionHandlers] = target[SubscriptionHandlers] || {};\n if (Array.isArray(topic)) {\n topic.forEach((t) => {\n target[SubscriptionHandlers][t] = {\n websocket,\n handler,\n condition,\n };\n });\n } else {\n target[SubscriptionHandlers][topic] = {\n websocket,\n handler: debounce(target, action(handler), 200),\n condition,\n };\n }\n };\n","/* eslint-disable no-param-reassign */\nimport { DependencyLifecycle } from \"../../types\";\nimport { IKosDataModel } from \"../kosModel\";\nimport { SubscriptionHandlers } from \"./propKeys\";\n\n/**\n * Configuration parameters for defining a Kos topic handler function within a Kos Data Model class.\n *\n * @typeparam Response - The type of the raw response payload received from the topic.\n * @typeparam Model - The type of the Kos Data Model to which the topic handler belongs.\n * @typeparam TransformedResponse - The type of the transformed response payload after applying the transformation function.\n */\nexport interface IKosTopicHandlerParams<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n> {\n /**\n * The topic or array of topics to which the handler should respond.\n */\n topic: string | string[];\n\n /**\n * A conditional function that determines whether the handler should be invoked based on the received payload and the Kos Data Model instance.\n * If not provided, the handler will always be invoked when a matching topic is received.\n *\n * @param payload - The transformed payload received from the topic.\n * @param model - The Kos Data Model instance to which the topic handler belongs.\n * @returns `true` if the handler should be invoked, `false` otherwise.\n */\n condition?: (\n payload: TransformedResponse,\n model: Model,\n raw: Response\n ) => boolean;\n\n /**\n * A transformation function that converts the raw response payload into a desired format.\n * If not provided, the payload will be used as is.\n *\n * @param payload - The raw response payload received from the topic.\n * @returns The transformed payload in the desired format.\n */\n transform?: (payload: Response) => TransformedResponse;\n\n /**\n * Indicates whether the topic handler should listen for WebSocket messages.\n * If set to `true`, the handler will be invoked when WebSocket messages with matching topics are received.\n * Default is `false`.\n */\n websocket?: boolean;\n\n /**\n * @internal\n */\n fos?: boolean;\n\n /**\n * @internal\n */\n bridge?: boolean;\n\n lifecycle?: DependencyLifecycle;\n\n /**\n * @internal\n */\n skipParse?: boolean;\n}\n\n/**\n * Decorator for defining a Kos topic handler function within a Kos Data Model class.\n *\n * @param params - An object containing configuration parameters for the topic handler.\n * @returns A decorator function.\n *\n * @example\n * ```typescript\n * class MyKosDataModel implements IKosDataModel {\n * // ...\n *\n * @kosTopicHandler({\n * topic: 'exampleTopic',\n * condition: (payload, model) => payload.valid && model.active,\n * transform: (payload) => ({ modifiedPayload: payload }),\n * websocket: true,\n * })\n * handleExampleTopic(payload: any) {\n * // Handle the received topic payload here.\n * }\n * }\n * ```\n * @category kOS Model Decorator\n */\nexport function kosTopicHandler<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n>({\n topic,\n condition = (_payload, _model) => true,\n transform = (_payload) => _payload as any,\n websocket = false,\n fos = false,\n bridge = false,\n skipParse = false,\n lifecycle,\n}: IKosTopicHandlerParams<Response, Model, TransformedResponse>) {\n return (\n target: any,\n _propertyKey: string,\n descriptor: PropertyDescriptor\n ) => {\n // Ensure the SubscriptionHandlers property exists on the target object.\n target[SubscriptionHandlers] = target[SubscriptionHandlers] || {};\n\n // Register the topic handler(s) with their configurations.\n if (Array.isArray(topic)) {\n topic.forEach((t) => {\n target[SubscriptionHandlers][t] = {\n websocket,\n fos,\n bridge,\n handler: descriptor.value,\n condition,\n transform,\n lifecycle,\n skipParse,\n };\n });\n } else {\n target[SubscriptionHandlers][topic] = {\n websocket,\n fos,\n bridge,\n handler: descriptor.value,\n condition,\n transform,\n lifecycle,\n skipParse,\n };\n }\n };\n}\n","export enum KosModelState {\n CREATING = `creating`,\n CREATED = `created`,\n INITIALIZING = `initializing`,\n INITIALIZED = `initialized`,\n LOADING = `loading`,\n LOADED = `loaded`,\n ONLINE = `online`,\n READYING = `readying`,\n READY = `ready`,\n READY_FAILED = `ready_failed`,\n RESETTING = `resetting`,\n RESET = `reset`,\n OFFLINE = `offline`,\n UNLOADING = `unloading`,\n UNLOADED = `unloaded`,\n FAILED = `failed`,\n INACTIVE = \"inactive\",\n ACTIVE = \"active\",\n ACTIVATING = \"activating\",\n DEACTIVATING = \"deactivating\",\n}\n\nexport enum KosModelEvents {\n CREATE = `create`,\n INITIALIZE = `init`,\n LOAD = `load`,\n READY = `ready`,\n GO_ONLINE = `go_online`,\n GO_OFFLINE = `go_offline`,\n RESET = `go_offline`,\n UNLOAD = `unload`,\n FAILED = \"failed\",\n GO_ACTIVE = \"go_active\",\n GO_INACTIVE = \"go_inactive\",\n TIMEOUT = \"timeout\",\n}\n","import { ObservableMap } from \"mobx\";\nimport { DependencyModels } from \"../core/decorators\";\nimport { resolveParameters } from \"../core/decorators/resolve-parameters\";\nimport { IKosModelContainer } from \"../core/kos-container-model\";\nimport { KosCore } from \"../core/kosCore\";\nimport type { IKosDataModel, IKosModel } from \"../core/kosModel\";\nimport { KosModelEvents, KosModelState } from \"../core/lifecycle\";\nimport { KosLog } from \"../core/log\";\nimport {\n DependencyLifecycle,\n KosDependencyParams,\n} from \"../types/kos-dependency\";\n\nconst PROMISE_TIMEOUT = 5000;\nexport interface ModelPromise {\n promise?: Promise<void>;\n modelId?: string;\n model?: IKosModel;\n type?: string;\n status?: string;\n}\n\nclass ModelError extends Error {\n model: IKosModel;\n constructor(message: string | undefined, model) {\n super(message);\n this.model = model;\n }\n}\nexport type ModelPromiseResolver = (model: IKosModel) => Promise<void>;\n\nconst rejectAfterDelay = (\n ms: number,\n model: IKosModel,\n status: string\n): { promise: Promise<void>; cancel: () => void } => {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const promise = new Promise<void>((_, reject) => {\n timeoutId = setTimeout(() => {\n KosLog.error(\n `Model ${model.modelId} - ${model.modelTypeName} - ${status} timed out after ${ms}ms`\n );\n reject(\n new ModelError(\n `${model.modelId} - ${model.modelTypeName} - ${status}`,\n model\n )\n );\n }, ms);\n });\n\n const cancel = () => {\n if (timeoutId) clearTimeout(timeoutId);\n };\n\n return { promise, cancel };\n};\n\nexport const transitionToActive = (model: IKosModel): Promise<void> =>\n model.transition(KosModelEvents.GO_ACTIVE, KosModelState.ACTIVE);\n\nexport const transitionToReady = (model: IKosModel): Promise<void> =>\n model.whenReady();\n\nexport const transitionToLoad = (model: IKosModel): Promise<void> =>\n model.transition(KosModelEvents.LOAD, KosModelState.LOADED);\n\nexport const transitionToUnload = (model: IKosModel): Promise<void> =>\n model.transition(KosModelEvents.UNLOAD, KosModelState.UNLOADED);\n\nexport const transitionToInit = (model: IKosModel): Promise<void> =>\n model.transition(KosModelEvents.INITIALIZE, KosModelState.INITIALIZED);\n\nexport enum Transitions {\n ACTIVE = \"active\",\n READY = \"ready\",\n LOAD = \"load\",\n UNLOAD = \"unload\",\n INIT = \"init\",\n}\nexport const TransitionMap = {\n [Transitions.ACTIVE]: transitionToActive,\n [Transitions.READY]: transitionToReady,\n [Transitions.LOAD]: transitionToLoad,\n [Transitions.INIT]: transitionToInit,\n};\n\nexport const createModelDependency = (\n model: IKosModel,\n dependency: KosDependencyParams<any>\n) => {\n const _dataModelId = dependency.id || dependency.modelType;\n const dataModelId = resolveParameters({\n value: _dataModelId,\n modelData: model.modelData,\n modelId: model.modelId,\n }) as string;\n KosLog.debug(\n `activating dependent model ${dependency.modelType} with id ${dataModelId}`\n );\n const options = Object.keys(dependency?.options || {}).reduce((acc, curr) => {\n const value = dependency.options[curr];\n acc[curr] = resolveParameters({\n value: value,\n modelData: model.modelData,\n modelId: model.modelId,\n });\n return acc;\n }, {});\n const dependentModel = KosCore.getInstance().modelManager.createModelInstance(\n dependency.modelType,\n dataModelId,\n options\n );\n\n return { dependentModel, dataModelId };\n};\n\nexport const getDependenciesByLifecycle = (\n model: IKosModel,\n lifecycle: DependencyLifecycle = DependencyLifecycle.READY\n) => {\n const dependencies = model.modelData?.[DependencyModels] || {};\n if (Object.keys(dependencies).length === 0) {\n KosLog.debug(`${model.modelId} has no dependencies. Returning`);\n return [];\n }\n const dependenciesByLifecycle = Object.keys(dependencies)\n // find all the dependencies that match the lifecycle\n .filter((key) => dependencies[key].lifecycle === lifecycle)\n .map((key) => {\n const dependency = dependencies[key];\n const { dependentModel, dataModelId } = createModelDependency(\n model,\n dependency\n );\n model.modelData[key] = dependentModel.data;\n KosLog.debug(\n `waiting for dependent model ${dependency.modelType} with id ${dataModelId} - waiting for WHENREADY`\n );\n const readyFn = async (\n dependentModel: IKosModel,\n modelType: string,\n id: string\n ) => {\n await dependentModel.whenReady?.();\n KosLog.debug(`dependent model ${modelType} with id ${id} - READY`);\n };\n const { promise, cancel } = rejectAfterDelay(\n PROMISE_TIMEOUT,\n model,\n model.status\n );\n return Promise.race([\n readyFn(dependentModel.model, dependency.modelType, dataModelId).then(\n () => {\n cancel();\n }\n ),\n promise,\n ]);\n })\n .filter((p) => !!p);\n\n return dependenciesByLifecycle;\n};\n\nexport const executeListLifecycle = async (\n sourceModel: IKosModel,\n models: (IKosModel | undefined)[],\n target: Transitions,\n sourceLifecycle: DependencyLifecycle\n) => {\n KosLog.debug(`Execute lifecycle with ${models.length} models`);\n if (models.length === 0) {\n KosLog.debug(`${sourceModel.modelId} has no children. Returning`);\n return;\n }\n if (!target) {\n KosLog.error(\n `${sourceModel.modelId} is not transitioning with a valid target ${target}`\n );\n return;\n }\n const childPromises = models\n .map<ModelPromise>((model) => {\n let p: Promise<void> | undefined;\n\n if (TransitionMap[target] && model) {\n p = TransitionMap[target](model);\n } else {\n if (!model) {\n KosLog.error(\"model is undefined. This shouldn't happen\");\n }\n\n if (!TransitionMap[target]) {\n KosLog.error(\n `There is no promise in the Transition Map for ${target}`\n );\n }\n }\n\n return {\n promise: p,\n modelId: model?.modelId,\n model,\n type: model?.modelTypeName,\n status: model?.status,\n };\n })\n .filter((modelPromise) => {\n if (!modelPromise.promise) {\n KosLog.error(`No promise found ${modelPromise.modelId}`);\n return false;\n }\n\n if (!modelPromise.model) {\n KosLog.error(`No model found ${modelPromise.modelId}`);\n return false;\n }\n return true;\n });\n\n const settledChildren = await Promise.allSettled(\n childPromises.map((promise) => {\n const { promise: timeoutPromise, cancel: timeoutCancel } =\n rejectAfterDelay(PROMISE_TIMEOUT, promise.model!, promise.status!);\n return Promise.race([\n promise.promise?.then(() => {\n timeoutCancel();\n }),\n timeoutPromise,\n ]);\n })\n );\n const failedChildren = settledChildren.filter((p) => p.status === \"rejected\");\n\n if (failedChildren.length > 0) {\n KosLog.error(\n `Model ${sourceModel.modelId} had ${failedChildren.length} failed child models on ${sourceLifecycle}`\n );\n }\n};\n\nexport const executeChildrenModelLifecycle = async (\n model: IKosModel,\n target: Transitions,\n sourceLifecycle: DependencyLifecycle\n) => {\n await executeListLifecycle(\n model,\n model.getChildren().filter((child) => !!child),\n target,\n sourceLifecycle\n );\n};\n\nexport const executeDependentModelLifecycle = async (\n model: IKosModel,\n lifecycle: DependencyLifecycle\n) => {\n // wait for all non-lazy dependencies to be ready\n const settled = await Promise.allSettled(\n getDependenciesByLifecycle(model, lifecycle)\n );\n const failed = settled.filter((p) => p.status === \"rejected\");\n if (failed.length) {\n KosLog.error(\n `There were ${failed.length} failed dependent models on ${lifecycle}`\n );\n KosLog.error(failed);\n }\n};\n\nexport const isKosDataModel = (model: any): model is IKosDataModel =>\n model[DependencyModels] !== undefined;\n\nexport const isKosModelContainer = (\n model: any\n): model is IKosModelContainer<any> =>\n model.revision !== undefined && model.index !== undefined;\n\nexport const resolveChild = (attribute: any) => {\n if (!attribute) return undefined;\n if (isKosDataModel(attribute)) return attribute;\n if (isKosModelContainer(attribute)) return attribute.data;\n if (\n attribute instanceof Map ||\n attribute instanceof ObservableMap ||\n attribute instanceof Set\n ) {\n return Array.from(attribute.values()).filter(isKosDataModel);\n }\n if (Array.isArray(attribute)) {\n return attribute.filter(isKosDataModel);\n }\n return undefined;\n};\n","import {\n action,\n createMachine,\n interpret,\n invoke,\n state,\n transition,\n} from \"robot3\";\nimport { IKosModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { KosModelEvents, KosModelState } from \"./constants\";\n\nconst log = KosLog.createLogger({ name: \"model-active-machine\" });\n\nexport const activeMachine = (model: IKosModel) => {\n const machine = createMachine(KosModelState.INACTIVE, {\n [KosModelState.FAILED]: state(\n transition(KosModelEvents.GO_ACTIVE, KosModelState.ACTIVATING)\n ),\n [KosModelState.INACTIVE]: state(\n transition(KosModelEvents.GO_ACTIVE, KosModelState.ACTIVATING)\n ),\n [KosModelState.ACTIVATING]: invoke(\n () => {\n model.activeStatus = KosModelState.ACTIVATING;\n return model.activate!();\n },\n transition(\n `done`,\n KosModelState.ACTIVE,\n action(() => {\n model.activeStatus = KosModelState.ACTIVE;\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.activeStatus = KosModelState.FAILED;\n })\n )\n ),\n [KosModelState.ACTIVE]: state(\n transition(KosModelEvents.GO_INACTIVE, KosModelState.DEACTIVATING)\n ),\n [KosModelState.DEACTIVATING]: invoke(\n () => {\n model.activeStatus = KosModelState.DEACTIVATING;\n return model.deactivate!();\n },\n transition(\n `done`,\n KosModelState.INACTIVE,\n action(() => {\n model.activeStatus = KosModelState.INACTIVE;\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.activeStatus = KosModelState.FAILED;\n })\n )\n ),\n });\n const service = interpret(machine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n return { service, machine };\n};\n","import { action, createMachine, interpret, state, transition } from \"robot3\";\nimport { IKosModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { KosModelEvents, KosModelState } from \"./constants\";\n\nconst log = KosLog.createLogger({ name: \"model-online-machine\" });\nexport const onlineMachine = (model: IKosModel) => {\n const machine = createMachine(KosModelState.OFFLINE, {\n [KosModelState.ONLINE]: state(\n transition(\n KosModelEvents.GO_OFFLINE,\n KosModelState.OFFLINE,\n action(async () => {\n await model.offline!();\n model.onlineStatus = KosModelState.OFFLINE;\n })\n )\n ),\n [KosModelState.OFFLINE]: state(\n transition(\n KosModelEvents.GO_ONLINE,\n KosModelState.ONLINE,\n action(async () => {\n log.debug(`Going online with model ${model.modelId}`);\n await model.online!();\n model.onlineStatus = KosModelState.ONLINE;\n await model.transition(\n KosModelEvents.INITIALIZE,\n KosModelState.INITIALIZED\n );\n })\n )\n ),\n });\n\n const service = interpret(machine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n return { machine, service };\n};\n","import {\n action,\n createMachine,\n immediate,\n invoke,\n state,\n transition,\n} from \"robot3\";\nimport { IKosModel } from \"../kosModel\";\nimport { KosModelEvents, KosModelState } from \"./constants\";\nimport { activeMachine } from \"./model-active-machine\";\nimport { onlineMachine } from \"./model-online-machine\";\nimport { kosAction } from \"../..\";\n\nexport const machine = (model: IKosModel) => {\n const active = activeMachine(model).service;\n const online = onlineMachine(model).service;\n return createMachine(KosModelState.CREATING, {\n [KosModelState.CREATING]: state(\n transition(KosModelEvents.CREATE, KosModelState.CREATED)\n ),\n [KosModelState.CREATED]: state(immediate(KosModelState.INITIALIZING)),\n [KosModelState.INITIALIZING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.INITIALIZING;\n });\n return model.init!();\n },\n transition(\n `done`,\n KosModelState.INITIALIZED,\n action(() => {\n model.status = KosModelState.INITIALIZED;\n })\n )\n ),\n [KosModelState.INITIALIZED]: state(immediate(KosModelState.LOADING)),\n [KosModelState.LOADING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.LOADING;\n });\n return model.load!();\n },\n transition(\n `done`,\n KosModelState.LOADED,\n action(() => {\n model.status = KosModelState.LOADED;\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.status = KosModelState.FAILED;\n })\n )\n ),\n [KosModelState.LOADED]: state(\n immediate(KosModelState.READYING),\n transition(KosModelEvents.UNLOAD, KosModelState.UNLOADING)\n ),\n [KosModelState.RESETTING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.RESETTING;\n });\n\n model.unload?.();\n return model.load!();\n },\n transition(\n `done`,\n KosModelState.LOADED,\n action(() => {\n model.status = KosModelState.LOADED;\n })\n )\n ),\n\n [KosModelState.READYING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.READYING;\n });\n return model.ready!();\n },\n\n transition(\n `done`,\n KosModelState.READY,\n action(() => {\n kosAction(() => {\n model.status = KosModelState.READY;\n });\n online.send(KosModelEvents.GO_ONLINE);\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.status = KosModelState.FAILED;\n })\n )\n ),\n\n [KosModelState.READY]: state(\n transition(\n KosModelEvents.UNLOAD,\n KosModelState.UNLOADED,\n action(model.unload?.bind(model))\n ),\n transition(KosModelEvents.RESET, KosModelState.RESETTING),\n transition(\n KosModelEvents.GO_ONLINE,\n KosModelState.READY,\n action(() => {\n online.send(KosModelEvents.GO_ONLINE);\n })\n ),\n transition(\n KosModelEvents.GO_OFFLINE,\n KosModelState.READY,\n action(() => {\n online.send(KosModelEvents.GO_OFFLINE);\n })\n ),\n transition(\n KosModelEvents.GO_ACTIVE,\n KosModelState.READY,\n action(() => {\n active.send(KosModelEvents.GO_ACTIVE);\n })\n ),\n transition(\n KosModelEvents.GO_INACTIVE,\n KosModelState.READY,\n action(() => {\n active.send(KosModelEvents.GO_INACTIVE);\n })\n )\n ),\n\n [KosModelState.UNLOADED]: state(),\n [KosModelState.FAILED]: state(),\n });\n};\n","/* eslint-disable max-classes-per-file */\n\nimport { interpret } from \"robot3\";\nimport type { IKosModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { machine } from \"./model-machine\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-lifecycle\" });\nexport interface KosOn {\n [k: string]: string;\n}\n\nexport interface KosInvoke<Context> {\n id: string;\n src: (context: Context) => Promise<any>;\n onDone: {\n target: string;\n };\n}\nexport interface KosLifecycleState {\n on: KosOn;\n}\nexport interface KosLifecycleStateContainer<Context> {\n [k: string]: {\n initial?: string;\n states?: KosLifecycleStateContainer<Context>;\n on?: KosOn;\n invoke?: KosInvoke<Context>;\n };\n}\n\nexport interface KosLifecycle<Context = any> {\n id: string;\n initial: string;\n states: KosLifecycleStateContainer<Context>;\n context: Context;\n}\n\nexport const fsm = (model: IKosModel) => {\n const service = interpret(machine(model), (_service) =>\n log.debug(\n `state machine for model ${model.modelId}: ${_service.machine.current});`\n )\n );\n\n return { service };\n};\n","import type { Transport } from \"./transport\";\n\nexport class WebSocketBridgeTransport extends WebSocket implements Transport {\n constructor(address: string) {\n super(address);\n }\n}\n","import { makeObservable, observable, runInAction } from \"mobx\";\nimport { EventBus, KosWsEvents } from \"../../../common\";\nimport { KosLog } from \"../log\";\nimport { Transport } from \"./transport\";\nimport { WebSocketBridgeTransport } from \"./web-socket-transport-adapter\";\n\nexport enum WebSocketEvents {\n CONNECTED = `websocket.connected`,\n DISCONNECTED = `websocket.disconnected`,\n}\nexport interface TransportParams {\n host: string;\n port: number;\n protocol: string;\n alias?: string;\n onConnectionEstablished?: () => void;\n onConnectionLost?: () => void;\n Transport?: new (url: string) => Transport;\n}\nexport interface MessageTransport {\n socket: Transport;\n send: (data: string | ArrayBufferLike | Blob | ArrayBufferView) => void;\n connectionEstablished: boolean;\n addOfflineMessage: (msg: string) => void;\n}\n\nexport interface KosInternalEvent {\n headers: Record<string | `topic` | `http-request-id`, string>;\n body: string;\n}\n\ninterface OfflineMessage {\n msg: string;\n fos?: boolean;\n}\n\nexport function processKosMessage(data: string): KosInternalEvent {\n const MESSAGE_SEPARATOR = `\\n\\n`;\n const SEPARATOR = `\\n`;\n const HEADER_SEPARATOR = /:(.*)/s;\n\n const [headerText, body] = data\n .split(MESSAGE_SEPARATOR)\n .map((line: string) => line.trim());\n const headers = headerText\n .split(SEPARATOR)\n .reduce((acc: any, curr: string) => {\n const [header, value] = curr\n .split(HEADER_SEPARATOR)\n .map((raw: string) => raw.trim());\n if (header && value) {\n acc[header] = value;\n }\n return acc;\n }, {});\n\n return {\n headers,\n body: body,\n };\n}\nexport function processKosSnifferMessage(data: string): KosInternalEvent {\n const MESSAGE_SEPARATOR = `\\n\\n`;\n const SEPARATOR = `\\n`;\n const HEADER_SEPARATOR = /:(.*)/s;\n\n const [, headerText, body] = data\n .split(MESSAGE_SEPARATOR)\n .map((line: string) => line.trim());\n const headers = headerText\n .split(SEPARATOR)\n .reduce((acc: any, curr: string) => {\n const [header, value] = curr\n .split(HEADER_SEPARATOR)\n .map((raw: string) => raw.trim());\n if (header && value) {\n acc[header] = value;\n }\n return acc;\n }, {});\n\n return {\n headers,\n body: body,\n };\n}\n\nexport abstract class BaseTransport implements MessageTransport {\n protected host: string;\n protected port: number;\n protected protocol: string;\n public socket: Transport;\n public connectionEstablished: boolean;\n private alias?: string;\n private onConnectionEstablished?: () => void;\n private onConnectionLost?: () => void;\n protected offlineMessages: OfflineMessage[] = [];\n protected abstract RESPONSE_ID_HEADER: string;\n private oldSend: (\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n ) => void;\n constructor({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n Transport = WebSocketBridgeTransport,\n }: TransportParams) {\n this.host = host;\n this.port = port;\n this.protocol = protocol;\n this.onConnectionEstablished = onConnectionEstablished;\n this.onConnectionLost = onConnectionLost;\n this.alias = alias;\n this.socket = new Transport(\n `${this.protocol}${this.host}:${this.port}/events`\n );\n this.socket.onmessage = this.onMessage.bind(this);\n this.socket.onopen = this.onOpen.bind(this);\n this.socket.onclose = this.onClose.bind(this);\n this.oldSend = this.socket.send;\n this.connectionEstablished = false;\n EventBus.subscribe(\"/mock/msg/receive\", (data) => {\n if (data?.body) {\n KosLog.wsReceive(data?.body);\n const msg: MessageEvent = {\n data: data.body,\n } as unknown as MessageEvent;\n this.socket?.onmessage?.(msg);\n }\n });\n\n makeObservable(this, {\n connectionEstablished: observable,\n });\n }\n\n addOfflineMessage(msg: string) {\n this.offlineMessages.push({ msg });\n }\n processMessageEvent(msg: MessageEvent): KosInternalEvent {\n const { data } = msg;\n return processKosMessage(data);\n }\n\n onMessage(event: Event) {\n try {\n // parsing the message payload\n KosLog.debug(\"webSocketTransport: onMessage received\");\n\n const { headers, body } = this.processMessageEvent(event as MessageEvent);\n KosLog.wsReceive((event as MessageEvent).data);\n const subscriptionTopic =\n headers[\"subscription\"] ||\n headers[this.RESPONSE_ID_HEADER] ||\n headers[\"topic\"] ||\n headers[\"type\"];\n if (subscriptionTopic) {\n let msgBody = body;\n let msgHeaders = headers;\n\n if (subscriptionTopic === \"kos.sniffer.msg\") {\n const { headers: snifferHeaders, body: snifferBody } =\n processKosSnifferMessage((event as MessageEvent).data);\n msgBody = snifferBody;\n msgHeaders = {\n ...headers,\n ...snifferHeaders,\n };\n }\n\n EventBus.publish(subscriptionTopic, msgBody, msgHeaders);\n }\n } catch (ex: any) {\n KosLog.error(`onMessage exception`, ex.message, ex.stack);\n }\n }\n\n onOpen(event: Event) {\n KosLog.info(`websocket connection opened`);\n\n this.socket = event.currentTarget as Transport;\n runInAction(() => {\n this.connectionEstablished = true;\n if (this.alias) {\n this.socket.send(`type:kos.addr.alias\\nalias:${this.alias}\\n\\n`);\n }\n KosLog.debug(\n `sending ${this.offlineMessages.length} offline FOS messages`\n );\n this.offlineMessages.forEach((msg) => {\n KosLog.debug(`sending offline message ${msg.msg}`);\n this.socket?.send(msg.msg);\n });\n\n this.offlineMessages = [];\n this.onConnectionEstablished?.();\n });\n }\n\n onClose() {\n if (this.socket) {\n this.socket.close();\n }\n\n runInAction(() => {\n this.connectionEstablished = false;\n });\n\n KosLog.debug(`websocket disconnected. Attempting calling callback`);\n if (this.onConnectionLost) {\n setTimeout(this.onConnectionLost, 2500);\n }\n }\n\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {\n KosLog.wsSend(data);\n if (window.kosLogEvents) {\n const { headers, body } = processKosMessage(String(data));\n EventBus.publish(KosWsEvents.SEND, { headers, body });\n }\n if (window.kosTopicIntercept && window.kosEnableMocks) {\n const { handler, requestId } = window.kosTopicIntercept(data);\n if (handler) {\n data = `mocked:true\\n${data}`;\n\n const msg = handler(requestId);\n const returnData: MessageEvent = {\n data: `mocked:true\\n${msg}`,\n } as unknown as MessageEvent;\n this.socket?.onmessage?.(returnData);\n } else {\n this.oldSend.call(this.socket, data);\n }\n } else {\n this.oldSend.call(this.socket, data);\n }\n }\n}\n","import log from \"loglevel\";\nimport type { Transport } from \"./transport\";\n\ntype MessageType = string | ArrayBufferLike | Blob | ArrayBufferView;\nexport class BridgeTransport implements Transport {\n addEventListener!: () => any;\n dispatchEvent!: () => any;\n removeEventListener!: () => any;\n private _onclose!: ((ev: CloseEvent) => any) | null;\n private _onerror!: ((ev: Event) => any) | null;\n private _onmessage!: ((ev: MessageEvent) => any) | null;\n private _onopen!: ((ev: Event) => any) | null;\n private messageQueue: MessageType[] = [];\n private isSending = false;\n\n constructor(addr: string) {\n log.debug(`called Bridge Transport with addr ${addr}`);\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this;\n globalThis.kosWindowWebsocketRecv = (msg: string) => {\n if (that.onmessage) {\n const data: MessageEvent = { data: msg } as unknown as MessageEvent;\n that.onmessage(data);\n }\n };\n // initalize the transport\n log.debug(\"Opening bridge transport\");\n globalThis.kosWindowWebsocketOpen();\n log.debug(\"Opened bridge transport\");\n\n this._onclose = null;\n this._onerror = null;\n this._onmessage = null;\n this._onopen = null;\n this.addEventListener = () => log.debug(\"not implemented\");\n this.dispatchEvent = () => log.debug(\"not implemented\");\n this.removeEventListener = () => log.debug(\"not implemented\");\n }\n\n close() {\n log.debug(\"closing\");\n }\n\n private sendNextMessage() {\n if (this.messageQueue.length > 0) {\n const message = this.messageQueue.shift();\n globalThis.kosWindowWebsocketSend(message);\n setTimeout(() => this.sendNextMessage(), 1);\n } else {\n this.isSending = false;\n }\n }\n enqueueMessage(message: MessageType) {\n this.messageQueue.push(message);\n if (!this.isSending) {\n this.isSending = true;\n this.sendNextMessage();\n }\n }\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {\n globalThis.kosWindowWebsocketSend(data);\n }\n\n get onmessage() {\n return this._onmessage;\n }\n set onmessage(fn: ((ev: MessageEvent) => any) | null) {\n this._onmessage = fn;\n }\n\n get onopen() {\n return this._onopen;\n }\n set onopen(fn: ((ev: Event) => any) | null) {\n this._onopen = fn;\n }\n\n get onclose() {\n return this._onclose;\n }\n set onclose(fn: ((ev: CloseEvent) => any) | null) {\n this._onclose = fn;\n }\n\n get onerror() {\n return this._onerror;\n }\n set onerror(fn: ((ev: Event) => any) | null) {\n this._onopen = fn;\n }\n}\n","import { BaseTransport, TransportParams } from \"./base-message-transport\";\nimport { BridgeTransport } from \"./bridge-transport\";\n\nexport class BridgeMessageTransport extends BaseTransport {\n protected RESPONSE_ID_HEADER: string;\n constructor({ host, port, alias }: TransportParams) {\n super({\n host,\n port,\n Transport: BridgeTransport,\n alias,\n protocol: \"kos://\",\n });\n this.RESPONSE_ID_HEADER = `response-id`;\n }\n}\n","import { BaseTransport, TransportParams } from \"./base-message-transport\";\n\nexport class FosTransport extends BaseTransport {\n protected RESPONSE_ID_HEADER: string;\n constructor({ host, port }: TransportParams) {\n super({ host, port, protocol: `ws://` });\n this.RESPONSE_ID_HEADER = `requestId`;\n }\n}\n","import { BaseTransport, TransportParams } from \"./base-message-transport\";\n\nexport class KosTransport extends BaseTransport {\n protected RESPONSE_ID_HEADER: string;\n constructor({\n host,\n port,\n protocol,\n onConnectionEstablished,\n onConnectionLost,\n alias,\n }: TransportParams) {\n super({\n host,\n port,\n onConnectionEstablished,\n onConnectionLost,\n alias,\n protocol,\n });\n this.RESPONSE_ID_HEADER = `response-id`;\n }\n}\n","// eslint-disable-next-line spaced-comment, @typescript-eslint/triple-slash-reference\n/// <reference path=\"../../types/global.d.ts\" />\nimport { KosLog } from \"../log\";\nimport { BridgeMessageTransport } from \"./bridge-message-transport\";\nimport { FosTransport } from \"./fos-message-transport\";\nimport { KosTransport } from \"./kos-message-transport\";\n\nwindow.kosEnableMocks = process.env.KOS_MOCK_WS === \"true\";\nwindow.kosLogEvents = process.env.KOS_LOG_WS === \"true\";\n\ninterface FactoryParams {\n host: string;\n port: number;\n protocol: string;\n fos?: boolean;\n alias?: string;\n onConnectionEstablished?: () => void;\n onConnectionLost?: () => void;\n}\n\n/**\n *\n * @description\n * Extend event to get access to the data property.\n */\nexport interface KosInternalEvent {\n headers: Record<string | `topic` | `http-request-id`, string>;\n body: string;\n}\n\nexport class TransportFactory {\n static build({\n host,\n port,\n protocol,\n fos,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n }: FactoryParams) {\n KosLog.debug(`initializing websocket connection`);\n KosLog.warn(\n `kosWindowWebsocketOpen: ${\n globalThis.kosWindowWebsocketOpen ? `true` : `false`\n }`\n );\n KosLog.warn(`fos: ${fos ? `true` : `false`}`);\n if (window.kosMockWs || (globalThis.kosWindowWebsocketOpen && !fos)) {\n KosLog.warn(`Using bridged message transport`);\n const transport = new BridgeMessageTransport({\n host,\n port,\n protocol,\n onConnectionEstablished,\n onConnectionLost,\n alias,\n });\n return transport;\n }\n if (fos) {\n const transport = new FosTransport({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n });\n return transport;\n } else {\n const transport = new KosTransport({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n });\n return transport;\n }\n }\n}\n","import Logger from \"loglevel\";\nimport {\n action,\n computed,\n makeObservable,\n observable,\n reaction,\n when,\n} from \"mobx\";\nimport { EventBus, EventCallback } from \"../../../common\";\n\nimport { getQueryParams } from \"../../util/get-query-params\";\nimport { KosLog } from \"../log\";\nimport { MessageTransport } from \"./base-message-transport\";\nimport { TransportFactory } from \"./transport-factory\";\n\nconst params = getQueryParams();\nif ((params as any).fos) {\n window.kosUseFos = true;\n}\nconst fosPort = process.env.KOS_FOS_PORT;\nwindow.kosUseFos = !!(window.kosUseFos || process.env.KOS_USE_FOS === \"true\");\nwindow.kosFosPort = fosPort ? parseInt(fosPort) : 0;\n\nconst log = Logger.getLogger(\"web-socket-transport\");\nexport enum KosWSTransportStatus {\n NOT_INITIALIZED = \"not_initialized\",\n INITIALIZED = \"initialized\",\n OFFLINE = \"OFFLINE\",\n ONLINE = \"ONLINE\",\n}\nexport interface IKosMessage {\n [k: string]: string | number | boolean;\n}\n\nexport interface IKosConnectionStatus {\n status: string;\n message?: string;\n}\n\nexport interface KosSubscriptionParams {\n topic: string;\n callback: EventCallback;\n fos?: boolean;\n bridge?: boolean;\n}\nexport interface IKosServiceTransport {\n host: string;\n port: number;\n protocol: string;\n token?: string;\n alias?: string;\n connectionEstablished: boolean;\n authorized: boolean;\n socket?: MessageTransport;\n init(): IKosServiceTransport;\n subscribeTopic(params: KosSubscriptionParams): VoidFunction;\n whenReady(): Promise<IKosConnectionStatus>;\n fosSocket?: MessageTransport;\n}\n\nexport type KosCallback = (msg: IKosMessage) => void;\n\nexport enum WebSocketEvents {\n CONNECTED = `websocket.connected`,\n DISCONNECTED = `websocket.disconnected`,\n RELOAD = `websocket.reload`,\n}\n\ninterface WebSocketTransportParams {\n host?: string;\n port?: number;\n protocol?: string;\n token?: string;\n initialize?: boolean;\n alias?: string;\n fos?: {\n port: number;\n };\n}\n\nexport class WebSocketTransport implements IKosServiceTransport {\n private static _instance: IKosServiceTransport;\n\n host: string;\n\n port: number;\n\n protocol: string;\n\n private _token?: string;\n\n private webSocketSupported = !!globalThis.WebSocket;\n\n authorized: boolean;\n\n alias?: string;\n\n socket?: MessageTransport;\n\n fosSocket?: MessageTransport;\n\n fosPort?: number;\n\n useFosTransport: boolean;\n\n constructor({\n host = `localhost`,\n port = 8080,\n protocol = \"ws://\",\n token,\n initialize,\n alias,\n fos,\n }: WebSocketTransportParams) {\n this.host = host;\n this.port = port;\n this.protocol = protocol;\n this._token = token;\n this.alias = alias;\n this.authorized = process.env.KOS_ALLOW_ANONYMOUS === \"true\" ? true : false;\n\n this.useFosTransport = !!fos;\n this.fosPort = fos?.port;\n this.socket = undefined;\n this.fosSocket = undefined;\n\n let initialized = false;\n makeObservable(this, {\n authorized: observable,\n socket: observable,\n fosSocket: observable,\n init: action,\n connectionEstablished: computed,\n });\n\n reaction(\n () => this.connectionEstablished,\n (connectionEstablished) => {\n if (connectionEstablished) {\n log.warn(\"Connection Established\");\n\n EventBus.publish(\n WebSocketEvents.CONNECTED,\n WebSocketEvents.CONNECTED\n );\n if (initialized) {\n // reload only if the websocket has been initialized once\n EventBus.publish(WebSocketEvents.RELOAD, WebSocketEvents.RELOAD);\n }\n initialized = true;\n }\n }\n );\n\n if (initialize) {\n this.init();\n }\n }\n\n get connectionEstablished() {\n if (!this.webSocketSupported) {\n return false;\n }\n if (!this.socket) {\n return false;\n }\n\n if (this.useFosTransport && !this.fosSocket) {\n return false;\n }\n\n if (this.useFosTransport && this.fosSocket) {\n return (\n this.socket.connectionEstablished &&\n this.fosSocket.connectionEstablished\n );\n }\n if (!this.useFosTransport && this.socket) {\n return this.socket.connectionEstablished;\n }\n return false;\n }\n\n init() {\n KosLog.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`);\n if (this.useFosTransport) {\n this.fosSocket = TransportFactory.build({\n host: this.host,\n port: this.fosPort || 9854,\n protocol: this.protocol,\n fos: true,\n });\n }\n this.socket = TransportFactory.build({\n host: this.host,\n port: this.port,\n protocol: this.protocol,\n alias: this.alias,\n onConnectionLost: () => {\n log.error(`Connection Lost`);\n EventBus.publish(\n WebSocketEvents.DISCONNECTED,\n WebSocketEvents.DISCONNECTED\n );\n this.init();\n },\n });\n\n if (globalThis.kosWindowWebsocketOpen) {\n const ev: Event = {\n currentTarget: this.socket.socket,\n } as unknown as Event;\n this.socket.socket?.onopen?.(ev);\n }\n return this;\n }\n\n private _sendSubscriptionMessage(\n topic: string,\n type: \"subscribe\" | \"unsubscribe\",\n fos = false,\n bridge = false\n ) {\n log.debug(`${type} to topic ${topic}`);\n const params = getQueryParams();\n const connectionParam = (params as any)?.connId;\n const connId = connectionParam || (window as any)?.kosBridge?.(\"connId\");\n log.debug(`subscribing with connId ${connId}`);\n\n const dstAddr = connId ? `dst-addr:${connId}\\n` : \"\";\n const msg = fos\n ? `subscribe:${topic}`\n : bridge\n ? `type:fos.broker\\ncmd:${type}\\n${dstAddr}topics:${topic}\\n`\n : `${dstAddr}type:kos.broker.${type}\\n\\n[\"${topic}\"]`;\n const established = fos\n ? this.fosSocket?.connectionEstablished\n : this.socket?.connectionEstablished;\n if (established) {\n const socket = fos ? this.fosSocket : this.socket;\n socket?.socket?.send(msg);\n } else {\n log.debug(`no connection adding to offline messages`);\n const socket = fos ? this.fosSocket : this.socket;\n socket?.addOfflineMessage(msg);\n }\n }\n\n subscribeTopic({ topic, callback, fos, bridge }: KosSubscriptionParams) {\n const { unsubscribe, count } = EventBus.subscribe(topic, callback);\n log.debug(`Topic ${topic} currently has ${count} subscribers`);\n this._sendSubscriptionMessage(topic, \"subscribe\", fos, bridge);\n\n return () => {\n const { count } = unsubscribe();\n log.debug(`Topic ${topic} currently has ${count} subscribers`);\n if (count === 0) {\n this._sendSubscriptionMessage(topic, \"unsubscribe\", fos);\n }\n };\n }\n\n async whenReady() {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this;\n if (!this.webSocketSupported) {\n return {\n status: `not supported`,\n };\n }\n await when(\n () =>\n !!that.socket?.connectionEstablished &&\n (!that.useFosTransport || !!that.fosSocket?.connectionEstablished) &&\n that.authorized\n );\n return {\n status: `success`,\n };\n }\n\n get token() {\n return this._token!;\n }\n set token(token: string) {\n this._token = token;\n this.init();\n }\n public static host(host = `localhost`) {\n this.getInstance().host = host;\n return this;\n }\n\n public static port(port = 8080) {\n this.getInstance().port = port;\n return this;\n }\n\n public static alias(alias: string) {\n this.getInstance().alias = alias;\n }\n\n public static getInstance(port = 8080, token?: string) {\n if (!this._instance) {\n const fos = window.kosUseFos\n ? { port: window.kosFosPort || 8081 }\n : undefined;\n this._instance = new this({ port, token, fos });\n }\n return this._instance;\n }\n}\n","/* eslint-disable max-len */\nimport logger from \"loglevel\";\nimport {\n autorun,\n IReactionDisposer,\n autorun as kosAutoEffect,\n makeAutoObservable,\n reaction,\n runInAction,\n when,\n} from \"mobx\";\nimport {\n ChildModels,\n ModelEffects,\n SubscriptionHandlers,\n} from \"./decorators/propKeys\";\n\nimport { EventBus } from \"../../common\";\n\n// import { KosModelManager } from \"./kosModelManager\";\n\nimport { ExtensionManager } from \"../core/extension/extension-manager\";\n\nimport { DependencyLifecycle } from \"../types/kos-dependency\";\nimport { getMessageBody } from \"../util/kos-message-utils\";\nimport {\n executeChildrenModelLifecycle,\n executeDependentModelLifecycle,\n resolveChild,\n Transitions,\n} from \"../util/model-utils\";\nimport {\n KosContext,\n KosContextBean,\n KosContextManager,\n} from \"./context/kos-context-manager\";\nimport { KosModelEvents, KosModelState } from \"./lifecycle/constants\";\nimport { fsm } from \"./lifecycle/kosModelLifecycle\";\nimport { KosLog } from \"./log\";\nimport { WebSocketTransport } from \"./transport/webSocketTransport\";\nimport type { IKosIdentifiable, KosParentAware } from \"./types\";\nimport type { IKosModelManager } from \"./types/kos-model-manager-types\";\n\nconst log = logger.getLogger(\"kos-model\");\n\nconst MODEL_LOADER = \"kos.extension.model.loader\";\nexport interface IKosModelLifecycle {\n init?(context?: KosContext): Promise<void>;\n load?(context?: KosContext): Promise<void>;\n ready?(context?: KosContext): Promise<void>;\n online?(context?: KosContext): Promise<void>;\n offline?(context?: KosContext): Promise<void>;\n unload?(context?: KosContext): void;\n activate?(context?: KosContext): Promise<void>;\n deactivate?(context?: KosContext): Promise<void>;\n}\n\nexport interface IKosVisitor<T extends IKosDataModel | IKosModel> {\n visit: (model: T) => void;\n}\n\nexport interface IKosVisitorHost<T extends IKosDataModel | IKosModel> {\n accept?: (visitor: IKosVisitor<T>) => void;\n}\n\nexport type KosContextLogger = ReturnType<typeof KosLog.getLogger>;\nexport interface IKosModelLogger {\n logger: KosContextLogger;\n}\n\nexport interface KosCreationContext extends IKosModelLogger {\n kosContext: KosContextBean;\n [key: string]: any;\n}\n\nexport interface IKosDataModel\n extends IKosModelLifecycle,\n IKosVisitorHost<IKosDataModel> {\n id: string;\n getDependencies?(): void;\n getChildren?: () => IKosDataModel[];\n update?: (values) => Promise<void>;\n}\n\nexport interface IKosCompanionOptions<\n T extends IKosDataModel = IKosDataModel,\n O extends object = object\n> extends KosParentAware {\n companionParent: T;\n data?: O;\n}\n\nexport interface IKosContainerModel<\n T extends IKosDataModel,\n R extends object = Record<string, unknown>\n> {\n models: T[];\n createModel?: (request: R) => Promise<unknown>;\n deleteModel?: (id: string) => Promise<void>;\n getModel?: (id: string) => T | undefined;\n}\n\nexport interface ReloadAware {\n reload: () => Promise<void>;\n}\n\nexport interface UnloadAware {\n unload: () => Promise<void>;\n}\n\nexport interface UpdateAware<O extends object = Record<string, any>> {\n updateModel: (options: O) => void;\n}\n\nexport interface IKosModel<DataDef extends IKosDataModel = IKosDataModel>\n extends IKosCompanionModelContainer,\n IKosModelLifecycle,\n IKosVisitorHost<IKosModel> {\n modelId: string;\n status: KosModelState;\n onlineStatus: KosModelState;\n activeStatus: KosModelState;\n modelTypeName: string;\n loaded: boolean;\n isReady(): boolean;\n isActive(): boolean;\n isOnline(): boolean;\n whenReady(): Promise<void>;\n whenInitialized(): Promise<void>;\n registerSubscribers(): Promise<void>;\n getChildren(): IKosModel[];\n modelData: DataDef;\n _offlineQueue: any[];\n transition: (\n event: KosModelEvents,\n target: KosModelState,\n error?: KosModelState\n ) => Promise<void>;\n}\n\ninterface KosModelParameters<DataType extends IKosDataModel> {\n modelTypeName: string;\n id?: string | number;\n modelData: DataType;\n modelManager: IKosModelManager;\n}\n\ninterface IKosCreateParam<Options extends object = Record<string, any>> {\n id?: string;\n modelTypeId: string;\n options?: Options;\n}\n\ninterface HandlerFactoryProps {\n subscription: any;\n modelData: IKosDataModel;\n skipParse?: boolean;\n model: IKosModel;\n resolvedTopic: string;\n}\n\nconst handlerFactory =\n ({\n subscription,\n modelData,\n skipParse,\n model,\n resolvedTopic,\n }: HandlerFactoryProps) =>\n (payload) => {\n // try to convert it to the model payload\n\n try {\n if (!model?.isReady) {\n KosLog.warn(\n `model ${model?.modelId} not ready. adding message for topic ${resolvedTopic} to offline queue`\n );\n const offlineHandler = () => {\n KosLog.warn(\n `processing offline message for ${resolvedTopic} on model ${model?.modelId}`\n );\n const body = getMessageBody(payload, skipParse);\n const data = subscription.transform(body);\n if (subscription.condition(data, modelData)) {\n return subscription.handler.call(\n modelData,\n data,\n payload,\n modelData\n );\n }\n return undefined;\n };\n model._offlineQueue.push(offlineHandler);\n } else {\n const body = getMessageBody(payload, skipParse);\n const data = subscription.transform(body);\n if (subscription.condition(data, modelData, payload)) {\n return subscription.handler.call(modelData, data, payload, modelData);\n }\n }\n } catch (e) {\n log.error(e);\n }\n\n return undefined;\n };\n\nconst resolveTopic = (\n topic: string,\n modelId: string,\n modelData?: IKosDataModel\n) => {\n const propRegex = new RegExp(\".*({PROP_(.+)})\");\n let _topic = topic.includes(`{MODEL_ID}`)\n ? topic.replace(`{MODEL_ID}`, modelId)\n : topic;\n const match = _topic.match(propRegex);\n if (match && modelData) {\n if (Object.getOwnPropertyNames(modelData).includes(match[2])) {\n const prop = modelData[match[2]];\n _topic = _topic.replace(match[1], prop);\n }\n }\n\n return _topic;\n};\n\nexport type IKosDataModelBuilder<D, M extends IKosDataModel> = (data: D) => M;\n\nexport type IKosDataModelCreator<\n M extends IKosDataModel = IKosDataModel,\n O extends object = Record<string, any>\n> = (params: IKosCreateParam<O>) => M;\n\nexport interface IKosDataModelFactory<D, M extends IKosDataModel> {\n build?: IKosDataModelBuilder<D, M>;\n create?: IKosDataModelCreator<M>;\n}\n\ninterface IKosCompanionModelContainer {\n clearCompanionModels: () => void;\n addCompanionModel: (model: IKosModel) => void;\n companionModels: Map<string, IKosModel>;\n}\nexport class KosModel<DataDef extends IKosDataModel = IKosDataModel>\n implements IKosModel<DataDef>, IKosCompanionModelContainer\n{\n private _id: string;\n\n private _status: KosModelState;\n\n private _activeStatus: KosModelState;\n private _onlineStatus: KosModelState;\n\n private _subscriptions: VoidFunction[];\n private _onlineSubscriptions: VoidFunction[];\n\n modelData: DataDef;\n\n modelTypeName: string;\n\n initialized: boolean;\n\n loaded: boolean;\n _offlineQueue: any[];\n fsmService: ReturnType<typeof fsm>;\n private disposers: VoidFunction[] = [];\n private modelManager: IKosModelManager;\n private _companionModels: Map<string, IKosModel>;\n constructor({\n modelTypeName,\n id,\n modelData,\n modelManager,\n }: KosModelParameters<DataDef>) {\n this.modelManager = modelManager;\n this._id = typeof id !== \"undefined\" ? `${id}` : modelTypeName;\n this.modelTypeName = modelTypeName;\n this.initialized = false;\n this.loaded = false;\n this.modelData = modelData;\n this._status = KosModelState.CREATED;\n this._activeStatus = KosModelState.INACTIVE;\n this._onlineStatus = KosModelState.OFFLINE;\n this.fsmService = fsm(this);\n this._subscriptions = [];\n this._onlineSubscriptions = [];\n this.fsmService.service.send(KosModelEvents.CREATE);\n this._companionModels = new Map();\n this._offlineQueue = [];\n makeAutoObservable(this);\n }\n\n get companionModels() {\n return this._companionModels;\n }\n\n set status(status: KosModelState) {\n this._status = status;\n }\n\n get status() {\n return this._status;\n }\n get modelId() {\n return this._id;\n }\n\n get id() {\n return this._id;\n }\n get activeStatus() {\n return this._activeStatus;\n }\n set activeStatus(activeStatus: KosModelState) {\n this._activeStatus = activeStatus;\n }\n\n get onlineStatus() {\n return this._onlineStatus;\n }\n set onlineStatus(onlineStatus: KosModelState) {\n this._onlineStatus = onlineStatus;\n }\n\n isActive() {\n return this._status === KosModelState.ACTIVE;\n }\n\n isOnline() {\n return this._onlineStatus === KosModelState.ONLINE;\n }\n\n isReady() {\n return this._status === KosModelState.READY;\n }\n\n async deactivate(): Promise<void> {\n log.debug(\n `deactivating model ${this.modelTypeName} with id ${this.modelId}`\n );\n try {\n // wait for any child models be be activated\n // await Promise.allSettled(\n // this.getChildren().map((model) =>\n // model.transition(KosModelEvents.GO_INACTIVE, KosModelState.INACTIVE)\n // )\n // );\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.deactivate?.(context);\n log.debug(\n `Model ${this.modelTypeName} with id ${this.modelId} deactivated`\n );\n } catch (e) {\n log.debug(`Model ${this.modelId} failed to deactivated`);\n throw e;\n }\n }\n\n transition(\n event: KosModelEvents,\n target: KosModelState,\n error: KosModelState = KosModelState.FAILED\n ) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this;\n const transitionStatus =\n target === KosModelState.ACTIVE || target === KosModelState.INACTIVE\n ? that.activeStatus\n : that.status;\n\n if (transitionStatus === target) {\n log.debug(\n `model ${this.modelId} already at target state ${target}. resolving immediately. `\n );\n return Promise.resolve();\n }\n\n let dispose: IReactionDisposer;\n return new Promise<void>((resolve, reject) => {\n dispose = kosAutoEffect(() => {\n const transitionStatus =\n target === KosModelState.ACTIVE || target === KosModelState.INACTIVE\n ? that.activeStatus\n : that.status;\n if (transitionStatus === error) {\n reject(Error(`Failed to transition ${that.modelId} to ${event}`));\n } else if (transitionStatus === target) {\n resolve();\n }\n });\n\n that.fsmService.service.send(event);\n }).then(() => {\n dispose?.();\n });\n }\n\n async activate(): Promise<void> {\n log.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`);\n await executeDependentModelLifecycle(this, DependencyLifecycle.ACTIVATE);\n\n // await executeChildrenModelLifecycle(\n // this,\n // Transitions.ACTIVE,\n // DependencyLifecycle.ACTIVATE\n // );\n\n // wait for any child models be be activated\n\n try {\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.activate?.(context);\n log.debug(\n `Model ${this.modelTypeName} with id ${this.modelId} activated`\n );\n } catch (e) {\n log.debug(`Model ${this.modelId} failed to activate`);\n throw e;\n }\n\n return;\n }\n\n async whenInitialized(): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this;\n let errorDispose: IReactionDisposer;\n let targetDispose: IReactionDisposer;\n return new Promise<void>((resolve, reject) => {\n errorDispose = when(\n () => that._status === KosModelState.FAILED,\n () => {\n reject(\n Error(`Failed to load ${that.modelId} model ${that.modelTypeName}`)\n );\n }\n );\n\n targetDispose = when(\n () => that.initialized,\n () => {\n resolve();\n }\n );\n }).then(() => {\n errorDispose?.();\n targetDispose?.();\n });\n }\n async whenReady(): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this;\n let errorDispose: IReactionDisposer;\n let targetDispose: IReactionDisposer;\n return new Promise<void>((resolve, reject) => {\n errorDispose = when(\n () => that._status === KosModelState.FAILED,\n () => {\n reject(\n Error(`Failed to load ${that.modelId} model ${that.modelTypeName}`)\n );\n }\n );\n\n targetDispose = when(\n () => that._status === KosModelState.READY,\n () => {\n resolve();\n }\n );\n }).then(() => {\n errorDispose?.();\n targetDispose?.();\n });\n }\n\n async ready() {\n if (this.fsmService.service.machine.current === KosModelState.READY) {\n log.debug(\n `already readying model ${this.modelTypeName} with id ${this.modelId} returning`\n );\n return;\n }\n try {\n log.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`);\n // wait for all non-lazy dependencies to be ready\n await executeDependentModelLifecycle(this, DependencyLifecycle.READY);\n\n await executeChildrenModelLifecycle(\n this,\n Transitions.READY,\n DependencyLifecycle.READY\n );\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.ready?.(context);\n\n if (this._offlineQueue.length > 0) {\n KosLog.warn(\n `processing ${this._offlineQueue.length} messages offline queue for ${this.modelId}`\n );\n this._offlineQueue.forEach((handler) => handler());\n KosLog.info(`offline queue processed for ${this.modelId}`);\n }\n\n this._offlineQueue = [];\n\n // await this.registerSubscribers();\n log.debug(`Model ${this.modelId} is ready`);\n } catch (e) {\n log.error(e);\n throw Error(e as any);\n }\n }\n\n async load(): Promise<void> {\n if (\n this.fsmService.service.machine.current === KosModelState.LOADED ||\n this.fsmService.service.machine.current === KosModelState.LOADING\n ) {\n log.debug(\n `already loaded model ${this.modelTypeName} with id ${this.modelId} returning`\n );\n return;\n }\n log.debug(`loading model ${this.modelTypeName} with id ${this.modelId}`);\n\n await executeDependentModelLifecycle(this, DependencyLifecycle.LOAD);\n\n log.debug(`loading model ${this.modelTypeName} with id ${this.modelId}`);\n try {\n const context = KosContextManager.getContext(this.modelId);\n const loadedContext = await ExtensionManager.loader.executeLoader(\n MODEL_LOADER,\n {}\n );\n\n if (loadedContext) {\n log.info(\n `setting loaded context for ${this.modelId}, type: ${this.modelTypeName}`\n );\n context?.set(MODEL_LOADER, loadedContext);\n }\n await this.modelData?.load?.(context);\n this.loaded = true;\n log.debug(`Model ${this.modelTypeName} with id ${this.modelId} loaded`);\n this.registerSubscribers(DependencyLifecycle.LOAD);\n const modelEffects = this.modelData?.[ModelEffects] || {};\n Object.keys(modelEffects).forEach((effect) => {\n const handler = modelEffects[effect].value.bind(this.modelData);\n const autoRunHandler = function (this: KosModel) {\n log.info(\n `running effect ${effect} for model type ${this.modelTypeName} id: ${this.modelId}`\n );\n\n runInAction(() => {\n handler.apply(this.modelData);\n });\n };\n if (modelEffects[effect].dependencies) {\n const depFn = () =>\n modelEffects[effect].dependencies(this.modelData as any);\n const disposer = reaction(depFn, autoRunHandler.bind(this));\n this.disposers.push(disposer);\n } else {\n const disposer = autorun(autoRunHandler.bind(this));\n this.disposers.push(disposer);\n }\n });\n } catch (e) {\n log.error(`Model ${this.modelId} failed to load`);\n throw e;\n }\n }\n\n async unload(): Promise<void> {\n log.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);\n try {\n const childrenUnload = this.getChildren()\n .map((child) => child.unload?.())\n .filter((p) => !!p);\n await Promise.allSettled(childrenUnload);\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.unload?.(context);\n this.loaded = false;\n this._onlineSubscriptions.forEach((unsub) => unsub());\n this._onlineSubscriptions = [];\n log.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`);\n this.disposers.forEach((disposer) => disposer());\n this.disposers = [];\n } catch (e) {\n log.debug(`Model ${this.modelId} failed to unload`);\n throw e;\n }\n }\n async init(): Promise<void> {\n log.debug(\n `initializing init dependencies of model ${this.modelTypeName} with id ${this.modelId}`\n );\n await executeDependentModelLifecycle(this, DependencyLifecycle.INIT);\n\n log.debug(\n `initializing model ${this.modelTypeName} with id ${this.modelId}`\n );\n try {\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.init?.(context);\n this.initialized = true;\n log.debug(\n `Model ${this.modelTypeName} with id ${this.modelId} initialized`\n );\n const onlineUnsub = EventBus.subscribe(\"/kosCore/online\", async () => {\n log.debug(\n `online subscription called for ${this.modelId} waiting for ready state`\n );\n await this.whenReady();\n log.debug(` ${this.modelId} is ready. Going online`);\n this.fsmService.service.send(KosModelEvents.GO_ONLINE);\n });\n\n const offlineUnsub = EventBus.subscribe(\"/kosCore/offline\", async () => {\n log.debug(\n ` offline sub called for model ${this.modelId}. Going offline`\n );\n this.fsmService.service.send(KosModelEvents.GO_OFFLINE);\n });\n\n this._onlineSubscriptions.push(onlineUnsub.unsubscribe);\n this._onlineSubscriptions.push(offlineUnsub.unsubscribe);\n this.registerSubscribers(DependencyLifecycle.INIT);\n } catch (e) {\n log.error(`Model ${this.modelId} failed to initialize`);\n throw e;\n }\n }\n\n _registerSubscription(_subscription, resolvedTopic, handler) {\n if (_subscription.websocket) {\n log.debug(`subscribing ${resolvedTopic} via WebSocketTransport`);\n const subscription = WebSocketTransport.getInstance().subscribeTopic({\n topic: resolvedTopic,\n callback: handler,\n fos: _subscription.fos,\n bridge: _subscription.bridge,\n });\n this._subscriptions.push(subscription);\n } else {\n log.debug(`subscribing ${resolvedTopic} directly to EventBus`);\n const { unsubscribe } = EventBus.subscribe(resolvedTopic, handler);\n this._subscriptions.push(unsubscribe);\n }\n }\n async registerSubscribers(lifecycle?: DependencyLifecycle) {\n log.debug(\n `registering subscribers in ${this.modelTypeName} with id ${this.modelId}`\n );\n const subscriptions = this.modelData?.[SubscriptionHandlers] || {};\n log.debug(\n `found ${Object.keys(subscriptions).length} topics to subscribe to`\n );\n\n Object.keys(subscriptions).forEach((topic) => {\n const _lifecycle = subscriptions[topic].lifecycle;\n if (lifecycle && lifecycle !== _lifecycle) {\n return;\n }\n const skipParse = !!subscriptions[topic].skipParse;\n\n log.debug(`found subscription for ${topic}`);\n log.debug(`${topic} skipParse: ${skipParse}`);\n const resolvedTopic = resolveTopic(topic, this.modelId, this.modelData);\n log.debug(`resolved subscription to ${resolvedTopic}`);\n const handler = handlerFactory({\n model: this,\n resolvedTopic,\n skipParse,\n modelData: this.modelData,\n subscription: subscriptions[topic],\n });\n this._registerSubscription(subscriptions[topic], resolvedTopic, handler);\n });\n }\n\n async online() {\n log.debug(`online model ${this.modelTypeName} with id ${this.modelId}`);\n this.registerSubscribers();\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.online?.(context);\n }\n\n async offline() {\n log.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`);\n this._subscriptions.forEach((sub) => {\n sub();\n });\n this._subscriptions = [];\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.offline?.(context);\n }\n\n accept(visitor: IKosVisitor<IKosModel>) {\n visitor.visit(this);\n }\n getChildren(): IKosModel[] {\n const decoratedChildren = this.getDecoratedChildren();\n const resolvedChildren = this.getResolvedChildren(decoratedChildren);\n const children = this.getAdditionalChildren();\n\n const uniqueChildren: IKosIdentifiable[] = Array.from(\n new Set([\n ...resolvedChildren,\n ...children,\n ...Array.from(this._companionModels.values()),\n ])\n ) as IKosIdentifiable[];\n\n return this.filterAndMapToModels(uniqueChildren);\n }\n\n clearCompanionModels() {\n this._companionModels.clear();\n }\n\n addCompanionModel(model: IKosModel<IKosDataModel>) {\n this._companionModels.set(model.modelTypeName, model);\n }\n\n getDecoratedChildren(): Record<string, any> {\n return this.modelData?.[ChildModels] || {};\n }\n\n getResolvedChildren(decoratedChildren: Record<string, any>): IKosDataModel[] {\n return Object.keys(decoratedChildren)\n .map((key) => resolveChild(this.modelData?.[key]))\n .filter((model) => !!model)\n .flat() as IKosDataModel[];\n }\n\n getAdditionalChildren(): IKosDataModel[] {\n return this.modelData?.getChildren?.() || [];\n }\n\n filterAndMapToModels(uniqueChildren: IKosIdentifiable[]): IKosModel[] {\n const filtered = uniqueChildren\n .map((child) => this.modelManager.getModelById(child.id || \"\"))\n .filter((model) => !!model) as IKosModel[];\n filtered.forEach((model) => {\n try {\n KosContextManager.setParentContext(model.modelId, this.modelId);\n } catch {\n log.error(\n `failed to set parent context for model ${model.modelId} with parent ${this.modelId}`\n );\n }\n });\n return filtered;\n }\n}\n","import { DataLoader, DataMapper, PropertyMapper } from \"../extension\";\nimport type {\n IKosDataModel,\n IKosDataModelBuilder,\n IKosDataModelCreator,\n IKosModel,\n} from \"../kosModel\";\n\nexport interface IKosSubscriptionSpecification {\n webSocket: boolean;\n handler: (payload: any, model: IKosModel) => void;\n}\n\nexport interface TroubleHandlerContext {\n title: string;\n subtitle: string;\n steps?: Record<string, { title: string; subtitle: string }>;\n canDismiss?: boolean;\n showTimeRemaining?: boolean;\n}\nexport interface TroubleHandler extends TroubleHandlerContext {\n type: string;\n context?: Record<string, TroubleHandlerContext>;\n}\n\nexport interface IKosModelRegistration {\n builder?: IKosDataModelBuilder<any, any>;\n create?: IKosDataModelCreator<any, any>;\n class?: new (...args) => IKosDataModel;\n\n singleton?: boolean;\n preload?: boolean;\n subscriptions?: Record<string, IKosSubscriptionSpecification>;\n}\n\nexport interface ExtensionRegistration {\n dataMapper?: Record<string, DataMapper | DataMapper[]>;\n propertyMapper?: Record<string, PropertyMapper>;\n contextLoader?: Record<string, DataLoader>;\n}\n\nexport type KosCompanionTypeFactory<T extends IKosDataModel = IKosDataModel> = (\n model: T,\n options: any\n) => string | undefined;\nexport type KosCompanionModelType<T extends IKosDataModel = IKosDataModel> =\n | string\n | KosCompanionTypeFactory<T>;\n\nexport const isKosCompanionTypeFactory = (\n obj: any\n): obj is KosCompanionTypeFactory => typeof obj === \"function\";\nexport interface IKosCompanionRegistration {\n type: KosCompanionModelType<any>;\n}\n\nexport type Preloaded =\n | string\n | { modelType: string; modelId: string; options?: any };\nexport interface IKosRegistry {\n alias?: string;\n models: Record<string, IKosModelRegistration>;\n companionModels?: Record<string, IKosCompanionRegistration[]>;\n troubleHandlers?: Record<string, TroubleHandler>;\n\n // eslint-disable-next-line no-use-before-define\n preloadModels: Preloaded[];\n\n extensions?: ExtensionRegistration;\n}\n","/* eslint-disable max-len */\n\nimport { observable } from \"mobx\";\nimport { ModelFactory, type BaseKosModelRegistrationBean } from \"../types\";\nimport { modelFactory } from \"../util\";\nimport { KosContextManager } from \"./context/kos-context-manager\";\nimport { KosDeletionManager } from \"./kos-deletion-manager\";\nimport {\n IKosDataModel,\n IKosDataModelBuilder,\n IKosModel,\n IKosVisitor,\n KosModel,\n} from \"./kosModel\";\nimport { KosModelEvents, KosModelState } from \"./lifecycle\";\nimport { KosLog } from \"./log\";\nimport { IKosModelManager } from \"./types/kos-model-manager-types\";\nimport {\n IKosRegistry,\n isKosCompanionTypeFactory,\n type KosCompanionModelType,\n} from \"./types/registration\";\n\nexport const MODEL_DELETION_DELAY = 10;\n\nconst log = KosLog.createLogger({ name: \"kos-model-manager\" });\nexport class KosModelManager implements IKosModelManager {\n private _modelsById: Map<string, IKosModel>;\n\n private _registry: IKosRegistry;\n\n private _usesCache: Map<string, string[]>; // modelId -> [modelId]\n\n private _isPreloaded = false;\n\n private _preloaded: IKosModel[];\n\n private _usedByCache: Map<string, string[]>; // modelId -> [modelId]\n\n private _toDelete: Map<string, IKosModel>;\n private constructor() {\n this._modelsById = observable.map(new Map<string, IKosModel>());\n this._registry = {\n models: {},\n preloadModels: [],\n };\n\n this._preloaded = [];\n this._usedByCache = new Map<string, string[]>(); // modelId -> [modelId]\n this._usesCache = new Map<string, string[]>(); // modelId -> [modelId]\n this._toDelete = new Map<string, IKosModel>();\n globalThis.kos = globalThis.kos || {};\n globalThis.kos.modelManager = this;\n }\n\n get registry() {\n return this._registry;\n }\n\n set registry(registry: IKosRegistry) {\n this._registry = registry;\n }\n\n get preloadedModels() {\n log.debug(\"preloading models\");\n\n if (this._isPreloaded) {\n log.error(\"returning cased preloaded models\");\n return this._preloaded;\n }\n this._preloaded = this._registry.preloadModels.map((modelKey) => {\n log.debug(`preloading ${modelKey}`);\n if (typeof modelKey === \"string\") {\n return this.createModelInstance(modelKey).model;\n } else {\n return this.createModelInstance(\n modelKey.modelType,\n modelKey.modelId,\n modelKey.options\n ).model;\n }\n });\n // this._isPreloaded = true;\n return this._preloaded;\n }\n\n get models() {\n return Array.from(this._modelsById.values());\n }\n\n removeModel(model: IKosModel): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this;\n log.debug(\n `Removing models: Currently ${that._modelsById.size} models cached`\n );\n const deleteVistor: IKosVisitor<IKosModel> = {\n visit(kosModel) {\n const children = kosModel.getChildren();\n children?.forEach((child) => {\n child.accept?.(this);\n });\n log.debug(\n `removing ${kosModel.modelTypeName} model ${kosModel.modelId} from model manager`\n );\n kosModel.offline?.();\n kosModel.clearCompanionModels();\n KosContextManager.deleteContext(kosModel.modelId);\n that._modelsById.delete(kosModel.modelId);\n that._toDelete.delete(kosModel.modelId);\n },\n };\n\n model.accept?.(deleteVistor);\n log.debug(\n `Models Removed: Currently ${that._modelsById.size} models cached`\n );\n }\n\n addModel<T extends IKosDataModel>(model: IKosModel<T>): IKosModel<T> {\n log.debug(\"adding model to kosModelManager\");\n const activeModel = this.getModelById(model.modelId) || model;\n this._modelsById.set(activeModel.modelId, activeModel);\n return activeModel as IKosModel<T>;\n }\n\n hasModel(modelId?: string): boolean {\n return !!modelId && !!this.getModelById(modelId);\n }\n\n getModelById<T extends IKosDataModel>(id: string): IKosModel<T> {\n // this.restoreModelFromDeleteCache(id);\n if (this._toDelete.has(id)) {\n return undefined as unknown as KosModel<T>;\n }\n const model = this._modelsById.get(id) as IKosModel<T>;\n return model;\n }\n\n getModelsByType<T extends IKosDataModel>(\n typeId: string,\n modelFilter: (model: T) => boolean\n ) {\n const result: T[] = Array.from(this._modelsById.values())\n .filter((model) => model.modelTypeName === typeId)\n .filter((model) => !this._toDelete.get(model.modelId))\n .filter((model) =>\n modelFilter ? modelFilter(model.modelData as T) : true\n )\n .map((model) => model.modelData as T);\n\n return result;\n }\n\n private getModelTypeRegistry(typeId: string) {\n const modelRegistry = this._registry?.models?.[typeId];\n if (!modelRegistry) {\n throw Error(`No registration defined for model type ${typeId}}`);\n }\n return modelRegistry;\n }\n\n getModelSubscriptions(typeId: string) {\n return this.getModelTypeRegistry(typeId)?.subscriptions || {};\n }\n\n getDataModelBuilder<D = unknown, M extends IKosDataModel = IKosDataModel>(\n typeId: string\n ): IKosDataModelBuilder<D, M> {\n return this.getModelTypeRegistry(typeId)?.builder as IKosDataModelBuilder<\n D,\n M\n >;\n }\n\n getModelFactory<T extends IKosDataModel>(modelType: string) {\n return modelFactory<T>(modelType) as ModelFactory<T>;\n }\n\n private restoreModelFromDeleteCache(modelId?: string) {\n if (modelId && this._toDelete.has(modelId)) {\n const model = this._toDelete.get(modelId);\n this._toDelete.delete(modelId);\n this._modelsById.set(modelId, model!);\n }\n }\n addDependency(modelId: string, dependencyId: string) {\n KosDeletionManager.cancelDeletion(dependencyId);\n this.restoreModelFromDeleteCache(dependencyId);\n if (!this._usedByCache) {\n this._usedByCache = new Map();\n }\n\n if (!this._usesCache) {\n this._usesCache = new Map();\n }\n const usedBy = this._usedByCache.get(dependencyId) || [];\n if (!usedBy.includes(modelId)) {\n usedBy.push(modelId);\n this._usedByCache.set(dependencyId, usedBy);\n }\n\n const uses = this._usesCache.get(modelId) || [];\n if (!uses.includes(dependencyId)) {\n uses.push(dependencyId);\n this._usesCache.set(modelId, uses);\n }\n }\n\n removeDependency(modelId: string, dependencyId: string) {\n if (!this._usedByCache) {\n this._usedByCache = new Map();\n }\n if (!this._usesCache) {\n this._usesCache = new Map();\n }\n const usedBy = this._usedByCache.get(dependencyId) || [];\n const index = usedBy.indexOf(modelId);\n if (index > -1) {\n usedBy.splice(index, 1);\n this._usedByCache.set(dependencyId, usedBy);\n }\n\n const uses = this._usesCache.get(modelId) || [];\n const usesIndex = uses.indexOf(dependencyId);\n if (usesIndex > -1) {\n uses.splice(usesIndex, 1);\n this._usesCache.set(modelId, uses);\n }\n }\n\n async reloadModel(model: IKosDataModel) {\n if (model.id) {\n log.info(`fetching model ${model.id} to reload`);\n const kosModel = this.getModelById(model.id);\n if (kosModel) {\n log.info(`reloading model ${model.id}`);\n\n await kosModel.transition(\n KosModelEvents.RESET,\n KosModelState.RESETTING\n );\n } else {\n log.warn(`${model.id} not found in KOS Model Manager`);\n }\n }\n }\n\n private canDestroyModel(modelId: string) {\n const usedBy = this._usedByCache.get(modelId);\n if (usedBy && usedBy.length > 0) {\n log.info(\n `model ${modelId} is used by ${usedBy.join(\n \", \"\n )}. Returning without destroying.`\n );\n return false;\n }\n return true;\n }\n /**\n * Initiates the destruction of a model. If the model is not used by any other models, it will be destroyed immediately.\n * Otherwise, it will be added to a deletion queue and destroyed after a delay.\n * @param model\n * @returns\n * @memberof KosModelManager\n * **/\n async initiateDestroyModel(model: IKosDataModel) {\n if (!model.id) {\n throw new Error(\"Model ID is required\");\n }\n const modelId = model.id;\n if (this.canDestroyModel(modelId)) {\n log.info(`fetching model ${modelId} to add to deletion queue`);\n const kosModel = this.getModelById(model.id);\n if (kosModel) {\n this._modelsById.delete(modelId);\n this._toDelete.set(modelId, kosModel);\n KosDeletionManager.addToDeletionQueue(\n model.id,\n setTimeout(async () => {\n this.destroyModel(kosModel);\n }, MODEL_DELETION_DELAY)\n );\n }\n }\n }\n\n registerCompanionModel(\n typeId: string,\n companionRegistration: KosCompanionModelType<any>\n ) {\n if (!this.registry.companionModels) {\n this.registry.companionModels = {};\n }\n if (!this.registry.companionModels[typeId]) {\n this.registry.companionModels[typeId] = [];\n }\n\n const exists = !!this.registry.companionModels[typeId].find(\n (c) => c.type === companionRegistration\n );\n\n if (!exists) {\n this.registry.companionModels[typeId].push({\n type: companionRegistration,\n });\n }\n }\n\n registerModel<T extends BaseKosModelRegistrationBean<any, any>>(\n modelRegistration: T\n ) {\n const typeId = modelRegistration.type;\n if (!this.registry.models) {\n this.registry.models = {};\n }\n\n if (!this.registry.models[typeId]) {\n log.info(\n `Model with type ${typeId} doesn't exist. Adding new registration`\n );\n this.registry.models = {\n ...this.registry.models,\n ...modelRegistration.registration,\n };\n }\n }\n /**\n * Destroys a model immediately. This should only be called by the deletion queue.\n * @param model\n * @returns\n * @memberof KosModelManager\n * **/\n async destroyModel(model: IKosModel) {\n if (model?.modelId) {\n const modelId = model.modelId;\n if (this.canDestroyModel(modelId)) {\n if (model) {\n log.info(`destroying model ${modelId}`);\n await model.unload?.();\n this.removeModel(model);\n } else {\n log.warn(`${modelId} not found in KOS Model Manager`);\n }\n }\n }\n }\n createModelInstance<\n DataDef extends IKosDataModel,\n Options extends Record<string, any> = {}\n >(typeId: string, id?: string, options?: Options) {\n log.debug(\n `retrieving new model instance of type ${typeId} ${id ? id : \"\"}`\n );\n try {\n const modelRegistry = this.getModelTypeRegistry(typeId);\n const modelCreator = modelRegistry.create;\n const ModelClass = modelRegistry.class!;\n const modelId = modelRegistry.singleton ? typeId : id;\n\n // restore the model if it was in the delete cache\n this.restoreModelFromDeleteCache(modelId);\n\n if (!this.hasModel(modelId)) {\n log.debug(`model ${modelId} not found in cache...creating`);\n const dataInstance = (\n modelCreator\n ? modelCreator({ modelTypeId: typeId, id: modelId, options })\n : new ModelClass(modelId, options || {})\n ) as DataDef;\n\n // check if in cache\n // eslint-disable-next-line max-len\n const model = new KosModel<DataDef>({\n modelTypeName: typeId,\n id: modelId,\n modelData: dataInstance,\n modelManager: this,\n });\n this._modelsById.set(modelId!, model);\n\n if (this.registry.companionModels?.[typeId]) {\n const companionModels = this.registry.companionModels[typeId];\n companionModels.forEach((companionSpec) => {\n let companionModelType = companionSpec.type;\n if (isKosCompanionTypeFactory(companionModelType)) {\n log.debug(`using companionModelType factory for ${typeId}`);\n const compType = companionModelType(model.modelData, options);\n if (!compType) {\n // factory returns undefined, skip\n return;\n }\n companionModelType = compType;\n log.debug(`factory resolved to type ${companionModelType}`);\n }\n const companionId = `${companionModelType}-${modelId}`;\n const companionModel = this.createModelInstance(\n companionModelType,\n companionId,\n {\n data: options,\n companionParent: model.modelData,\n kosParentId: modelId,\n }\n );\n model.addCompanionModel(companionModel.model);\n });\n }\n } else {\n log.debug(`model ${modelId} found in cache`);\n }\n\n const activeModel = this.getModelById<DataDef>(modelId!);\n log.debug(`returning model ${modelId} from createModelInstance`);\n return {\n model: activeModel,\n data: activeModel.modelData,\n };\n } catch (e) {\n log.error(`Error creating model instance: ${e}`);\n throw e;\n }\n }\n\n public static create(registry: IKosRegistry, reset?: boolean) {\n const instance = this.getInstance(reset);\n instance.registry = registry;\n return instance;\n }\n\n public static getInstance(reset?: boolean) {\n if (!globalThis.kos?.modelManager || reset) {\n log.debug(`Creating new instance of KosModelManager`);\n new this();\n }\n return globalThis.kos?.modelManager;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { KosContext } from \"../context\";\nimport { ExtensionManager } from \"../extension\";\n\nexport interface ExtensionPointOptions {\n extension: string;\n}\nexport interface InitializeContextExtensionPointOptions\n extends ExtensionPointOptions {\n context?: KosContext;\n}\n\nexport interface ContextDataExtensionPoint<D extends object, T extends object>\n extends ExtensionPointOptions {\n data: D;\n contextData: T;\n}\n/**\n * Executes an extension point and adds the value to the specified context\n * @param options The options for the extension point\n * @param options.context The kOS model context to add the value to. If not specified, the value will not be added to any context.\n * @param options.extension The extension point to execute\n *\n * @returns The value returned from the extension point\n * */\nexport const executeLoaderExtension = async ({\n context,\n extension,\n}: InitializeContextExtensionPointOptions) => {\n const contextData = await ExtensionManager.loader.executeLoader(\n extension,\n {}\n );\n\n context?.set(extension, contextData);\n\n return contextData;\n};\n\n/**\n * Executes a registered data transformation extension point. This extension point is used to transform data from the backend into a format that is\n * usable by the application.\n *\n * @param options The options for the extension point\n * @param options.contextData The context data to pass to the extension point\n * @param options.data The data to transform\n * @param options.extension The extension point to execute\n * @returns The transformed data\n * */\nexport const executeDataMapperExtension = async <\n D extends object = any,\n R extends object = any,\n T extends object = any\n>({\n extension,\n contextData,\n data,\n}: ContextDataExtensionPoint<D, T>) => {\n const transformed = await ExtensionManager.dataMapper.executeMapper<D, R>(\n extension,\n data,\n contextData\n );\n\n return transformed;\n};\n\n/**\n * Executes a registered data transformation extension point. This extension point is used to map a single property value and\n * is typically used to map a property value from the backend into a format that is usable by the application.\n *\n *\n * @param options The options for the extension point\n * @param options.contextData The context data to pass to the extension point\n * @param options.data The data to transform\n * @param options.extension The extension point to execute\n * @returns The transformed data\n * */\nexport const executePropertyMapperExtension = async <\n D extends object = any,\n T extends object = any\n>({\n extension,\n contextData,\n data,\n}: ContextDataExtensionPoint<D, T>) => {\n const value = await ExtensionManager.propertyMapper.executeMapper(\n extension,\n data,\n contextData\n );\n\n return value;\n};\n","export const PLUGIN_EXTENSION_NAME = \"Extensions\";\n\n/**\n * Represents the type for the extensions.\n */\nexport interface PluginExtensionsType {\n [k: string]: {\n [k: string]: {\n component?: string;\n remote?: string;\n };\n };\n}\nexport class PluginExtensionManager {\n private extensions: PluginExtensionsType;\n\n constructor() {\n this.extensions = {};\n }\n register(extensionPoint: string, name: string, component: string) {\n this.extensions[extensionPoint] = {} || this.extensions[extensionPoint];\n this.extensions[extensionPoint][name] = { component };\n }\n\n get(extension: string, id: string) {\n if (!this.extensions[extension]) {\n throw new Error(`Extension point ${extension} not found`);\n }\n return this.extensions[extension][id];\n }\n\n get allExtensions() {\n return this.extensions;\n }\n}\n","import log from \"loglevel\";\nimport { runInAction } from \"mobx\";\nimport {\n action,\n createMachine,\n immediate,\n interpret,\n invoke,\n state,\n transition,\n} from \"robot3\";\nimport type { IKosCoreManager } from \"../kosCore\";\n\nexport enum KosCoreState {\n CREATING = `creating`,\n CREATED = `created`,\n INITIALIZING = `initializing`,\n INITIALIZED = `initialized`,\n LOADING = `loading`,\n LOADED = `loaded`,\n ONLINE = `online`,\n READYING = `readying`,\n READY = `ready`,\n OFFLINE = `offline`,\n UNLOADING = `unloading`,\n UNLOADED = `unloaded`,\n RELOADING = `reloading`,\n}\n\nexport enum KosCoreEvents {\n CREATE = `create`,\n INITIALIZE = `init`,\n READY = `ready`,\n GO_ONLINE = `go_online`,\n GO_OFFLINE = `go_offline`,\n UNLOAD = `unload`,\n RELOAD = `reload`,\n}\n\nexport interface KosOn {\n [k: string]: string;\n}\n\nexport interface KosInvoke<Context> {\n id: string;\n src: (context: Context) => Promise<any>;\n onDone: {\n target: string;\n };\n}\nexport interface KosLifecycleState {\n on: KosOn;\n}\nexport interface KosLifecycleStateContainer<Context> {\n [k: string]: {\n initial?: string;\n states?: KosLifecycleStateContainer<Context>;\n on?: KosOn;\n invoke?: KosInvoke<Context>;\n };\n}\n\nexport interface KosLifecycle<Context = any> {\n id: string;\n initial: string;\n states: KosLifecycleStateContainer<Context>;\n context: Context;\n}\n\nexport const coreFsm = (core: IKosCoreManager) => {\n const onlineMachine = createMachine(KosCoreState.OFFLINE, {\n [KosCoreState.ONLINE]: state(\n transition(\n KosCoreEvents.GO_OFFLINE,\n KosCoreState.OFFLINE,\n action(() => {\n core.offline!();\n runInAction(() => {\n core.isOnline = false;\n });\n })\n )\n ),\n [KosCoreState.OFFLINE]: state(\n transition(\n KosCoreEvents.GO_ONLINE,\n KosCoreState.ONLINE,\n action(() => {\n core.online!();\n runInAction(() => {\n core.isOnline = true;\n });\n })\n )\n ),\n });\n const online = interpret(onlineMachine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n const machine = createMachine({\n [KosCoreState.CREATING]: state(\n transition(KosCoreEvents.CREATE, KosCoreState.CREATED)\n ),\n [KosCoreState.CREATED]: state(immediate(KosCoreState.INITIALIZING)),\n [KosCoreState.INITIALIZING]: invoke(\n () => core.init!(),\n transition(`done`, KosCoreState.INITIALIZED)\n ),\n [KosCoreState.INITIALIZED]: state(immediate(KosCoreState.LOADING)),\n [KosCoreState.LOADING]: invoke(\n () => core.load!(),\n transition(`done`, KosCoreState.LOADED)\n ),\n [KosCoreState.LOADED]: state(\n immediate(KosCoreState.READYING),\n transition(KosCoreEvents.UNLOAD, KosCoreState.UNLOADING)\n ),\n\n [KosCoreState.READYING]: invoke(\n () => core.ready!(),\n transition(\n `done`,\n KosCoreState.READY,\n action(() => {\n runInAction(() => {\n core.status = KosCoreState.READY;\n });\n })\n )\n ),\n [KosCoreState.RELOADING]: invoke(\n () => core.reload!(),\n transition(`done`, KosCoreState.LOADING)\n ),\n [KosCoreState.READY]: state(\n transition(KosCoreEvents.RELOAD, KosCoreState.RELOADING),\n transition(\n KosCoreEvents.UNLOAD,\n KosCoreState.UNLOADED,\n action(core.unload.bind(core))\n ),\n transition(\n KosCoreEvents.GO_ONLINE,\n KosCoreState.READY,\n action(() => {\n online.send(KosCoreEvents.GO_ONLINE);\n })\n ),\n transition(\n KosCoreEvents.GO_OFFLINE,\n KosCoreState.READY,\n action(() => {\n online.send(KosCoreEvents.GO_OFFLINE);\n })\n )\n ),\n\n [KosCoreState.UNLOADED]: state(),\n });\n\n const service = interpret(machine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n return { service, online };\n};\n","import { KosCore } from \"../core/kosCore\";\nimport { IKosDataModel } from \"../core/kosModel\";\n/**\n * Asynchronously waits for a Kos Data Model to become ready for use.\n *\n * This utility function is used to ensure that a Kos Data Model is fully\n * loaded and ready to be accessed before performing any operations on it.\n *\n * @category Utility\n * @name whenReady\n * @version 1.0.0\n * @param dataModel - The Kos Data Model to wait for readiness.\n * @throws {Error} If the specified data model is not found or if it has no ID.\n * @returns A promise that resolves to the same data model when it becomes ready.\n *\n * @example\n * // Wait for the 'dataModel' to become ready before using it.\n * const dataModel = await whenReady(dataModel);\n */\nexport const whenReady = async (dataModel: IKosDataModel) => {\n if (dataModel.id) {\n // Retrieve the model associated with the provided ID.\n const model = KosCore.getInstance().modelManager.getModelById(dataModel.id);\n\n // If the model is not found, throw an error.\n if (!model) {\n throw new Error(`Model with ID ${dataModel.id} not found`);\n }\n\n // Wait for the model to become ready before resolving the promise.\n await model?.whenReady();\n } else {\n // If the data model has no ID, throw an error.\n throw new Error(\"Data model must have a valid ID\");\n }\n\n // Return the same data model once it becomes ready.\n return dataModel;\n};\n","import { KosCore } from \"../core/kosCore\";\nimport { IKosDataModel, type IKosModel } from \"../core/kosModel\";\nimport { KosModelEvents, KosModelState } from \"../core/lifecycle\";\nimport { KosLog } from \"../core/log\";\nimport { whenReady } from \"./when-ready\";\n\n/**\n * Asynchronously destroys a kOS data model.\n *\n * @async\n * @param model - The kOS data model to destroy.\n * @throws An error if the model cannot be destroyed.\n */\nexport const destroyKosModel = async (model: IKosDataModel) => {\n await KosCore.getInstance().whenReady();\n await KosCore.getInstance().modelManager.initiateDestroyModel(model);\n};\n\nexport const unloadKosModel = async (dataModel: IKosDataModel) => {\n await KosCore.getInstance().whenReady();\n if (!dataModel.id) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(dataModel.id);\n if (model) {\n await model.transition(KosModelEvents.UNLOAD, KosModelState.UNLOADED);\n }\n};\n/**\n * Asynchronously resets a kOS data model.\n *\n * @async\n * @param model - The kOS data model to reset.\n * @throws An error if the model cannot be reset.\n */\nexport const resetKosModel = async (model: IKosDataModel) => {\n await KosCore.getInstance().whenReady();\n\n await KosCore.getInstance().modelManager.reloadModel(model);\n KosLog.debug(\n `reload model initiated for model ${\n model.id\n }, model ready: ${isKosModelReady(model)} - ${Date.now()} `\n );\n await whenReady(model);\n KosLog.debug(\n `reload model complete for model ${\n model.id\n }, model ready: ${isKosModelReady(model)} - ${Date.now()} `\n );\n};\n\n/**\n * Asynchronously retrieves the type of a kOS data model.\n *\n * @async\n * @param modelId - The ID of the kOS data model.\n * @returns The type of the kOS data model.\n * @throws An error if the model ID is not provided or the model cannot be found.\n */\nexport const getKosModelType = async (modelId: string) => {\n await KosCore.getInstance().whenReady();\n if (!modelId) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n\n return model?.modelTypeName;\n};\n\n/**\n * Asynchronously retrieves a kOS data model and its type.\n *\n * @async\n * @param modelId - The ID of the kOS data model.\n * @returns An object containing the kOS data model and its type.\n * @throws An error if the model ID is not provided or the model cannot be found.\n */\nexport const getKosModel = async <T extends IKosDataModel = IKosDataModel>(\n modelId: string\n) => {\n await KosCore.getInstance().whenReady();\n if (!modelId) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n\n return { model: model?.modelData as T, type: model?.modelTypeName };\n};\n\n/**\n * Synchronously retrieves a kOS data model and its type.\n *\n * @param modelId - The ID of the kOS data model.\n * @returns An object containing the kOS data model and its type.\n * @throws An error if the model ID is not provided or the model cannot be found.\n */\nexport const getKosModelSync = <T extends IKosDataModel = IKosDataModel>(\n modelId: string\n) => {\n if (!modelId) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n\n return { model: model?.modelData as T, type: model?.modelTypeName };\n};\n\n/**\n * Finds and filters kOS data models of a specific type based on a predicate.\n *\n * @param modelType - The type of the kOS data models to search for.\n * @param predicate - An object representing filter conditions.\n * @returns An array of filtered kOS data models.\n * @throws An error if the model type is not provided.\n */\nexport const findModels = <T extends IKosDataModel>(\n modelType: string,\n predicate: { [k: string]: any }\n) => {\n if (!modelType) {\n throw new Error(\"Model type is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelsByType(modelType);\n const filtered = model.filter((m) =>\n Object.keys(predicate).every((key) => m[key] === predicate[key])\n );\n return filtered as T[];\n};\n\n/**\n * Finds and retrieves the first kOS data model of a specific type based on a predicate.\n *\n * @param modelType - The type of the kOS data models to search for.\n * @param predicate - An object representing filter conditions.\n * @returns The first matching kOS data model, or undefined if none is found.\n * @throws An error if the model type is not provided.\n */\nexport const findModel = <T extends IKosDataModel>(\n modelType: string,\n predicate: { [k: string]: any }\n) => findModels<T>(modelType, predicate)[0];\n\n/**\n * Retrieves a companion kOS data model of a specific type associated with a given model.\n *\n * @param model - The kOS data model for which to retrieve a companion model.\n * @param type - The type of the companion model.\n * @returns The companion kOS data model of the specified type.\n * @throws An error if the model ID is not provided, the model cannot be found, or the companion model does not exist.\n */\nexport const getKosCompanionModel = <T extends IKosDataModel>(\n model: IKosDataModel,\n type: string\n) => {\n if (!model.id) {\n throw new Error(\"Model ID is required\");\n }\n const kosModel = KosCore.getInstance().modelManager.getModelById(model.id);\n if (!kosModel) {\n throw new Error(\"Model not found\");\n }\n\n const companionModel = kosModel.companionModels.get(type);\n return companionModel?.modelData as T;\n};\n\n/**\n * Retrieves all companion models for a given model.\n *\n * @param model - The kOS data model for which to retrieve a companion model.\n * @returns The list of companion kOS data models\n * @throws An error if the model ID is not provided, the model cannot be found, or the companion model does not exist.\n */\nexport const getAllKosCompanionModels = (model: IKosDataModel) => {\n if (!model.id) {\n throw new Error(\"Model ID is required\");\n }\n const kosModel = KosCore.getInstance().modelManager.getModelById(model.id);\n if (!kosModel) {\n throw new Error(\"Model not found\");\n }\n\n const companionModels = Array.from(kosModel.companionModels.values()).map(\n (m) => m.modelData\n );\n\n return companionModels;\n};\nexport const resolveKosCompanion = <T extends IKosDataModel>(\n modelId: string,\n resolver: (model: T) => boolean\n): IKosModel | undefined => {\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n if (!model) {\n KosLog.info(`Model not found for id ${modelId}`);\n return undefined;\n }\n const companionModel = Array.from(model.companionModels.values()).find((m) =>\n resolver(m.modelData as T)\n );\n\n return companionModel;\n};\n\n/**\n * Checks if an object is an instance of a specific kOS data model type.\n *\n * @param type - The type of the kOS data model to check against.\n * @returns A type guard function that checks if an object is an instance of the specified kOS data model type.\n */\nexport const isKosModel =\n <T extends IKosDataModel>(type: string) =>\n (model: any): model is T =>\n Object.getPrototypeOf(model).modelTypeId === type;\n\nexport const isKosModelReady = (model: IKosDataModel) => {\n const kosModel = KosCore.getInstance().modelManager.getModelById(model.id);\n if (!kosModel) {\n throw new Error(\"Model not found\");\n }\n return kosModel.isReady();\n};\n","import { ModelFactory } from \"../types\";\nimport { KosContextManager } from \"./context/kos-context-manager\";\nimport { KosCore } from \"./kosCore\";\nimport { IKosDataModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-factory\" });\nexport const KosModelFactory = {\n byModelType: <T extends IKosDataModel, O extends {} = any>(\n modelType: string\n ) =>\n KosCore.getInstance().modelManager.getModelFactory<T>(\n modelType\n ) as ModelFactory<T, O>,\n getModelInstance: <T extends IKosDataModel, O extends {} = any>(\n id: string,\n modelType: string,\n options?: O\n ) => {\n const factory = KosModelFactory.byModelType<T, O>(modelType);\n if (!factory) {\n log.error(\n `No registered factory found for model type ${modelType}. Please register a factory for this model type. `\n );\n throw Error(`No factory found for model type ${modelType}`);\n }\n\n return factory.build(id, options);\n },\n};\n\nexport const Kos = {\n Factory: {\n create:\n <T extends IKosDataModel, O extends {} = any>(modelType: string) =>\n (id: string) =>\n (options?: O, parentId?: string) => {\n if (parentId) {\n KosContextManager.setParentContext(id, parentId);\n }\n const model = KosModelFactory.getModelInstance<T, O>(\n id,\n modelType,\n options\n );\n\n return model;\n },\n },\n\n Singleton: {\n create:\n <T extends IKosDataModel, O extends {} = any>(modelType: string) =>\n (options?: O, parentId?: string) => {\n if (parentId) {\n KosContextManager.setParentContext(modelType, parentId);\n }\n const model = KosModelFactory.getModelInstance<T, O>(\n modelType,\n modelType,\n options\n );\n\n return model;\n },\n },\n\n Model: {\n instance:\n <T extends IKosDataModel, O extends {} = any>(modelType: string) =>\n (id: string) =>\n KosModelFactory.getModelInstance<T, O>(id, modelType),\n },\n};\n","import type { BaseKosModelRegistrationBean } from \"../../types/model\";\nimport { KosCore } from \"../kosCore\";\nimport type {\n IKosModelRegistration,\n IKosRegistry,\n KosCompanionModelType,\n} from \"../types/registration\";\nimport {\n isKosModelRegistration,\n type KosModelRegistrationType,\n} from \"./model-registration\";\n\ndeclare global {\n interface Window {\n KosRegistry: {\n coreModels: Map<string, IKosModelRegistration>;\n preloadModels: string[];\n companionModels: Map<string, KosCompanionModelType<any>[]>;\n models: Map<string, BaseKosModelRegistrationBean<any, any>>;\n };\n }\n}\nwindow.KosRegistry =\n (window.KosRegistry as any) ||\n ({\n coreModels: new Map<string, IKosModelRegistration>(),\n preloadModels: [],\n companionModels: new Map<string, KosCompanionModelType<any>>(),\n models: new Map<string, BaseKosModelRegistrationBean<any, any>>(),\n } as any);\nconst coreModels = window.KosRegistry.coreModels;\nconst preloadModels: string[] = window.KosRegistry.preloadModels;\nconst companionModels = window.KosRegistry.companionModels;\nconst models = window.KosRegistry.models;\n\nexport interface RegistrationResult<R> {\n preload: (type: string) => RegistrationResult<R>;\n model: (\n registration:\n | BaseKosModelRegistrationBean<any, any>\n | KosModelRegistrationType<any, any>,\n preload?: boolean\n ) => RegistrationResult<R>;\n companion: (\n parentType: string,\n companion: KosCompanionModelType<any>\n ) => RegistrationResult<R>;\n legacy: <T extends IKosModelRegistration>(\n type: string,\n registration: T\n ) => RegistrationResult<R>;\n root: R;\n}\nexport const RegistrationManager = {\n model: {\n registerLegacyModel:\n <R>(root: R) =>\n <T extends IKosModelRegistration>(\n type: string,\n registration: T\n ): RegistrationResult<R> => {\n coreModels.set(type, registration);\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n preloadModel:\n <R>(root: R) =>\n (type: string): RegistrationResult<R> => {\n if (!preloadModels.includes(type)) {\n preloadModels.push(type);\n }\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n register:\n <R>(root: R) =>\n <\n T extends\n | BaseKosModelRegistrationBean<any, any>\n | KosModelRegistrationType<any, any>\n >(\n registration: T,\n preload?: boolean\n ): RegistrationResult<R> => {\n const register: BaseKosModelRegistrationBean<any, any> =\n isKosModelRegistration(registration)\n ? registration.registration()\n : registration;\n models.set(register.type, register as any);\n\n if (isKosModelRegistration(registration)) {\n registration.relatedModels.forEach((model) =>\n models.set(model.type, model.registration() as any)\n );\n }\n\n if (KosCore.getInstance().isReady) {\n if (\n !KosCore.getInstance().modelManager.registry.models[register.type]\n ) {\n console.info(\n `Model with type ${register.type} doesn't exist. Adding new registration`\n );\n KosCore.getInstance().modelManager.registry.models[register.type] =\n register.registration[register.type];\n if (isKosModelRegistration(registration)) {\n registration.relatedModels.forEach(\n (model) =>\n (KosCore.getInstance().modelManager.registry.models[\n model.type\n ] = model.registration().registration)\n );\n }\n }\n }\n if (preload) {\n RegistrationManager.model.preloadModel(root)(register.type);\n }\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n get: (type: string) => models.get(type),\n getAll: () => Array.from(models.entries()),\n getPreloadModels: () => preloadModels,\n getLegacyModels: () =>\n Array.from(coreModels.entries()).reduce((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {} as IKosRegistry[\"models\"]),\n },\n companion: {\n register:\n <R>(root: R) =>\n (\n parentType: string,\n companion: KosCompanionModelType<any>\n ): RegistrationResult<R> => {\n const companions = companionModels.get(parentType) || [];\n companions.push(companion);\n companionModels.set(parentType, companions);\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n getAll: () => Array.from(companionModels.entries()),\n },\n};\n\nexport const registerLegacyModel =\n RegistrationManager.model.registerLegacyModel;\nexport const registerKosModel = RegistrationManager.model.register;\nexport const registerCompanionModel = RegistrationManager.companion.register;\nexport const preloadKosModel = RegistrationManager.model.preloadModel;\n","import type { BaseKosModelRegistrationBean } from \"../../types/model\";\nimport { isKosModel } from \"../../util/kos-model-utils\";\nimport { Kos } from \"../kos-model-factory\";\nimport type {\n IKosDataModel,\n KosCreationContext,\n UpdateAware,\n} from \"../kosModel\";\nimport type { KosModelRegistrationFactory } from \"./base-kos-model-registration\";\nimport { RegistrationManager } from \"./registration-manager\";\nimport type { SingletonKosModelRegistrationFactory } from \"./singleton-kos-model-registration-factory\";\n\nexport const isUpdateable = (model: any): model is UpdateAware =>\n typeof model.updateModel === \"function\";\ninterface ModelRegistration<\n B extends boolean,\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n singleton: boolean;\n class: new (modelId: string, options: O, context: KosCreationContext) => T;\n type: string;\n factory: FactoryType<B, T, O>;\n}\n\ntype FactoryType<\n B extends boolean,\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = B extends true\n ? ReturnType<typeof Kos.Singleton.create<T, O>>\n : ReturnType<typeof Kos.Factory.create<T, O>>;\n\ntype KosOptionsFunction<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = (options: O) => { build: () => T };\nexport interface KosInstance<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n get: () => T;\n options: KosOptionsFunction<T, O>;\n forceUpdate: {\n options: KosOptionsFunction<T, O>;\n };\n}\n\nexport type KosModelRegistrationType<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> =\n | KosModelRegistrationFactory<T, O>\n | SingletonKosModelRegistrationFactory<T, O>;\n\nexport const isKosModelRegistration = (\n item: any\n): item is KosModelRegistrationType<any, any> =>\n item.registration !== undefined && typeof item.registration === \"function\";\nexport abstract class KosBaseModelRegistration<\n B extends boolean,\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n singleton: boolean;\n type: string;\n class: new (modelId: string, options: O, context: KosCreationContext) => T;\n guard: ReturnType<typeof isKosModel<T>>;\n factory: FactoryType<B, T, O>;\n relatedModels: KosModelRegistrationType<any, any>[] = [];\n constructor(props: ModelRegistration<B, T, O>) {\n this.singleton = props.singleton;\n this.guard = isKosModel(props.type);\n this.type = props.type;\n this.factory = props.factory;\n this.class = props.class;\n }\n\n addRelatedModel(model: KosModelRegistrationType<any, any>) {\n this.relatedModels.push(model);\n }\n\n registerRelatedModels() {\n this.relatedModels.forEach((model) => model.register());\n }\n\n abstract registration(): BaseKosModelRegistrationBean<T, O>;\n\n register() {\n RegistrationManager.model.register({})(this.registration());\n this.registerRelatedModels();\n }\n\n abstract instance(id?: string): KosInstance<T, O>;\n}\n\nexport type KosModelRegistrationProps<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = Omit<ModelRegistration<false, T, O>, \"singleton\" | \"factory\">;\n","import type { BaseKosModelRegistrationBean } from \"../../types\";\nimport { getKosModelSync } from \"../../util/kos-model-utils\";\nimport { Kos } from \"../kos-model-factory\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport {\n KosBaseModelRegistration,\n isUpdateable,\n type KosInstance,\n type KosModelRegistrationProps,\n} from \"./model-registration\";\n\nexport class KosModelRegistrationFactory<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> extends KosBaseModelRegistration<false, T, O> {\n constructor(props: KosModelRegistrationProps<T, O>) {\n super({\n ...props,\n singleton: false,\n factory: Kos.Factory.create<T, O>(props.type),\n });\n }\n\n instance(id: string): KosInstance<T, O> {\n const optionsFactory = this.factory(id);\n return {\n get: () => {\n const model = getKosModelSync(id);\n if (!model) {\n throw new Error(\"Model not found with id \" + id);\n }\n if (this.guard(model)) {\n return model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n forceUpdate: {\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n if (isUpdateable(model)) {\n model.updateModel(options);\n } else {\n throw new Error(\n `Model ${this.type} is not updateable. Please implement UpdateAware interface`\n );\n }\n\n return model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n };\n },\n },\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n return model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n };\n },\n };\n }\n registration(): BaseKosModelRegistrationBean<T, O> {\n return {\n type: this.type,\n predicate: this.guard,\n registration: {\n [this.type]: {\n class: this.class,\n singleton: false,\n },\n },\n\n factory: this.factory,\n };\n }\n}\n","import type { BaseKosModelRegistrationBean } from \"../../types\";\nimport { getKosModelSync } from \"../../util/kos-model-utils\";\nimport { Kos } from \"../kos-model-factory\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport {\n KosBaseModelRegistration,\n isUpdateable,\n type KosInstance,\n type KosModelRegistrationProps,\n} from \"./model-registration\";\n\nexport class SingletonKosModelRegistrationFactory<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> extends KosBaseModelRegistration<true, T, O> {\n constructor(props: KosModelRegistrationProps<T, O>) {\n super({\n ...props,\n singleton: true,\n factory: Kos.Singleton.create<T, O>(props.type),\n });\n }\n\n instance(): KosInstance<T, O> {\n const optionsFactory = this.factory;\n const result = {\n get: () => {\n const model = getKosModelSync(this.type);\n if (!model) {\n throw new Error(\"Model not found with id \" + this.type);\n }\n if (this.guard(model)) {\n return model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n forceUpdate: {\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n if (isUpdateable(model)) {\n model.updateModel(options);\n } else {\n throw new Error(\n `Model ${this.type} is not updateable. Please implement UpdateAware interface`\n );\n }\n\n return model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n };\n },\n },\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n return model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n };\n },\n };\n return result;\n }\n registration(): BaseKosModelRegistrationBean<T, O> {\n return {\n type: this.type,\n predicate: this.guard,\n registration: {\n [this.type]: {\n class: this.class,\n singleton: true,\n },\n },\n\n factory: this.factory,\n };\n }\n}\n","import { makeAutoObservable, when } from \"mobx\";\nimport { KosModelManager } from \"./kosModelManager\";\nimport {\n IKosServiceTransport,\n WebSocketEvents,\n WebSocketTransport,\n} from \"./transport/webSocketTransport\";\nimport { IKosRegistry } from \"./types/registration\";\n\nimport { runInAction as kosAction } from \"mobx\";\nimport { EventBus } from \"../../common\";\nimport { getQueryParams } from \"../util/get-query-params\";\nimport \"../util/kos-config-init\";\nimport { ExtensionManager } from \"./extension\";\nimport { IKosModel, ReloadAware, UnloadAware } from \"./kosModel\";\nimport {\n KosCoreEvents,\n KosCoreState,\n coreFsm,\n} from \"./lifecycle/kosCoreLifecycle\";\nimport { KosLog } from \"./log\";\nimport { RegistrationManager } from \"./registration\";\nimport { IKosModelManager } from \"./types/kos-model-manager-types\";\n\nconst log = KosLog.createLogger({ name: \"kos-core\" });\n\ndeclare global {\n interface Window {\n KosCore: IKosCoreManager;\n }\n}\n\nconst getDefaultProtocol = () => {\n const defaultProtocol = window.location.protocol;\n\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n let protocol;\n try {\n const _url = new URL(hostUrl);\n protocol = _url.protocol === \"https:\" ? \"wss://\" : \"ws://\";\n } catch {\n // ignore errors\n }\n\n const result = protocol\n ? protocol\n : defaultProtocol === \"https:\"\n ? \"wss://\"\n : \"ws://\";\n return result;\n};\n\nconst getDefaultHost = () => {\n const defaultHost = window.location.hostname;\n const envHost = process.env.KOS_HOST;\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n let host;\n try {\n const _url = new URL(hostUrl);\n host = _url.hostname;\n } catch {\n // ignore errors\n }\n\n const result = host ?? envHost ?? defaultHost;\n return result;\n};\n\nconst getDefaultPort = () => {\n const defaultPort = window.location.port;\n const envPort = process.env.KOS_PORT;\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n let port;\n try {\n const _url = new URL(hostUrl);\n port = _url.port;\n } catch {\n // ignore errors\n }\n\n const result = port ?? envPort ?? defaultPort;\n return result;\n};\n\nconst rejectAfterDelay = (\n ms: number,\n model: IKosModel\n): { promise: Promise<void>; cancel: () => void } => {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const promise = new Promise<void>((_, reject) => {\n timeoutId = setTimeout(() => {\n if (model) {\n KosLog.error(\n `Model ${model.modelId} - ${model.modelTypeName} preloading - timed out after ${ms}ms`\n );\n } else {\n KosLog.error(`kOS Core preloading timed out after ${ms}ms`);\n }\n reject(\n new Error(\n `Model ${model?.modelId} - ${model?.modelTypeName} - timed out after ${ms}ms`\n )\n );\n }, ms);\n });\n\n const cancel = () => {\n if (timeoutId) clearTimeout(timeoutId);\n };\n\n return { promise, cancel };\n};\nconst isReloadable = (model: any): model is ReloadAware =>\n typeof model.reload === \"function\";\n\nconst isUnloadable = (model: any): model is UnloadAware =>\n typeof model.unload === \"function\";\nexport interface IKosCoreLifecycle {\n /**\n * lifecycle function to initialize the core and provide initial values that\n * will be used by the system. For example, loading the logger, setting up\n * internationialization or performing any capability validation would occur here\n */\n init(): Promise<void>;\n\n load(): Promise<void>;\n\n unload(): Promise<void>;\n\n ready(): Promise<void>;\n\n online(): Promise<void>;\n\n offline(): Promise<void>;\n\n whenReady(): Promise<void>;\n\n reload(): Promise<void>;\n\n isReady: boolean;\n}\nexport interface IKosWebSocketTransportContainer {\n transport: IKosServiceTransport;\n connectionAlias?: string;\n}\nexport interface IKosModelManagerContainer {\n status: KosCoreState;\n isOnline: boolean;\n onlineStatus: boolean;\n modelManager: IKosModelManager;\n}\n\nexport type IKosCoreManager = IKosCoreLifecycle &\n IKosModelManagerContainer &\n IKosWebSocketTransportContainer & { reloading: boolean };\n\nexport enum AuthState {\n LOGGED_IN = \"logged_in\",\n LOGGED_OUT = \"logged_out\",\n}\nexport class KosCore implements IKosCoreManager {\n fsmService: ReturnType<typeof coreFsm>;\n\n private static _instance: IKosCoreManager;\n\n status: KosCoreState;\n\n private initialized: boolean;\n\n private loaded: boolean;\n\n private _transport: IKosServiceTransport;\n\n public modelManager!: IKosModelManager;\n\n public authState: AuthState;\n public isOnline: boolean;\n\n private _reloading: boolean;\n private _unloading: boolean;\n connectionAlias?: string;\n\n private constructor(connectionAlias?: string) {\n this.initialized = false;\n this.connectionAlias = connectionAlias;\n this.loaded = false;\n this.isOnline = false;\n this.status = KosCoreState.CREATED;\n this.authState = AuthState.LOGGED_OUT;\n this._reloading = false;\n this._unloading = false;\n makeAutoObservable(this);\n\n EventBus.subscribe(\"token\", (data) => {\n if (data) {\n this.transport.token = data.body;\n }\n });\n\n EventBus.subscribe(WebSocketEvents.CONNECTED, async () => {\n await this.whenReady();\n this.fsmService.service.send(KosCoreEvents.GO_ONLINE);\n });\n\n EventBus.subscribe(WebSocketEvents.DISCONNECTED, async () => {\n this.fsmService.service.send(KosCoreEvents.GO_OFFLINE);\n });\n EventBus.subscribe(\"/studioServer/auth/LOGGED_IN\", () => {\n this.authState = AuthState.LOGGED_IN;\n this.transport.authorized = true;\n // this.fsmService.service.send(KosCoreEvents.RELOAD);\n });\n EventBus.subscribe(\"/studioServer/auth/LOGIN_REQUIRED\", () => {\n this.authState = AuthState.LOGGED_OUT;\n this.transport.authorized = false;\n });\n\n EventBus.subscribe(WebSocketEvents.RELOAD, () => {\n this.fsmService.service.send(KosCoreEvents.RELOAD);\n });\n\n EventBus.subscribe(\"/studio/project/reload\", () => {\n this.fsmService.service.send(KosCoreEvents.RELOAD);\n });\n\n // EventBus.subscribe(\"/studioServer/auth/LOGGED_OUT\", () => {\n // this.fsmService.service.send(KosCoreEvents.UNLOAD);\n // });\n const ws = WebSocketTransport.getInstance();\n\n const host = getDefaultHost();\n const port = getDefaultPort();\n const protocol = getDefaultProtocol();\n ws.host = host;\n\n ws.port = Number.parseInt(port);\n\n ws.protocol = protocol;\n if (process.env.KOS_ALLOW_ANONYMOUS === \"true\") {\n ws.authorized = true;\n }\n\n const alias = connectionAlias || process.env.KOS_CONNECTION_ALIAS;\n if (alias) {\n ws.alias = alias.replace(\"{{TIMESTAMP}}\", Date.now().toString());\n }\n\n this._transport = ws.init();\n this.fsmService = coreFsm(this);\n this.fsmService.service.send(KosCoreEvents.CREATE);\n }\n\n get onlineStatus() {\n return this.isOnline && !this._reloading && !this._unloading;\n }\n get reloading() {\n return this._reloading;\n }\n\n get unloading() {\n return this._unloading;\n }\n async reload(): Promise<void> {\n const currentTime = Date.now();\n if (this._reloading) {\n log.info(\"reload already in progress\");\n return;\n }\n this._reloading = true;\n log.warn(\"reloading KOS Core\");\n log.warn(\"reloading preloaded models\");\n const modelManager = this.modelManager;\n for (const model of modelManager.preloadedModels) {\n if (isReloadable(model.modelData)) {\n log.info(`reloading model ${model.modelId}`);\n model.unload?.();\n await model.modelData.reload();\n log.info(`reloading model ${model.modelId} complete`);\n }\n }\n\n for (const model of modelManager.models) {\n // only reload models that are not preloaded\n if (\n !modelManager.preloadedModels.includes(model) &&\n isReloadable(model.modelData)\n ) {\n model.unload?.();\n await model.modelData.reload();\n }\n }\n const elapsed = Date.now() - currentTime;\n setTimeout(() => {\n kosAction(() => {\n log.warn(\"reloading KOS Core complete\");\n this._reloading = false;\n });\n }, 1000 - elapsed);\n }\n\n async online(): Promise<void> {\n log.debug(\"KOS Core going online\");\n await this._transport.whenReady();\n log.debug(\"KOS Transport Ready. Calling online() for models\");\n EventBus.publish(\"/kosCore/online\", \"/kosCore/online\");\n console.timeEnd(\"kosCore:startup\");\n }\n async offline(): Promise<void> {\n log.debug(\"KOS Core going offline\");\n EventBus.publish(\"/kosCore/offline\", \"/kosCore/offline\");\n }\n\n async unload(): Promise<void> {\n log.debug(\"Unloading kOS Core\");\n const currentTime = Date.now();\n this._unloading = true;\n log.debug(\"unloading KOS Core\");\n const modelManager = this.modelManager;\n for (const model of modelManager.models) {\n if (isUnloadable(model.modelData)) {\n model.unload?.();\n }\n }\n const elapsed = Date.now() - currentTime;\n setTimeout(() => {\n kosAction(() => {\n this._unloading = false;\n });\n }, 1000 - elapsed);\n }\n\n async whenReady() {\n await when(() => this.status === KosCoreState.READY);\n }\n async ready(): Promise<void> {\n log.debug(\"Readying KOS Core\");\n await this._transport.whenReady();\n\n const promises = this.modelManager!.preloadedModels.map((model) => {\n return {\n modelId: model.modelId,\n model,\n promise: model.whenReady!(),\n };\n });\n\n const settled = await Promise.allSettled(\n promises.map((promise) => {\n const { promise: timeoutPromise, cancel: timeoutCancel } =\n rejectAfterDelay(5000, promise.model);\n Promise.race([\n promise.promise.then(() => {\n timeoutCancel();\n }),\n timeoutPromise,\n ]);\n })\n );\n const failed = settled.filter((p) => p.status === \"rejected\");\n if (failed.length) {\n log.error(\n `There were ${failed.length} failed models on model preloading`\n );\n\n throw Error(\n `There were ${failed.length} failed models on model preloading`\n );\n }\n\n log.debug(`leaving kos-core ready() `);\n }\n\n get isReady() {\n return this.status === KosCoreState.READY;\n }\n set transport(transport: IKosServiceTransport) {\n this._transport = transport;\n }\n get transport() {\n return this._transport;\n }\n\n get coreInitialized() {\n return this.initialized;\n }\n\n get modelsLoaded() {\n return this.loaded;\n }\n\n async init(): Promise<void> {\n log.debug(\"entering kos-core init()\");\n\n console.time(\"kosCore:startup\");\n console.time(\"kosCore:init\");\n await this._transport.whenReady();\n\n this.initialized = true;\n log.debug(\"initialized - leaving kos-core init()\");\n console.timeEnd(\"kosCore:init\");\n }\n\n async load(): Promise<void> {\n log.debug(\"entering kos-core load()\");\n console.time(\"kosCore:load\");\n\n this.loaded = true;\n log.debug(\"loaded - leaving kos-core load()\");\n console.timeEnd(\"kosCore:load\");\n }\n\n public static create(\n registry: IKosRegistry,\n reset?: boolean,\n connectionAlias?: string\n ) {\n const instance = this.getInstance({ reset, connectionAlias });\n\n if (registry.extensions?.dataMapper) {\n Object.keys(registry.extensions.dataMapper).forEach((key) => {\n const dataMapper = registry.extensions?.dataMapper?.[key];\n if (dataMapper) {\n if (Array.isArray(dataMapper)) {\n dataMapper.forEach((mapper) => {\n ExtensionManager.dataMapper.registerDataMapper(key, mapper);\n });\n } else {\n ExtensionManager.dataMapper.registerDataMapper(key, dataMapper);\n }\n }\n });\n }\n\n if (registry.extensions?.propertyMapper) {\n Object.keys(registry.extensions.propertyMapper).forEach((key) => {\n const propertyMapper = registry.extensions?.propertyMapper?.[key];\n if (propertyMapper) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n key,\n propertyMapper\n );\n }\n });\n }\n\n if (registry.extensions?.contextLoader) {\n Object.keys(registry.extensions.contextLoader).forEach((key) => {\n const loader = registry.extensions?.contextLoader?.[key];\n if (loader) {\n ExtensionManager.loader.registerLoader(key, loader);\n }\n });\n }\n\n RegistrationManager.model.getAll().forEach(([, value]) => {\n registry.models = { ...registry.models, ...value.registration };\n });\n\n registry.models = {\n ...registry.models,\n ...RegistrationManager.model.getLegacyModels(),\n };\n\n RegistrationManager.companion.getAll().forEach(([key, value]) => {\n registry.companionModels = { ...registry.companionModels };\n registry.companionModels[key] = registry.companionModels[key] || [];\n for (const companion of value) {\n registry.companionModels[key].push({ type: companion });\n }\n });\n\n RegistrationManager.model.getPreloadModels().forEach((preload) => {\n if (registry.preloadModels.includes(preload)) {\n return;\n }\n registry.preloadModels.push(preload);\n });\n const modelManager = KosModelManager.create(registry, reset);\n instance.modelManager = modelManager;\n return instance;\n }\n\n public static getInstance(data?: {\n reset?: boolean;\n connectionAlias?: string;\n }): IKosCoreManager {\n this._instance = window.KosCore as any;\n // Do you need arguments? Make it a regular static method instead.\n if (!this._instance || data?.reset) {\n window.KosCore = new this(data?.connectionAlias) as any;\n this._instance = window.KosCore as any;\n }\n return this._instance;\n }\n}\n","import { EventBus } from \"../../common\";\nimport { KosCore } from \"../core/kosCore\";\nimport { KosLog } from \"../core/log\";\nimport { KosFetchOptions, Response } from \"../types/utils/kos-fetch\";\nimport { uuid } from \"./api-request-id\";\nimport {\n createBaseMessage,\n createFosBaseMessage,\n createHeaders,\n createMessageBody,\n createReadableStream,\n createStudioMessage,\n} from \"./kos-message-utils\";\n\nconst log = KosLog.createLogger({ name: \"kos-fetch\" });\n\n/**\n * Represents the response data received from a Kos service.\n *\n * @typeparam T - The type of data in the response.\n */\nexport interface KosServiceResponse<T> {\n data: T;\n status: number;\n}\n\n/**\n * The WebSocket timeout duration in milliseconds.\n */\nconst WS_TIMEOUT = process.env.KOS_WS_TIMEOUT\n ? parseInt(process.env.KOS_WS_TIMEOUT)\n : 30000;\n\n/**\n * A delay function used to resolve promises with a delay.\n *\n * @returns A promise that resolves after a minimal delay.\n */\nconst delay = () =>\n new Promise((resolve) => {\n setTimeout(() => {\n resolve(true);\n }, 0);\n });\n\n/**\n * Determines the appropriate message factory function based on the provided options.\n *\n * @param options - The Kos fetch options.\n * @returns A message factory function.\n */\nconst fetchMessageFactory = (options?: KosFetchOptions) => {\n if (options?.studio) {\n return createStudioMessage;\n } else if (options?.fos) {\n return createFosBaseMessage;\n } else {\n return createBaseMessage;\n }\n};\n\n/**\n * Performs a Kos WebSocket fetch operation, providing fetch-like behavior over a WebSocket transport.\n *\n * @async\n * @param url - The URL to fetch from.\n * @param options - The Kos fetch options.\n * @returns A promise that resolves to the response from the server.\n */\nconst kosFetchWs = async (\n url: string,\n options?: KosFetchOptions\n): Promise<Response> => {\n const transport = KosCore.getInstance().transport;\n await transport.whenReady();\n const requestId = uuid();\n const urlObj = new URL(url);\n const path = `${urlObj.pathname}${urlObj.search}`;\n const TIMEOUT = options?.timeout || WS_TIMEOUT;\n const messageFactory = fetchMessageFactory(options);\n const msg = createMessageBody(\n messageFactory({\n path,\n requestId,\n method: options?.method || `GET`,\n destinationAddress: options?.destinationAddress || \"\",\n ordered: options?.ordered,\n tracker: options?.tracker,\n bridge: options?.bridge,\n }),\n options?.body\n );\n\n return new Promise((resolve) => {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n log.error(`Timeout occurred - url: ${url}`);\n controller.abort();\n resolve({\n headers: createHeaders({}),\n status: 404,\n ok: false,\n json: async <T>(): Promise<T | null> => null,\n body: createReadableStream(``),\n redirected: false,\n statusText: ``,\n type: `basic`,\n url: ``,\n clone: function (): Response {\n throw new Error(`Function not implemented.`);\n },\n bodyUsed: false,\n arrayBuffer: function (): Promise<ArrayBuffer> {\n throw new Error(`Function not implemented.`);\n },\n blob: function (): Promise<Blob> {\n throw new Error(`Function not implemented.`);\n },\n formData: function (): Promise<FormData> {\n throw new Error(`Function not implemented.`);\n },\n text: function (): Promise<string> {\n throw new Error(`Function not implemented.`);\n },\n });\n }, TIMEOUT);\n const { unsubscribe } = EventBus.subscribe(requestId, (responseMsg) => {\n clearTimeout(timeoutId);\n const response: Response = {\n headers: createHeaders(responseMsg?.headers || {}),\n status:\n (responseMsg?.headers?.[`status`] &&\n parseInt(responseMsg?.headers?.[`status`])) ||\n 200,\n ok: responseMsg?.headers?.[`status`] === `200`,\n\n json: async <T>(): Promise<T | null> => {\n try {\n return responseMsg?.body?.length\n ? (JSON.parse(responseMsg.body) as T)\n : null;\n } catch (e) {\n throw Error(`Not a JSON response`);\n }\n },\n text: async (): Promise<string> => responseMsg?.body || \"\",\n body: createReadableStream(responseMsg?.body || ``),\n redirected: false,\n statusText: ``,\n type: `basic`,\n url: ``,\n clone: function (): Response {\n throw new Error(`Function not implemented.`);\n },\n bodyUsed: false,\n arrayBuffer: function (): Promise<ArrayBuffer> {\n throw new Error(`Function not implemented.`);\n },\n blob: function (): Promise<Blob> {\n throw new Error(`Function not implemented.`);\n },\n formData: function (): Promise<FormData> {\n throw new Error(`Function not implemented.`);\n },\n };\n\n // Clean up the subscription\n unsubscribe();\n delay().then(() => resolve(response));\n });\n\n const socket = options?.fos ? transport.fosSocket : transport.socket;\n if (!socket) {\n throw Error(`No web socket transport available: ${options}`);\n }\n socket?.send(msg);\n });\n};\n\n/**\n * Represents the base URL for Kos fetch requests.\n */\nlet BASE_URL = `kos:`;\nlet kosFetch = kosFetchWs;\n// Check if mocking of fetch requests is enabled\nif (process.env.KOS_MOCK_FETCH === `true`) {\n const PORT = process.env.KOS_PORT || \"9999\";\n kosFetch = fetch; // Use the standard fetch for mocking\n BASE_URL = `http://localhost:${PORT}`;\n}\n\n// Export the kosFetch function and BASE_URL for use in other modules\nexport { BASE_URL, kosFetch };\n","import { KosCore } from \"../core/kosCore\";\nimport { IKosDataModel, IKosModel, IKosVisitor } from \"../core/kosModel\";\nimport { KosLog } from \"../core/log\";\n\nconst log = KosLog.createLogger({\n name: \"kos-model-visitor\",\n group: \"kos-ui-core\",\n});\n\n/**\n * Represents a base class for visiting and processing Kos data models.\n *\n * @abstract\n * @implements IKosVisitor<IKosModel>\n * @category Core\n */\nexport abstract class KosModelVisitor implements IKosVisitor<IKosModel> {\n /**\n * A set to keep track of visited model IDs to prevent redundant visits.\n */\n visitedModels: Set<string> = new Set();\n\n /**\n * Initializes a new instance of the KosModelVisitor class.\n */\n constructor() {\n this.visitedModels = new Set();\n }\n\n /**\n * Starts the visiting process from a root Kos data model.\n *\n * @param rootModel - The root Kos data model to start visiting from.\n * @throws An error if the rootModel does not have an ID or if it cannot be found.\n */\n start(rootModel: IKosDataModel): void {\n if (rootModel.id === undefined) {\n throw new Error(\"rootModel must have an id\");\n }\n\n const kosModel = KosCore.getInstance().modelManager.getModelById(\n rootModel.id\n );\n\n if (!kosModel) {\n throw new Error(`Could not find rootModel with id: ${rootModel.id}`);\n }\n\n this.visitedModels.clear();\n kosModel.accept?.(this);\n }\n\n /**\n * Visits and processes a Kos model.\n *\n * @param model - The Kos model to visit and process.\n */\n visit(model: IKosModel): void {\n if (this.visitedModels.has(model.modelId)) {\n log.info(`model ${model.modelId} already visited`);\n return;\n }\n\n // Call the visitModel method to allow custom processing of the model.\n const stopVisiting = !!this.visitModel(model.modelData, this);\n\n this.visitedModels.add(model.modelId);\n\n if (stopVisiting) {\n return;\n }\n\n // Visit and process the children of the current model.\n model.getChildren?.().forEach((child) => {\n child.accept?.(this);\n });\n }\n\n /**\n * Abstract method to visit and process a Kos data model.\n *\n * @param model - The Kos data model to visit and process.\n * @param context - The KosModelVisitor instance for context.\n * @returns `true` to stop visiting further models, or `false` or `undefined` to continue visiting.\n */\n abstract visitModel<T extends IKosDataModel = IKosDataModel>(\n model: T,\n context: KosModelVisitor\n ): boolean | void;\n}\n","import type { KosFetchOptions } from \"../types\";\nimport { BASE_URL, kosFetch } from \"./kos-fetch\";\n\n/**\n * Resolves the service URL configuration.\n * @param _service - The optional service name (not used).\n * @returns An object with `isMock` and `URL` properties.\n */\nexport const resolveBaseUrl = () => {\n const MOCK = false;\n const URL = BASE_URL;\n return { isMock: MOCK, URL };\n};\n\nconst ERROR_UNKNOWN = \"errUnknown\";\ntype NonNeverKeys<T> = {\n [K in keyof T]-?: T[K] extends never | undefined ? never : K;\n}[keyof T];\n\nexport type AvailableMethods<T> = Exclude<\n NonNeverKeys<T>,\n \"parameters\" | \"requestBody\"\n>;\n\nexport type PathsByMethod<T> = {\n [Method in \"get\" | \"put\" | \"post\" | \"delete\"]: {\n [K in keyof T]: Method extends AvailableMethods<T[K]> ? K : never;\n }[keyof T & keyof { [K in keyof T]: Method extends keyof T[K] ? K : never }];\n};\n\ntype ClientGetParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"get\"] extends { parameters: infer P } ? P : never;\n\ntype ClientPostParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"post\"] extends { parameters: infer P } ? P : never;\n\ntype ClientPutParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"put\"] extends { parameters: infer P } ? P : never;\n\ntype ClientDeleteParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"delete\"] extends { parameters: infer P } ? P : never;\n\ntype ClientGetBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"get\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\ntype ClientPostBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"post\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\ntype ClientPutBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"put\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\ntype ClientDeleteBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"delete\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\nexport type ClientResponse<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n> = Paths[K][M] extends { responses: { 200: { content: infer R } } }\n ? R[keyof R]\n : unknown;\n\ntype ClientParams<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n> = Paths[K][M] extends { parameters: infer P } ? P : never;\n\ntype ClientBody<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n> = Paths[K][M] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\nexport type ServiceResponse<T> = [string, null] | [null, T];\n\nexport type DeepRequired<T> = {\n [K in keyof T]-?: T[K] extends object ? DeepRequired<T[K]> : T[K];\n};\nexport type ElementType<T> = T extends (infer U)[] ? U : never;\n\n// Define a generic request function using your custom transport layer\nasync function clientRequest<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n>(\n endpoint: K,\n method: M,\n options?: RequestOptions,\n params?: ClientParams<Paths, K, M>,\n body?: ClientBody<Paths, K, M>\n): Promise<ServiceResponse<ClientResponse<Paths, K, M>>> {\n const url = (params as any)?.path\n ? Object.keys((params as any).path).reduce<string>(\n (acc, key) =>\n String(acc).replace(`{${key}}`, (params as any)?.path[key]),\n String(endpoint)\n )\n : String(endpoint);\n\n const query = (params as any)?.query\n ? Object.keys((params as any).query)\n .map((key) => `${key}=${(params as any).query[key]}`)\n .join(\"&\")\n : \"\";\n\n const fullUrl = `${resolveBaseUrl().URL}//${url}${\n query ? `?${encodeURIComponent(query)}` : \"\"\n }`;\n const fetchOptions = {\n method: String(method).toUpperCase() as any,\n body: null as any,\n ...options,\n };\n if (body) {\n fetchOptions.body = JSON.stringify(body);\n }\n const response = await kosFetch(fullUrl, fetchOptions);\n\n if (response.status < 200 || response.status >= 400) {\n return [`${response.statusText || ERROR_UNKNOWN}`, null];\n }\n\n const payload = await response.json();\n return [null, payload.data];\n}\n\ntype RequestOptions = Omit<KosFetchOptions, \"method\" | \"body\">;\nexport function createClient<Paths extends Record<string, any>>() {\n // Extract valid paths for each method\n type ValidPaths = PathsByMethod<Paths>;\n\n return {\n get: <K extends ValidPaths[\"get\"]>(\n endpoint: K,\n params?: ClientGetParams<Paths, K>,\n options?: RequestOptions\n ) => clientRequest<Paths, K, \"get\">(endpoint, \"get\", options, params),\n\n post: <K extends ValidPaths[\"post\"]>(\n endpoint: K,\n params?: ClientPostParams<Paths, K>,\n body?: ClientPostBody<Paths, K>,\n options?: RequestOptions\n ) =>\n clientRequest<Paths, K, \"post\">(endpoint, \"post\", options, params, body),\n\n put: <K extends ValidPaths[\"put\"]>(\n endpoint: K,\n params?: ClientPutParams<Paths, K>,\n body?: ClientPutBody<Paths, K>,\n options?: RequestOptions\n ) => clientRequest<Paths, K, \"put\">(endpoint, \"put\", options, params, body),\n\n delete: <K extends ValidPaths[\"delete\"]>(\n endpoint: K,\n params?: ClientDeleteParams<Paths, K>,\n options?: RequestOptions\n ) => clientRequest<Paths, K, \"delete\">(endpoint, \"delete\", options, params),\n };\n}\n","export type Middleware<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n> = (context: Context<D, R>, next: () => Promise<void>) => Promise<void>;\n\nexport interface Context<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n> {\n data: D;\n result: Partial<R>;\n}\n\ntype ScalarValue = string | number | boolean | null | undefined;\nexport class MiddlewareChain<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>,\n T extends Context<D, R> = Context<D, R>\n> {\n private middlewares: Middleware<D, R>[] = [];\n\n use(middleware: Middleware<D, R>): void {\n this.middlewares.push(middleware);\n }\n\n async execute(context: T): Promise<void> {\n let index = 0;\n\n const next = async (): Promise<void> => {\n index++;\n if (index < this.middlewares.length) {\n await this.middlewares[index](context, next);\n }\n };\n\n await this.middlewares[index](context, next);\n }\n}\n\nexport const processMiddleware = async <\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n>(\n data: D,\n middleware: Middleware<D, R>[]\n) => {\n const chain = new MiddlewareChain<D, R>();\n middleware.forEach((m) => chain.use(m));\n\n const context: Context<D, R> = { data, result: {} as R };\n await chain.execute(context);\n return context.result as R;\n};\n","import { IKosDataModel } from \"../core/kosModel\";\nimport { KosCore } from \"../core/kosCore\";\nimport { ModelFactory } from \"../types/model\";\n\nexport const modelFactory = <T extends IKosDataModel, O extends Object = {}>(\n typeId: string\n): ModelFactory<T, O> => {\n return {\n type: typeId,\n build: (modelId?: string, options?: O) =>\n KosCore.getInstance().modelManager.createModelInstance<T, O>(\n typeId,\n modelId,\n options\n ).data,\n\n buildAsync: async (modelId?: string, options?: O) => {\n const response = KosCore.getInstance().modelManager.createModelInstance<\n T,\n O\n >(typeId, modelId, options);\n await response.model.whenInitialized();\n return response.data;\n },\n };\n};\n","import { KosCore } from \"../core/kosCore\";\nimport type { KosCompanionModelType } from \"../core/types/registration\";\nimport type { BaseKosModelRegistrationBean } from \"../types/model\";\n\nexport const updateModelRegistration = <\n T extends BaseKosModelRegistrationBean<any, any>\n>(\n modelRegistration: T\n): void => {\n KosCore.getInstance().modelManager.registerModel(modelRegistration);\n};\n\nexport const updateCompanionModelRegistration = (\n typeId: string,\n companionRegistration: KosCompanionModelType<any>\n): void => {\n KosCore.getInstance().modelManager.registerCompanionModel(\n typeId,\n companionRegistration\n );\n};\n","import { IAtom, createAtom, observable } from \"mobx\";\n\nexport const KosObservableData = Symbol(\"KosObservableData\");\nclass ObservableDataMap<T extends Record<string | number | symbol, any>> {\n private map: Map<keyof T, T[keyof T]>;\n\n private atomMap: Map<keyof T, IAtom> = new Map();\n constructor() {\n this.map = observable.map(new Map<keyof T, T[keyof T]>());\n }\n\n // Set a value in the map\n setValue<K extends keyof T>(key: K, value: T[K]): void {\n this.map.set(key, value);\n }\n\n // Get a value from the map\n getValue<K extends keyof T>(key: K): T[K] | undefined {\n return this.map.get(key);\n }\n\n has(key: keyof T): boolean {\n return this.map.has(key);\n }\n\n get entries(): [keyof T, T[keyof T]][] {\n return Array.from(this.map.entries());\n }\n\n // Getter for keys in the map\n get keys(): string[] {\n return Array.from(this.map.keys()) as string[];\n }\n\n get values(): T[keyof T][] {\n return Array.from(this.map.values());\n }\n\n // Create a proxy handler to intercept property accesses\n private proxyHandler: ProxyHandler<ObservableDataMap<T>> = {\n get: (target, property: any) => {\n if (target[property] !== undefined) {\n return target[property];\n }\n if (this.atomMap.has(property)) {\n if (this.atomMap.get(property)?.reportObserved()) {\n return this.getValue(property);\n }\n }\n return this.getValue(property);\n }, // Retrieve value from the map // Retrieve value from the map\n set: (_target, property: keyof T, value: T[keyof T]) => {\n this.setValue(property, value); // Set value in the map\n if (!this.atomMap.has(property)) {\n this.atomMap.set(property, createAtom(property.toString()));\n }\n this.atomMap.get(property)?.reportChanged(); // Notify MobX that the value has changed\n return true;\n },\n ownKeys: () => Array.from(this.map.keys()) as string[],\n };\n\n setValues(initialData?: T) {\n if (initialData) {\n Object.keys(initialData).forEach((key) => {\n this.setValue(key as keyof T, initialData[key]);\n });\n }\n }\n // Create a proxy for the class instance\n get proxy(): T {\n return new Proxy(this, this.proxyHandler) as unknown as KosData<T>;\n }\n}\n\nObservableDataMap.prototype[KosObservableData] = true;\n\ntype Constructor<T> = new (...args: any[]) => T;\n\nfunction createObservableData<T extends Record<string, any>>(\n BaseClass: Constructor<ObservableDataMap<T>>,\n initialData?: T\n): Constructor<ObservableDataMap<T>> {\n return new Proxy(BaseClass, {\n construct: (_target, args) => {\n const instance = new BaseClass(...args);\n instance.setValues(initialData);\n return instance.proxy as unknown as T & {\n setValues: (initialData?: T) => void;\n };\n },\n });\n}\n\nexport type KosData<T extends Record<any, any>> = T & {\n setValues: (initialData?: T) => void;\n keys: (keyof T)[];\n entries: [keyof T, T[keyof T]][];\n values: T[keyof T][];\n has: (key: keyof T) => boolean;\n};\n\nexport const ObservableData = <T extends Record<string, any>>(\n initialData?: T\n): KosData<T> => {\n const od = createObservableData(ObservableDataMap<T>, initialData);\n return new od(initialData) as unknown as KosData<T>;\n};\n","import { KosCore } from \"../core/kosCore\";\nimport { sendKosMessageResponse } from \"./kos-message-utils\";\n\nconst TOPIC = \"/kos/ui/internal/heartbeat/\";\n\ninterface HeartbeatOptions {\n // An ID to identify the pairing between the two clients.\n relationshipId: string;\n // The websocket client ID that the active one should pair with.\n destinationAddress: string;\n // A function called if the pairing is aborted.\n onAbort?: () => void;\n // By default the utlity will emit a beat every 2000 miliseconds. Use this\n // to change that.\n beatTime?: number;\n // By default the utlity will wait 3 seconds without a beat from the paired client\n // before aborting. Use this to change that.\n waitTime?: number;\n}\n\n/**\n * Sets up a connection between two clients such that\n * if one is closed, the other is notified of its closure.\n *\n * @category Utility\n */\nexport const pairedClientHeartbeat = ({\n relationshipId,\n destinationAddress,\n onAbort,\n waitTime,\n beatTime,\n}: HeartbeatOptions) => {\n const transport = KosCore.getInstance().transport;\n\n // Create an abort controller so we can cancel any requests that depend\n // on both clients being open (e.g in the case where one client is waiting for a response from another)\n const controller = new AbortController();\n\n let lastHeartBeat: number = performance.now();\n\n // Subscribe to the client heartbeat topic using the intent reponse id.\n const unsubscribe = transport.subscribeTopic({\n topic: `${TOPIC}${relationshipId}`,\n callback: () => {\n lastHeartBeat = performance.now();\n },\n });\n\n const _waitTime = waitTime ?? 3000;\n\n // If the last heartbeat was more than 5 seconds ago, abort the operation.\n const waitInterval = window.setInterval(() => {\n let timeDiff = performance.now() - lastHeartBeat;\n timeDiff = timeDiff / 1000;\n\n if (timeDiff > _waitTime / 1000) {\n controller.abort();\n }\n // Check that the last pulse was within the last 3 seconds.\n }, _waitTime);\n\n const _beatTime = beatTime ?? 2000;\n\n const beatInterval = window.setInterval(() => {\n sendKosMessageResponse({\n msg: {},\n options: {\n topic: `${TOPIC}${relationshipId}`,\n destinationAddress,\n },\n });\n }, _beatTime);\n\n const cleanUpHeartbeat = () => {\n window.clearInterval(beatInterval);\n window.clearInterval(waitInterval);\n unsubscribe();\n };\n\n const handleAbort = () => {\n cleanUpHeartbeat();\n if (onAbort) {\n onAbort();\n }\n controller.signal.removeEventListener(\"abort\", handleAbort);\n };\n\n controller.signal.addEventListener(\"abort\", handleAbort);\n\n return { cleanUpHeartbeat };\n};\n","type PipeFn = (arg: any) => any;\nexport const pipe =\n (...fns: PipeFn[]) =>\n (x: any) =>\n fns.reduce((v, f) => f(v), x);\n","import { KosLog } from \"../core/log\";\n\ninterface BackoffOptions {\n /** the maximum number of attempts to make */\n maxAttempts: number;\n\n /** the base delay (in ms) between attempts */\n baseDelayMs: number;\n\n /** the factor by which to increase the delay with each attempt */\n backoffFactor: number;\n}\n/**\n * Default backoff options.\n */\nconst BASE_OPTIONS: BackoffOptions = {\n maxAttempts: 5,\n baseDelayMs: 100,\n backoffFactor: 1.5,\n};\n\n/**\n * Provides exponential backoff for a given operation.\n * @param operation - the async operation to perform\n * @param options - optional backoff options\n * @returns - the result of the operation if successful\n * @throws - the last error if all attempts fail\n */\nexport async function retryWithExponentialBackoff<T>(\n operation: () => Promise<T>,\n options?: Partial<BackoffOptions>\n): Promise<T> {\n let attempt = 1;\n const _options = { ...BASE_OPTIONS, ...options };\n const { maxAttempts, baseDelayMs, backoffFactor } = _options;\n let delayMs = baseDelayMs;\n\n while (attempt <= maxAttempts) {\n try {\n const result = await operation();\n return result; // If the operation succeeds, return the result\n } catch (error) {\n KosLog.error(`Attempt ${attempt} failed: ${error}`);\n\n if (attempt < maxAttempts) {\n // Exponential backoff: increase the delay exponentially with each attempt\n delayMs = baseDelayMs * Math.pow(backoffFactor, attempt);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n attempt++;\n } else {\n throw error; // If all attempts fail, re-throw the error\n }\n }\n }\n\n // If we reach this point, all attempts have failed, so reject with the last error\n throw new Error(\"All attempts failed\");\n}\n","/**\n * @module ServiceFactory\n * @description\n * The ServiceFactory module provides functions for interacting with Kos services, such as retrieving, modifying, and deleting entities.\n * These functions communicate with the server and handle various service operations.\n *\n * @example\n * // Create a Kos service instance for managing entities.\n * const entityService = ServiceFactory.build({\n * basePath: \"/api/entities\",\n * getAllPath: \"/list\",\n * getOnePath: \"/get\",\n * deleteModelPath: \"/delete\",\n * addModelPath: \"/add\",\n * modifyModelPath: \"/modify\",\n * });\n *\n * // Fetch a list of entities.\n * const entities = await entityService.getAll({ ordered: true });\n *\n * // Get details of a specific entity by ID.\n * const entityDetails = await entityService.getModelById({ id: \"entity123\" });\n *\n * // Add a new entity to the server.\n * const newEntity = { name: \"New Entity\" };\n * await entityService.addModel({ model: newEntity });\n *\n * // Modify an existing entity.\n * const updatedEntity = { id: \"entity123\", name: \"Updated Entity\" };\n * await entityService.modifyModel({ model: updatedEntity });\n */\n\nimport type { KosFetchOptions } from \"../types/utils/kos-fetch\";\nimport type { KosServiceResponse } from \"./kos-fetch\";\nimport { BASE_URL, kosFetch } from \"./kos-fetch\";\n\n/**\n * Resolves the service URL configuration.\n * @param _service - The optional service name (not used).\n * @returns An object with `isMock` and `URL` properties.\n */\nexport const resolveServiceUrl = (_service?: string) => {\n const MOCK = false;\n const URL = BASE_URL;\n return { isMock: MOCK, URL };\n};\n\n/**\n * Represents a function that can be used for fetching data.\n */\ntype FetchType = typeof kosFetch | typeof fetch;\n\n/**\n * Represents parameters for deleting an entity from the server.\n */\ninterface DeleteModelParams extends CommonParams {\n id: string;\n urlOverride?: string;\n tracker?: string;\n}\n\n/**\n * Removes an entity from the server based on its ID.\n * @param destinationAddress - The destination address for the request.\n * @param url - The base URL for the service.\n * @param _fetch - The fetch function to use.\n * @returns An empty response with status 200.\n */\nconst deleteModel =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <ResponseType = unknown>({\n id,\n tracker,\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n }: DeleteModelParams) => {\n const options: KosFetchOptions = {\n method: `DELETE`,\n };\n\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n if (tracker) {\n options.tracker = tracker;\n }\n\n addCommonParams(options, {\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const response = await _fetch(urlOverride || `${url}/${id}`, options);\n\n if (!response.ok) {\n throw Error(\n `There was a problem deleting the model; returned status ${response.status}`\n );\n }\n\n const configResponse: KosServiceResponse<ResponseType> | undefined =\n await response.json();\n\n return configResponse;\n };\n\n/**\n * Represents common parameters shared across different service operations.\n */\ntype CommonParams = Partial<Orderable> &\n Partial<StudioRequest> &\n Partial<FosRequest> &\n Partial<RoutableRequest> &\n Partial<TimeoutAware>;\n\n/**\n * Represents parameters for fetching a list of entities.\n */\ninterface GetAllParams extends CommonParams {\n urlOverride?: string;\n tracker?: string;\n}\n\n/**\n * Represents parameters for fetching a single entity by ID.\n */\ninterface GetModelByIdParams extends GetAllParams {\n id: string;\n}\n\n/**\n * Adds common parameters to a KosFetchOptions object.\n * @param options - The KosFetchOptions object to modify.\n * @param param1 - The common parameters to add.\n * @returns The modified KosFetchOptions object.\n */\nconst addCommonParams = (\n options: KosFetchOptions,\n { ordered, studio, fos, destinationAddress, bridge, timeout }: CommonParams\n) => {\n if (timeout) {\n options.timeout = timeout;\n }\n if (ordered) {\n options.ordered = ordered;\n }\n\n if (studio) {\n options.studio = studio;\n }\n\n if (fos) {\n options.fos = fos;\n }\n\n if (bridge) {\n options.bridge = bridge;\n }\n\n if (destinationAddress || destinationAddress === \"\") {\n options.destinationAddress = destinationAddress;\n }\n\n return options;\n};\n\n/**\n * Retrieves a list of entities managed by the kOS Server.\n * @param destinationAddress - The destination address for the request.\n * @param url - The base URL for the service.\n * @param _fetch - The fetch function to use.\n * @returns The list of entities.\n */\nconst getAll =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Response>({\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n timeout,\n destinationAddress: destinationAddressOverride,\n }: GetAllParams) => {\n const options: KosFetchOptions = {\n method: `GET`,\n };\n\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || url;\n\n const response = await _fetch(resolvedUrl, options);\n\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem retrieving the model; returned status ${response.status}`,\n payload\n );\n }\n\n const configResponse: KosServiceResponse<Response[]> | undefined =\n await response.json();\n\n return configResponse;\n };\n\n/**\n * Represents parameters for fetching a single entity.\n */\nconst getOne =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Response>({\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n tracker,\n timeout,\n destinationAddress: destinationAddressOverride,\n }: GetAllParams) => {\n const options: KosFetchOptions = {\n method: `GET`,\n };\n\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n if (tracker) {\n options.tracker = tracker;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || url;\n const response = await _fetch(resolvedUrl, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem retrieving the model; returned status ${response.status}`,\n payload\n );\n }\n const configResponse: KosServiceResponse<Response> | undefined =\n await response.json();\n return configResponse;\n };\n\nconst getModelById =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Response>({\n urlOverride,\n id,\n ordered,\n studio,\n fos,\n bridge,\n timeout,\n destinationAddress: destinationAddressOverride,\n }: GetModelByIdParams) => {\n const options: KosFetchOptions = {\n method: `GET`,\n };\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || `${url}/${id}`;\n const response = await _fetch(resolvedUrl, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem retrieving the model; returned status ${response.status}`,\n payload\n );\n }\n const configResponse: KosServiceResponse<Response> | undefined =\n await response.json();\n return configResponse;\n };\n\ninterface Orderable {\n ordered: boolean;\n}\n\ninterface TimeoutAware {\n timeout: number;\n}\n\ninterface FosRequest {\n fos: boolean;\n bridge: boolean;\n}\n\ninterface StudioRequest {\n studio: boolean;\n}\n\ninterface RoutableRequest {\n destinationAddress: string;\n}\ninterface AddModelParams<Request>\n extends Partial<Orderable>,\n Partial<StudioRequest>,\n Partial<FosRequest>,\n Partial<RoutableRequest>,\n Partial<TimeoutAware> {\n model: Request;\n urlOverride?: string;\n tracker?: string;\n}\n\ninterface ModifyModelParams<Request>\n extends Partial<Orderable>,\n Partial<StudioRequest>,\n Partial<FosRequest>,\n Partial<RoutableRequest>,\n Partial<TimeoutAware> {\n model?: Request;\n id: string;\n urlOverride?: string;\n}\n\nexport class FetchError<\n T extends Record<string, any> | string = { error: string }\n> extends Error {\n payload?: T;\n constructor(message: string, payload?: T) {\n super(message);\n this.name = \"FetchException\";\n this.payload = payload;\n }\n}\n/**\n * Adds a new Entity to the server.\n *\n * Only members of the `kos.freestyle` org have permissions to invoke this operation.\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the corresponding event channel.\n *\n * @param model - the model to be added\n * @returns an empty response with status 200.\n */\nconst add =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Request>({\n model,\n urlOverride,\n ordered,\n tracker,\n studio,\n fos,\n bridge,\n timeout,\n destinationAddress: destinationAddressOverride,\n }: AddModelParams<Request>) => {\n const options: KosFetchOptions = {\n method: `POST`,\n body: typeof model === \"string\" ? model : JSON.stringify(model),\n };\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n if (tracker) {\n options.tracker = tracker;\n }\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const response = await _fetch(urlOverride || url, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem sending the POST data; returned status ${response.status}`,\n payload\n );\n }\n const configResponse: KosServiceResponse<any> | undefined =\n await response.json();\n return configResponse;\n };\n\n/**\n * Modifies an existing model on the server.\n * @param method - The HTTP method to use for the modification operation (default is \"POST\").\n * @param destinationAddress - The destination address for the request.\n * @param url - The base URL for the service.\n * @param _fetch - The fetch function to use.\n * @returns An empty response with status 200.\n */\nconst modifyModel =\n (\n method: \"PUT\" | \"POST\" = \"POST\",\n destinationAddress: string,\n url: string,\n _fetch: FetchType\n ) =>\n async <Request>({\n // Reqeust should be Request = unknown...\n model,\n id,\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n timeout,\n destinationAddress: destinationAddressOverride,\n }: ModifyModelParams<Request>) => {\n const options: KosFetchOptions = {\n method,\n };\n if (model) {\n options.body = JSON.stringify(model);\n }\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const response = await _fetch(urlOverride || `${url}/${id}`, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem modifying the model; returned status ${response.status}`,\n payload\n );\n }\n const configResponse: KosServiceResponse<any> | undefined = // <--- KosServiceResponse<any> should be KosServiceResponse<Request>...\n await response.json();\n return configResponse;\n };\n/**\n * Represents parameters for creating a service instance.\n */\ninterface ServiceFactoryParams {\n destinationAddress?: string;\n basePath: string;\n getAllPath?: string;\n getOnePath?: string;\n deleteModelPath?: string;\n addModelPath?: string;\n modifyModelPath?: string;\n mock?: boolean;\n}\n\n/**\n * A factory for creating service instances with common configurations.\n */\nexport const ServiceFactory = {\n /**\n * Builds a service instance with the specified configuration.\n *\n * @param params - The configuration parameters for the service instance.\n * @returns An object with service methods for interacting with the server.\n *\n * @example\n * // Create a Kos service instance for managing entities.\n * const entityService = ServiceFactory.build({\n * basePath: \"/api/entities\",\n * getAllPath: \"/list\",\n * getOnePath: \"/get\",\n * deleteModelPath: \"/delete\",\n * addModelPath: \"/add\",\n * modifyModelPath: \"/modify\",\n * });\n *\n * // Fetch a list of entities.\n * const entities = await entityService.getAll({ ordered: true });\n *\n * // Get details of a specific entity by ID.\n * const entityDetails = await entityService.getModelById({ id: \"entity123\" });\n *\n * // Add a new entity to the server.\n * const newEntity = { name: \"New Entity\" };\n * await entityService.addModel({ model: newEntity });\n *\n * // Modify an existing entity.\n * const updatedEntity = { id: \"entity123\", name: \"Updated Entity\" };\n * await entityService.modifyModel({ model: updatedEntity });\n */\n build: ({\n destinationAddress = \"\",\n basePath,\n getAllPath,\n getOnePath,\n deleteModelPath,\n addModelPath,\n modifyModelPath,\n mock = false,\n }: ServiceFactoryParams) => {\n const _fetch = mock ? fetch : kosFetch;\n return {\n /**\n * Retrieves a list of entities managed by the kOS Server.\n *\n * @param params - The parameters for the request, including common options.\n * @returns The list of entities.\n */\n getAll: getAll(destinationAddress, getAllPath || basePath, _fetch),\n\n /**\n * Retrieves details of a specific entity by its ID.\n *\n * @param params - The parameters for the request, including common options and the entity ID.\n * @returns Details of the requested entity.\n */\n getModelById: getModelById(\n destinationAddress,\n getOnePath || basePath,\n _fetch\n ),\n\n /**\n * Retrieves details of a single entity.\n *\n * @param params - The parameters for the request, including common options.\n * @returns Details of the requested entity.\n */\n getOne: getOne(destinationAddress, getOnePath || basePath, _fetch),\n\n /**\n * Adds a new entity to the server.\n *\n * @param params - The parameters for the request, including common options and the new entity model.\n * @returns An empty response with status 200.\n */\n addModel: add(destinationAddress, addModelPath || basePath, _fetch),\n\n /**\n * Deletes an entity from the server based on its ID.\n *\n * @param params - The parameters for the request, including common options and the entity ID.\n * @returns An empty response with status 200.\n */\n deleteModel: deleteModel(\n destinationAddress,\n deleteModelPath || basePath,\n _fetch\n ),\n\n /**\n * Modifies an existing entity on the server.\n *\n * @param params - The parameters for the request, including common options and the entity model.\n * @returns An empty response with status 200.\n */\n modifyModel: modifyModel(\n \"POST\",\n destinationAddress,\n modifyModelPath || basePath,\n _fetch\n ),\n\n /**\n * Modifies an existing entity on the server using the HTTP PUT method.\n *\n * @param params - The parameters for the request, including common options and the entity model.\n * @returns An empty response with status 200.\n */\n putModel: modifyModel(\n \"PUT\",\n destinationAddress,\n modifyModelPath || basePath,\n _fetch\n ),\n\n /**\n * Adds a new entity to the server using the HTTP POST method.\n *\n * @param params - The parameters for the request, including common options and the new entity model.\n * @returns An empty response with status 200.\n */\n postModel: add(destinationAddress, addModelPath || basePath, _fetch),\n };\n },\n};\n","import { uuid } from \"./api-request-id\";\n\nconst _sessionKey = uuid();\n\nexport const getKosSessionKey = (): string => `kos-${_sessionKey}`;\n\nexport const isLocalRefId = (id?: string): boolean =>\n !!id && !id.includes(\"VM_SERVICE\") && id.startsWith(getKosSessionKey());\n","import log from \"loglevel\";\nimport { EventBus } from \"../../common\";\n\nimport { uuid } from \"./api-request-id\";\nimport { KosServiceResponse } from \"./kos-fetch\";\n\nexport interface ErrorResponse {\n error?: string;\n}\n\nexport const waitForRequest = async <ResponseType extends ErrorResponse>(\n requestId: string,\n timeout = 60000\n) =>\n new Promise<ResponseType>((resolve, reject) => {\n const { unsubscribe } = EventBus.subscribe(requestId, (op) => {\n log.debug(`recieved response for refId ${requestId}: ${op}`);\n unsubscribe();\n clearTimeout(cancel);\n try {\n const body: ResponseType = op?.body ? JSON.parse(op.body) : {};\n resolve(body);\n } catch {\n const body = (op?.body as unknown) || {};\n resolve(body as ResponseType);\n }\n });\n\n const cancel = setTimeout(() => {\n unsubscribe();\n reject(Error(`Request with ID ${requestId} timed out. Cancelling.`));\n }, timeout);\n });\n\nexport const sendRequest = async <R, T extends KosServiceResponse<any>>(\n requestPromise: (param: R) => Promise<T | undefined>,\n params: R,\n refId: string\n) => {\n const op = waitForRequest(refId);\n const result = await Promise.allSettled([requestPromise(params), op]);\n\n if (result[0].status === \"fulfilled\") {\n if (result[1].status === \"rejected\") {\n throw Error(result[1].reason);\n } else {\n if (result[0].value) {\n if (result[1].value.error) {\n throw Error(result[1].value.error);\n }\n result[0].value.data = result[1].value;\n return result[0].value;\n }\n }\n } else {\n throw Error(result[0].reason);\n }\n return undefined;\n};\n\ninterface SyncPublishParams<T> {\n topic: string;\n msg: T;\n requestId?: string;\n}\nexport const syncPublish = async <T, R extends ErrorResponse>({\n topic,\n msg,\n requestId,\n}: SyncPublishParams<T>) => {\n const _requestId = requestId ?? uuid();\n const responsePromise = waitForRequest<R>(_requestId);\n EventBus.publish(topic, msg, { sync: _requestId });\n const response = await responsePromise;\n if (response.error) {\n throw Error(response.error);\n }\n return response;\n};\n","import { ObservableMap, makeAutoObservable } from \"mobx\";\nimport { kosAction } from \"../..\";\nimport { getKosModelSync } from \"../../util\";\nimport { IKosDataModel } from \"../kosModel\";\nconst contextMap = new Map<string, KosContextBean>();\n\nexport interface KosContext {\n get(key: string): any;\n set(key: string, value: any): void;\n}\nexport class KosContextBean implements KosContext {\n private _context: ObservableMap<string, any>;\n private _parent?: string | undefined;\n private _id: string;\n constructor(id: string) {\n this._id = id;\n this._context = new ObservableMap({});\n this._parent = \"\";\n makeAutoObservable(this);\n }\n\n setParent(parent: string) {\n kosAction(() => {\n this._parent = parent;\n });\n }\n get id() {\n return this._id;\n }\n\n get context() {\n return this._context;\n }\n\n get parentModel() {\n if (!this._parent) {\n return undefined;\n }\n return getKosModelSync(this._parent)?.model;\n }\n\n get(key: string) {\n if (this._context.has(key)) {\n return this._context.get(key);\n }\n if (this._parent) {\n return contextMap.get(this._parent)?.get(key);\n }\n return undefined;\n }\n set(key: string, value: any) {\n this._context.set(key, value);\n }\n remove(key: string) {\n this._context.delete(key);\n }\n clear() {\n this._context.clear();\n }\n}\n\nexport const KosContextManager = {\n createContext: (id: string, parentId?: string) => {\n const context = contextMap.get(id) ?? new KosContextBean(id);\n if (parentId) {\n if (!contextMap.has(parentId)) {\n throw new Error(`Parent context ${parentId} does not exist`);\n }\n context.setParent(parentId);\n } else if (id !== \"root\") {\n context.setParent(\"root\");\n }\n contextMap.set(id, context);\n return context;\n },\n getContext: (id: string) => contextMap.get(id),\n deleteContext: (id: string) => {\n contextMap.delete(id);\n },\n setParentContext: (id: string, parentId: string) => {\n if (!contextMap.has(parentId)) {\n throw new Error(`Parent context ${parentId} does not exist`);\n }\n contextMap.get(id)?.setParent(parentId);\n },\n rootContext: () => contextMap.get(\"root\"),\n};\n\nKosContextManager.createContext(\"root\");\n\nexport const resolveKosContext = (model: IKosDataModel) =>\n KosContextManager.getContext(model.id);\n","import { autorun, makeAutoObservable, observable, runInAction } from \"mobx\";\nimport { KosLog } from \"../core/log\";\nimport { ObservableData, type KosData } from \"../util\";\nimport { IKosBaseContainer } from \"./kos-container-model\";\nimport type { IKosDataModel } from \"./kosModel\";\nimport { IKosIdentifiable } from \"./types/model\";\n\ninterface KosContainerIndexOptions<T extends IKosIdentifiable> {\n container: IKosBaseContainer<T>;\n key: keyof T | IndexMapper<T>;\n}\n\nexport interface IKosContainerIndex<T extends IKosIdentifiable> {\n index: Map<string, Set<T>>;\n keys: string[];\n data: KosData<Record<string, T[]>>;\n getByKey: (key: string) => T[];\n refresh: () => void;\n}\n\nexport interface IndexMapper<T extends IKosIdentifiable> {\n (model: T):\n | Promise<string | string[] | undefined>\n | string\n | string[]\n | undefined;\n}\n\nfunction arraysAreEqual<T extends IKosDataModel = IKosDataModel>(\n arr1: T[],\n arr2: T[]\n): boolean {\n // Check if both arrays have the same length\n if (arr1.length !== arr2.length) return false;\n\n return arr1.every((item1) => arr2.includes(item1));\n}\n\nexport class KosContainerIndex<T extends IKosIdentifiable>\n implements IKosContainerIndex<T>\n{\n private _container: IKosBaseContainer<T>;\n private _map: Map<string, Set<T>>;\n private _key: string | number | symbol | IndexMapper<T>;\n\n data: KosData<Record<string, T[]>>;\n constructor({ container, key }: KosContainerIndexOptions<T>) {\n this._container = container;\n this._map = observable.map(new Map());\n this._key = key;\n this.data = ObservableData();\n\n this.generateIndex();\n autorun(() => {\n if (this._container.revision) {\n this.generateIndex();\n }\n });\n makeAutoObservable(this);\n }\n\n refresh() {\n this.generateIndex();\n }\n\n private addItemToIndex(\n key: string,\n model: T,\n map = this._map,\n data: Record<string, T[]> = this.data\n ) {\n const currentValue = map.get(key) || new Set<T>();\n currentValue.add(model);\n map.set(key, currentValue);\n data[key] = Array.from(currentValue);\n }\n\n private resolveIndex(map, data: Record<string, T[]>) {\n const toRemove = this.data.keys.filter(\n (key) => !Object.keys(data).includes(key)\n );\n\n toRemove.forEach((key) => {\n delete this.data[key];\n this._map.delete(key);\n });\n Object.keys(data).forEach((key) => {\n const values = data[key];\n const existing = this.data[key] || [];\n if (!arraysAreEqual(values, existing)) {\n this.data[key] = values;\n const set = map.get(key) || new Set<T>();\n this._map.set(key, set);\n } else {\n KosLog.debug(`KosContainerIndex - Index ${key} is the same`);\n }\n });\n }\n private generateIndex() {\n runInAction(async () => {\n // this._map.clear();\n\n const tempMap = new Map<string, Set<T>>();\n const tempData: Record<string, T[]> = {};\n for (const model of this._container.data) {\n const value =\n typeof this._key === \"function\"\n ? await this._key(model)\n : model[this._key];\n if (Array.isArray(value)) {\n value.forEach((valueItem) => {\n this.addItemToIndex(valueItem, model, tempMap, tempData);\n });\n } else if (typeof value === \"string\" || typeof value === \"number\") {\n this.addItemToIndex(String(value), model, tempMap, tempData);\n } else if (typeof value === \"boolean\") {\n this.addItemToIndex(String(value), model, tempMap, tempData);\n }\n }\n\n this.resolveIndex(tempMap, tempData);\n });\n }\n\n get keys() {\n return Array.from(this._map.keys());\n }\n get index() {\n return this._map;\n }\n\n getByKey(key: string) {\n const models = this._map.get(key);\n if (models) {\n return Array.from(models);\n }\n return [];\n }\n}\n","import {\n isComputedProp,\n runInAction as kosAction,\n makeAutoObservable,\n observable,\n observe,\n reaction,\n} from \"mobx\";\n\nimport { destroyKosModel } from \"../util\";\nimport { ObservableData, type KosData } from \"../util/observable-proxy-map\";\nimport { KosContextManager } from \"./context/kos-context-manager\";\nimport { ExtensionManager } from \"./extension\";\nimport {\n IKosContainerIndex,\n IndexMapper,\n KosContainerIndex,\n} from \"./kos-container-index\";\nimport type { IKosDataModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\nimport { IKosIdentifiable } from \"./types/model\";\n\nexport interface IKosBaseContainer<T extends IKosIdentifiable> {\n revision: number;\n data: T[];\n idx: KosData<Record<string, Record<string, T[]>>>;\n index: Map<string, IKosContainerIndex<T>>;\n indexKeys: Record<string, string[] | undefined>;\n addModel: (model: T) => void;\n removeModel: (id: string) => void;\n addAll: (models: T[]) => void;\n removeAll: (ids: string[]) => void;\n getModel: (id: string) => T | undefined;\n increment: () => void;\n clear: () => Promise<void>;\n map: (typeof Array.prototype)[\"map\"];\n filter: (typeof Array.prototype)[\"filter\"];\n sort: (typeof Array.prototype)[\"sort\"];\n [Symbol.iterator](): IterableIterator<T>;\n}\n\nfunction observeComputedProperties(model, callback, keys: string[] = []) {\n // Get descriptors for all properties\n const descriptors = Object.getOwnPropertyDescriptors(model);\n\n // Filter to get only computed properties\n const computedProps = Object.keys(descriptors).filter((key) =>\n isComputedProp(model, key)\n );\n\n // Set up a reaction for each computed property\n const disposers = computedProps\n .filter((p) => keys.includes(p))\n .map((prop) =>\n reaction(\n () => model[prop], // Track the computed property\n (newValue, oldValue) => {\n // Call the callback with change details\n callback({ name: prop, newValue, oldValue });\n }\n )\n );\n\n // Return a function to dispose all reactions when needed\n return disposers;\n}\nexport interface IKosModelContainer<T extends IKosDataModel>\n extends IKosBaseContainer<T> {\n updateModel: (model: T) => void;\n getModel: (id: string) => T | undefined;\n getIndexByKey: (indexName: string, indexKey: string) => T[];\n getIndexKeys: (indexName: string) => string[];\n}\nconst log = KosLog.createLogger({ name: \"kos-container-model\" });\ntype PropType = string | number | symbol | undefined;\n\ninterface ContainerOptions<T extends IKosDataModel> {\n sortKey?: keyof T;\n indexMap?: Record<string, keyof T | IndexMapper<T>>;\n parentId?: string;\n extensionId?: string;\n}\nexport class KosModelContainer<T extends IKosDataModel>\n implements IKosModelContainer<T>\n{\n _data: Map<string, T>;\n private _sortKey?: PropType;\n private _revision: number;\n private _index: Map<string, IKosContainerIndex<T>>;\n private _optionsMap: ContainerOptions<T>[\"indexMap\"];\n private _disposerMap: Map<string, () => void> = new Map();\n private _parentId?: string;\n idx: KosData<Record<string, Record<string, T[]>>>;\n constructor(options?: ContainerOptions<T>) {\n this._data = observable.map(new Map());\n\n this._sortKey = options?.sortKey;\n this._revision = 1;\n const extensionOptions = options?.extensionId\n ? (ExtensionManager.indexExtension.loadIndexExtensions(\n options.extensionId\n ) as Record<string, keyof T | IndexMapper<T>>)\n : ({} as Record<string, keyof T | IndexMapper<T>>);\n const indexMap = options?.indexMap || {};\n this._optionsMap = { ...indexMap, ...extensionOptions };\n\n const tmp = options?.indexMap\n ? Object.keys(options.indexMap).reduce((acc, curr) => {\n acc[curr] = undefined;\n return acc;\n }, {})\n : {};\n this._index = observable.map(tmp);\n this.idx = ObservableData();\n this._parentId = options?.parentId;\n\n makeAutoObservable(this);\n this.init();\n }\n\n init() {\n Object.keys(this._optionsMap!).forEach((key) => {\n const modelKey = this._optionsMap![key];\n const idx = new KosContainerIndex<T>({\n container: this,\n key: modelKey,\n });\n this._index.set(key, idx);\n this.idx[key] = idx.data;\n });\n }\n [Symbol.iterator]() {\n return this.data[Symbol.iterator]();\n }\n\n get index() {\n return this._index;\n }\n get revision() {\n return this._revision;\n }\n\n get indexKeys() {\n return Array.from(this.index.keys()).reduce<\n Record<string, string[] | undefined>\n >((acc, curr) => {\n acc[curr] = this.index.get(curr)?.keys;\n return acc;\n }, {});\n }\n\n sortFn(a, b): number {\n const sortKey = this._sortKey;\n\n if (sortKey) {\n return String(a[sortKey]).localeCompare(String(b[sortKey]), undefined, {\n numeric: true,\n });\n }\n return 0;\n }\n\n get data() {\n const list = Array.from(this._data.values());\n\n if (this._sortKey) {\n list.sort(this.sortFn.bind(this));\n }\n return list;\n }\n\n increment() {\n kosAction(() => {\n this._revision = this._revision + 1;\n });\n }\n\n addAll(models: T[]) {\n kosAction(() => {\n models.forEach((model) => this.addModel(model, true));\n });\n this.increment();\n }\n\n removeAll(ids: string[]) {\n kosAction(() => {\n ids.forEach((id) => this.removeModel(id, true));\n this.increment();\n });\n }\n\n addModel(model: T, defer?: boolean) {\n this._data.set(model.id || \"\", model);\n if (model.id && this._parentId) {\n KosContextManager.setParentContext(model.id, this._parentId);\n }\n if (!defer) {\n this.increment();\n }\n const _disposer = this._disposerMap.get(model.id);\n if (_disposer) {\n _disposer();\n this._disposerMap.delete(model.id);\n }\n const _entries = Object.entries(this._optionsMap || {});\n const _values = Object.values(this._optionsMap || {});\n const _reverseMap = new Map(_entries.map(([k, v]) => [v, k]));\n const handler = (change) => {\n // if any of the index keys change refresh that specific index\n if (_values.includes(change.name as any)) {\n this.index.get(_reverseMap.get(change.name) as string)?.refresh();\n }\n // refresh all of the function based indexes.\n // could look to optimize this if needed but it would require a react hooks-like\n // dependency tracking system.\n const fnIndexs = _entries.filter(\n ([, value]) => typeof value === \"function\"\n );\n\n for (const [key] of fnIndexs) {\n this.index.get(key)?.refresh();\n }\n };\n const computedDisposers = observeComputedProperties(\n model,\n handler,\n _values.filter((v) => typeof v === \"string\") as string[]\n );\n const disposer = observe(model, handler);\n this._disposerMap.set(model.id || \"\", () =>\n [disposer, ...computedDisposers].forEach((d) => d())\n );\n }\n\n removeModel(id: string, defer?: boolean) {\n this._data.delete(id);\n if (!defer) {\n this.increment();\n }\n const disposer = this._disposerMap.get(id);\n if (disposer) {\n disposer();\n this._disposerMap.delete(id);\n }\n }\n\n updateModel(model: T) {\n this._data.set(model.id || \"\", model);\n this.increment();\n }\n\n getModel(id: string) {\n return this._data.get(id);\n }\n\n getIndexKeys(indexName: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n return idx.keys ?? [];\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n getIndexByKey(indexName: string, indexKey: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n if (idx.index.has(indexKey)) {\n return idx.getByKey(indexKey);\n } else {\n log.info(\n `key ${indexKey} not found in ${indexName} index: ${Array.from(\n idx.index.keys()\n )}`\n );\n return [];\n }\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n\n async clear() {\n this._data.forEach((model) => {\n const modelId = model.id;\n destroyKosModel(model)\n .then(() => {\n log.debug(`${modelId} destroyed, removing from map`);\n this.removeModel(modelId!, true);\n })\n .catch((e) => log.error(e));\n });\n this.increment();\n }\n\n filter<S extends any>(\n predicate: (value: any, index: number, array: any[]) => value is S,\n thisArg?: any\n ) {\n return this.data.filter(predicate, thisArg);\n }\n\n sort(compareFn?: ((a: any, b: any) => number) | undefined) {\n return this.data.sort(compareFn);\n }\n map<U>(\n callbackfn: (value: any, index: number, array: any[]) => U,\n thisArg?: any\n ) {\n return this.data.map(callbackfn, thisArg);\n }\n\n forEach(\n callbackfn: (value: any, index: number, array: any[]) => void,\n thisArg?: any\n ) {\n this.data.forEach(callbackfn, thisArg);\n }\n}\n","import {\n isObservable,\n runInAction as kosAction,\n makeAutoObservable,\n observable,\n observe,\n} from \"mobx\";\n\nimport { ObservableData, type KosData } from \"../util/observable-proxy-map\";\nimport {\n IKosContainerIndex,\n IndexMapper,\n KosContainerIndex,\n} from \"./kos-container-index\";\nimport { IKosBaseContainer } from \"./kos-container-model\";\nimport { KosLog } from \"./log\";\nimport { IKosIdentifiable } from \"./types/model\";\n\nexport interface IKosDataContainer<T extends IKosIdentifiable>\n extends IKosBaseContainer<T> {\n updateModel: (model: T) => void;\n getModel: (id: string) => T | undefined;\n getIndexByKey: (indexName: string, indexKey: string) => T[];\n getIndexKeys: (indexName: string) => string[];\n}\nconst log = KosLog.createLogger({ name: \"kos-data-container\" });\ntype PropType = string | number | symbol | undefined;\n\ninterface ContainerOptions<T extends IKosIdentifiable> {\n sortKey?: keyof T;\n indexMap?: Record<string, keyof T | IndexMapper<T>>;\n}\nexport class KosDataContainer<T extends IKosIdentifiable>\n implements IKosDataContainer<T>\n{\n _data: Map<string, T>;\n private _sortKey?: PropType;\n private _revision: number;\n private _index: Map<string, IKosContainerIndex<T>>;\n private _optionsMap: ContainerOptions<T>[\"indexMap\"];\n private _disposerMap: Map<string, () => void> = new Map();\n idx: KosData<Record<string, Record<string, T[]>>>;\n constructor(options?: ContainerOptions<T>) {\n this._data = observable.map(new Map());\n this._sortKey = options?.sortKey;\n this._revision = 1;\n this._optionsMap = options?.indexMap || {};\n const tmp = options?.indexMap\n ? Object.keys(options.indexMap).reduce((acc, curr) => {\n acc[curr] = undefined;\n return acc;\n }, {})\n : {};\n this._index = observable.map(tmp);\n this.idx = ObservableData();\n makeAutoObservable(this, {});\n this.init();\n }\n\n init() {\n Object.keys(this._optionsMap!).forEach((key) => {\n const modelKey = this._optionsMap![key];\n const idx = new KosContainerIndex<T>({\n container: this,\n key: modelKey,\n });\n this._index.set(key, idx);\n this.idx[key] = idx.data;\n });\n }\n\n [Symbol.iterator]() {\n return this.data[Symbol.iterator]();\n }\n\n get index() {\n return this._index;\n }\n\n get indexKeys() {\n return Array.from(this.index.keys()).reduce<\n Record<string, string[] | undefined>\n >((acc, curr) => {\n acc[curr] = this.index.get(curr)?.keys;\n return acc;\n }, {});\n }\n\n get revision() {\n return this._revision;\n }\n\n addAll(models: T[]) {\n kosAction(() => {\n models.forEach((model) => this.addModel(model));\n });\n }\n\n removeAll(ids: string[]) {\n kosAction(() => {\n ids.forEach((id) => this.removeModel(id));\n });\n }\n\n sortFn(a, b): number {\n const sortKey = this._sortKey;\n\n if (sortKey) {\n return String(a[sortKey]).localeCompare(String(b[sortKey]), undefined, {\n numeric: true,\n });\n }\n return 0;\n }\n\n get data() {\n const list = Array.from(this._data.values());\n\n if (this._sortKey) {\n list.sort(this.sortFn.bind(this));\n }\n return list;\n }\n\n increment() {\n kosAction(() => {\n this._revision = this._revision + 1;\n });\n }\n addModel(model: T, defer?: boolean) {\n const observableData = isObservable(model)\n ? model\n : observable.object(model);\n const _disposer = this._disposerMap.get(model.id);\n if (_disposer) {\n _disposer();\n this._disposerMap.delete(model.id);\n }\n this._data.set(observableData.id || \"\", observableData);\n if (!defer) {\n this.increment();\n }\n\n const disposer = observe(observableData, (change) => {\n if (Object.values(this._optionsMap || {}).includes(change.name as any)) {\n this.increment();\n }\n });\n this._disposerMap.set(observableData.id || \"\", disposer);\n }\n\n removeModel(id: string) {\n this._data.delete(id);\n this.increment();\n const disposer = this._disposerMap.get(id);\n if (disposer) {\n disposer();\n this._disposerMap.delete(id);\n }\n }\n\n updateModel(model: T) {\n const observableData = observable.object(model);\n this._data.set(observableData.id || \"\", observableData);\n this.increment();\n }\n\n getModel(id: string) {\n return this._data.get(id);\n }\n\n getIndexKeys(indexName: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n return idx.keys ?? [];\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n\n getIndexByKey(indexName: string, indexKey: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n if (idx.index.has(indexKey)) {\n return idx.getByKey(indexKey);\n } else {\n log.info(\n `key ${indexKey} not found in ${indexName} index: ${Array.from(\n idx.index.keys()\n )}`\n );\n return [];\n }\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n\n async clear() {\n this._data.clear();\n this.increment();\n }\n\n filter<S extends any>(\n predicate: (value: any, index: number, array: any[]) => value is S,\n thisArg?: any\n ) {\n return this.data.filter(predicate, thisArg);\n }\n\n sort(compareFn?: ((a: any, b: any) => number) | undefined) {\n return this.data.sort(compareFn);\n }\n map<U>(\n callbackfn: (value: any, index: number, array: any[]) => U,\n thisArg?: any\n ) {\n return this.data.map(callbackfn, thisArg);\n }\n\n forEach(\n callbackfn: (value: any, index: number, array: any[]) => void,\n thisArg?: any\n ) {\n this.data.forEach(callbackfn, thisArg);\n }\n}\n","import {\n IdentifiableModelFactory,\n KosIdentifiableModelRegistration,\n KosModelClassRegistration,\n KosSingletonModelClassRegistration,\n SingletonFactory,\n} from \"../types\";\nimport { isKosModel } from \"../util\";\nimport { Kos } from \"./kos-model-factory\";\nimport { IKosDataModel, KosCreationContext } from \"./kosModel\";\n\ntype IdentifiableChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosModelClassRegistration<T, O> & {\n singleton: false;\n factory: IdentifiableModelFactory<T, O>;\n};\n\ntype SingletonChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n singleton: true;\n factory: SingletonFactory<T, O>;\n};\n\ntype ChildRegistration<\n T extends IKosDataModel = any,\n O extends object = Record<string, any>\n> = IdentifiableChildRegistration<T, O> | SingletonChildRegistration<T, O>;\n\ntype Reg<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosIdentifiableModelRegistration<T, O> & {\n singleton: false;\n factory: IdentifiableModelFactory<T, O>;\n};\ninterface ModelRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n [k: string]: Reg<T, O>;\n}\ninterface RegistrationProps<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n}\nexport class KosRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n childRegistration?: any;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n constructor({ type, model, childRegistration }: RegistrationProps<T, O>) {\n this.type = type;\n this.model = model;\n this.childRegistration = childRegistration;\n }\n\n get factory() {\n return Kos.Factory.create<T, O>(this.type);\n }\n\n get registration(): ModelRegistration<T, O> {\n return {\n [this.type]: {\n class: this.model,\n singleton: false,\n factory: this.factory,\n },\n ...this.childRegistration,\n } as ModelRegistration<T, O>;\n }\n\n get predicate() {\n return isKosModel<T>(this.type);\n }\n}\n","import {\n IdentifiableModelFactory,\n KosIdentifiableModelRegistration,\n KosSingletonModelClassRegistration,\n SingletonFactory,\n} from \"../types\";\nimport { isKosModel } from \"../util\";\nimport { Kos } from \"./kos-model-factory\";\nimport { IKosDataModel, KosCreationContext } from \"./kosModel\";\n\ntype IdentifiableChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosIdentifiableModelRegistration<T, O> & {\n factory: IdentifiableModelFactory<T, O>;\n};\n\ntype SingletonChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n factory: SingletonFactory<T, O>;\n};\n\ntype ChildRegistration<\n T extends IKosDataModel = any,\n O extends object = Record<string, any>\n> = IdentifiableChildRegistration<T, O> | SingletonChildRegistration<T, O>;\n\ntype Reg<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n factory: SingletonFactory<T, O>;\n};\ninterface Singleton<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n [k: string]: Reg<T, O>;\n}\n\ninterface RegistrationProps<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n}\nexport class KosSingletonRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n constructor({ type, model, childRegistration }: RegistrationProps<T, O>) {\n this.type = type;\n this.model = model;\n this.childRegistration = childRegistration;\n }\n\n get factory() {\n return Kos.Singleton.create<T, O>(this.type);\n }\n\n get registration(): Singleton<T, O> {\n return {\n [this.type]: {\n class: this.model,\n singleton: true,\n factory: this.factory,\n },\n ...this.childRegistration,\n } as Singleton<T, O>;\n }\n\n get predicate() {\n return isKosModel<T>(this.type);\n }\n}\n","import { makeAutoObservable } from \"mobx\";\nimport { EventBus } from \"../../../../common\";\n\nexport interface IKosToken {\n token?: string;\n}\nclass KosToken implements IKosToken {\n private _token?: string;\n constructor() {\n makeAutoObservable(this);\n EventBus.subscribe(\"token\", (token) => {\n this.token = token?.body;\n });\n }\n\n get token() {\n return this._token;\n }\n\n set token(token) {\n this._token = token;\n }\n}\n\nexport default KosToken;\n","// Extracts route parameter names from a path like \"/user/:id/profile/:section\"\ntype ExtractParams<T extends string> =\n T extends `${infer _Start}/:${infer Param}/${infer Rest}`\n ? { [K in Param | keyof ExtractParams<`/${Rest}`>]: string }\n : T extends `${infer _Start}/:${infer Param}`\n ? { [K in Param]: string }\n : {};\n\nexport type KosMethodTypes = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\nexport type KosRequest<TPath extends string = string> = {\n id: string;\n method: string;\n path: TPath;\n params: ExtractParams<TPath>;\n query?: Record<string, string>;\n body?: any;\n};\n\nexport type KosResponse = {\n send: (data: any) => void;\n status?: (code: number) => KosResponse;\n};\n\nexport type RouteMetadata = {\n method: string;\n path: string;\n description?: string;\n parameters?: any[]; // OpenAPI-compliant parameter definitions\n};\n\nexport type KosMiddleware<TPath extends string = string> = (\n req: KosRequest<TPath>,\n res: KosResponse,\n next: () => Promise<void> | void\n) => Promise<void> | void;\n\nexport class BrowserKosRouter {\n private routes: {\n method: string;\n path: string;\n middlewares: KosMiddleware<any>[];\n }[] = [];\n private openApiRoutes: RouteMetadata[] = [];\n\n use<TPath extends string = string>(\n method: string,\n path: TPath,\n ...middlewares: KosMiddleware<TPath>[]\n ) {\n this.routes.push({ method, path, middlewares });\n\n // Extract route parameters for OpenAPI\n const params = this.extractOpenApiParams(path);\n\n this.openApiRoutes.push({\n method,\n path,\n parameters: params,\n });\n }\n\n async handle(rawReq: Omit<KosRequest, \"params\" | \"query\">, res: KosResponse) {\n const { path, query, params } = this.extractPathParams(rawReq.path);\n const req: KosRequest = { ...rawReq, params, query };\n\n for (const route of this.routes) {\n const match = this.matchRoute(route.path, path);\n if (route.method === rawReq.method && match) {\n req.params = match; // Inject extracted path parameters\n let index = 0;\n\n const next = async () => {\n if (index < route.middlewares.length) {\n const middleware = route.middlewares[index++];\n await middleware(req, res, next);\n }\n };\n\n await next();\n return;\n }\n }\n\n res.status?.(404).send({ error: \"Route not found\" });\n }\n\n private extractOpenApiParams(routePath: string) {\n return routePath\n .split(\"/\")\n .filter((part) => part.startsWith(\":\"))\n .map((param) => {\n return {\n name: param.slice(1),\n in: \"path\",\n required: true,\n schema: { type: \"string\" },\n };\n });\n }\n\n generateOpenApiSpec() {\n const paths: Record<string, any> = {};\n\n for (const route of this.openApiRoutes) {\n if (!paths[route.path]) paths[route.path] = {};\n\n paths[route.path][route.method.toLowerCase()] = {\n summary: route.description || `Handles ${route.method} ${route.path}`,\n parameters: route.parameters || [],\n responses: {\n \"200\": {\n description: \"Successful response\",\n },\n },\n };\n }\n\n return {\n openapi: \"3.0.0\",\n info: {\n title: \"Kos Router API\",\n version: \"1.0.0\",\n description: \"Dynamically generated OpenAPI documentation\",\n },\n paths,\n };\n }\n\n private extractPathParams(requestPath: string) {\n const [path, queryString] = requestPath.split(\"?\");\n const query = this.parseQueryParams(queryString);\n\n for (const route of this.routes) {\n const match = this.matchRoute(route.path, path);\n if (match) {\n return { path, query, params: match };\n }\n }\n\n return { path, query, params: {} };\n }\n\n private matchRoute(\n routePath: string,\n requestPath: string\n ): Record<string, string> | null {\n const routeParts = routePath.split(\"/\").filter(Boolean);\n const requestParts = requestPath.split(\"/\").filter(Boolean);\n\n if (routeParts.length !== requestParts.length) return null;\n\n const params: Record<string, string> = {};\n for (let i = 0; i < routeParts.length; i++) {\n if (routeParts[i].startsWith(\":\")) {\n params[routeParts[i].slice(1)] = decodeURIComponent(requestParts[i]);\n } else if (routeParts[i] !== requestParts[i]) {\n return null;\n }\n }\n return params;\n }\n\n private parseQueryParams(queryString?: string): Record<string, string> {\n if (!queryString) return {};\n return queryString.split(\"&\").reduce((acc, param) => {\n const [key, value] = param.split(\"=\").map(decodeURIComponent);\n acc[key] = value ?? \"\";\n return acc;\n }, {} as Record<string, string>);\n }\n}\n","import { ApiCallback, EventBus } from \"../../../common\";\n\ntype IntentHandler = (props: any) => void;\n\ninterface Intent {\n type: string;\n options: any;\n}\nconst { unsubscribe: unsubscribeIntentService } = EventBus.subscribe(\n \"kos.intent\",\n (msg?: ApiCallback<Intent>) => {\n if (msg) {\n const intent = msg.body;\n const topic = intent.type;\n fireIntent(topic, intent.options);\n }\n }\n);\nconst intentMap = new Map<string, IntentHandler[]>();\nconst registerIntentHandler = (topic: string, handler: IntentHandler) => {\n const existingHandlers = intentMap.get(topic) || [];\n existingHandlers.push(handler);\n intentMap.set(topic, existingHandlers);\n};\n\nconst fireIntent = <T extends {} = {}>(topic: string, options: T) => {\n if (intentMap.has(topic)) {\n const handlers = intentMap.get(topic)!;\n handlers[0].call(undefined, options);\n }\n};\n\nexport { fireIntent, registerIntentHandler, unsubscribeIntentService };\n","export enum KosFetchMethods {\n GET = `GET`,\n PUT = `PUT`,\n POST = `POST`,\n DELETE = `DELETE`,\n}\n\ntype FetchMethodStrings = keyof typeof KosFetchMethods;\n\nexport interface Headers {\n append(name: string, value: string): void;\n delete(name: string): void;\n get(name: string): string | null;\n has(name: string): boolean;\n set(name: string, value: string): void;\n forEach(\n callbackfn: (value: string, key: string, parent: Headers) => void,\n thisArg?: any\n ): void;\n}\n\ninterface Body {\n readonly body: ReadableStream<Uint8Array> | null;\n readonly bodyUsed: boolean;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n formData(): Promise<FormData>;\n json<T = any>(): Promise<T | null>;\n text(): Promise<string>;\n}\n\nexport interface Response extends Body {\n readonly headers: Headers;\n readonly ok: boolean;\n readonly redirected: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly type: ResponseType;\n readonly url: string;\n clone(): Response;\n}\n\n/**\n * Represents the configuration options for performing a Kos WebSocket fetch operation.\n */\nexport interface KosFetchOptions {\n /**\n * The HTTP method for the request (e.g., 'GET', 'POST', 'PUT', 'DELETE', etc.).\n */\n method: FetchMethodStrings;\n\n /**\n * The request body as a string.\n */\n body?: string;\n\n /**\n * Indicates whether the request should be ordered.\n */\n ordered?: boolean;\n\n /**\n * The destination address for the WebSocket request.\n */\n destinationAddress?: string;\n\n /**\n * @internal\n */\n signal?: AbortSignal;\n\n /**\n * The tracker associated with the request.\n */\n tracker?: string;\n\n /**\n * @internal\n */\n studio?: boolean;\n\n /**\n * @internal\n */\n fos?: boolean;\n\n /**\n * @internal\n */\n bridge?: boolean;\n\n timeout?: number;\n}\n\nexport interface KosFetchResponse {\n headers: Headers;\n status: string | number | boolean;\n ok: boolean;\n json: <\n T = Record<string | number | symbol, string | number | symbol>\n >() => Promise<T>;\n body: ReadableStream<Uint8Array> | null;\n}\n\nexport interface KosFetchReqeust {\n path: string;\n requestId: string;\n method: FetchMethodStrings;\n destinationAddress?: string;\n ordered?: boolean;\n tracker?: string;\n bridge?: boolean;\n}\n\nexport interface KosMessageRequest\n extends Omit<KosFetchReqeust, \"method\" | \"path\" | \"requestId\"> {\n requestType: string;\n requestId?: string;\n headers?: Record<string, string>;\n}\nexport interface KosBroadcastRequest {\n topic: string;\n}\n\nexport interface KosMessageOptions extends KosBroadcastRequest {\n destinationAddress?: string;\n responseId?: string;\n type?: string;\n}\n\nexport interface KosHttpMessageOptions {\n destinationAddress: string;\n sourceAddress: string;\n responseId: string;\n status: number;\n type: string;\n contentType?: string;\n}\n\nexport interface KosFetchResponseParams {\n path: string;\n responseId?: string;\n destinationAddress: string;\n status: string | number | boolean;\n}\n\nexport interface KosFetchPostReqeust extends KosFetchReqeust {\n body?: string;\n}\n","import {\n autorun,\n computed,\n makeAutoObservable,\n makeObservable,\n observable,\n reaction,\n runInAction,\n when,\n} from \"mobx\";\nexport * from \"./core/api\";\nexport * from \"./core/context\";\nexport * from \"./core/decorators\";\nexport * from \"./core/extension\";\nexport * from \"./core/kos-container-index\";\nexport * from \"./core/kos-container-model\";\nexport * from \"./core/kos-data-container\";\nexport * from \"./core/kos-model-factory\";\nexport * from \"./core/kos-registration\";\nexport * from \"./core/kos-singleton-registration\";\nexport * from \"./core/kosCore\";\nexport * from \"./core/kosModel\";\nexport * from \"./core/kosModelManager\";\nexport { KosModelEvents, KosModelState } from \"./core/lifecycle\";\nexport * from \"./core/log\";\nexport * from \"./core/models\";\nexport { default as KosToken } from \"./core/models/kos-token\";\nexport {\n KosModelRegistrationFactory,\n preloadKosModel,\n registerCompanionModel,\n registerKosModel,\n registerLegacyModel,\n RegistrationManager,\n SingletonKosModelRegistrationFactory,\n type RegistrationResult,\n} from \"./core/registration\";\nexport * from \"./core/services\";\nexport * from \"./core/transport\";\nexport * from \"./core/types\";\nexport * from \"./types\";\nexport * from \"./util\";\nexport {\n kosAction,\n kosAutoEffect,\n kosComputed,\n kosEffect,\n kosObservable,\n kosWhen,\n makeAutoObservable,\n makeObservable,\n};\n\n/**\n * {@inheritDoc when}\n * @category Utility\n */\nconst kosWhen = when;\n\n/**\n * {@inheritDoc computed}\n * @category Utility\n */\nconst kosComputed = computed;\n/**\n * {@inheritDoc runInAction}\n * @category Utility\n */\nconst kosAction = runInAction;\n\n/**\n * Creates a named reactive view and keeps it alive, so that the view is always updated if one of the dependencies changes, even when the view is not further used by something else.\n *\n * @param view — The reactive view\n *\n * @returns — disposer function, which can be used to stop the view from being updated in the future.\n * @category Utility\n */\nconst kosAutoEffect = autorun;\n\n/**\n * {@inheritDoc reaction}\n * @category Utility\n */\nconst kosEffect = reaction;\n\n/**\n * {@inheritDoc observable}\n * @category Utility\n */\nconst kosObservable = observable;\n","export {};\n\nexport const FUTURE_NOT_ASSIGNED = \"Not Assigned\";\nexport const EVENT_TROUBLE_ADDED = \"kos.trouble.added\";\nexport const EVENT_TROUBLE_REMOVED = \"kos.trouble.removed\";\nexport enum KosCoreModelPropertyMapper {\n TroubleRank = \"kos.trouble.rank.mapper\",\n TroubleColor = \"kos.trouble.color.mapper\",\n TroubleRole = \"kos.trouble.role.mapper\",\n}\n\n/**\n * Enum for the different message bus topics that are used in the KOS system.\n */\nexport enum Topics {\n TIME_CHANGE = \"/kos/internal/time/time\",\n DAY_CHANGE = \"/kos/internal/time/day\",\n TIMEZONE_CHANGE = \"/kos/internal/time/timezone\",\n}\n","import { BASE_URL, KosLog, ServiceFactory } from \"../../../core\";\nimport { ConfigPropertyTypes } from \"../../models\";\n\nconst log = KosLog.createLogger({\n name: \"config-bean-service\",\n group: \"Services\",\n});\n\nconst URL = BASE_URL;\n\n/**\n * @category Service Module\n * @name /services/config-bean\n * @version 1.0.0\n * @author Mark Pomerant <mpomerant@coca-cola.com>\n *\n * Services that can be invoked to perform operations on Config Beans\n */\n\n/**\n * The response from the server when an organization is\n * created or updated\n */\nexport interface ConfigBeanResponse {\n scopes: string[];\n details: ConfigBeanDetailsResponse[];\n}\n\nexport interface ConfigScope {\n scope: string;\n overrides?: Record<string, ConfigPropertyTypes>;\n}\n\nexport interface ConfigBeanDetailsResponse {\n bean: {\n [key: string]: ConfigPropertyTypes;\n };\n scopes: ConfigScope[];\n schema: SchemaResponse;\n}\n\nexport interface ConfigBeanRequest {\n [k: string]: ConfigPropertyTypes;\n}\n\nexport interface DecimalOption {\n decimals: number;\n}\n\nexport const hasDecimals = (option?: any): option is DecimalOption =>\n (option as DecimalOption)?.decimals !== undefined;\nexport type SchemaNodeType = \"String\" | \"int\" | \"boolean\" | \"double\";\nexport interface UnitSystemKeypadOptions {\n unitSystems: {\n [k: string]: {\n min: number;\n max: number;\n decimals: number;\n };\n };\n type: \"unitSystemKeypad\";\n}\n\nexport interface UnitSystemListOptions {\n type: \"unitSystemList\";\n unitSystems: {\n [k: string]: {\n list: string[];\n };\n };\n}\n\nexport interface UnitSystemRangeCountOptions {\n type: \"unitSystemRangeCount\";\n unitSystems: {\n [k: string]: {\n start: number;\n end: number;\n count: number;\n decimals: number;\n };\n };\n}\n\nexport interface UnitSystemRangeIntervalOptions {\n type: \"unitSystemRangeInterval\";\n unitSystems: {\n [k: string]: {\n start: number;\n end: number;\n interval: number;\n decimals: number;\n };\n };\n}\nexport interface KeypadOptions {\n min: number;\n max: number;\n decimals: number;\n type: \"keypad\";\n}\n\nexport interface RangeCountOptions {\n type: \"rangeCount\";\n start: number;\n end: number;\n count: number;\n decimals: number;\n}\n\nexport interface RangeIntervalOptions {\n type: \"rangeInterval\";\n start: number;\n end: number;\n interval: number;\n decimals: number;\n}\nexport interface ListOptions {\n type: \"list\";\n list: string[];\n}\n\nexport type SchemaOptionsType =\n | KeypadOptions\n | RangeCountOptions\n | RangeIntervalOptions\n | ListOptions\n | UnitSystemKeypadOptions\n | UnitSystemListOptions\n | UnitSystemRangeCountOptions\n | UnitSystemRangeIntervalOptions;\n\nexport interface SchemaNode {\n type: SchemaNodeType;\n format?: string;\n options: SchemaOptionsType;\n}\n\nexport interface EnumSchemaNode {\n type: \"enum\";\n format?: string;\n values: string[];\n}\n\nexport type SchemaNodeDef = SchemaNode | EnumSchemaNode;\nexport interface SchemaResponse {\n paths: string[];\n schema: {\n [key: string]: SchemaNodeDef;\n };\n}\n\nconst { postModel, getOne } = ServiceFactory.build({\n destinationAddress: \"\",\n basePath: `${URL}/kos/config/`,\n});\n\ninterface ConfigBeanUpdateRecord {\n attr: string;\n currentValue: string;\n previousValue: string;\n}\n\nexport interface ConfigBeanUpdateResponse {\n changes: ConfigBeanUpdateRecord[];\n errors: string[];\n}\n/**\n * Modifies an ConfigBean from the server based on the id.\n *\n * @param id - the id of the ConfigBean to be modified\n * @returns an empty response with status 200.\n */\nexport const modifyConfigBean = async (\n id: string,\n model: ConfigBeanRequest,\n path = `/api/kos/config`\n) => {\n log.debug(`sending modify request for ConfigBean: ${id}`);\n const response = postModel({\n model,\n urlOverride: `${URL}${path}/${id}`,\n });\n return response;\n};\n\n/**\n * Modifies an ConfigBean from the server based on the id.\n *\n * @param id - the id of the ConfigBean to be modified\n * @returns an empty response with status 200.\n */\nexport const getConfigBean = async (id: string, path = `/api/kos/config`) => {\n log.debug(`sending get request for ConfigBean: ${id}`);\n const response = await getOne<ConfigBeanResponse>({\n urlOverride: `${URL}${path}/details/${id}/15`,\n });\n return response;\n};\n","export const isBoolean = (val: string) =>\n val.toLowerCase() === \"true\" || val.toLowerCase() === \"false\";\n\nexport const isNumber = (val: string) => {\n try {\n const result = Number(val);\n return !isNaN(result);\n } catch (e) {\n return false;\n }\n};\n","import { runInAction } from \"mobx\";\nimport { ModelFactory } from \"../../../core\";\nimport {\n ConfigBeanRequest,\n ConfigBeanResponse,\n ConfigBeanUpdateResponse,\n type ConfigScope,\n} from \"../../services/config-bean\";\nimport { isBoolean, isNumber } from \"../../utils/prop-utils\";\nimport { ConfigPropertyTypes } from \"../types\";\nimport type { IConfigBeanModel } from \"./config-bean-model\";\nimport type { IConfigBeanModelOptions } from \"./config-bean-types\";\n\nexport function evaluateScopes(scopes: ConfigScope[] = []) {\n return scopes.reverse().reduce((acc, curr) => {\n const { overrides } = curr;\n if (overrides) {\n acc = { ...acc, ...overrides };\n }\n return acc;\n }, {});\n}\nfunction flattenObject(obj: any, parentKey = \"\", result = {}) {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n // Construct new key for the flattened object\n const newKey = parentKey ? `${parentKey}.${key}` : key;\n\n if (\n typeof obj[key] === \"object\" &&\n obj[key] !== null &&\n !Array.isArray(obj[key])\n ) {\n // Recursively flatten for nested objects\n flattenObject(obj[key], newKey, result);\n } else {\n // Assign value to the new key in the flattened object\n result[newKey] = obj[key];\n }\n }\n }\n return result;\n}\n/**\n * Maps a `ConfigBeanResponse` DTO to an `IConfigBeanModel` object.\n *\n * @remarks\n * This function will run as a mobx action ensuring that all observers are notified\n * if any changes are made.\n *\n * @params dto - the Data Transfer Object received from the backend\n * @params model - the IModel to be update\n *\n * @internal\n * @category Config Bean\n */\nexport const mapDtoToConfigBeanModel = (\n dto: ConfigBeanResponse,\n model: IConfigBeanModel\n) => {\n const bean = dto.details[0].bean || evaluateScopes(dto.details[0].scopes);\n const flattened = flattenObject(bean);\n runInAction(() => {\n const values = {\n ...flattened,\n };\n\n model.props.setValues(values);\n });\n};\n\nexport const mapUpdateDtoToConfigBeanModel = (\n dto: ConfigBeanUpdateResponse,\n model: IConfigBeanModel\n) => {\n runInAction(() => {\n dto.changes.forEach((change) => {\n const key = change.attr;\n let val: ConfigPropertyTypes = change.currentValue;\n let previousValue: ConfigPropertyTypes = change.previousValue;\n\n if (typeof val === \"string\" && isBoolean(val)) {\n val = val.toLowerCase() == \"true\";\n previousValue = (previousValue as string)?.toLowerCase() == \"true\";\n }\n\n if (typeof val === \"string\" && isNumber(val)) {\n val = Number(val);\n previousValue = Number(previousValue);\n }\n\n model.props[key] = val;\n model.prevProps[key] = previousValue;\n });\n });\n};\n\n/**\n * Maps a `IConfigBeanModel` to a `ConfigBeanRequest` DTO that can be sent to the\n * server as part of a service request.\n *\n * @remarks\n * This function will perform any type conversion or data mapping required\n * by the `ConfigBeanRequest`.\n *\n * @params model - instance of the `IConfigBeanModel`\n * @returns - a valid `ConfigBeanRequest` that can be used to\n * instantiate a new model.\n *\n * @internal\n * @category Config Bean\n */\nexport const mapConfigBeanModelToDto = (model: IConfigBeanModel) => {\n const dto: ConfigBeanRequest = Object.fromEntries(model.props.entries);\n\n return dto;\n};\n\n/**\n * Curried function that will produce a function that can be used to retreive or create\n * new instances of a `IConfigBeanModel` given an ID and options.\n *\n * @remarks\n * This serves as a conveinience allowing for models to consumers to use a shorthand method when\n * multiple models need to be created.\n * The first level of function will accept a KOS Model Factory and return a function that can accept a single\n * model ID parameeter. This will return a factory function that can accept a model options parameter and\n * instantiate a new instance of a model or retreive a an existing model.\n *\n * @param factory - the model factory to be used\n * @returns - an instance of the `IConfigBeanModel` that was either created\n * or retrieved from the KOS Model framework if already existing.\n *\n * @internal\n * @category Config Bean\n */\nexport const buildConfigBeanModel =\n (factory: ModelFactory<IConfigBeanModel, IConfigBeanModelOptions>) =>\n (modelId: string) =>\n (configBeanOptions: IConfigBeanModelOptions) => {\n const configBeanModel = factory.build(modelId, configBeanOptions);\n return configBeanModel;\n };\n","import type {\n IKosDataModel,\n KosData,\n PublicModelInterface,\n} from \"../../../core\";\nimport {\n createPropKey,\n kosAction,\n kosModel,\n KosModelRegistrationFactory,\n kosTopicHandler,\n ObservableData,\n} from \"../../../core\";\nimport type {\n ConfigBeanKeys,\n IConfigBeanModelOptions,\n} from \"./config-bean-types\";\n\nimport { KosLog as Logger } from \"../../../core\";\nimport {\n getConfigBean as getConfigBeanService,\n modifyConfigBean as modifyConfigBeanService,\n type ConfigBeanUpdateResponse,\n type SchemaResponse,\n} from \"../../services/config-bean\";\nimport { ConfigPropertyTypes } from \"../types\";\nimport {\n mapConfigBeanModelToDto,\n mapDtoToConfigBeanModel,\n mapUpdateDtoToConfigBeanModel,\n} from \"./config-bean-model-builder\";\n\nexport type IConfigBeanModel<T extends {} = any> = PublicModelInterface<\n ConfigBeanModelImpl<T>\n>;\n\nfunction matchValue(patterns: string[], value: string): string | undefined {\n for (const pattern of patterns) {\n // Convert the pattern to a RegExp object\n const regex = new RegExp(`^${pattern}$`);\n if (regex.test(value)) {\n return pattern; // Return the matching pattern\n }\n }\n return undefined; // No match found\n}\nexport const CONFIG_BEAN_MODEL_TYPE = \"config-bean-model\";\nconst log = Logger.getLogger(CONFIG_BEAN_MODEL_TYPE);\n\nconst PATH_PROP = createPropKey<IConfigBeanModel>(\"path\");\n/**\n * @category Model\n * @name ConfigBeanModel\n * @version 1.0.0\n * @author Mark Pomerant <mpomerant@coca-cola.com>\n *\n * Represents a config bean.\n */\n\n@kosModel(CONFIG_BEAN_MODEL_TYPE)\nclass ConfigBeanModelImpl<T extends {} = any> implements IKosDataModel {\n private _modifyConfigBean: typeof modifyConfigBeanService;\n\n private _getConfigBean: typeof getConfigBeanService;\n\n private _schema?: SchemaResponse;\n id: string;\n path: string;\n props: KosData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>;\n\n prevProps: KosData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>;\n\n serviceBasePath?: string;\n /**\n * @category Constructor\n *\n * @param modelId - the unique modelId for this Config Bean\n * @param options - any options that should be merged into the Config Bean\n * @params options.id - the unique id of the Config Bean\n * @params options.name - the name of the Config Bean\n *\n */\n constructor(modelId: string, options: IConfigBeanModelOptions) {\n Object.assign(this, options);\n\n // assign the id from the passed in model id\n this.id = modelId;\n this.path = options.path;\n this.serviceBasePath = options.serviceBasePath;\n // assign private methods from options\n const {\n modifyConfigBean = modifyConfigBeanService,\n getConfigBean = getConfigBeanService,\n } = options;\n this._modifyConfigBean = modifyConfigBean;\n this._getConfigBean = getConfigBean;\n\n this.props =\n ObservableData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>();\n this.prevProps =\n ObservableData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>();\n }\n\n get values() {\n return this.props.values;\n }\n\n async ready() {\n log.debug(`readying config bean ${this.path}`);\n log.debug(`complete readying config bean ${this.path}`);\n }\n /**\n * @category Lifecycle\n *\n * @remarks\n * No action is taken as part of the load lifecycle method.\n *\n * In future additional information about the worksapce could be loaded\n */\n async load() {\n log.debug(`loading config bean ${this.path}`);\n const response = await this._getConfigBean(this.path, this.serviceBasePath);\n if (response?.data) {\n const data = response.data;\n mapDtoToConfigBeanModel(data, this as IConfigBeanModel<T>);\n log.debug(this.values);\n const schemaResponse = response?.data.details[0].schema;\n kosAction(() => {\n if (schemaResponse) {\n this._schema = schemaResponse;\n }\n });\n }\n }\n\n get schemaKeys() {\n return Object.keys(this._schema?.schema || {});\n }\n\n getSchemaForProperty(key: string) {\n if (this.schemaKeys.includes(key)) {\n return this._schema?.schema[key];\n }\n const match = matchValue(this.schemaKeys, key);\n if (match) {\n return this._schema?.schema[match];\n }\n return undefined;\n }\n\n // -------------------ACTIONS----------------------------\n\n async updateProperty(key: ConfigBeanKeys<T>, value: ConfigPropertyTypes) {\n this.props[key as string] = value;\n await this.updateConfigBean();\n }\n /**\n * @category Action\n *\n * @remark\n * Updates the current Config Bean representation in the backend.\n *\n * If a service was passed in as part of the options in the constructor\n * then it will be used. Otherwise the default services will be invoked.\n *\n * @see modifyConfigBeanService\n */\n async updateConfigBean() {\n const request = mapConfigBeanModelToDto(this as IConfigBeanModel<T>);\n await this._modifyConfigBean(this.path, request, this.serviceBasePath);\n }\n\n // ------------------SUBSCRIPTIONS----------------------\n\n /**\n * @category Subscription\n * Updates the Config Bean model when a `/kos/config//update` event\n * is recieved from the server.\n *\n *\n * @param data - the raw callback\n * @param data.body - the Config Bean that was updated.\n * @see ConfigBeanResponse\n */\n @kosTopicHandler({\n topic: `/kos/config/${PATH_PROP}`,\n websocket: true,\n })\n handleConfigBeanUpdated(configBean: ConfigBeanUpdateResponse) {\n mapUpdateDtoToConfigBeanModel(configBean, this as IConfigBeanModel<T>);\n }\n}\n\nexport const ConfigBean = new KosModelRegistrationFactory<\n IConfigBeanModel,\n IConfigBeanModelOptions\n>({\n class: ConfigBeanModelImpl<any>,\n type: CONFIG_BEAN_MODEL_TYPE,\n});\n","/* eslint-disable no-param-reassign */\nimport { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { ConfigBean } from \"../models/config-bean\";\n\ninterface KosConfigParams {\n path: string;\n lazy?: boolean;\n serviceBasePath?: string;\n}\n\nexport const kosConfigBean =\n ({ path, lazy, serviceBasePath }: KosConfigParams) =>\n (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: ConfigBean.type,\n id: `${ConfigBean.type}-${path}`,\n options: {\n path,\n serviceBasePath,\n },\n lifecycle: DependencyLifecycle.INIT,\n lazy,\n };\n };\n","/**\n * @internal\n */\nimport { ServiceFactory, resolveServiceUrl } from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"REGION_INFO_SERVICE\");\nconst { getOne, getAll } = ServiceFactory.build({\n basePath: `${URL}/api/kos/regions/info`,\n});\n\nexport interface DateFormat {\n id: string;\n format: string;\n order: string;\n}\nexport interface TimeFormat {\n id: string;\n format: string;\n ampm: boolean;\n}\nexport interface Unit {\n measure: string;\n name: string;\n scale: number;\n offset: number;\n decimals: number;\n alias: string;\n def: boolean;\n}\nexport interface UnitSystem {\n id: string;\n units: Unit[];\n}\nexport interface RegionInfoResponse {\n unitSystems: UnitSystem[];\n timeFormats: TimeFormat[];\n dateFormats: DateFormat[];\n}\n\nexport interface BaseRegionResponse {\n id: string;\n country: string;\n timeFormatId: string;\n dateFormatId: string;\n unitSystemId: string;\n timeZones: string[];\n hidden: boolean;\n}\nexport type RegionsResponse<\n AdditionalData extends BaseRegionResponse = BaseRegionResponse\n> = BaseRegionResponse & {\n [key in keyof AdditionalData]: AdditionalData[key];\n};\n/**\n * @category Service\n * @internal\n * Retrieves the initial Region Info data.\n */\nexport const getRegionInfo = async () => {\n const response = await getOne<RegionInfoResponse>({});\n return response;\n};\n\nexport const getRegions = async () => {\n const response = await getAll<RegionsResponse>({\n urlOverride: `${URL}/api/kos/regions`,\n });\n return response;\n};\n","import { IKosDataModel } from \"../../../../core\";\nimport { BaseRegionResponse, RegionsResponse, Unit } from \"../services\";\n\n// Represents a source for a unit measurement with optional system, measure, and name properties.\nexport interface UnitSource {\n system?: string; // Measurement system (e.g., metric, imperial)\n measure?: string; // Type of measure (e.g., length, weight)\n unit?: string; // Name of the unit (e.g., meter, kilogram)\n}\n\n// Can be a string or the literal 'default'.\nexport type MeasureMapKeys = string | \"default\";\n\n// Record mapping MeasureMapKeys to Unit, defining units for each measurement system.\nexport type SystemMeasureMap = Record<MeasureMapKeys, Unit>;\n\n// Record mapping measurement types to their respective SystemMeasureMap.\nexport type MeasureMap = Record<string, SystemMeasureMap>;\n\n// Record mapping strings, typically used for default settings.\nexport type SystemDefaultMap = Record<string, string>;\n\n// Record mapping unit systems to their default settings.\nexport type DefaultMeasureMap = Record<string, SystemDefaultMap>;\n\n// Empty interface, potentially for future extension related to region information.\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface RegionInfoOptions {}\n\n// Base interface for options requiring an id.\ninterface BaseOptions {\n id: string; // Unique identifier\n}\n\n// Interface extending BaseOptions with a format property.\ninterface FormatOptions extends BaseOptions {\n format: string; // Format specifier (e.g., date or time format)\n}\n\n/**\n * Interface for time format options, extending FormatOptions.\n * @internal\n **/\nexport interface TimeFormatOptions extends FormatOptions {\n ampm: boolean; // True if using 12-hour (AM/PM) format\n}\n\n/**\n * Interface for date format options, extending FormatOptions.\n * @internal\n **/\nexport interface DateFormatOptions extends FormatOptions {\n order: string; // Order of date components (e.g., 'MM/DD/YYYY')\n}\n\n/**\n * Interface for unit system options, extending BaseOptions.\n * @internal\n **/\nexport interface UnitSystemOptions extends BaseOptions {\n name: string; // Name of the unit system (e.g., metric, imperial)\n}\n\n/**\n * Represents a model for region information, extending the basic region options and data model.\n * It allows for managing regional settings and unit conversions.\n *\n * @category Model\n * @template AdditionalData - Extends the base region response to include additional data as needed.\n */\nexport interface RegionInfoModel<\n AdditionalData extends BaseRegionResponse = BaseRegionResponse\n> extends RegionInfoOptions,\n IKosDataModel {\n /** Unique identifier for the region model instance. */\n readonly id: string;\n\n /** The default unit system (e.g., metric or imperial) for the region. */\n readonly defaultUnitSystem: string;\n\n /** The currently selected unit system. */\n readonly selectedUnitSystem: string;\n\n /** The currently selected time format as a string. */\n readonly selectedTimeFormat: string;\n\n /** The currently selected date format as a string. */\n readonly selectedDateFormat: string;\n\n /** The order of date elements (e.g., day/month/year) for the selected format. */\n readonly selectedDateOrder: string;\n\n /** The currently selected country. */\n readonly selectedCountry: string;\n\n /** The currently selected time zone. */\n readonly selectedTimeZone: string;\n\n /**\n * The detailed information of the selected region, extended with additional data.\n * The type of additional data is determined by the generic parameter `AdditionalData`.\n */\n selectedRegion: RegionsResponse<AdditionalData>;\n\n /** Flag indicating if the 12-hour time format (AM/PM) is used. */\n is12HourTimeFormat: boolean;\n\n /** An array of available regions as strings. */\n availableRegions: string[];\n\n /** Identifier of the region. */\n regionId: string;\n\n readonly dateFormatId: string;\n readonly timeFormatId: string;\n readonly unitSystemId: string;\n\n /** An array of available time zones as strings. */\n timeZones: string[];\n\n /** An array of all available time zones as strings. */\n allTimeZones: string[];\n\n /** Time format options available for selection. */\n readonly timeFormatOptions: TimeFormatOptions[];\n\n /** Date format options available for selection. */\n readonly dateFormatOptions: DateFormatOptions[];\n\n /** Unit system options available for selection. */\n readonly unitSystemOptions: UnitSystemOptions[];\n\n /**\n * Converts a value from one unit to another.\n *\n * @param value - The numerical value to convert.\n * @param from - The unit source to convert from.\n * @param to - The unit source to convert to.\n * @returns The converted value as a string.\n * @internal\n */\n convert(value: number, from: UnitSource, to: UnitSource): string;\n\n /**\n * Sets the selected time format.\n *\n * @param id - The identifier of the time format to select.\n */\n setSelectedTimeFormat(id: string): void;\n\n /**\n * Sets the selected date format.\n *\n * @param id - The identifier of the date format to select.\n */\n setSelectedDateFormat(id: string): void;\n\n /**\n * Sets the selected unit system.\n *\n * @param id - The identifier of the unit system to select.\n */\n setSelectedUnitSystem(id: string): void;\n\n /**\n * Retrieves the default unit for a given measure in a specified unit system.\n *\n * @param measure - The measure for which to get the default unit.\n * @param unitSystem - The unit system in which to find the default unit.\n * @returns The default unit for the specified measure and system.\n */\n getDefaultUnitForMeasure(measure: string, unitSystem: string): string;\n\n /**\n * Retrieves the measure associated with a given unit.\n *\n * @param unit - The unit for which to get the measure.\n * @returns The measure associated with the specified unit.\n *\n * @internal\n */\n getUnitMeasure: (unit: string) => string;\n\n /**\n *\n * @internal\n */\n getUnitSystem: (unit?: string) => string;\n\n /**\n * Retrieves the default number of decimal places for a unit in a given measure and system.\n *\n * @param measure - The measure to consider.\n * @param unitSystem - The unit system in which the unit is defined.\n * @param unit - Optional specific unit to consider.\n * @returns The number of decimal places for the unit.\n */\n getDefaultUnitDecimalPlaces(\n measure: string,\n unitSystem: string,\n unit?: string\n ): number;\n}\n\n// Enum for keys used in UnitTuple.\nexport enum UnitTupleKeys {\n family,\n scale,\n offset,\n decimals,\n alias,\n system,\n}\n\n// Tuple type for unit properties: family, scale, offset, decimals, alias.\nexport type UnitTuple = [\n family: string, // Unit family (e.g., length, volume)\n scale: number, // Scale factor for unit conversion\n offset: number, // Offset for unit conversion\n decimals: number, // Number of decimal places for precision\n alias: string, // Alternative name or alias for the unit\n system: string // Measurement system (e.g., metric, imperial)\n];\n","import { UnitTuple } from \"../types\";\nconst timeTuples = {\n s: [\"time\", 1, 0, 0],\n second: [\"time\", 1, 0, 0],\n m: [\"time\", 1 / 60, 0, 0],\n minute: [\"time\", 1 / 60, 0, 0],\n h: [\"time\", 1 / 3600, 0, 0],\n hour: [\"time\", 1 / 3600, 0, 0],\n day: [\"time\", 1 / 86400, 0, 0],\n week: [\"time\", 1 / 604800, 0, 0],\n month: [\"time\", 1 / 2628000, 0, 0],\n year: [\"time\", 1 / 31536000, 0, 0],\n default: [\"time\", 1 / 0.001, 0, 0],\n ms: [\"time\", 1 / 0.001, 0, 0],\n millisecond: [\"time\", 1 / 0.001, 0, 0],\n microsecond: [\"time\", 1 / 0.000001, 0, 0],\n nanosecond: [\"time\", 1 / 0.000000001, 0, 0],\n picosecond: [\"time\", 1 / 0.000000000001, 0, 0],\n};\nexport function unitSystemMapReducer(acc, unitSystem) {\n const system = unitSystem.id;\n const units = unitSystem.units.reduce(\n (acc, unit) => {\n const unitTuple: UnitTuple = [\n unit.measure,\n unit.scale,\n unit.offset,\n unit.decimals,\n unit.alias,\n system,\n ];\n acc[unit.name] = unitTuple;\n if (unit.alias) {\n acc[unit.alias] = unitTuple;\n }\n return acc;\n },\n {\n ...timeTuples,\n }\n );\n\n return { ...acc, ...units };\n}\n\nexport function measureMapReducer(systemAcc, unitSystem) {\n const system = unitSystem.id;\n\n const measures = unitSystem.units.reduce(\n (acc, unit) => {\n const measure = acc[unit.measure] || {};\n\n const systemMeasure = measure[system] || {};\n measure[system] = systemMeasure;\n\n const unitTuple: UnitTuple = [\n unit.measure,\n unit.scale,\n unit.offset,\n unit.decimals,\n unit.alias,\n system,\n ];\n systemMeasure[unit.name] = unitTuple;\n if (Object.hasOwn(unit, \"default\")) {\n Object.defineProperty(systemMeasure, \"default\", {\n value: unitTuple,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n acc[unit.measure] = measure;\n if (unit.alias) {\n acc[unit.alias] = measure;\n }\n return acc;\n },\n {\n time: {\n [system]: {\n ...timeTuples,\n },\n },\n }\n );\n Object.keys(measures).forEach((measure) => {\n systemAcc[measure] = {\n ...systemAcc[measure],\n ...measures[measure],\n };\n });\n\n return systemAcc;\n}\n\nexport function defaultMeasureMapReducer(systemAcc, unitSystem) {\n const system = unitSystem.id;\n\n const measures = unitSystem.units.reduce(\n (acc, unit) => {\n const measure = acc[unit.measure] || {};\n\n if (Object.hasOwn(unit, \"default\")) {\n measure[system] = unit.name;\n }\n acc[unit.measure] = measure;\n return acc;\n },\n {\n time: {\n [system]: \"millisecond\",\n },\n }\n );\n Object.keys(measures).forEach((measure) => {\n systemAcc[measure] = {\n ...systemAcc[measure],\n ...measures[measure],\n };\n });\n\n return systemAcc;\n}\n","import { Kos, KosLog, kosModel } from \"../../../core\";\nimport { kosConfigBean } from \"../../decorators/kos-config-bean\";\n\nimport type { IConfigBeanModel } from \"../config-bean/config-bean-model\";\nimport {\n BaseRegionResponse,\n DateFormat,\n getRegionInfo,\n getRegions,\n RegionsResponse,\n TimeFormat,\n} from \"./services\";\nimport {\n DateFormatOptions,\n DefaultMeasureMap,\n MeasureMap,\n RegionInfoModel,\n RegionInfoOptions,\n TimeFormatOptions,\n UnitSource,\n UnitSystemOptions,\n UnitTuple,\n UnitTupleKeys,\n} from \"./types\";\nimport {\n defaultMeasureMapReducer,\n measureMapReducer,\n unitSystemMapReducer,\n} from \"./utils/unit-system-utils\";\n\ninterface RegionSettingsService {\n unitSystemId: string;\n timeFormatId: string;\n dateFormatId: string;\n country: string;\n timeZone: string;\n}\n\ninterface RegionService {\n regionId: string;\n}\n\ntype RegionSettingsConfigBean = IConfigBeanModel<RegionSettingsService>;\n\ntype RegionConfigBean = IConfigBeanModel<RegionService>;\n\nconst MODEL_TYPE = \"region-info-model\";\n\nconst log = KosLog.createLogger({ name: \"region-info-model\" });\n\n@kosModel(MODEL_TYPE)\nexport class RegionInfoModelImpl<\n AdditionalData extends BaseRegionResponse = BaseRegionResponse\n> implements RegionInfoModel\n{\n id: string;\n private unitSystemMap: Record<string, UnitTuple>;\n private measureMap: MeasureMap;\n private defaultMeasureMap: DefaultMeasureMap;\n\n private regionMap: Record<string, RegionsResponse<AdditionalData>>;\n private timeFormats: Record<string, TimeFormat>;\n private dateFormats: Record<string, DateFormat>;\n private unitSystems: Record<string, UnitSystemOptions>;\n @kosConfigBean({ path: \"kos:service:region:settings\" })\n regionSource!: RegionSettingsConfigBean;\n\n @kosConfigBean({ path: \"kos:service:region\" })\n private region!: RegionConfigBean;\n\n private regions: string[] = [];\n private timeZoneMap: Record<string, string[]> = {};\n\n constructor(modelId: string) {\n this.id = modelId;\n\n this.unitSystems = {};\n this.unitSystemMap = {};\n this.measureMap = {};\n this.defaultMeasureMap = {};\n\n this.timeFormats = {};\n this.regions = [];\n this.dateFormats = {};\n this.timeZoneMap = {};\n this.regionMap = {};\n }\n\n get availableRegions() {\n return this.regions;\n }\n get defaultUnitSystem() {\n return String(this.regionSource.props[\"unitSystemId\"]).toLowerCase() || \"\";\n }\n\n get unitSystemId() {\n return this.defaultUnitSystem;\n }\n\n get timeFormatId() {\n const _timeFormatId = this.regionSource.props[\"timeFormatId\"];\n if (!_timeFormatId) {\n return \"\";\n }\n const selectedTimeFormatId = String(_timeFormatId);\n\n const resolvedTimeFormatId = this.timeFormats[selectedTimeFormatId];\n return resolvedTimeFormatId ? String(resolvedTimeFormatId.id) : \"\";\n }\n\n get selectedTimeFormat() {\n const selectedTimeFormatId = this.timeFormatId;\n return selectedTimeFormatId\n ? String(this.timeFormats[selectedTimeFormatId].format)\n : \"HH:mm:ss\";\n }\n\n get is12HourTimeFormat() {\n const selectedTimeFormatId = this.timeFormatId;\n return selectedTimeFormatId\n ? this.timeFormats[selectedTimeFormatId].ampm\n : true;\n }\n\n get dateFormatId() {\n const _dateFormatId = this.regionSource.props[\"dateFormatId\"];\n if (!_dateFormatId) {\n return \"\";\n }\n const selectedDateFormatId = String(_dateFormatId);\n return selectedDateFormatId\n ? this.dateFormats[selectedDateFormatId].id\n : \"\";\n }\n\n get selectedDateFormat() {\n const selectedDateFormatId = this.dateFormatId;\n return selectedDateFormatId\n ? this.dateFormats[selectedDateFormatId].format\n : \"\";\n }\n\n get selectedDateOrder() {\n const selectedDateFormatId = this.dateFormatId;\n\n return selectedDateFormatId\n ? this.dateFormats[selectedDateFormatId].order.toLowerCase()\n : \"dmy\";\n }\n\n get selectedCountry() {\n return (this.regionSource.props[\"country\"] as string) || \"en\";\n }\n\n get selectedTimeZone() {\n return (this.regionSource.props[\"timeZone\"] as string) || \"\";\n }\n\n get timeZones() {\n return this.regionId ? this.timeZoneMap[this.regionId] || [] : [];\n }\n\n get allTimeZones() {\n // const allTimeZones = Object.values(this.timeZoneMap).flat();\n const allTimeZones = Intl.supportedValuesOf(\"timeZone\");\n\n return allTimeZones;\n }\n\n get regionId() {\n return (this.region.props[\"regionId\"] as string) || \"\";\n }\n\n get selectedRegion() {\n return this.regionMap[this.regionId];\n }\n\n get selectedUnitSystem() {\n return String(this.regionSource.props[\"unitSystemId\"]) || \"\";\n }\n\n get timeFormatOptions() {\n return Object.keys(this.timeFormats).map<TimeFormatOptions>((key) => {\n return {\n id: key,\n format: this.timeFormats[key].format,\n ampm: this.timeFormats[key].ampm,\n };\n });\n }\n\n get dateFormatOptions() {\n return Object.keys(this.dateFormats).map<DateFormatOptions>((key) => {\n return {\n id: key,\n format: this.dateFormats[key].format,\n order: this.dateFormats[key].order,\n };\n });\n }\n\n get unitSystemOptions() {\n return Object.keys(this.unitSystems).map<UnitSystemOptions>((key) => {\n return {\n id: key,\n name: key,\n };\n });\n }\n\n setSelectedTimeFormat(timeFormatId: string) {\n if (!this.timeFormatOptions.find((option) => option.id === timeFormatId)) {\n throw Error(\n `Invalid time format id. Must be one of ${this.timeFormatOptions\n .map((option) => option.id)\n .join(\", \")}`\n );\n }\n this.regionSource.updateProperty(\"timeFormatId\", timeFormatId);\n }\n\n setSelectedDateFormat(dateFormatId: string) {\n if (!this.dateFormatOptions.find((option) => option.id === dateFormatId)) {\n throw Error(\n `Invalid date format id. Must be one of ${this.dateFormatOptions\n .map((option) => option.id)\n .join(\", \")}`\n );\n }\n this.regionSource.updateProperty(\"dateFormatId\", dateFormatId);\n }\n\n setSelectedUnitSystem(unitSystemId: string) {\n if (!this.unitSystemOptions.find((option) => option.id === unitSystemId)) {\n throw Error(\n `Invalid date format id. Must be one of ${this.unitSystemOptions\n .map((option) => option.id)\n .join(\", \")}`\n );\n }\n this.regionSource.updateProperty(\"unitSystemId\", unitSystemId);\n }\n\n getUnitSystem(_unit?: string) {\n if (!_unit) {\n return this.defaultUnitSystem;\n }\n const unit = _unit === \"drt\" ? \"second\" : _unit;\n const unitTuple = this.unitSystemMap[unit];\n if (!unitTuple) {\n throw Error(\n `No unit found with name: ${unit}. Unit should be one of ${Object.keys(\n this.unitSystemMap\n ).join(\", \")}`\n );\n }\n return unitTuple[UnitTupleKeys.system];\n }\n getUnitMeasure(_unit: string) {\n const unit = _unit === \"drt\" ? \"second\" : _unit;\n const unitTuple = this.unitSystemMap[unit];\n if (!unitTuple) {\n throw Error(\n `No unit found with name: ${unit}. Unit should be one of ${Object.keys(\n this.unitSystemMap\n ).join(\", \")}`\n );\n }\n return unitTuple[UnitTupleKeys.family];\n }\n\n /**\n *@internal\n */\n getDefaultUnitDecimalPlaces(\n measure: string,\n unitSystem: string,\n _unit?: string\n ) {\n if (!measure || !unitSystem) {\n throw Error(\"Measure and unit system are required\");\n }\n const unit = _unit === \"drt\" ? \"second\" : _unit;\n const measureUnitSystems = this.measureMap[measure];\n if (!measureUnitSystems) {\n throw Error(\n `No unit systems found for measure: ${measure}. Measure should come from list of measures: ${Object.keys(\n this.measureMap\n ).join(\", \")}`\n );\n }\n\n const unitSystemUnits = measureUnitSystems[unitSystem.toLowerCase()];\n if (!unitSystemUnits) {\n throw Error(\n `No unit system found for measure: ${measure} and unit system: ${unitSystem}. Unit system should come form list of unit systems: ${Object.keys(\n measureUnitSystems\n ).join(\", \")}`\n );\n }\n\n const defaultUnit = unitSystemUnits[unit || \"default\"];\n if (!defaultUnit) {\n throw Error(\n `No unit \"${\n unit || \"default\"\n }\" found for measure: ${measure} and unit system: ${unitSystem}. Unit should come from list of units: ${Object.keys(\n unitSystemUnits\n ).join(\", \")}`\n );\n }\n return defaultUnit[UnitTupleKeys.decimals];\n }\n\n /**\n *@internal\n */\n getDefaultUnitForMeasure(measure: string, unitSystem: string) {\n if (!measure || !unitSystem) {\n throw Error(\"Measure and unit system are required\");\n }\n\n const measureUnitSystems = this.defaultMeasureMap[measure];\n if (!measureUnitSystems) {\n throw Error(\n `No unit systems found for measure: ${measure}. Measure should come from list of measures: ${Object.keys(\n this.measureMap\n ).join(\", \")}`\n );\n }\n\n const unitSystemUnits = measureUnitSystems[unitSystem.toLowerCase()];\n if (!unitSystemUnits) {\n throw Error(\n `No unit system found for measure: ${measure} and unit system: ${unitSystem}. Unit system should come form list of unit systems: ${Object.keys(\n measureUnitSystems\n ).join(\", \")}`\n );\n }\n return unitSystemUnits;\n }\n\n /**\n *@internal\n */\n\n convertByUnit(value: number, fromUnit: UnitTuple, toUnit: UnitTuple) {\n if (fromUnit[UnitTupleKeys.family] !== toUnit[UnitTupleKeys.family]) {\n throw new Error(\n `Cannot convert between units of different families: ${\n fromUnit[UnitTupleKeys.family]\n } and ${toUnit[UnitTupleKeys.family]}`\n );\n }\n\n const fromOffset = fromUnit[UnitTupleKeys.offset] as number;\n const fromScale = fromUnit[UnitTupleKeys.scale] as number;\n const toScale = toUnit[UnitTupleKeys.scale] as number;\n const toOffset = toUnit[UnitTupleKeys.offset] as number;\n const decimals = toUnit[UnitTupleKeys.decimals] as number;\n const convertedValue =\n (value - fromOffset) / (fromScale / toScale) + toOffset;\n\n return convertedValue.toFixed(decimals);\n }\n\n /**\n *@internal\n */\n convertByUnitName(value: number, from: string, to: string) {\n const fromUnit = this.unitSystemMap[from];\n const toUnit = this.unitSystemMap[to];\n if (!fromUnit || !toUnit) {\n throw new Error(\n `No unit found with name: ${from} or ${to}. Unit should be one of ${Object.keys(\n this.unitSystemMap\n ).join(\", \")}`\n );\n }\n return this.convertByUnit(value, fromUnit, toUnit);\n }\n\n /**\n * @internal\n */\n convert(value: number, from: UnitSource, to: UnitSource) {\n if (from.unit && to.unit) {\n return this.convertByUnitName(value, from.unit, to.unit);\n }\n\n const fromName = from.unit || \"\";\n const toName = to.unit || \"\";\n let fromUnit = this.unitSystemMap[fromName];\n let toUnit = this.unitSystemMap[toName];\n if (!toUnit && to.measure && to.system) {\n const measureSystems = this.measureMap[to.measure];\n if (!measureSystems) {\n throw Error(\n `Could not find measure ${\n to.measure\n }. Measure should be one of ${Object.keys(this.measureMap).join(\n \", \"\n )}`\n );\n }\n toUnit = measureSystems[to.system]?.[\"default\"];\n if (!toUnit) {\n log.info(\"Could not find default unit for measure\", to.measure);\n }\n }\n\n if (!fromUnit && from.measure && from.system) {\n const measureSystems = this.measureMap[from.measure];\n if (!measureSystems) {\n throw Error(\n `Could not find measure ${\n to.measure\n }. Measure should be one of ${Object.keys(this.measureMap).join(\n \", \"\n )}`\n );\n }\n fromUnit = measureSystems[from.system]?.[\"default\"];\n if (!fromUnit) {\n log.info(\"Could not find default unit for measure\", from.measure);\n }\n }\n\n if (!fromUnit || !toUnit) {\n log.warn(\"Could not find unit to convert to or from. Return value as is\");\n return String(value);\n }\n\n return this.convertByUnit(value, fromUnit, toUnit);\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n *@internal\n */\n async init(): Promise<void> {\n log.debug(\"initializing region info\");\n }\n\n /**\n *@internal\n */\n async load(): Promise<void> {\n log.debug(\"loading region info\");\n\n const regions = await getRegions();\n if (regions) {\n this.regions = regions.data.map((region) => region.id);\n this.timeZoneMap = regions.data.reduce((acc, region) => {\n return { ...acc, [region.id]: region.timeZones };\n }, this.timeZoneMap);\n this.regionMap = regions.data.reduce((acc, region) => {\n return { ...acc, [region.id]: region };\n }, {});\n }\n\n const regionInfo = await getRegionInfo();\n if (regionInfo) {\n this.unitSystems = regionInfo.data.unitSystems.reduce((acc, curr) => {\n const unitSystem = {\n id: curr.id,\n name: curr.id,\n };\n acc[curr.id] = unitSystem;\n return acc;\n }, this.unitSystems);\n this.unitSystemMap = regionInfo.data.unitSystems.reduce(\n unitSystemMapReducer,\n {}\n );\n\n this.measureMap = regionInfo.data.unitSystems.reduce(\n measureMapReducer,\n {}\n );\n\n this.defaultMeasureMap = regionInfo.data.unitSystems.reduce(\n defaultMeasureMapReducer,\n {}\n );\n\n this.timeFormats = regionInfo.data.timeFormats.reduce(\n (acc, timeFormat) => {\n return { ...acc, [timeFormat.id]: timeFormat };\n },\n {}\n );\n\n this.dateFormats = regionInfo.data.dateFormats.reduce(\n (acc, dateFormat) => {\n return { ...acc, [dateFormat.id]: dateFormat };\n },\n {}\n );\n }\n }\n\n /**\n *@internal\n */\n async ready(): Promise<void> {\n await this.regionSource.ready?.();\n }\n}\n\nconst Registration = {\n registration: {\n [MODEL_TYPE]: {\n class: RegionInfoModelImpl,\n singleton: true,\n },\n },\n type: MODEL_TYPE,\n factory: Kos.Singleton.create<RegionInfoModel, RegionInfoOptions>(MODEL_TYPE),\n};\nexport default Registration;\n","import { getKosModelSync, isKosModelReady } from \"../../core\";\nimport { RegionInfo } from \"../models/region-info\";\nimport { RegionInfoModel, UnitSource } from \"../models/region-info/types\";\n\nexport type UnitConversionSource = string | UnitSource;\n\ninterface CreateUnitSourceProps {\n source: UnitConversionSource;\n defaultSystem?: string;\n defaultMeasure?: string;\n}\nconst createUnitSource = ({\n source,\n defaultSystem = \"si\",\n defaultMeasure,\n}: CreateUnitSourceProps) => {\n let unit: UnitSource = { system: defaultSystem, measure: defaultMeasure };\n if (typeof source === \"string\") {\n unit = { ...unit, unit: source };\n } else {\n unit = { ...unit, ...source };\n }\n\n return unit;\n};\n\n/**\n * Region-aware unit conversion utility that can be used to convert between units of measure.\n *\n * When converting between units of measure, the source and target unit can be specified as a string or as a {@see UnitSource} object.\n * @example\n * in the simplest case, the source and target units can be specified as strings so long as they belong to the same measure (volume, length etc):\n *\n * ```typescript\n * import { convert } from \"@kosdev-code/kos-ui-sdk\";\n *\n * const value = convert(1000, \"milliliter\", \"fluid-ounce\");\n * ```\n *\n * The to unit can be omitted in which case the value will be converted to the default unit for the selected region measure:\n * @example\n * ```typescript\n * import { convert } from \"@kosdev-code/kos-ui-sdk\";\n *\n * // convert 1000 milliliters to the default unit for the region. If the region is set to US, the value will be converted to fluid ounces.\n * const value = convert(1000, \"milliliter\");\n * ```\n *\n * The source and target units can also be specified as {@see UnitSource} objects:\n * @example\n * ```typescript\n * import { convert } from \"@kosdev-code/kos-ui-sdk\";\n *\n * const value = convert(1000, {name: \"milliliter\", measure: \"volume\", system: \"si\"}, {name: \"fluid-ounce\", measure: \"volume\", system: \"us\"});\n * ```\n * In this case properties on the source and target are all optional so long as either the name or measure is specified.\n *\n * @param value - the value to convert\n * @param from - the source unit\n * @param to - the target unit. If omitted, the value will be converted to the default unit for the region measure.\n * @returns the converted value\n */\nexport const convert = (\n value: number,\n from: UnitConversionSource,\n to?: UnitConversionSource\n) => {\n const { model: regionInfo } = getKosModelSync<RegionInfoModel>(\n RegionInfo.type\n );\n if (!regionInfo) {\n throw new Error(\"RegionInfo model not found\");\n }\n\n if (!isKosModelReady(regionInfo)) {\n throw new Error(\"RegionInfo model not ready\");\n }\n const defaultToSource = { system: regionInfo.defaultUnitSystem };\n const fromUnit: UnitSource = createUnitSource({ source: from });\n\n const toUnit: UnitSource = createUnitSource({\n source: to || defaultToSource,\n defaultMeasure: regionInfo.getUnitMeasure(fromUnit.unit || \"\"),\n });\n\n return regionInfo.convert(value, fromUnit, toUnit);\n};\n","import {\n KeypadOptions,\n ListOptions,\n RangeCountOptions,\n RangeIntervalOptions,\n SchemaNodeDef,\n} from \"../../services/config-bean\";\nimport { UnitConversionSource, convert } from \"../../utils/conversion-utils\";\nimport { isNumber } from \"../../utils/prop-utils\";\n\ninterface DistributionProps {\n start: number;\n end: number;\n count: number;\n decimals?: number;\n}\nfunction generateEvenlyDistributedArray({\n start,\n end,\n count,\n decimals = 0,\n}: DistributionProps) {\n if (\n typeof start !== \"number\" ||\n typeof end !== \"number\" ||\n typeof count !== \"number\"\n ) {\n throw new Error(\"All input values should be numbers.\");\n }\n\n if (count < 2) {\n throw new Error(\"Count should be at least 2 for distribution.\");\n }\n\n if (start >= end) {\n throw new Error(\"Start should be less than end.\");\n }\n\n const step = (end - start) / (count - 1);\n const result: string[] = [];\n\n for (let i = 0; i < count; i++) {\n const value = Math.round(start + i * step);\n result.push(value.toFixed(decimals));\n }\n\n return result;\n}\n\ninterface IntervalProps {\n start: number;\n end: number;\n interval: number;\n decimals?: number;\n}\n\nfunction generateIntervalArray({\n start,\n end,\n interval,\n decimals = 0,\n}: IntervalProps) {\n if (\n typeof start !== \"number\" ||\n typeof end !== \"number\" ||\n typeof interval !== \"number\"\n ) {\n throw new Error(\"All input values should be numbers.\");\n }\n\n if (interval <= 0) {\n throw new Error(\"Interval should be a positive number.\");\n }\n\n if (start >= end) {\n throw new Error(\"Start should be less than end.\");\n }\n\n const result: string[] = [];\n\n let currentValue = start;\n while (currentValue <= end) {\n result.push(currentValue.toFixed(decimals));\n currentValue += interval;\n }\n\n // Ensure that the last value is always the end value\n if (result[result.length - 1] !== end.toString()) {\n result.push(end.toString());\n }\n\n return result;\n}\n\nconst conversionMap =\n (from?: UnitConversionSource, to?: UnitConversionSource) =>\n (item: string) => {\n if (!from || !to) {\n return item;\n }\n const result = isNumber(item) ? convert(Number(item), from, to) : item;\n return result;\n };\nexport const configOptionsFactory = (\n schema?: SchemaNodeDef,\n unitSystem?: string,\n from?: UnitConversionSource,\n to?: UnitConversionSource\n): string[] => {\n if (schema?.type === \"enum\" || !schema?.options) {\n return [];\n }\n\n if (schema.options.type === \"rangeCount\") {\n return generateEvenlyDistributedArray(schema.options).map(\n conversionMap(from, to)\n );\n } else if (schema.options.type === \"rangeInterval\") {\n return generateIntervalArray(schema.options).map(conversionMap(from, to));\n } else if (schema.options.type === \"list\") {\n const { list } = schema.options;\n\n return list.map(conversionMap(from, to));\n } else if (schema.options.type === \"unitSystemRangeCount\" && unitSystem) {\n return generateEvenlyDistributedArray(\n schema.options.unitSystems[unitSystem]\n ).map(conversionMap(from, to));\n } else if (schema.options.type === \"unitSystemRangeInterval\" && unitSystem) {\n const list = generateIntervalArray(\n schema.options.unitSystems[unitSystem]\n ).map(conversionMap(from, to));\n return list;\n } else if (schema.options.type === \"unitSystemList\" && unitSystem) {\n const { list } = schema.options.unitSystems[unitSystem];\n\n return list.map(conversionMap(from, to));\n }\n\n return [];\n};\n\nexport const displayOptionsFactory = (\n schema?: SchemaNodeDef,\n unitSystem?: string\n) => {\n if (schema?.type === \"enum\" || !schema?.options) {\n return undefined;\n }\n if (schema.options.type === \"unitSystemRangeCount\" && unitSystem) {\n const result: RangeCountOptions = {\n type: \"rangeCount\",\n ...schema.options.unitSystems[unitSystem],\n };\n return result;\n } else if (schema.options.type === \"unitSystemRangeInterval\" && unitSystem) {\n const result: RangeIntervalOptions = {\n type: \"rangeInterval\",\n ...schema.options.unitSystems[unitSystem],\n };\n return result;\n } else if (schema.options.type === \"unitSystemList\" && unitSystem) {\n const result: ListOptions = {\n type: \"list\",\n ...schema.options.unitSystems[unitSystem],\n };\n return result;\n } else if (schema.options.type === \"unitSystemKeypad\" && unitSystem) {\n const result: KeypadOptions = {\n type: \"keypad\",\n ...schema.options.unitSystems[unitSystem],\n };\n return result;\n }\n\n return schema.options;\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Kos,\n KosLog,\n createPropKey,\n kosDependency,\n kosModel,\n} from \"../../../core\";\nimport { kosConfigBean } from \"../../decorators/kos-config-bean\";\nimport type { UnitConverter } from \"../../decorators/kos-config-bean-prop\";\n\nimport { format } from \"date-fns\";\nimport {\n hasDecimals,\n type EnumSchemaNode,\n type SchemaNodeDef,\n} from \"../../services/config-bean\";\n\nimport type { IConfigBeanModel } from \"../config-bean/config-bean-model\";\nimport { RegionInfo, type RegionInfoModel } from \"../region-info\";\nimport type { UnitSource } from \"../region-info/types\";\nimport type { ConfigPropertyTypes } from \"../types\";\nimport {\n configOptionsFactory,\n displayOptionsFactory,\n} from \"./config-options-factory\";\nimport type {\n ConfigBeanPropOptions,\n ConfigPropConverter,\n FormatOptions,\n KosConfigProperty,\n OptionsExpander,\n OptionsType,\n} from \"./types\";\n\nfunction isEnum(schema?: SchemaNodeDef): schema is EnumSchemaNode {\n return schema?.type === \"enum\";\n}\n\nfunction convertFormats(format: string) {\n switch (format) {\n case \"s\":\n return \"second\";\n case \"ms\":\n return \"millisecond\";\n case \"min\":\n return \"minute\";\n case \"h\":\n return \"hour\";\n case \"d\":\n return \"day\";\n case \"w\":\n return \"week\";\n case \"m\":\n return \"month\";\n case \"y\":\n return \"year\";\n case \"ml\":\n return \"milliliter\";\n default:\n return format;\n }\n}\n\nfunction secondsToFormattedTime(\n secondsSinceMidnight: number,\n formatString: string\n): string {\n // Create a reference to the start of the day (midnight)\n const midnight = new Date();\n midnight.setHours(0, 0, 0, 0);\n\n // Add the seconds to the midnight time\n const time = new Date(midnight.getTime() + secondsSinceMidnight * 1000);\n\n return format(time, formatString);\n}\n\nconst MODEL_TYPE = \"config-bean-prop-model\";\nconst log = KosLog.createLogger({ name: \"config-bean-prop-model\" });\nconst PATH_PROP = createPropKey<KosConfigProperty>(\"path\");\n\nconst SERVICE_PATH_PROP = createPropKey<KosConfigProperty>(\"serviceBasePath\");\n/**\n * @inheritdoc\n */\n@kosModel(MODEL_TYPE)\nclass KosConfigPropertyImpl implements KosConfigProperty {\n id: string;\n path: string;\n attribute: string;\n converter?: ConfigPropConverter;\n formatter?: FormatOptions;\n optionsExpander?: OptionsExpander;\n serviceBasePath?: string;\n @kosDependency({ modelType: RegionInfo.type })\n regionInfo!: RegionInfoModel;\n\n @kosConfigBean({ path: PATH_PROP, serviceBasePath: SERVICE_PATH_PROP })\n bean!: IConfigBeanModel;\n\n constructor(modelId: string, options: ConfigBeanPropOptions) {\n this.id = modelId;\n this.path = options.path;\n this.attribute = options.attribute;\n this.converter = options.converter;\n this.formatter = options.formatter;\n this.serviceBasePath = options.serviceBasePath;\n this.optionsExpander = options.optionsExpander;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * For cases where the default unit system is used, this method will return\n * the number of decimal places to use for the given measure.\n * @param measure the measure to get the default decimal places for\n * @param unitSystem the unit system to use\n * @returns the number of decimal places to use for the given measure\n * @throws Error if measure is not provided\n **/\n getDefaultUnitDecimalPlaces(\n measure: string,\n unitSystem: string,\n unit?: string\n ) {\n if (!measure) {\n throw new Error(\"measure is required\");\n }\n\n if (!unitSystem) {\n throw new Error(\"unitSystem is required\");\n }\n\n const displayDecimals = hasDecimals(this.displayOptions)\n ? this.displayOptions.decimals\n : this.regionInfo.getDefaultUnitDecimalPlaces(measure, unitSystem, unit);\n return displayDecimals;\n }\n\n /**\n * For cases where the default unit system is used, this method will return\n * the default unit for the given measure.\n * @param measure the measure to get the default unit for\n * @param unitSystem the unit system to use\n * @returns the default unit for the given measure\n * @throws Error if measure is not provided\n * @throws Error if unitSystem is not provided\n * @throws Error if the default unit for the given measure is not found\n **/\n getDefaultUnitForMeasure(measure: string, unitSystem: string) {\n if (!measure) {\n throw new Error(\"measure is required\");\n }\n\n if (!unitSystem) {\n throw new Error(\"unitSystem is required\");\n }\n return this.regionInfo.getDefaultUnitForMeasure(measure, unitSystem);\n }\n\n get schemaType() {\n const schema = this.bean.getSchemaForProperty(this.attribute);\n if (schema?.type) {\n return schema.type;\n } else {\n return \"String\";\n }\n }\n\n get schemaFormat() {\n const schema = this.bean.getSchemaForProperty(this.attribute);\n if (schema?.format) {\n return convertFormats(schema.format);\n }\n return \"\";\n }\n\n get options() {\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n const converter = this.getConverter();\n const system = converter?.to?.system ?? defaultUnitSystem;\n const schema = this.bean.getSchemaForProperty(this.attribute);\n const values = isEnum(schema)\n ? schema.values\n : configOptionsFactory(schema, system, converter?.from, converter?.to);\n\n const defaultOptions: OptionsType[] =\n values.length > 0\n ? values.map((value) => {\n return { label: value, value };\n })\n : [];\n\n if (this.optionsExpander) {\n if (typeof this.optionsExpander === \"function\") {\n return this.optionsExpander(system, values);\n } else {\n return this.optionsExpander;\n }\n }\n return defaultOptions;\n }\n\n convertUnit(\n converter?: UnitConverter,\n defaultSystem?: string,\n defaultMeasure?: string\n ) {\n const measure = converter?.measure || defaultMeasure;\n const system = converter?.system || defaultSystem;\n const unit = converter?.unit;\n\n return {\n measure,\n system,\n unit,\n };\n }\n\n getConverterUnits() {\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n const converter = this.getConverter();\n if (!converter) {\n throw Error(\"No converter defined\");\n }\n const measure = converter.measure;\n const backend: UnitSource = this.convertUnit(converter.from, \"si\", measure);\n const display = this.convertUnit(converter.to, defaultUnitSystem, measure);\n\n return { backend, display };\n }\n\n set value(value: ConfigPropertyTypes) {\n this.updateProperty(value);\n }\n get value() {\n return this.getValue(true);\n }\n\n get rawValue() {\n return this.bean.props[this.attribute];\n }\n\n get significantValue() {\n const _val = this.value;\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n const converter = this.getConverter();\n const measure = converter?.measure || converter?.to?.measure;\n\n if (!isNaN(_val as any) && converter && measure) {\n const decimals = this.getDefaultUnitDecimalPlaces(\n measure,\n defaultUnitSystem,\n converter?.to?.unit\n );\n\n try {\n const formatter = this.getFormatterOptions(converter);\n if (formatter) {\n let result = String(_val);\n\n result = formatter.formatToParts(Number(_val))[0].value;\n\n return Number(result);\n }\n } catch (e) {\n log.info(`error formatting value ${_val}`, e);\n }\n const result = Number(_val).toFixed(decimals);\n return result;\n }\n\n return _val;\n }\n\n get previousValue() {\n return this.getValue(false);\n }\n\n getValue(current: boolean) {\n const _val = this.bean[current ? \"props\" : \"prevProps\"][this.attribute];\n if (typeof _val === \"boolean\") {\n return _val;\n }\n\n const converter = this.getConverter();\n if (converter && !isNaN(_val as any)) {\n const { backend, display } = this.getConverterUnits();\n const result = this.regionInfo.convert(Number(_val), backend, display);\n return result;\n }\n return _val || \"\";\n }\n async activate() {\n log.debug(`activating config bean ${this.id}`);\n }\n\n get displayValue() {\n const _val = this.value;\n if (typeof _val === \"boolean\") {\n return String(_val);\n }\n\n if (this.schemaFormat === \"drt\") {\n const is12Hr = this.regionInfo.is12HourTimeFormat;\n const timeFormatString = is12Hr ? \"h:mm:ss a\" : \"HH:mm:ss\";\n return secondsToFormattedTime(_val as number, timeFormatString);\n }\n if (!isNaN(_val as any)) {\n try {\n const converter = this.getConverter();\n const formatter = this.getFormatterOptions(converter);\n if (formatter) {\n let result = String(_val);\n\n result = formatter.format(Number(_val));\n\n return result;\n }\n } catch (e) {\n log.error(`error formatting value ${_val}`, e);\n }\n }\n return String(_val);\n }\n\n get unit() {\n const converter = this.getConverter();\n if (!isNaN(this.value as any)) {\n const formatter = this.getFormatterOptions(converter);\n if (formatter) {\n const parts = formatter.formatToParts(Number(this.value));\n const _unit = parts.find((part) => part.type === \"unit\");\n return _unit?.value ?? this.getDefaultUnit(converter);\n }\n }\n return this.getDefaultUnit(converter);\n }\n\n get displayOptions() {\n const schema = this.bean.getSchemaForProperty(this.attribute);\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n const converter = this.getConverter();\n const system = converter?.to?.system ?? defaultUnitSystem;\n return displayOptionsFactory(schema, system);\n }\n\n private getMeasureFromFormat() {\n const format = this.schemaFormat;\n if (format) {\n const measure = this.regionInfo.getUnitMeasure(format);\n return measure;\n }\n return \"\";\n }\n private getConverterFromFormat() {\n const measure = this.getMeasureFromFormat();\n if (measure) {\n const currentSystem = this.regionInfo.selectedUnitSystem;\n const unit =\n this.schemaFormat ||\n this.regionInfo.getDefaultUnitForMeasure(measure, currentSystem);\n return { unit, measure };\n }\n return {};\n }\n private getDefaultUnit(converter?: ConfigPropConverter) {\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n const measure = converter?.measure;\n if (measure) {\n const defaultUnit =\n converter?.to?.unit ||\n this.getDefaultUnitForMeasure(\n measure,\n converter?.to?.system || defaultUnitSystem\n );\n return defaultUnit;\n }\n\n return this.getConverterFromFormat().unit;\n }\n\n getFormatterOptions(converter?: ConfigPropConverter) {\n const defaultUnitSystem = this.regionInfo.defaultUnitSystem;\n\n const measure = converter?.measure;\n const locale = new Intl.NumberFormat().resolvedOptions().locale;\n let formatter: Intl.NumberFormat | null = null;\n\n if (measure || this.formatter) {\n const defaultFormatter: Intl.NumberFormatOptions | null = measure\n ? {\n style: \"unit\",\n unit: this.getDefaultUnit(converter),\n }\n : null;\n\n const _formatter = this.formatter || defaultFormatter;\n if (_formatter) {\n let formatOptions =\n typeof _formatter === \"function\"\n ? _formatter(converter?.to?.system || defaultUnitSystem)\n : _formatter;\n if (measure) {\n formatOptions = {\n unit: this.getDefaultUnit(converter),\n ...formatOptions,\n };\n\n if (formatOptions.style === \"unit\") {\n formatOptions.maximumFractionDigits =\n formatOptions.maximumFractionDigits ??\n this.getDefaultUnitDecimalPlaces(\n measure,\n converter?.to?.system || defaultUnitSystem,\n converter?.to?.unit\n );\n }\n }\n try {\n formatter = new Intl.NumberFormat(locale, { ...formatOptions });\n } catch (e) {\n log.error(\n `error creating formatter ${formatOptions}. Returning the raw value`,\n e\n );\n }\n } else {\n log.debug(\n `no formatter found for config bean prop ${this.id}. Returning the raw value`\n );\n }\n }\n\n return formatter;\n }\n\n private getConverter(): ConfigPropConverter | undefined {\n const { unit: _unit, measure } = this.getConverterFromFormat();\n const unit = _unit === \"drt\" ? \"second\" : _unit;\n if (this.converter) {\n const globalMeasure = this.converter?.measure;\n const toMeasure = this.converter?.to?.measure;\n const fromMeasure = this.converter?.from?.measure;\n const _measure = globalMeasure || toMeasure || fromMeasure || measure;\n\n const toUnit =\n this.converter?.to?.unit ||\n this.regionInfo.getDefaultUnitForMeasure(\n _measure!,\n this.converter?.to?.system ?? this.regionInfo.defaultUnitSystem\n );\n const toSystem =\n this.converter?.to?.system ?? this.regionInfo.getUnitSystem(toUnit);\n\n const fromUnit =\n this.schemaFormat === \"drt\" ? \"second\" : this.schemaFormat || unit;\n return {\n ...this.converter,\n from: {\n unit: fromUnit,\n ...this.converter.from,\n },\n\n to: {\n ...this.converter.to,\n unit: toUnit,\n system: toSystem,\n },\n measure: _measure,\n };\n }\n\n if (unit && measure) {\n const toUnit = this.regionInfo.getDefaultUnitForMeasure(\n measure,\n this.regionInfo.defaultUnitSystem\n );\n const fromSystem = this.regionInfo.getUnitSystem(unit);\n const toSystem = this.regionInfo.getUnitSystem(toUnit);\n\n const isSameSystem = fromSystem === toSystem;\n return {\n measure,\n to: {\n unit: isSameSystem ? unit : toUnit,\n },\n };\n }\n return undefined;\n }\n async updateProperty(value: ConfigPropertyTypes) {\n log.debug(`updating property ${this.attribute} with value ${value}`);\n let _value = value;\n\n const converter = this.getConverter();\n if (converter && !isNaN(_value as any)) {\n const { backend, display } = this.getConverterUnits();\n\n _value = this.regionInfo.convert(Number(_value), display, backend);\n }\n\n const updateValue = Array.isArray(_value)\n ? JSON.stringify(_value)\n : String(_value);\n await this.bean.updateProperty(this.attribute, updateValue);\n }\n}\n\nconst Registration = {\n registration: {\n [MODEL_TYPE]: {\n class: KosConfigPropertyImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n factory: Kos.Factory.create<KosConfigProperty, ConfigBeanPropOptions>(\n MODEL_TYPE\n ),\n};\nexport default Registration;\n","/* eslint-disable no-param-reassign */\n\nimport { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { KosConfigPropertySpec } from \"../models/config-bean-prop\";\nimport { OptionsExpander } from \"../models/config-bean-prop/types\";\n\nexport interface ToUnitConverterSystem {\n iface: \"system\";\n system: string;\n}\n\nexport interface ToUnitConverterSystemUnit {\n iface: \"systemunit\";\n system: string;\n unit: string;\n}\n\nexport interface ToUnitConverterMeasure {\n iface: \"measure\";\n measure: string;\n}\n\nexport interface ToUnitConverterUnit {\n iface: \"unit\";\n unit: string;\n}\n\nexport type ToUnitConverter =\n | ToUnitConverterSystem\n | ToUnitConverterSystemUnit\n | ToUnitConverterMeasure\n | ToUnitConverterUnit;\nexport interface UnitConverter {\n system?: string;\n measure?: string;\n unit?: string;\n alias?: string;\n}\ninterface KosConfigParams {\n path: string;\n attribute: string;\n formatter?:\n | Intl.NumberFormatOptions\n | ((system: string) => Intl.NumberFormatOptions);\n optionsExpander?: OptionsExpander;\n lazy?: boolean;\n serviceBasePath?: string;\n converter?: {\n measure?: string;\n from?: UnitConverter | string;\n to?: UnitConverter | string;\n };\n}\n\nexport function kosConfigProperty(params: KosConfigParams) {\n const {\n path,\n attribute,\n converter,\n formatter,\n lazy,\n optionsExpander,\n serviceBasePath,\n } = params;\n const _converter = converter;\n if (_converter) {\n if (\n typeof _converter !== \"function\" &&\n typeof _converter.from === \"string\"\n ) {\n _converter.from = { unit: _converter.from };\n }\n\n if (typeof _converter !== \"function\" && typeof _converter.to === \"string\") {\n _converter.to = { unit: _converter.to };\n }\n }\n return (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: KosConfigPropertySpec.type,\n id: `${path}-${attribute}`,\n options: {\n path,\n attribute,\n serviceBasePath,\n converter: _converter,\n formatter,\n optionsExpander,\n },\n\n lifecycle: DependencyLifecycle.INIT,\n lazy,\n };\n };\n}\n","import {\n kosAutoEffect,\n KosLog,\n kosObservable,\n makeAutoObservable,\n} from \"../../../core\";\nimport {\n FutureAwareContainer,\n FutureContainer,\n IFutureModel,\n} from \"./future-types\";\n\nexport class MultipleFutureHandler<T extends {} = Record<string, unknown>>\n implements FutureAwareContainer<T>\n{\n private futures: Map<string, IFutureModel<T>>;\n private defaultContext: string;\n private context: string;\n private disposers = new Map<string, () => void>();\n private container?: FutureContainer<T>;\n constructor(container?: FutureContainer<T>, defaultContext?: string) {\n this.futures = kosObservable.map(new Map<string, IFutureModel<T>>());\n this.context = \"\";\n this.defaultContext = defaultContext || \"\";\n this.container = container;\n makeAutoObservable(this);\n }\n\n get allFutures() {\n return Array.from(this.futures.values());\n }\n\n get future() {\n return this.futures.get(this.defaultContext);\n }\n addFuture(future: IFutureModel<T>, alias?: string) {\n this.futures.set(alias || future.id, future);\n this.context = alias || future.id;\n const disposer = kosAutoEffect(() => {\n if (future.endState || future.progress) {\n this.container?.onFutureUpdate?.(future);\n }\n });\n this.disposers.set(alias || future.id, disposer);\n }\n\n removeFuture(alias?: string) {\n this.futures.delete(alias || this.context);\n this.disposers.get(alias || this.context)?.();\n this.disposers.delete(alias || this.context);\n }\n\n getFuture(alias?: string) {\n const future = this.futures.get(alias || this.context);\n return future;\n }\n}\n\nexport class FutureHandler<T extends object = Record<string, unknown>>\n implements FutureAwareContainer<T>\n{\n private disposer?: () => void;\n\n private _future?: IFutureModel<T>;\n private container?: FutureContainer<T>;\n constructor(container?: FutureContainer<T>) {\n this._future = undefined;\n this.container = container;\n makeAutoObservable(this);\n }\n removeFuture() {\n this._future = undefined;\n this.disposer?.();\n this.disposer = undefined;\n }\n\n get future() {\n return this._future;\n }\n getFuture(): IFutureModel<T> | undefined {\n return this._future;\n }\n\n addFuture(future: IFutureModel<T>) {\n this._future = future;\n\n const disposer = kosAutoEffect(() => {\n if (future.endState || future.progress) {\n this.container?.onFutureUpdate?.(future);\n }\n });\n this.disposer = disposer;\n }\n\n onFutureUpdate?: ((future: IFutureModel<T>) => void) | undefined;\n\n get allFutures() {\n return this._future ? [this._future] : [];\n }\n get timeRemaining() {\n return this._future?.timeRemaining || \"\";\n }\n\n get status() {\n return this._future?.status || \"NOT_RESOLVED\";\n }\n\n get progress() {\n return this._future?.progress || -1;\n }\n\n async cancel() {\n if (this._future) {\n try {\n await this._future.cancelFuture();\n } catch (e) {\n KosLog.error(e);\n throw e;\n }\n }\n }\n}\n","import { modelFactory } from \"../../../core\";\n\nimport type { IFutureModel, IFutureModelOptions } from \"./future-types\";\n\nexport const FUTURE_MODEL_TYPE = \"future-model\";\nexport const FutureFactory = modelFactory<IFutureModel, IFutureModelOptions>(\n FUTURE_MODEL_TYPE\n);\n","import { KosLog, resolveServiceUrl, ServiceFactory } from \"../../../core\";\n\nconst log = KosLog.createLogger({ name: \"future-service\", group: \"Services\" });\n\nconst { isMock, URL } = resolveServiceUrl(\"FUTURE_SERVICE\");\n\n/**\n * @category Service Module\n * @name /services/future\n * @version 1.0.0\n * @author Matthew Holman <maholman@coca-cola.com>\n *\n * Services that can be invoked to perform operations on Futures\n */\n\n/**\n * The possible endState codes returned by a Future\n */\nexport enum FutureEndState {\n Success = \"SUCCESS\",\n Fail = \"FAIL\",\n Aborted = \"ABORT\",\n Canceled = \"CANCEL\",\n}\n\n/**\n * The response from the server when an organization is\n * created or updated\n */\nexport interface FutureResponse {\n tracker?: string;\n /** the id of the Future */\n id: string;\n /** the remaining time of the Future */\n remainingTimeMs?: number;\n /** the progress of the Future */\n progress?: number;\n /** the end state of the Future */\n endState?: FutureEndState;\n /** the reason for a failure */\n reason?: string;\n /** object containing client data */\n clientData?: Record<string, unknown>;\n /** object containing reason data */\n reasonData?:\n | {\n name: string;\n version: string;\n }\n | {\n vmId: string;\n target: string;\n }\n | {\n vmId: string;\n target: string;\n }[];\n /** object containing client data */\n note?: string;\n}\n\nexport interface FutureRequest {\n /** the id of the Future to create */\n id: string;\n}\n\nconst { getAll, modifyModel, addModel, deleteModel, postModel } =\n ServiceFactory.build({\n destinationAddress: \"\",\n basePath: `${URL}/api/future`,\n mock: isMock,\n });\n\n// ------------------SERVICES----------------------\n\n/**\n * @category Service\n * Retrieves the list of Futures.\n */\nexport const getFutures = async () => {\n const response = await getAll<FutureResponse>({});\n return response;\n};\n\n/**\n * Removes an Future based on the id.\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the `/future/delete` event channel.\n *\n * @param futureId - the id of the future to be deleted\n * @returns an empty response with status 200.\n */\nexport const deleteFuture = async (id: string, path = \"/api/kos/future\") => {\n log.info(`sending delete request for Future: ${id}`);\n const response = await deleteModel({\n id,\n urlOverride: `${URL}${path}/${id}`,\n });\n return response;\n};\n\n/**\n * Adds a new Future.\n *\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the `/future/add` event channel.\n *\n * @param organization - the organization to be added\n * @returns an empty response with status 200.\n * @internal\n */\nexport const addFuture = async (\n future: FutureRequest,\n path = \"/api/kos/future\"\n) => {\n log.info(`sending add request for Future`);\n const response = await addModel({\n model: future,\n urlOverride: `${URL}${path}`,\n });\n return response;\n};\n\n/**\n * Modifies an Future from the server based on the id.\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the `/future/update` event channel.\n *\n * @param id - the id of the Future to be modified\n * @returns an empty response with status 200.\n */\nexport const modifyFuture = async (\n id: string,\n model: FutureRequest,\n path = \"/api/kos/future\"\n) => {\n log.info(`sending modify request for Future: ${id}`);\n const response = modifyModel({\n model,\n id,\n urlOverride: `${URL}${path}/${id}`,\n });\n return response;\n};\n\n/**\n * Cancels a Future from the server based on the id.\n *\n * @param id - the id of the Future to be modified\n * @returns an empty response with status 200.\n */\nexport const cancelFuture = async (id: string, path = \"/api/kos/future\") => {\n log.info(`sending cancel request for Future: ${id}`);\n const response = postModel({\n urlOverride: `${URL}${path}/${id}/cancel`,\n ordered: true,\n model: {},\n });\n return response;\n};\n","import { runInAction } from \"mobx\";\nimport { KosLog, ModelFactory, kosAction, pipe } from \"../../../core\";\nimport type { FutureResponse } from \"../../services/future\";\nimport type { IFutureModel, IFutureModelOptions } from \"./future-types\";\n\n/**\n * Maps a `FutureResponse` DTO to an `IFutureModelOptions` object.\n *\n * @remarks\n * This function will perform any type conversion or data mapping required\n * by the IKosDataModel. For example, date conversion or changes in interfaces\n * can be managed at this layer rather than having the models deal with the\n * various versions of the interface directly.\n *\n * @params dto - the Data Transfer Object received from the backend\n * @returns - a valid `IFutureModelOptions` that can be used to\n * instantiate a new model.\n * @internal\n * @category future\n */\nexport const mapDtoToFutureOptions = (dto: FutureResponse) => {\n const options: IFutureModelOptions = {\n id: String(dto.id),\n progress: dto.progress,\n remainingTimeMs: dto.remainingTimeMs,\n endState: dto.endState,\n reason: dto.reason,\n clientData: dto.clientData,\n reasonData: dto.reasonData,\n note: dto.note,\n tracker: dto.tracker,\n };\n\n return options;\n};\n\n/**\n * Maps a `FutureResponse` DTO to an `IFutureModel` object.\n *\n * @remarks\n * This function will run as a mobx action ensuring that all observers are notified\n * if any changes are made.\n *\n * @params dto - the Data Transfer Object received from the backend\n * @params model - the IModel to be update\n * @internal\n * @category future\n */\nexport const mapDtoToFutureModel = (\n dto: FutureResponse,\n model: IFutureModel\n) => {\n KosLog.debug(`future dto ${dto.id} end state ${dto.endState}`);\n KosLog.debug(`future model ${model.id} end state ${model.endState}`);\n if (!model.endState) {\n KosLog.debug(`updating future model ${model.id}`);\n // This just maps to the new options and auto updates the model with the props\n runInAction(() => {\n const options = mapDtoToFutureOptions(dto);\n\n kosAction(() => {\n Object.keys(options).forEach((prop) => {\n if (prop === \"id\") {\n model[\"futureId\"] = options[\"id\"];\n if (!options[\"tracker\"]) {\n model.id = options[\"id\"];\n }\n } else if (prop === \"tracker\") {\n model.id = options[\"tracker\"]!;\n } else {\n // checked if the model is already in an if (!model.endState) {\n model[prop] = options[prop];\n }\n });\n });\n });\n } else {\n KosLog.debug(`future model ${model.id} is already complete`);\n }\n};\n\n/**\n * Curried function that will produce a function that can be used to retrieve or create\n * new instances of a `IFutureModel` given an ID and options.\n *\n * @remarks\n * This serves as a convenience allowing for models to consumers to use a shorthand method when\n * multiple models need to be created.\n * The first level of function will accept a KOS Model Factory and return a function that can accept a single\n * model ID parameter. This will return a factory function that can accept a model options parameter and\n * instantiate a new instance of a model or retrieve a an existing model.\n *\n * @param factory - the model factory to be used\n * @returns - an instance of the `IFutureModel` that was either created\n * or retrieved from the KOS Model framework if already existing.\n *\n * @internal\n * @category future\n */\nexport const buildFutureModel =\n (factory: ModelFactory<IFutureModel, IFutureModelOptions>) =>\n (modelId: string) =>\n (futureOptions: IFutureModelOptions) => {\n const futureModel = factory.build(String(modelId), futureOptions);\n return futureModel;\n };\n\n/**\n * Factory function that simplifies the creation of a new model\n *\n * @remarks\n * This method will map the response object to an `IFutureModelOptions` instance and\n * construct a new instance of a model using the provided factory. This will provide a shorthand\n * for consumers when creating instances of models and allows for additional operations to be performed\n * as part of the creation process.\n *\n * @example\n * // create a new (potentially static) instance of the factory that can be used throughout the code.\n * const buildFutureModel = buildFuture((FutureModel.Factory));\n *\n * // use the builder to create a new instance of the model from an options instance.\n * const future: IFutureResponse = someFunctionToGetResponseFromServer();\n * const futureModel = buildFutureModel(future);\n *\n * @param factory - The model factory that can be used to\n *\n * @internal\n * @category future\n */\nexport const buildFuture =\n (factory: ModelFactory<IFutureModel, IFutureModelOptions>) =>\n (future: FutureResponse) =>\n pipe(\n mapDtoToFutureOptions,\n buildFutureModel(factory)(future.tracker || future.id)\n )(future);\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport {\n KosLog,\n destroyKosModel,\n kosModel,\n kosTopicHandler,\n kosWhen,\n type KosContextLogger,\n type KosCreationContext,\n} from \"../../../core\";\nimport {\n FutureEndState,\n cancelFuture,\n cancelFuture as cancelFutureService,\n type FutureResponse,\n} from \"../../services/future\";\nimport { mapDtoToFutureModel } from \"./future-model-builder\";\nimport type { IFutureModel, IFutureModelOptions } from \"./future-types\";\n\nimport { KOS_MODEL_ID } from \"../../../common\";\nimport { FUTURE_NOT_ASSIGNED } from \"../../constants\";\nimport { FutureFactory } from \"./future-factory\";\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\ninterface FutureModel extends IFutureModel {}\ntype TimeUnits = \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\";\nconst log = KosLog.getLogger(FutureFactory.type);\n\n/**\n * @category future\n * @name FutureModel\n * @version 1.0.0\n * @author Matthew Holman <maholman@coca-cola.com>\n *\n * Represents a future.\n */\n@kosModel(FutureFactory.type)\nclass FutureModel implements IFutureModel {\n private logger: KosContextLogger;\n private _cancelFuture: (\n id: string,\n path?: string\n ) => ReturnType<typeof cancelFutureService>;\n futureId: string;\n /**\n * @category Constructor\n *\n * @param modelId - the unique modelId for this Future\n * @param options - any options that should be merged into the Future\n * @params options.id - the unique id of the Future\n * @params options.name - the name of the Future\n *\n */\n constructor(\n modelId: string,\n options: IFutureModelOptions,\n context: KosCreationContext\n ) {\n Object.assign(this, options);\n\n this.logger = context.logger;\n // assign the id from the passed in model id\n this.id = modelId;\n this.futureId = options.id;\n this.namespace = options.namespace || \"kos\";\n // assign private methods from options\n\n this._cancelFuture = cancelFuture;\n\n kosWhen(\n () =>\n this.status === FutureEndState.Success ||\n this.status === FutureEndState.Fail,\n () => {\n log.info(`Future ${this.id} has completed with status ${this.status}`);\n destroyKosModel(this);\n }\n );\n }\n\n /**\n * @category Lifecycle\n *\n * @remarks\n * No action is taken as part of the load lifecycle method.\n *\n * In future additional information about the workspace could be loaded\n */\n async load() {\n log.debug(`loading Future ${this.id}`);\n }\n\n unload() {\n log.info(`unloading Future ${this.id}`);\n }\n\n // -------------------ACTIONS----------------------------\n\n /**\n * @category Action\n *\n * @remark\n * Cancels the current future.\n *\n * If a service was passed in as part of the options in the constructor\n * then it will be used. Otherwise the default services will be invoked.\n *\n * @see cancelFutureService\n */\n async cancelFuture() {\n const path =\n this.namespace === \"studio\"\n ? `/api/future`\n : `/api/${this.namespace}/future`;\n await kosWhen(() => this.futureId !== FUTURE_NOT_ASSIGNED);\n await this._cancelFuture(this.futureId, path);\n }\n\n get status() {\n return this.endState\n ? this.endState\n : this.progress > -1\n ? \"IN_PROGRESS\"\n : \"NOT_ACTIVE\";\n }\n\n get timeRemaining() {\n const remaining = this.remainingTimeMs || -1;\n\n if (remaining < 0) {\n return \"\";\n }\n\n const units: Record<TimeUnits, number> = {\n year: 1000 * 60 * 60 * 24 * 365,\n month: 1000 * 60 * 60 * 24 * 30,\n day: 1000 * 60 * 60 * 24,\n hour: 1000 * 60 * 60,\n minute: 1000 * 60,\n second: 1000,\n };\n\n let unit: Intl.RelativeTimeFormatUnit = \"second\",\n value = 0;\n for (const [key, milliseconds] of Object.entries(units)) {\n if (Math.abs(remaining) >= milliseconds) {\n unit = key as TimeUnits;\n value = Math.round(remaining / milliseconds);\n break;\n }\n }\n\n const rtf = new Intl.RelativeTimeFormat(\"en\", { numeric: \"auto\" });\n const parts = rtf.formatToParts(value, unit);\n\n // Step 6: Construct the custom \"remaining\" message\n const formattedTime =\n parts.length === 3\n ? `${parts[1]?.value ?? 0} ${parts[2]?.value ?? \"\"}`\n : \"0 seconds\";\n\n return formattedTime;\n }\n\n // ------------------SUBSCRIPTIONS----------------------\n\n /**\n * @category Subscription\n * Updates the Future model when a `kos.future/ID` event\n * is received from the server.\n *\n *\n * @param data - the raw callback\n * @param data.body - the Future that was updated.\n * @see FutureResponse\n */\n @kosTopicHandler({\n topic: `kos.future/${KOS_MODEL_ID}`,\n })\n handleFutureUpdated(future: FutureResponse) {\n this.logger.debug(\n `Future ${this.id} updated. future: ${future.id} endState: ${future.endState} progress: ${future.progress} remainingTimeMs: ${future.remainingTimeMs}`\n );\n mapDtoToFutureModel(future, this);\n }\n}\n\nexport default FutureModel;\n","import {\n createClient,\n type AvailableMethods,\n type ClientResponse,\n} from \"../../core\";\nimport type { paths } from \"./types\";\n\nexport const api = createClient<paths>();\n\nexport type BaseResponseType<\n K extends keyof paths,\n M extends AvailableMethods<paths[K]>\n> = ClientResponse<paths, K, M>;\n","import {\n BrowserKosRouter,\n type IKosDataModel,\n type IKosIdentifiable,\n type KosContextLogger,\n type KosCreationContext,\n type KosMethodTypes,\n type KosMiddleware,\n kosModel,\n type KosRequest,\n type KosResponse,\n kosTopicHandler,\n type PublicModelInterface,\n sendKosHttpMessageResponse,\n} from \"../../../core\";\n\nimport type { BrowserRouterOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"browser-router-model\";\n\nconst HTTP_REQUEST_TOPIC = \"kos.http.request\";\nconst HTTP_RESPONSE_TOPIC = \"kos.http.response\";\nexport type KosBrowserRouter = Omit<\n PublicModelInterface<BrowserRouterModelImpl>,\n \"load\" | \"init\"\n>;\n\n@kosModel(MODEL_TYPE)\nexport class BrowserRouterModelImpl implements IKosDataModel, IKosIdentifiable {\n private _id: string;\n private logger: KosContextLogger;\n\n private router: BrowserKosRouter;\n constructor(\n modelId: string,\n _options: BrowserRouterOptions,\n context: KosCreationContext\n ) {\n this._id = modelId;\n this.logger = context.logger;\n this.router = new BrowserKosRouter();\n }\n\n get id(): string {\n return this._id;\n }\n\n @kosTopicHandler({\n topic: HTTP_REQUEST_TOPIC,\n })\n private async handleRequest(_data, payload): Promise<void> {\n const destination = payload.headers[\"src-addr\"];\n const src = payload.headers[\"dst-addr\"];\n const url = payload.headers[\"url\"];\n const method = payload.headers[\"method\"];\n const requestId = payload.headers[\"request-id\"];\n const rawReq: Omit<KosRequest, \"params\" | \"query\"> = {\n id: requestId,\n method,\n path: url,\n };\n\n let status = 200;\n const res: KosResponse = {\n send: (data: any) => {\n this.logger.debug(`sending response to ${src}`);\n this.logger.debug(data);\n sendKosHttpMessageResponse({\n msg: data,\n options: {\n responseId: requestId,\n destinationAddress: destination,\n type: HTTP_RESPONSE_TOPIC,\n sourceAddress: src,\n status: status,\n },\n });\n },\n status: function (code) {\n status = code;\n return this;\n },\n };\n\n if (rawReq.path === \"/openapi.json\") {\n res.send(this.router.generateOpenApiSpec());\n return;\n }\n await this.router.handle(rawReq, res);\n }\n\n use<TPath extends string = string>(\n method: KosMethodTypes,\n path: TPath,\n ...middlewares: KosMiddleware<TPath>[]\n ): void {\n this.router.use(method, path, ...middlewares);\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing browser-router ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading browser-router ${this.id}`);\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { KosBrowserRouter } from \"./browser-router-model\";\nimport { BrowserRouterModelImpl, MODEL_TYPE } from \"./browser-router-model\";\nimport type { BrowserRouterOptions } from \"./types\";\n\n/**\n * # BrowserRouter\n *\n * The registration bean includes convenience methods for creating and working with BrowserRouterModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: BrowserRouter.type, id: \"browserRouterId\"})\n * private browserRouterModel: BrowserRouterModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new BrowserRouterModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = BrowserRouter.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a BrowserRouterModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (BrowserRouter.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to BrowserRouterModel\n * // and the compiler will know that the model has the BrowserRouterModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { BrowserRouter } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(BrowserRouter);\n * ```\n *\n * ## registration.singleton\n \n * The browserRouter model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const BrowserRouter = new SingletonKosModelRegistrationFactory<\n KosBrowserRouter,\n BrowserRouterOptions\n>({\n class: BrowserRouterModelImpl,\n type: MODEL_TYPE,\n});\n","import { modelFactory } from \"../../../core\";\n\nimport type {\n IFutureContainerModel,\n IFutureContainerModelOptions,\n} from \"./future-container-types\";\n\nexport const FUTURE_CONTAINER_MODEL_TYPE = \"future-container-model\";\nexport const FutureContainerFactory = modelFactory<\n IFutureContainerModel,\n IFutureContainerModelOptions\n>(FUTURE_CONTAINER_MODEL_TYPE);\n","import type { IFutureModel } from \"../../models/future/future-types\";\nimport { FutureFactory } from \"../../models/future/future-factory\";\nimport { buildFuture } from \"../../models/future/future-model-builder\";\nimport { FutureResponse } from \"../../services/future\";\nimport { FutureContainerFactory } from \"../../models/future-container/future-container-factory\";\n\nconst buildFutureModel = (payload: FutureResponse): IFutureModel => {\n /**\n * Handle all plumbing for creating a new Future.\n */\n const buildFutureModelFactory = buildFuture(FutureFactory);\n const newFutureModel = buildFutureModelFactory(payload);\n return newFutureModel;\n\n /** Callback where once an event comes it, we can immediately create the Future\n * and push it into the container.\n */\n /** Initiate Future - call the 'buildFuture' and then add it to the container */\n};\n\nconst initiateFuture = (payload: FutureResponse) => {\n const futureModel = buildFutureModel(payload);\n\n // get the Future container to add a model\n const futureContainer = FutureContainerFactory.build(\n FutureContainerFactory.type,\n {}\n );\n\n futureContainer.addFutureModel(futureModel);\n return futureModel;\n};\n\nconst getFuture = <T extends {}>(id: string) => {\n const futureContainer = FutureContainerFactory.build(\n FutureContainerFactory.type,\n {}\n );\n\n return futureContainer.getFuture(String(id)) as IFutureModel<T>;\n};\n\nexport const FutureManager = {\n buildFutureModel,\n initiateFuture,\n getFuture,\n};\n","/**\n * @internal\n */\nimport {\n KosContextLogger,\n KosLog,\n KosModelContainer,\n kosChild,\n kosModel,\n kosTopicHandler,\n type IKosModelContainer,\n type KosCreationContext,\n type KosServiceResponse,\n} from \"../../../core\";\nimport type { FutureRequest, FutureResponse } from \"../../services/future\";\n\nimport { EventBus, type ApiCallback } from \"../../../common\";\nimport {\n addFuture as addFutureService,\n deleteFuture as deleteFutureService,\n} from \"../../services/future\";\nimport { FutureManager } from \"../../utils/future-manager\";\nimport type { IFutureModel } from \"../future\";\nimport { buildFuture } from \"../future\";\nimport { FutureFactory } from \"../future/future-factory\";\nimport { FutureContainerFactory } from \"./future-container-factory\";\nimport type {\n IFutureContainerModel,\n IFutureContainerModelOptions,\n} from \"./future-container-types\";\nconst log = KosLog.getLogger(FutureContainerFactory.type);\n\n/**\n * @category future\n * @name FutureContainerModel\n * @version 1.0.0\n * @author Matthew Holman <maholman@coca-cola.com>\n * @internal\n * Represents a list of Future\n */\n@kosModel(FutureContainerFactory.type)\nclass FutureContainerModel implements IFutureContainerModel {\n id: string;\n private logger: KosContextLogger;\n private _deleteFuture: (\n groupId: string\n ) => Promise<KosServiceResponse<unknown> | undefined>;\n private _addFuture: (\n future: FutureRequest\n ) => Promise<KosServiceResponse<any> | undefined>;\n\n @kosChild\n private _futures: IKosModelContainer<IFutureModel>;\n createModel: <T = void>(request: FutureRequest) => Promise<T>;\n deleteModel: (id: string) => Promise<void>;\n\n constructor(\n modelId: string,\n options: IFutureContainerModelOptions,\n context: KosCreationContext\n ) {\n const { deleteFuture = deleteFutureService, addFuture = addFutureService } =\n options;\n this.logger = context.logger;\n this._deleteFuture = deleteFuture;\n this._addFuture = addFuture;\n this.id = modelId;\n this._futures = new KosModelContainer();\n this.createModel = this.createFuture;\n this.deleteModel = this.removeFuture;\n }\n\n /**\n * @category Computed\n * @getter\n * Computed value that will recalculate automatically whenever Futures\n * are added or removed from the map.\n *\n * @returns the list of Futures\n *\n * @internal\n */\n get futures() {\n return this._futures.data;\n }\n\n get models() {\n return this.futures;\n }\n\n /**\n * Convenience function that will retrieve the IFutureModel based on\n * the id.\n *\n * @param futureId - the id of the future to be retrieved\n * @returns the `IFutureModel` or `undefined` if not available in the list\n * @internal\n */\n getFuture(futureId: string) {\n return this._futures.getModel(futureId);\n }\n\n /**\n * @category Action\n * Internally adds the provided Future to the map\n *\n * @param group - The Future model to add\n * @internal\n */\n addFutureModel(model: IFutureModel) {\n this._futures.addModel(model);\n }\n\n /**\n * @category Action\n * Internally adds the provided Future to the map\n *\n * @param group - The Future model to add\n * @internal\n */\n removeFutureModel(id: string) {\n this._futures.removeModel(id);\n }\n\n /**\n * This is the entry point which enables an this model to be “visited” by a visitor object.\n *\n * @remarks\n * Futures as part of a KOS Model Visitor pattern allowing clients\n * to traverse the KOS Model hierarchy and perform operations on elements\n * as they are \"visited\".\n *\n * Ths method serves as an entry point for visitors allowing them to dispatch\n * actions on elements in a collection without requiring the models to have\n * explicit knowledge of the operation being performed.\n *\n * @category KOS Model\n * @internal\n */\n\n /**\n * Gets the direct children of this Future collection.\n *\n * @remarks\n * Allows the KOS Model framework to operate off of a directed graph\n * and perform generic operations on collections of models by traversing\n * the hierarchy.\n *\n * This method will inform the framework of what child models exist in a containment\n * relationship.\n *\n * @returns - the collection of Future models maintained by this model.\n * @category KOS Model\n * @internal\n */\n\n // -------------------ACTIONS----------------------------\n /**\n * Removes a Future model from the collection.\n *\n * @remarks\n * If a remove service function was passed in as part of the options\n * in the constructor then it will be used. Otherwise the default\n * delete service will be invoked.\n *\n * @param id - the id of the Future to be removed\n *\n * @see deleteFutureService\n * @category Action\n * @internal\n */\n async removeFuture(id: string) {\n try {\n await this._deleteFuture(id);\n } catch (e) {\n log.error(`error deleting a Future`);\n log.error(e);\n }\n }\n /**\n * Adds a Future model into the collection.\n *\n * @remarks\n * If an add service function was passed in as part of the options\n * in the constructor then it will be used. Otherwise the default\n * add service will be invoked.\n *\n * @param model - the Future model to be added\n *\n * @see addFutureService\n * @category Action\n * @internal\n */\n async createFuture(model: FutureRequest) {\n try {\n const response = await this._addFuture(model);\n const data: FutureResponse | undefined = response?.data;\n if (data) {\n const model = buildFuture(FutureFactory)(data);\n this.addFutureModel(model);\n return model;\n }\n } catch (e) {\n log.error(`error creating a Future`);\n log.error(e);\n throw e;\n }\n return undefined;\n }\n\n // ------------------SUBSCRIPTIONS----------------------\n\n @kosTopicHandler({\n topic: \"kos.future\",\n })\n handleFutureUpdated(future: FutureResponse, payload: ApiCallback) {\n const newFutureModel = FutureManager.buildFutureModel(future);\n this.addFutureModel(newFutureModel);\n const topic = `kos.future/${future.tracker || future.id}`;\n this.logger.debug(`publishing future update to ${topic}`);\n EventBus.publish(topic, payload.body, payload.headers);\n }\n}\n\nexport default FutureContainerModel;\n","import { KosLog, ServiceFactory, resolveServiceUrl } from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"KEY_VALUE_SERVICE\");\nconst { getOne, postModel, deleteModel } = ServiceFactory.build({\n basePath: `${URL}/api/keyVal`,\n});\n\nconst log = KosLog.createLogger({\n name: \"key-value-service\",\n group: \"Services\",\n});\ninterface KeyValueResponse {\n [key: string]: string | number | boolean;\n}\n\nexport interface KeyValueUpdate {\n namespace: string;\n key: string;\n value: string;\n}\n\nexport const deleteKeyValue = async (namespace: string, key: string) => {\n await deleteModel({\n urlOverride: `${URL}/api/keyVal/${namespace}/${key}`,\n id: key,\n });\n};\nexport const updateKeyValue = async (\n namespace: string,\n key: string,\n value: string | number | boolean\n) => {\n const response = await postModel<string>({\n urlOverride: `${URL}/api/keyVal/${namespace}/${key}`,\n model: value.toString(),\n });\n\n if (response?.status !== 200) {\n log.error(\"Failed to update studio-state data\", response);\n throw new Error(\n `Failed to update studio-state data for namespace ${namespace}`\n );\n }\n return response.data;\n};\n/**\n * @category Service\n * Retrieves the initial studio-state data.\n */\nexport const getKeyValue = async (namespace = \"studio\") => {\n log.debug(\"sending GET for studio-state\");\n const response = await getOne<KeyValueResponse>({\n urlOverride: `${URL}/api/keyVal/${namespace}`,\n });\n\n if (response?.status !== 200) {\n log.error(\"Failed to retrieve studio-state data\", response);\n throw new Error(\n `Failed to retrieve studio-state data for namespace ${namespace}`\n );\n }\n return response.data;\n};\n\nexport const deleteKeyValueNamespace = async (namespace: string) => {\n await deleteModel({\n urlOverride: `${URL}/api/keyVal/${namespace}}`,\n id: \"\",\n });\n};\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n KosContextLogger,\n KosCreationContext,\n KosData,\n PublicModelInterface,\n} from \"../../../core\";\nimport { ObservableData, kosModel, kosTopicHandler } from \"../../../core\";\nimport {\n deleteKeyValue,\n getKeyValue,\n updateKeyValue,\n type KeyValueUpdate,\n} from \"./services\";\nimport type { KeyValueOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"key-value-model\";\n\nexport type KeyValueModel = PublicModelInterface<KeyValueModelImpl>;\n\n@kosModel(MODEL_TYPE)\nexport class KeyValueModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n private logger: KosContextLogger;\n private namespace: string;\n data: KosData<Record<string, string | number | boolean | undefined>>;\n constructor(\n modelId: string,\n options: KeyValueOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.data = ObservableData();\n this.namespace = options.namespace || \"studio\";\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing studio-state ${this.id}`);\n }\n\n async updateState(\n key: string,\n value: string | number | boolean | undefined\n ): Promise<void> {\n this.logger.debug(`updating studio-state ${key} with value ${value}`);\n if (value !== undefined) {\n await updateKeyValue(this.namespace, key, value);\n this.data[key] = value;\n } else {\n await deleteKeyValue(this.namespace, key);\n this.data[key] = undefined;\n }\n }\n async load(): Promise<void> {\n this.logger.debug(`loading studio-state ${this.id}`);\n const studioState = await getKeyValue(this.namespace);\n this.data.setValues(studioState);\n }\n\n @kosTopicHandler({ topic: \"/keyVal/set\" })\n handleStateUpdate(update: KeyValueUpdate) {\n if (update.namespace !== this.namespace) {\n return;\n }\n this.data[update.key] = update.value;\n }\n\n @kosTopicHandler({ topic: \"/keyVal/remove\" })\n handleStateDelete(update: KeyValueUpdate) {\n if (update.namespace !== this.namespace) {\n return;\n }\n this.data[update.key] = undefined;\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core\";\nimport type { KeyValueModel } from \"./key-value-model\";\nimport { KeyValueModelImpl, MODEL_TYPE } from \"./key-value-model\";\nimport type { KeyValueOptions } from \"./types\";\n\n/**\n * # KeyValue\n *\n * The registration bean includes convenience methods for creating and working with KeyValueModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: KeyValue.type, id: \"studioStateId\"})\n * private studioStateModel: KeyValueModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new KeyValueModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = KeyValue.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a KeyValueModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (KeyValue.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to KeyValueModel\n * // and the compiler will know that the model has the KeyValueModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { KeyValue } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(KeyValue);\n * ```\n *\n * ## registration.singleton\n \n * The studioState model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const KeyValue = new KosModelRegistrationFactory<\n KeyValueModel,\n KeyValueOptions\n>({\n class: KeyValueModelImpl,\n type: MODEL_TYPE,\n});\n","import {\n KosLog,\n ServiceFactory,\n resolveServiceUrl,\n type KosServiceResponse,\n} from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"KOS-TIME_SERVICE\");\nconst { postModel, getOne } = ServiceFactory.build({\n basePath: `${URL}/api/kos-time`,\n});\n\ninterface TimeBean {\n hour: number;\n min: number;\n sec: number;\n}\n\ninterface DateBean {\n month: number;\n day: number;\n year: number;\n}\n\ninterface TimezoneResponse {\n timeZone: string;\n}\n\nconst log = KosLog.createLogger({\n name: \"kos-time-service\",\n group: \"Services\",\n});\ninterface KosTimeResponse {\n id: string;\n}\n\nexport const setTime = async (time: TimeBean) => {\n const response: KosServiceResponse<any> | undefined =\n await postModel<TimeBean>({\n model: time,\n urlOverride: `${URL}/api/kos/time/time`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set time\");\n }\n\n return response.data;\n};\n\nexport const setDate = async (date: DateBean) => {\n const response: KosServiceResponse<any> | undefined =\n await postModel<DateBean>({\n model: date,\n urlOverride: `${URL}/api/kos/time/date`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set time\");\n }\n\n return response.data;\n};\n\nexport const setTimezone = async (timezone: string) => {\n const response: KosServiceResponse<any> | undefined = await postModel({\n model: {},\n urlOverride: `${URL}/api/kos/time/timezone?tz=${timezone}`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set timezone\");\n }\n\n return response.data;\n};\n\nexport const getTimezone = async () => {\n const response: KosServiceResponse<TimezoneResponse> | undefined =\n await getOne<TimezoneResponse>({\n urlOverride: `${URL}/api/kos/time/timezone`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set timezone\");\n }\n\n return response.data.timeZone;\n};\n","import { EventBus } from \"../../../common\";\nimport type {\n IKosDataModel,\n IKosModelLogger,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosModel, kosTopicHandler } from \"../../../core\";\nimport { Topics } from \"../../constants\";\nimport { getTimezone, setDate, setTime, setTimezone } from \"./services\";\nimport { type DateBean, type KosTimeOptions, type TimeBean } from \"./types\";\nexport const MODEL_TYPE = \"kos-time-model\";\n\nconst TOPIC_TIME_CHANGE = \"/kos/time/time\";\nconst TOPIC_DAY_CHANGE = \"/kos/time/day\";\nconst TOPIC_TIMEZONE_CHANGE = \"/kos/time/timezone\";\n\nexport type KosTimeModel = PublicModelInterface<KosTimeModelImpl>;\n@kosModel(MODEL_TYPE)\nexport class KosTimeModelImpl implements IKosModelLogger, IKosDataModel {\n id: string;\n logger: KosContextLogger;\n timezone: string;\n constructor(\n modelId: string,\n _options: KosTimeOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.timezone = \"\";\n }\n\n /**\n * Updates the system clock to the provided time.\n *\n * @param time - The time to set the system time to\n */\n async updateSystemTime(time: TimeBean) {\n await setTime(time);\n }\n\n /**\n * Updates the system clock to the provided date.\n *\n * @param date - The date to set the system date to\n */\n async updateSystemDate(date: DateBean) {\n await setDate(date);\n }\n\n /**\n * Updates the system clock to the provided timezone.\n * @param timezone - The timezone to set the system timezone to\n */\n async updateSystemTimezone(timezone: string) {\n await setTimezone(timezone);\n }\n\n @kosTopicHandler({ topic: TOPIC_TIME_CHANGE, websocket: true })\n handleTimeChange(): void {\n // Handle time change here.\n EventBus.publish(Topics.TIME_CHANGE, {});\n }\n\n @kosTopicHandler({ topic: TOPIC_DAY_CHANGE, websocket: true })\n handleDayChange(): void {\n // Handle day change here.\n EventBus.publish(Topics.DAY_CHANGE, {});\n }\n\n @kosTopicHandler({ topic: TOPIC_TIMEZONE_CHANGE, websocket: true })\n async handleTimeZoneChange() {\n await this.retrieveTimezone();\n // Handle timezone change here.\n EventBus.publish(Topics.TIMEZONE_CHANGE, {});\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing kos-time ${this.id}`);\n }\n\n private async retrieveTimezone() {\n const tz = await getTimezone();\n this.setTimezone(tz);\n }\n setTimezone(tz: string) {\n this.timezone = tz;\n }\n async load(): Promise<void> {\n this.logger.debug(`loading kos-time ${this.id}`);\n this.retrieveTimezone();\n }\n}\n","import type { SingletonKosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport type { KosTimeModel } from \"./kos-time-model\";\nimport { KosTimeModelImpl, MODEL_TYPE } from \"./kos-time-model\";\nimport type { KosTimeOptions } from \"./types\";\n\n/**\n * # KosTime\n *\n * The registration bean includes convenience methods for creating and working with KosTimeModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: KosTime.type, id: \"kosTimeId\"})\n * private kosTimeModel: KosTimeModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new KosTimeModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = KosTime.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a KosTimeModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (KosTime.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to KosTimeModel\n * // and the compiler will know that the model has the KosTimeModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { KosTime } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...KosTime.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The kosTime model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n * @private\n * */\nexport const KosTime: Readonly<\n SingletonKosModelRegistrationBean<KosTimeModel, KosTimeOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: KosTimeModelImpl,\n singleton: true,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Singleton.create<KosTimeModel, KosTimeOptions>(MODEL_TYPE),\n};\n","import { kosChild, kosModel } from \"../../../core/core/decorators\";\nimport {\n KosModelContainer,\n type IKosModelContainer,\n} from \"../../../core/core/kos-container-model\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type {\n IKosModelHolder,\n PublicModelInterface,\n} from \"../../../core/types\";\n\nimport type { LogBlockModel } from \"./log-block-model\";\nimport type { LogBlockContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"log-block-container-model\";\n\nexport type LogBlockContainerModel =\n PublicModelInterface<LogBlockContainerModelImpl>;\n\n@kosModel(MODEL_TYPE)\nexport class LogBlockContainerModelImpl\n implements IKosIdentifiable, IKosModelHolder<LogBlockModel>, IKosDataModel\n{\n id: string;\n private logger: KosContextLogger;\n @kosChild private _models: IKosModelContainer<LogBlockModel>;\n constructor(\n modelId: string,\n options: LogBlockContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._models = new KosModelContainer<LogBlockModel>({\n parentId: modelId,\n sortKey: \"blockNum\",\n });\n if (options) {\n // Assign options properties here.\n }\n }\n\n getModel(id: string) {\n return this._models.getModel(id);\n }\n get models() {\n return this._models;\n }\n get data() {\n return this._models.data;\n }\n\n addModel(model: LogBlockModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing log-block-container container ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading log-block-container container ${this.id}`);\n }\n}\n","import { createClient, type PathsByMethod } from \"../../core\";\nimport { paths } from \"./openapi\";\n\nconst api = createClient<paths>();\n\nexport type KosApi = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\nexport type GetPaths = ValidPaths[\"get\"];\nexport type PostPaths = ValidPaths[\"post\"];\nexport type PutPaths = ValidPaths[\"put\"];\nexport type DeletePaths = ValidPaths[\"delete\"];\n\nexport default api;\n","import {\n getQueryParams,\n KosLog,\n type ClientResponse,\n type DeepRequired,\n type ElementType,\n type ServiceResponse,\n} from \"../../../../core\";\n\nimport API, { type ApiPath, type KosApi } from \"../../../utils/service\";\nimport type { LogLinesType } from \"../../log-block\";\n\nconst log = KosLog.createLogger({\n name: \"log-stream-container-service\",\n group: \"Services\",\n});\n\nexport const getKosConnectionId = (): string | undefined => {\n const params = getQueryParams();\n const connId = (params as any)?.connId;\n const result = connId || (window as any)?.kosBridge?.(\"connId\");\n\n KosLog.error(`getKosConnectionId: ${result}`);\n\n return result;\n};\n\nconst destinationAddress = getKosConnectionId();\n\nconst SERVICE_PATH: ApiPath = \"/api/kos/logs/node/{nodeId}/streams\";\nexport type LogStreamContainerClientResponse = ClientResponse<\n KosApi,\n typeof SERVICE_PATH,\n \"get\"\n>;\nexport type LogStreamContainerResponse = DeepRequired<\n ElementType<LogStreamContainerClientResponse>\n>;\n\n/**\n * @category Service\n * Retrieves the initial list of log-stream-container data.\n */\nexport const getLogStreams = async (): Promise<\n ServiceResponse<LogStreamContainerClientResponse>\n> => {\n log.debug(\"sending GET for log-stream-container\");\n return await API.get(\n SERVICE_PATH,\n {\n path: {\n nodeId: \"primary\",\n },\n },\n {\n destinationAddress,\n }\n );\n};\n\nexport const subscribeToLogStream = async (\n stream: string,\n nodeId = \"primary\"\n): Promise<void> => {\n const repsonse = await API.post(\n \"/api/kos/logs/node/{nodeId}/{stream}/subscribe\",\n {\n path: {\n nodeId: nodeId,\n stream,\n },\n },\n undefined,\n {\n destinationAddress,\n }\n );\n};\n\nexport const unsubscribeFromLogStream = async (\n stream: string\n): Promise<void> => {\n const repsonse = await API.post(\n \"/api/kos/logs/node/{nodeId}/{stream}/unsubscribe\",\n { path: { nodeId: \"primary\", stream } },\n undefined,\n {\n destinationAddress,\n }\n );\n};\n\nexport const createOverride = async (): Promise<void> => {\n const repsonse = await API.post(\n \"/api/kos/logs/overrides\",\n {},\n {\n level: \"WARN\",\n name: \"com.example\",\n nodeType: \"java\",\n type: \"package\",\n },\n {\n destinationAddress,\n }\n );\n};\n\nconst SERVICE_BLOCKS_PATH: ApiPath =\n \"/api/kos/logs/node/{nodeId}/{stream}/blocks\";\nexport type LogStreamBlocksClientResponse = ClientResponse<\n KosApi,\n typeof SERVICE_BLOCKS_PATH,\n \"get\"\n>;\n\nexport const getLogStreamBlocks = async (\n stream: string\n): Promise<ServiceResponse<LogStreamBlocksClientResponse>> => {\n const response = await API.get(\n \"/api/kos/logs/node/{nodeId}/{stream}/blocks\",\n {\n path: {\n nodeId: \"primary\",\n stream,\n },\n },\n {\n destinationAddress,\n }\n );\n return response;\n};\n\nexport const getLogStreamBlock = async (\n stream: string,\n blockId: number\n): Promise<ServiceResponse<LogLinesType>> => {\n const response = await API.get(\n \"/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}\",\n {\n path: {\n nodeId: \"primary\",\n stream,\n blockId,\n },\n },\n {\n destinationAddress,\n }\n );\n return response as ServiceResponse<LogLinesType>;\n};\n","import { kosModel } from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { getLogStreamBlock } from \"../log-stream/services\";\n\nimport type { LogBlockOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"log-block-model\";\n\nexport type LogBlockModel = PublicModelInterface<LogBlockModelImpl>;\n\n@kosModel(MODEL_TYPE)\nexport class LogBlockModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n private logger: KosContextLogger;\n nodeId: string;\n stream: string;\n blockNum: number;\n startLineNum: number;\n endLineNum: number;\n startTime: Date;\n endTime: Date;\n lineCount: number;\n lines: string[];\n\n inc: number;\n constructor(\n modelId: string,\n options: LogBlockOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n this.nodeId = options.nodeId;\n this.stream = options.stream;\n this.blockNum = options.blockNum;\n this.startLineNum = options.startLineNum;\n this.endLineNum = options.endLineNum;\n this.startTime = options.startTime;\n this.endTime = options.endTime;\n this.lineCount = options.lineCount;\n this.lines = [];\n this.inc = 0;\n }\n\n async syncLines(): Promise<void> {\n const [error, blockData] = await getLogStreamBlock(\n this.stream,\n this.blockNum\n );\n\n if (error) {\n this.logger.error(`Failed to get log block ${this.blockNum}`);\n return;\n }\n if (blockData) {\n this.addLines(blockData.lines, true);\n }\n }\n\n updateModel(options: LogBlockOptions): void {\n this.startLineNum = options.startLineNum;\n this.endLineNum = options.endLineNum;\n this.startTime = options.startTime;\n this.endTime = options.endTime;\n this.lineCount = options.lineCount;\n }\n\n addLines(lines: string[], replace?: boolean): void {\n const baseLines = replace ? [] : this.lines;\n\n this.lines = [...baseLines, ...lines];\n this.inc += 1;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing log-block ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading log-block ${this.id}`);\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { LogBlockModel } from \"./log-block-model\";\nimport { LogBlockModelImpl, MODEL_TYPE } from \"./log-block-model\";\nimport type { LogBlockOptions } from \"./types\";\n\n/**\n * # LogBlock\n *\n * The registration bean includes convenience methods for creating and working with LogBlockModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: LogBlock.type, id: \"logBlockId\"})\n * private logBlockModel: LogBlockModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new LogBlockModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = LogBlock.factory(\"logBlockId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a LogBlockModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (LogBlock.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to LogBlockModel\n * // and the compiler will know that the model has the LogBlockModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { LogBlock } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(LogBlock);\n * ```\n *\n * ## registration.singleton\n \n * The logBlock model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const LogBlock = new KosModelRegistrationFactory<\n LogBlockModel,\n LogBlockOptions\n>({\n class: LogBlockModelImpl,\n type: MODEL_TYPE,\n});\n","import { KosModelRegistrationFactory } from \"../../../core\";\nimport type { LogBlockContainerModel } from \"./log-block-container-model\";\nimport {\n LogBlockContainerModelImpl,\n MODEL_TYPE,\n} from \"./log-block-container-model\";\nimport { LogBlock } from \"./log-block-registration\";\nimport type { LogBlockContainerOptions } from \"./types\";\n\n/**\n * # LogBlockContainer\n *\n * The registration bean includes convenience methods for creating and working with LogBlockContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: LogBlockContainer.type, id: \"logBlockContainerId\"})\n * private logBlockContainerModel: LogBlockContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new LogBlockContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = LogBlockContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a LogBlockContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (LogBlockContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to LogBlockContainerModel\n * // and the compiler will know that the model has the LogBlockContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { LogBlockContainer } from \"@kosdev-code/kos-ui-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...LogBlockContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The logBlockContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const LogBlockContainer = new KosModelRegistrationFactory<\n LogBlockContainerModel,\n LogBlockContainerOptions\n>({\n class: LogBlockContainerModelImpl,\n type: MODEL_TYPE,\n});\n\nLogBlockContainer.addRelatedModel(LogBlock);\n","import { kosEffect } from \"../../../core\";\nimport { kosChild, kosModel } from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n IKosVisitor,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport {\n LogBlock,\n LogBlockContainer,\n type LogBlockContainerModel,\n type LogBlockOptions,\n type LogBlockType,\n} from \"../log-block\";\nimport {\n getLogStreamBlocks,\n subscribeToLogStream,\n unsubscribeFromLogStream,\n} from \"./services\";\n\nimport type { LogStreamOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"log-stream-model\";\n\nexport type LogStreamModel = PublicModelInterface<LogStreamModelImpl>;\n\n@kosModel(MODEL_TYPE)\nexport class LogStreamModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n private logger: KosContextLogger;\n nodeId: string;\n @kosChild\n private _blocks: LogBlockContainerModel;\n name: string;\n currentBlockId: string;\n isResetting: boolean;\n constructor(\n modelId: string,\n options: LogStreamOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.currentBlockId = \"\";\n this.name = options.name;\n this.nodeId = options.nodeId;\n this.isResetting = true;\n this._blocks = LogBlockContainer.instance(`${modelId}-blocks`)\n .options({})\n .build();\n }\n\n get firstLineNum() {\n const firstBlock = this.populated[0];\n return firstBlock ? firstBlock.startLineNum : 0;\n }\n get currentBlock() {\n const currentBlockId = this.currentBlockId;\n const block = this._blocks.getModel(currentBlockId);\n return block;\n }\n\n get populated() {\n return this._blocks.data.filter((block) => block.lines.length > 0);\n }\n get blocks() {\n return this._blocks.data;\n }\n\n get totalLineCount() {\n return this.populated.reduce((acc, block) => acc + block.lineCount, 0);\n }\n\n accept(visitor: IKosVisitor<IKosDataModel>) {\n visitor.visit(this);\n }\n\n updateBlock(blockData: LogBlockType) {\n let block = this._blocks.models.getModel(\n `${blockData.stream}-block-${blockData.blockNum}`\n );\n const options: LogBlockOptions = {\n nodeId: blockData.nodeId,\n blockNum: blockData.blockNum,\n endLineNum: blockData.endLineNum,\n lineCount: blockData.lineCount,\n startLineNum: blockData.startLineNum,\n stream: this.name,\n endTime: new Date(blockData.endTime),\n startTime: new Date(blockData.startTime),\n };\n if (!block) {\n block = LogBlock.instance(\n `${blockData.stream}-block-${blockData.blockNum}`\n )\n .options(options)\n .build();\n this._blocks.addModel(block);\n }\n if (block) {\n block.updateModel(options);\n }\n if (\n !this.currentBlock ||\n blockData.blockNum >= this.currentBlock?.blockNum\n ) {\n this.currentBlockId = `${blockData.stream}-block-${blockData.blockNum}`;\n }\n }\n addBlock(blockData: LogBlockType) {\n const block = LogBlock.instance(\n `${blockData.stream}-block-${blockData.blockNum}`\n )\n .options({\n nodeId: blockData.nodeId,\n blockNum: blockData.blockNum,\n endLineNum: blockData.endLineNum,\n lineCount: blockData.lineCount,\n startLineNum: blockData.startLineNum,\n stream: this.name,\n endTime: new Date(blockData.endTime),\n startTime: new Date(blockData.startTime),\n })\n .build();\n this._blocks.addModel(block);\n if (\n !this.currentBlock ||\n blockData.blockNum >= this.currentBlock?.blockNum\n ) {\n this.currentBlockId = `${blockData.stream}-block-${blockData.blockNum}`;\n }\n }\n\n removeBlock(blockNum: number) {\n this._blocks.models.removeModel(`${this.name}-block-${blockNum}`);\n }\n async subscribe(): Promise<void> {\n await subscribeToLogStream(this.name);\n }\n\n async unsubscribe(): Promise<void> {\n await unsubscribeFromLogStream(this.name);\n }\n // -------------------LIFECYCLE----------------------------\n\n async reset(): Promise<void> {\n this.isResetting = true;\n if (this.populated.length > 0) {\n return;\n }\n this.logger.debug(`resetting log-stream ${this.id}`);\n for (const block of this._blocks.models.data) {\n block.lines = [];\n }\n\n const lastBlock = this._blocks.data[this._blocks.data.length - 1];\n if (lastBlock) {\n await lastBlock.syncLines();\n }\n\n this.isResetting = false;\n }\n async init(): Promise<void> {\n this.logger.debug(`initializing log-stream ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading log-stream ${this.id}`);\n\n const [error, previousBlocks] = await getLogStreamBlocks(this.name);\n if (error) {\n this.logger.error(`Error loading log stream: ${error}`);\n return;\n }\n if (previousBlocks) {\n for (const block of previousBlocks) {\n this.addBlock(block as LogBlockType);\n }\n }\n\n const lastBlock = this._blocks.data[this._blocks.data.length - 1];\n if (lastBlock) {\n await lastBlock.syncLines();\n }\n if (this._blocks.data.length > 1) {\n const secondLastBlock = this._blocks.data[this._blocks.data.length - 2];\n if (secondLastBlock) {\n await secondLastBlock.syncLines();\n }\n }\n }\n private generatorInstance?: AsyncGenerator<string, void, void>;\n private shouldStop = false;\n\n start() {\n this.shouldStop = false;\n this.generatorInstance = this.streamLogs();\n return this.generatorInstance;\n }\n\n stop() {\n this.shouldStop = true;\n this.generatorInstance?.next(); // Allows the generator to check `shouldStop`\n console.log(\"Requested generator stop.\");\n }\n async *streamLogs(): AsyncGenerator<string, void, void> {\n const queue: string[] = [];\n let resolveQueue: (() => void) | null = null;\n let currentIndex = 0;\n let initialized = false;\n let currentBlockId: string | undefined = this.currentBlockId;\n // reaction to listen for new log lines\n const disposer = kosEffect(\n () => {\n const block = this.currentBlock;\n return block\n ? {\n blockId: this.currentBlockId,\n lineCount: block.lines.length,\n }\n : null;\n }, // Track changes in lines\n (prev) => {\n const latestBlock = this.currentBlock;\n\n if (latestBlock) {\n if (currentBlockId !== prev?.blockId) {\n currentBlockId = prev?.blockId;\n currentIndex = 0;\n queue.push(...latestBlock.lines);\n } else {\n const newLines = latestBlock.lines.slice(currentIndex);\n\n queue.push(...newLines);\n currentIndex += newLines.length;\n }\n }\n\n // Wake up the generator if it was waiting\n if (resolveQueue) {\n resolveQueue();\n resolveQueue = null;\n }\n },\n { fireImmediately: true }\n );\n\n try {\n // Yield all existing lines first\n for (const block of this.populated.filter(\n (block) => block !== this.currentBlock\n )) {\n for (const line of block.lines) {\n yield line;\n }\n }\n\n // Wait for new lines and yield them as they arrive\n while (true) {\n if (queue.length === 0) {\n await new Promise<void>((resolve) => (resolveQueue = resolve));\n }\n while (queue.length > 0) {\n yield queue.shift()!;\n }\n }\n } finally {\n disposer(); // Cleanup reaction when generator is stopped\n }\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { LogStreamOptions } from \"./types\";\nimport { LogStreamModelImpl, MODEL_TYPE } from \"./log-stream-model\";\nimport type { LogStreamModel } from \"./log-stream-model\";\n\n/**\n * # LogStream\n *\n * The registration bean includes convenience methods for creating and working with LogStreamModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: LogStream.type, id: \"logStreamId\"})\n * private logStreamModel: LogStreamModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new LogStreamModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = LogStream.factory(\"logStreamId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a LogStreamModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (LogStream.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to LogStreamModel\n * // and the compiler will know that the model has the LogStreamModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { LogStream } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(LogStream);\n * ```\n *\n * ## registration.singleton\n \n * The logStream model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const LogStream = new KosModelRegistrationFactory<\n LogStreamModel,\n LogStreamOptions\n>({\n class: LogStreamModelImpl,\n type: MODEL_TYPE,\n});\n","import {\n kosChild,\n kosModel,\n kosTopicHandler,\n} from \"../../../core/core/decorators\";\nimport {\n KosModelContainer,\n type IKosModelContainer,\n} from \"../../../core/core/kos-container-model\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type {\n IKosModelHolder,\n PublicModelInterface,\n} from \"../../../core/types\";\nimport type { LogBlockType, LogLinesType } from \"../log-block\";\n\nimport type { LogStreamModel } from \"./log-stream-model\";\nimport { LogStream } from \"./log-stream-registration\";\nimport { getLogStreams } from \"./services\";\nimport type { LogStreamContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"log-stream-container-model\";\n\nexport type LogStreamContainerModel =\n PublicModelInterface<LogStreamContainerModelImpl>;\nconst TOPIC_ADD_BLOCK = \"/kos/logs/subscription/addBlock/*\";\nconst TOPIC_UPDATE_BLOCK = \"/kos/logs/subscription/updateBlock/*\";\nconst TOPIC_REMOVE_BLOCK = \"/kos/logs/subscription/removeBlock/*\";\nconst TOPIC_LOG_LINES = \"/kos/logs/subscription/lines/*\";\nconst TOPIC_ADD_STREAM = \"/kos/logs/streams/add/*\";\n\n@kosModel(MODEL_TYPE)\nexport class LogStreamContainerModelImpl\n implements IKosIdentifiable, IKosModelHolder<LogStreamModel>, IKosDataModel\n{\n id: string;\n private logger: KosContextLogger;\n selectedStream?: LogStreamModel;\n @kosChild private _models: IKosModelContainer<LogStreamModel>;\n constructor(\n modelId: string,\n options: LogStreamContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._models = new KosModelContainer<LogStreamModel>({ parentId: modelId });\n this.selectedStream = undefined;\n if (options) {\n // Assign options properties here.\n }\n }\n\n getModel(id: string) {\n return this._models.getModel(id);\n }\n get models() {\n return this._models;\n }\n get data() {\n return this._models.data;\n }\n\n updateModel(_options: LogStreamContainerOptions): void {\n // Update model properties here.\n }\n\n addModel(model: LogStreamModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n // -------------------LIFECYCLE----------------------------\n\n updateSelectedStream(stream?: LogStreamModel) {\n this.selectedStream = stream;\n }\n\n @kosTopicHandler({\n topic: [TOPIC_ADD_STREAM],\n websocket: true,\n })\n handleStreamAdded(data: { stream: string }) {\n this.logger.debug(`Received topic: ${TOPIC_ADD_STREAM}`);\n const streamName = data.stream;\n const logStream = LogStream.instance(streamName)\n .options({\n name: streamName,\n nodeId: \"primary\",\n })\n .build();\n this.addModel(logStream);\n }\n\n @kosTopicHandler({\n topic: [TOPIC_ADD_BLOCK],\n websocket: true,\n })\n handleAddBlock(data: LogBlockType, payload) {\n this.logger.debug(`Received topic: ${payload.headers.topic}`);\n const stream = data.stream;\n const logStream = this.models.getModel(stream);\n if (logStream) {\n logStream.addBlock(data);\n }\n }\n\n @kosTopicHandler({\n topic: [TOPIC_REMOVE_BLOCK],\n websocket: true,\n })\n handleRemoveBlock(data: LogBlockType, payload) {\n this.logger.debug(`Received topic: ${payload.headers.topic}`);\n const stream = data.stream;\n const logStream = this.models.getModel(stream);\n if (logStream) {\n logStream.removeBlock(data.blockNum);\n }\n }\n\n @kosTopicHandler({\n topic: [TOPIC_UPDATE_BLOCK],\n websocket: true,\n })\n handleUpdateBlock(data: LogBlockType, payload) {\n this.logger.debug(`Received topic: ${payload.headers.topic}`);\n const stream = data.stream;\n const logStream = this.models.getModel(stream);\n if (logStream) {\n logStream.updateBlock(data);\n }\n }\n\n @kosTopicHandler({\n topic: [TOPIC_LOG_LINES],\n websocket: true,\n })\n handleLogLine(data: LogLinesType, payload) {\n this.logger.debug(`Received topic: ${payload.headers.topic}`);\n const stream = data.stream;\n const logStream = this.models.getModel(stream);\n if (logStream) {\n logStream.currentBlock?.addLines(data.lines);\n }\n }\n async init(): Promise<void> {\n this.logger.debug(`initializing log-stream-container container ${this.id}`);\n }\n\n async subscribeToLogStream(stream: string): Promise<void> {\n const logStream = LogStream.instance(stream)\n .options({\n name: stream,\n nodeId: \"primary\",\n })\n .build();\n this.addModel(logStream);\n await logStream.subscribe();\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading log-stream-container container ${this.id}`);\n\n const [error, streams] = await getLogStreams();\n if (error) {\n this.logger.error(`Error loading log-streams: ${error}`);\n return;\n }\n\n if (streams) {\n streams.forEach((stream) => {\n const logStream = LogStream.instance(stream)\n .options({\n name: stream,\n nodeId: \"primary\",\n })\n .build();\n this.addModel(logStream);\n });\n }\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport { LogBlock, LogBlockContainer } from \"../log-block\";\nimport type { LogStreamContainerModel } from \"./log-stream-container-model\";\nimport {\n LogStreamContainerModelImpl,\n MODEL_TYPE,\n} from \"./log-stream-container-model\";\nimport { LogStream } from \"./log-stream-registration\";\nimport type { LogStreamContainerOptions } from \"./types\";\n\n/**\n * # LogStreamContainer\n *\n * The registration bean includes convenience methods for creating and working with LogStreamContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: LogStreamContainer.type, id: \"logStreamContainerId\"})\n * private logStreamContainerModel: LogStreamContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new LogStreamContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = LogStreamContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a LogStreamContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (LogStreamContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to LogStreamContainerModel\n * // and the compiler will know that the model has the LogStreamContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { LogStreamContainer } from \"@kosdev-code/kos-ui-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...LogStreamContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The logStreamContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const LogStreamContainer = new SingletonKosModelRegistrationFactory<\n LogStreamContainerModel,\n LogStreamContainerOptions\n>({\n class: LogStreamContainerModelImpl,\n type: MODEL_TYPE,\n});\n\nLogStreamContainer.addRelatedModel(LogStream);\nLogStreamContainer.addRelatedModel(LogBlockContainer);\nLogStreamContainer.addRelatedModel(LogBlock);\n","import type { TroubleResponse } from \"../models/trouble/services\";\n\ninterface RankAwareTrouble {\n rank: number;\n}\n\ninterface RoleAwareTrouble {\n visibleRole: string;\n}\n\ninterface ColorAwareTrouble {\n color: string;\n}\n\nconst isRankedInfo = (i: any): i is RankAwareTrouble => i.rank !== undefined;\n\nconst isRoleAwareInfo = (i: any): i is RoleAwareTrouble =>\n i.visibleRole !== undefined;\n\nconst isColorAwareInfo = (i: any): i is ColorAwareTrouble =>\n i.color !== undefined;\n\nexport const defaultTroubleRankMapper = (trouble: TroubleResponse) => {\n const info = trouble.info;\n if (isRankedInfo(info)) {\n return info.rank; // return the rank\n }\n return 0; // return 0 if not ranked\n};\n\nexport const defaultTroubleColorMapper = (trouble: TroubleResponse) => {\n const info = trouble.info;\n if (isColorAwareInfo(info)) {\n return info.color; // return the color\n }\n return \"orange\"; // return ORANGE if no color defined\n};\n\nexport const defaultTroubleRoleMapper = (trouble: TroubleResponse) => {\n const info = trouble.info;\n if (isRoleAwareInfo(info)) {\n return info.visibleRole; // return the role\n }\n return \"TECHNICIAN\"; // return empty if no role\n};\n","/**\n * @internal\n */\nimport {\n KosServiceResponse,\n ServiceFactory,\n resolveServiceUrl,\n} from \"../../../../core\";\nimport { FutureEndState, FutureResponse } from \"../../../services/future\";\nimport { FutureManager } from \"../../../utils/future-manager\";\nconst { URL } = resolveServiceUrl(\"TROUBLE_SERVICE\");\nconst { getAll, postModel } = ServiceFactory.build({\n basePath: `${URL}/api/kos/troubles`,\n});\n\nexport interface TroubleResponse {\n reason: string;\n createTime: string;\n resolvable: boolean;\n ifaces: string[];\n id: string;\n clientData: any;\n type: string;\n tags: string[];\n info: any;\n}\n/**\n * @category Service\n * @internal\n * Retrieves the initial Trouble data.\n */\nexport const getTroubles = async () => {\n const response = await getAll<TroubleResponse>({});\n return response;\n};\n\nexport const resolveTrouble = async (troubleId: string, tracker?: string) => {\n try {\n const response: KosServiceResponse<FutureResponse> = (await postModel({\n model: {},\n urlOverride: `${URL}/api/kos/troubles/resolve/${troubleId}`,\n tracker,\n })) as KosServiceResponse<FutureResponse>;\n if (response?.data) {\n FutureManager.initiateFuture(response.data);\n }\n return response.data;\n } catch (error) {\n const futureResponse: FutureResponse = {\n id: tracker || \"\",\n endState: FutureEndState.Fail,\n tracker: tracker,\n reason: \"Failed to resolve trouble\",\n };\n FutureManager.initiateFuture(futureResponse);\n return futureResponse;\n }\n};\n\nexport const bulkResolveTroubles = async (\n troubleIds: string[],\n tracker?: string\n) => {\n try {\n const response: KosServiceResponse<FutureResponse> = (await postModel({\n model: troubleIds,\n urlOverride: `${URL}/api/kos/troubles/resolve/`,\n tracker,\n })) as KosServiceResponse<FutureResponse>;\n\n if (response?.data) {\n FutureManager.initiateFuture(response.data);\n }\n return response.data;\n } catch (error) {\n const futureResponse: FutureResponse = {\n id: tracker || \"\",\n endState: FutureEndState.Fail,\n tracker: tracker,\n reason: \"Failed to resolve troubles\",\n };\n FutureManager.initiateFuture(futureResponse);\n return futureResponse;\n }\n};\n","import { KosLog, registerExtensionPoint } from \"../../../../core\";\nimport type { TroubleModel } from \"../types\";\nexport const EXTENSION_TROUBLE_DATA_MAPPER = \"troubleDataMapper\";\nexport type TroubleDataMapper = (\n trouble: TroubleModel\n) => Promise<Record<string, any>>;\nconst troubleMappers = new Map<string, TroubleDataMapper[]>();\nregisterExtensionPoint(EXTENSION_TROUBLE_DATA_MAPPER, {\n register: (id: string, mapper: TroubleDataMapper) => {\n if (!troubleMappers.has(id)) {\n troubleMappers.set(id, []);\n }\n troubleMappers.get(id)?.push(mapper);\n },\n execute: async (id: string, trouble: TroubleModel) => {\n const mapper = troubleMappers.get(id);\n if (!mapper) {\n return {\n ...trouble.data,\n };\n }\n const promises = mapper.map((m) => m(trouble));\n const results = await Promise.allSettled(promises);\n const data = results.reduce(\n (acc, r) => {\n if (r.status === \"fulfilled\") {\n acc = { ...acc, ...r.value };\n } else {\n KosLog.info(`Trouble mapper ${id} failed: ${r.reason}`);\n }\n\n return acc;\n },\n { ...trouble.data }\n );\n\n return data;\n },\n});\n","import { KosLog, registerExtensionPoint } from \"../../../../core\";\nimport type { TroubleModel } from \"../types\";\nexport const EXTENSION_TROUBLE_MAPPER = \"troubleMapper\";\nexport type TroubleMapper = (trouble: TroubleModel) => Promise<string[]>;\nconst troubleMappers = new Map<string, TroubleMapper[]>();\nregisterExtensionPoint(EXTENSION_TROUBLE_MAPPER, {\n register: (id: string, mapper: TroubleMapper) => {\n if (!troubleMappers.has(id)) {\n troubleMappers.set(id, []);\n }\n troubleMappers.get(id)?.push(mapper);\n },\n execute: async (id: string, trouble: TroubleModel) => {\n const mapper = troubleMappers.get(id);\n if (!mapper) {\n return [];\n }\n const promises = mapper.map((m) => m(trouble));\n const results = await Promise.allSettled(promises);\n const paths = results\n\n .map((r) => {\n if (r.status === \"fulfilled\") {\n return r.value;\n } else {\n KosLog.info(`Trouble mapper ${id} failed: ${r.reason}`);\n return [];\n }\n })\n .flat();\n\n return Array.from(new Set(paths));\n },\n});\n","import { ExtensionManager } from \"../../../core\";\nimport type {\n HandleTroubleData,\n NozzleTroubleData,\n TroubleModel,\n} from \"../trouble/types\";\nimport \"../trouble/utils/trouble-data-extension\";\nimport { EXTENSION_TROUBLE_DATA_MAPPER } from \"../trouble/utils/trouble-data-extension\";\nimport \"../trouble/utils/trouble-extension\";\nimport { EXTENSION_TROUBLE_MAPPER } from \"../trouble/utils/trouble-extension\";\n\nExtensionManager[EXTENSION_TROUBLE_MAPPER].register(\n \"nozzle\",\n async (trouble: TroubleModel<NozzleTroubleData>) => [trouble.data.nozzlePath]\n);\n\nExtensionManager[EXTENSION_TROUBLE_MAPPER].register(\n \"path\",\n async (trouble: TroubleModel<HandleTroubleData>) => [trouble.data.path]\n);\n\nexport const troublePathFactory = async (trouble: TroubleModel) => {\n const result = new Set<string>();\n const ifaces = trouble.ifaces;\n\n const promises = ifaces?.map(\n (iface) =>\n ExtensionManager[EXTENSION_TROUBLE_MAPPER].execute(\n iface,\n trouble\n ) as Promise<string[]>\n );\n\n const results = await Promise.allSettled(promises);\n\n results.forEach((r) => {\n if (r.status === \"fulfilled\") {\n (r.value as string[]).forEach((path) => result.add(path));\n }\n });\n\n return Array.from(result);\n};\n\nexport const troubleDataFactory = async (trouble: TroubleModel) => {\n const ifaces = trouble.ifaces;\n\n const promises = ifaces?.map(\n (iface) =>\n ExtensionManager[EXTENSION_TROUBLE_DATA_MAPPER].execute(\n iface,\n trouble\n ) as Promise<Record<string, any>>\n );\n\n const troubleExtension = ExtensionManager[\n EXTENSION_TROUBLE_DATA_MAPPER\n ].execute(trouble.type, trouble) as Promise<Record<string, any>>;\n\n promises.push(troubleExtension);\n\n const results = await Promise.allSettled(promises);\n\n const result = results.reduce((acc, r) => {\n if (r.status === \"fulfilled\") {\n acc = { ...acc, ...r.value };\n }\n return acc;\n }, {});\n\n return { ...trouble.data, ...result };\n};\n","import { TroubleHandler } from \"../../../../core\";\n\nexport class ResolvableTroubleHandler implements TroubleHandler {\n type = \"ResolvableTrouble\";\n title = \"Resolvable Trouble\";\n subtitle = \"Trouble\";\n}\n\nexport class BlockPumpTroubleHandler implements TroubleHandler {\n type = \"BlockPumpTrouble\";\n title = \"Block Pump Trouble\";\n subtitle = \"Trouble\";\n}\n\nexport class TroubleHandlerFactory {\n static getHandler(type: string): TroubleHandler | undefined {\n switch (type) {\n case \"ResolvableTrouble\":\n return new ResolvableTroubleHandler();\n case \"BlockPumpTrouble\":\n return new BlockPumpTroubleHandler();\n default:\n return undefined;\n }\n }\n}\n","import {\n kosModel,\n resolveKosCompanion,\n type IKosModelLogger,\n type KosContextLogger,\n type KosCreationContext,\n} from \"../../../core\";\nimport { kosFuture } from \"../../decorators/future-service\";\nimport { FutureHandler } from \"../future/future-aware\";\nimport type { FutureAwareContainer } from \"../future/future-types\";\nimport { troubleDataFactory } from \"../trouble-container/trouble-utils\";\nimport { TroubleHandlerFactory } from \"./handlers/resolvable-trouble-handler\";\nimport { resolveTrouble } from \"./services\";\nimport type { DeferAware, TroubleModel, TroubleOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"trouble-model\";\n\nfunction isDeferAware(obj: any): obj is DeferAware {\n return typeof obj.shouldDefer === \"boolean\";\n}\n@kosModel(MODEL_TYPE)\nexport class TroubleModelImpl<AdditionalData extends object = any>\n implements TroubleModel<AdditionalData>, IKosModelLogger\n{\n id: string;\n logger: KosContextLogger;\n private _troubleId: string;\n private _resolvable: boolean;\n\n type: string;\n futureHandler: FutureAwareContainer;\n ifaces: string[];\n clientData: unknown;\n info: unknown;\n role: string;\n color: string;\n tags: string[];\n data: AdditionalData;\n rank: number;\n\n group?: string;\n createTime?: string;\n private _mapped: Record<any, any> = {};\n constructor(\n modelId: string,\n {\n resolvable,\n tags,\n info,\n id,\n clientData,\n rank,\n ifaces,\n type,\n group,\n createTime,\n role,\n color,\n ...rest\n }: TroubleOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.type = type;\n this._troubleId = id;\n this._resolvable = !!resolvable;\n this.ifaces = ifaces;\n this.rank = rank;\n this.role = role;\n this.color = color;\n this.tags = tags;\n this.info = info;\n this.group = group;\n\n this.createTime = createTime;\n this.clientData = clientData;\n this.data = {} as AdditionalData;\n\n Object.assign(this.data, rest);\n this.futureHandler = new FutureHandler(this);\n }\n\n // -------------------LIFECYCLE----------------------------\n\n getTitleWithContext(context: string) {\n // get the context from the handler\n // return the default context if the context is not found\n const ctx = context\n ? TroubleHandlerFactory.getHandler(this.type)?.context?.[context]\n : TroubleHandlerFactory.getHandler(this.type);\n\n // return the title from the context\n return ctx?.title || \"Trouble\";\n }\n\n getSubtitleWithContext(context: string) {\n // get the context from the handler\n // return the default context if the context is not found\n const ctx = context\n ? TroubleHandlerFactory.getHandler(this.type)?.context?.[context]\n : TroubleHandlerFactory.getHandler(this.type);\n\n // return the subtitle from the context\n return ctx?.subtitle || \"Trouble\";\n }\n\n get rawId() {\n return this._troubleId;\n }\n get title() {\n return TroubleHandlerFactory.getHandler(this.type)?.title || \"Trouble\";\n }\n\n get subtitle() {\n return TroubleHandlerFactory.getHandler(this.type)?.subtitle || \"Trouble\";\n }\n\n get troubleId() {\n return this._troubleId;\n }\n\n get resolvable() {\n return this._resolvable;\n }\n\n get future() {\n return this.futureHandler.future;\n }\n\n async resolveMappedData() {\n return await troubleDataFactory(this);\n }\n\n get deferredCompanion() {\n const companion = resolveKosCompanion(this.id, (m) => isDeferAware(m));\n if (companion && isDeferAware(companion.modelData)) {\n return companion.modelData;\n }\n return undefined;\n }\n get deferred() {\n if (this.deferredCompanion) {\n return this.deferredCompanion.deferred;\n }\n return false;\n }\n get shouldDefer(): boolean {\n const companion = resolveKosCompanion(this.id, (m) => isDeferAware(m));\n if (companion && isDeferAware(companion.modelData)) {\n return companion.modelData.shouldDefer;\n }\n return false;\n }\n\n clearDefer() {\n this.deferredCompanion?.clearDefer();\n }\n defer() {\n this.deferredCompanion?.defer();\n }\n\n getChildren() {\n const allFutures = this.futureHandler.allFutures;\n return [...allFutures];\n }\n\n @kosFuture()\n async resolve(tracker?: string) {\n if (!this._resolvable) {\n this.logger.error(\n `attempting to resolve an unresolvable trouble with id ${this._troubleId}`\n );\n throw new Error(\"Trouble is not resolvable\");\n }\n\n if (this.shouldDefer) {\n this.deferredCompanion?.defer();\n return undefined;\n }\n return await resolveTrouble(this._troubleId, tracker);\n }\n}\n","import type { KosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport { MODEL_TYPE, TroubleModelImpl } from \"./trouble-model\";\nimport type { TroubleModel, TroubleOptions } from \"./types\";\n\n/**\n * # Translation\n *\n * The registration bean includes convenience methods for creating and working with TranslationModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: Translation.type, id: \"translationId\"})\n * private translationModel: TranslationModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new TranslationModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = Translation.factory(\"translationId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a TranslationModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (Translation.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to TranslationModel\n * // and the compiler will know that the model has the TranslationModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { Translation } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...Translation.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The translation model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const Trouble: Readonly<\n KosModelRegistrationBean<TroubleModel, TroubleOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: TroubleModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Factory.create<TroubleModel, TroubleOptions>(MODEL_TYPE),\n};\n","import {\n DependencyLifecycle,\n ExtensionManager,\n KosLog,\n KosModelContainer,\n destroyKosModel,\n kosChild,\n kosModel,\n kosTopicHandler,\n type IKosModelContainer,\n} from \"../../../core\";\n\nimport { KosCoreModelPropertyMapper } from \"../../constants\";\nimport {\n defaultTroubleColorMapper,\n defaultTroubleRankMapper,\n defaultTroubleRoleMapper,\n} from \"../../utils/trouble-utils\";\nimport { getTroubles, type TroubleResponse } from \"../trouble/services\";\nimport { Trouble } from \"../trouble/trouble-registration\";\nimport type { TroubleModel } from \"../trouble/types\";\nimport { troublePathFactory } from \"./trouble-utils\";\nimport type { TroubleContainerModel } from \"./types\";\n\nconst log = KosLog.createLogger({ name: \"trouble-container-model\" });\n\nfunction troubleRankMapper(trouble: TroubleResponse): number {\n const _rank = ExtensionManager.propertyMapper.hasMapper(\n KosCoreModelPropertyMapper.TroubleRank\n )\n ? ExtensionManager.propertyMapper.executeMapper<TroubleResponse, number>(\n KosCoreModelPropertyMapper.TroubleRank,\n trouble\n )\n : defaultTroubleRankMapper(trouble);\n return _rank;\n}\n\nfunction troubleColorMapper(trouble: TroubleResponse): string {\n const color = ExtensionManager.propertyMapper.hasMapper(\n KosCoreModelPropertyMapper.TroubleColor\n )\n ? ExtensionManager.propertyMapper.executeMapper<TroubleResponse, string>(\n KosCoreModelPropertyMapper.TroubleColor,\n trouble\n )\n : defaultTroubleColorMapper(trouble);\n return color.toLowerCase();\n}\n\nfunction troubleRoleMapper(trouble: TroubleResponse): string {\n const role = ExtensionManager.propertyMapper.hasMapper(\n KosCoreModelPropertyMapper.TroubleRole\n )\n ? ExtensionManager.propertyMapper.executeMapper<TroubleResponse, string>(\n KosCoreModelPropertyMapper.TroubleRole,\n trouble\n )\n : defaultTroubleRoleMapper(trouble);\n return role.toLowerCase();\n}\nexport const MODEL_TYPE = \"trouble-container-model\";\n\nexport class Troubles {\n static readonly INDEX_TROUBLES_BY_IFACE = \"byIface\";\n static readonly INDEX_TROUBLES_BY_TYPE = \"byType\";\n static readonly INDEX_TROUBLES_BY_GROUP = \"byGroup\";\n static readonly INDEX_TROUBLES_BY_DEFERRED = \"byDeferred\";\n static readonly SORT_KEY_RANK = \"rank\";\n static readonly TROUBLES_DEFERRED = \"true\";\n}\n@kosModel(MODEL_TYPE)\nexport class TroubleContainerModelImpl implements TroubleContainerModel {\n id: string;\n\n @kosChild troubles: IKosModelContainer<TroubleModel>;\n constructor(modelId: string) {\n this.id = modelId;\n\n this.troubles = new KosModelContainer({\n indexMap: {\n [Troubles.INDEX_TROUBLES_BY_IFACE]: troublePathFactory,\n [Troubles.INDEX_TROUBLES_BY_TYPE]: \"type\",\n [Troubles.INDEX_TROUBLES_BY_GROUP]: \"group\",\n [Troubles.INDEX_TROUBLES_BY_DEFERRED]: \"deferred\",\n },\n sortKey: Troubles.SORT_KEY_RANK,\n parentId: modelId,\n });\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async load(): Promise<void> {\n log.debug(\"loading trouble container\");\n const _troubles = await getTroubles();\n try {\n _troubles?.data.forEach((trouble) => {\n const options = {\n ...trouble,\n rank: troubleRankMapper(trouble),\n color: troubleColorMapper(trouble),\n role: troubleRoleMapper(trouble),\n id: String(trouble.id),\n };\n\n const newTrouble = Trouble.factory(`trouble-${trouble.id}`)(options);\n this.troubles.addModel(newTrouble);\n });\n } catch (e) {\n log.error(e);\n throw e;\n }\n }\n\n @kosTopicHandler({\n topic: \"/kos/trouble/remove\",\n websocket: true,\n lifecycle: DependencyLifecycle.INIT,\n })\n handleTroubleRemoved(id: string) {\n const troubleId = `trouble-${id}`;\n const removed = this.troubles.getModel(troubleId);\n\n this.troubles.removeModel(troubleId);\n if (removed) {\n destroyKosModel(removed);\n }\n }\n\n @kosTopicHandler({ topic: \"/kos/trouble/add\", websocket: true })\n handleTroubleAdded(trouble: TroubleResponse) {\n const options = {\n ...trouble,\n rank: troubleRankMapper(trouble),\n color: troubleColorMapper(trouble),\n role: troubleRoleMapper(trouble),\n id: String(trouble.id),\n };\n if (options.role === \"NONE\") {\n // ignore troubles with role NONE\n return;\n }\n const newTrouble = Trouble.factory(`trouble-${trouble.id}`)(options);\n this.troubles.addModel(newTrouble);\n }\n}\n","import type { SingletonKosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport { TroubleContainerModelImpl } from \"./trouble-container-model\";\nimport type { TroubleContainerModel, TroubleContainerOptions } from \"./types\";\n\n/**\n * # Translation\n *\n * The registration bean includes convenience methods for creating and working with TranslationModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: Translation.type, id: \"translationId\"})\n * private translationModel: TranslationModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new TranslationModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = Translation.factory(\"translationId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a TranslationModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (Translation.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to TranslationModel\n * // and the compiler will know that the model has the TranslationModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { Translation } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...Translation.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The translation model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\n\nconst MODEL_TYPE = \"trouble-container-model\";\nexport const TroubleContainer: Readonly<\n SingletonKosModelRegistrationBean<\n TroubleContainerModel,\n TroubleContainerOptions\n >\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: TroubleContainerModelImpl,\n singleton: true,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Singleton.create<TroubleContainerModel, TroubleContainerOptions>(\n MODEL_TYPE\n ),\n};\n","import { KosLog, ServiceFactory, resolveServiceUrl } from \"../../../../core\";\nimport type { OTAArtifactResponse } from \"../types\";\n\nconst { URL } = resolveServiceUrl(\"OTA-SERVICE\");\n\nconst { getAll } = ServiceFactory.build({\n basePath: `${URL}/api/kos/ota`,\n});\n\nconst log = KosLog.createLogger({\n name: \"ota-service\",\n group: \"Services\",\n});\n\n/**\n * @category Service\n * GET request to /api/kos/ota/artifacts\n */\nexport const getArtifacts = async () => {\n log.debug(\"sending GET request to /api/kos/ota/artifacts\");\n\n const response = await getAll<OTAArtifactResponse>({\n urlOverride: `${URL}/api/kos/ota/artifacts`,\n });\n\n log.debug(\"getArtifacts - response:\", response);\n\n return response?.data;\n};\n","import {\n kosDependency,\n kosModel,\n kosTopicHandler,\n} from \"../../../core/core/decorators\";\nimport {\n KosDataContainer,\n type IKosDataContainer,\n} from \"../../../core/core/kos-data-container\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { TroubleContainer } from \"../trouble-container/trouble-container-registration\";\nimport type { TroubleContainerModel } from \"../trouble-container/types\";\nimport { getArtifacts } from \"./services\";\nimport type {\n OTAArtifactResponse,\n OTARequest,\n UpdaterItem,\n UpdaterOptions,\n UpdaterStatus,\n} from \"./types\";\n\nexport const MODEL_TYPE = \"ota-model\";\n\nexport type OtaModel = PublicModelInterface<OtaModelImpl>;\n\nconst getLastRequest = (\n requests: Record<string, OTARequest>\n): OTARequest | null => {\n let lastRequest: OTARequest | null = null;\n\n for (const provider in requests) {\n const currentConfig = requests[provider];\n const currentLastUpdateTime = currentConfig.lastUpdateTime;\n\n if (!lastRequest || lastRequest.lastUpdateTime < currentLastUpdateTime) {\n lastRequest = currentConfig;\n }\n }\n\n return lastRequest;\n};\n\nconst mapOTAArtifactResponseToUpdaterItem = (\n otaArtifactResponse: OTAArtifactResponse\n): UpdaterItem | undefined => {\n const artifactInfo = otaArtifactResponse.artifactInfo;\n\n const lastRequest = getLastRequest(otaArtifactResponse.requests);\n\n const id = artifactInfo?.identifier || lastRequest?.kabId;\n if (!id) return undefined;\n\n let status: UpdaterStatus;\n switch (otaArtifactResponse.status) {\n case \"INSTALLED\":\n status = \"ready\";\n break;\n case \"INVALID\":\n status = \"error\";\n break;\n case \"MISSING\":\n status = (lastRequest?.currentSize || 0) > 0 ? \"downloading\" : \"idle\";\n break;\n case \"STAGED\":\n status = \"pending\";\n }\n\n const manifest = artifactInfo === undefined;\n\n return {\n id,\n manifest,\n label: artifactInfo?.version,\n name: artifactInfo?.name,\n status,\n error: status === \"error\" ? lastRequest?.lastErrorReason : undefined,\n errorCount: status === \"error\" ? lastRequest?.errorCount : 0,\n progress:\n status === \"downloading\" && lastRequest && !manifest\n ? (lastRequest.currentSize / artifactInfo?.size) * 100\n : undefined,\n size: artifactInfo?.size,\n };\n};\n\n@kosModel(MODEL_TYPE)\nexport class OtaModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n private logger: KosContextLogger;\n\n private data: IKosDataContainer<UpdaterItem> = new KosDataContainer();\n\n @kosDependency({ modelType: TroubleContainer.type })\n private troubleContainer!: TroubleContainerModel;\n\n get downloadInProgressTrouble() {\n const downloadInProgressTrouble =\n this.troubleContainer.troubles.getIndexByKey(\n \"byType\",\n \"OTADownloadInProgressTrouble\"\n )?.[0];\n\n return downloadInProgressTrouble;\n }\n\n get updatePendingTrouble() {\n const updatePendingTrouble = this.troubleContainer.troubles.getIndexByKey(\n \"byType\",\n \"OTAUpdatePendingTrouble\"\n )?.[0];\n\n return updatePendingTrouble;\n }\n\n get pausedDueToErrorsTrouble() {\n const pendingTrouble = this.troubleContainer.troubles.getIndexByKey(\n \"byType\",\n \"OTAPausedDueToErrorsTrouble\"\n )?.[0];\n\n return pendingTrouble;\n }\n\n get updates() {\n return this.data;\n }\n\n get status(): UpdaterStatus {\n const status = this.pausedDueToErrorsTrouble\n ? \"error\"\n : this.downloadInProgressTrouble\n ? \"downloading\"\n : this.updatePendingTrouble\n ? \"pending\"\n : \"idle\";\n\n return status;\n }\n\n constructor(\n modelId: string,\n options: UpdaterOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n if (options) {\n // Assign options properties here.\n }\n }\n\n installAndReboot() {\n if (!this.updatePendingTrouble) {\n this.logger.error(\n \"installAndReboot - OTAUpdatePendingTrouble not present\"\n );\n }\n\n this.logger.debug(\"installAndReboot - resolve OTAUpdatePendingTrouble\");\n\n this.updatePendingTrouble?.resolve();\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing ota ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading ota ${this.id}`);\n\n try {\n const artifacts = await getArtifacts();\n if (artifacts) {\n artifacts.forEach((otaArtifactResponse) => {\n const model =\n mapOTAArtifactResponseToUpdaterItem(otaArtifactResponse);\n\n if (model) this.data.addModel(model);\n });\n }\n } catch (error) {\n this.logger.error(`loading ota ${this.id} - error:`, error);\n }\n }\n\n // -------------------TOPIC-HANDLERS-----------------------\n\n @kosTopicHandler({\n topic: \"/kos/ota/artifacts/all\",\n websocket: true,\n })\n async handleAllArtifacts(artifacts: OTAArtifactResponse[]) {\n this.logger.debug(\"handleAllArtifacts:\", artifacts);\n\n await this.data.clear();\n\n try {\n artifacts.forEach((otaArtifactResponse) => {\n const model = mapOTAArtifactResponseToUpdaterItem(otaArtifactResponse);\n\n if (model) this.data.addModel(model);\n });\n } catch (error) {\n this.logger.error(`handleAllArtifacts ${this.id} - error:`, error);\n }\n }\n\n @kosTopicHandler({\n topic: \"/kos/ota/artifacts/changed\",\n websocket: true,\n })\n handleChangedArtifacts(artifacts: OTAArtifactResponse[]) {\n this.logger.debug(\"handleChangedArtifacts:\", artifacts);\n\n try {\n artifacts.forEach((otaArtifactResponse) => {\n const model = mapOTAArtifactResponseToUpdaterItem(otaArtifactResponse);\n\n if (model) this.data.updateModel(model);\n });\n } catch (error) {\n this.logger.error(`handleChangedArtifacts ${this.id} - error:`, error);\n }\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { OtaModel } from \"./ota-model\";\nimport { MODEL_TYPE, OtaModelImpl } from \"./ota-model\";\nimport type { UpdaterOptions } from \"./types\";\n\n/**\n * # Ota\n *\n * The registration bean includes convenience methods for creating and working with OtaModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: Ota.type, id: \"oTAId\"})\n * private oTAModel: OtaModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new OtaModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = Ota.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a OtaModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (Ota.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to OtaModel\n * // and the compiler will know that the model has the OtaModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { Ota } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(Ota);\n * ```\n *\n * ## registration.singleton\n \n * The oTA model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const Ota = new SingletonKosModelRegistrationFactory<\n OtaModel,\n UpdaterOptions\n>({\n class: OtaModelImpl,\n type: MODEL_TYPE,\n});\n","/**\n * @internal\n */\n// eslint-disable-next-line @nx/enforce-module-boundaries\nimport { FetchError, KosLog, resolveBaseUrl } from \"../../../../core\";\nimport { api, type BaseResponseType } from \"../../../utils\";\n\nconst { URL } = resolveBaseUrl();\n\nconst log = KosLog.createLogger({\n name: \"software-info-service\",\n group: \"Services\",\n});\nexport interface Nodes {\n [key: string]: NodeSoftwareInfo[]; // Use an index signature for dynamic keys\n}\n\nexport interface NodeSoftwareInfo {\n node: string;\n artifacts: SoftwareInfoDescriptorFragment[];\n}\n\nexport interface SoftwareInfoDescriptorFragment {\n name: string;\n group: string;\n version: string;\n}\n\nexport type DeviceSoftwareInfoResponse = BaseResponseType<\n \"/api/kos/manifest/info\",\n \"get\"\n>;\n\n/**\n * @category Service\n * @internal\n * Retrieves the initial software-info data.\n */\nexport const getSoftwareInfos =\n async (): Promise<DeviceSoftwareInfoResponse> => {\n log.debug(\"sending GET for software-info\");\n const [error, response] = await api.get(\"/api/kos/manifest/info\");\n\n if (!response) {\n log.error(\"Failed to fetch software-info\", error);\n throw new FetchError(\"Failed to fetch software-info\");\n }\n\n return response as DeviceSoftwareInfoResponse;\n };\n","import { kosAction } from \"../../../core\";\nimport { kosModel } from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport { FetchError } from \"../../../core/util/service-factory\";\nimport { getSoftwareInfos } from \"./services\";\nimport type {\n ArtifactsType,\n NodeInfoType,\n SoftwareInfoModel,\n SoftwareInfoOptions,\n} from \"./types\";\n\nexport const MODEL_TYPE = \"software-info-model\";\n\n@kosModel(MODEL_TYPE)\nexport class SoftwareInfoModelImpl implements SoftwareInfoModel, IKosDataModel {\n id: string;\n private logger: KosContextLogger;\n\n nodes: NodeInfoType[] | undefined;\n constructor(\n modelId: string,\n _options: SoftwareInfoOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.nodes = [];\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing software-info ${this.id}`);\n }\n groupBy(arr: ArtifactsType[], property: keyof ArtifactsType) {\n return arr.reduce(\n (acc: Record<string, ArtifactsType[]>, cur: ArtifactsType) => {\n acc[cur[property]] = [...(acc[cur[property]] || []), cur];\n return acc;\n },\n {}\n );\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading software-info ${this.id}`);\n try {\n const response = await getSoftwareInfos();\n const nodes = response?.nodes || {};\n kosAction(() => {\n const nodeList = Object.keys(nodes).map((el: string) => nodes[el][0]);\n const updatedList = nodeList.map((el) => {\n return {\n nodeName: el.node,\n group: this.groupBy(el.artifacts, \"group\"),\n };\n });\n this.nodes = updatedList;\n });\n } catch (error) {\n if (error instanceof FetchError) {\n this.logger.error(`Failed to fetch software-info`, error);\n }\n }\n }\n}\n","import { Kos } from \"../../../core/core/kos-model-factory\";\nimport type { KosModelRegistrationBean } from \"../../../core/types\";\nimport { isKosModel } from \"../../../core/util/kos-model-utils\";\nimport { MODEL_TYPE, SoftwareInfoModelImpl } from \"./software-info-model\";\nimport type { SoftwareInfoModel, SoftwareInfoOptions } from \"./types\";\n\n/**\n * # SoftwareInfo\n *\n * The registration bean includes convenience methods for creating and working with SoftwareInfoModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: SoftwareInfo.type, id: \"softwareInfoId\"})\n * private softwareInfoModel: SoftwareInfoModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new SoftwareInfoModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = SoftwareInfo.factory(\"softwareInfoId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a SoftwareInfoModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (SoftwareInfo.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to SoftwareInfoModel\n * // and the compiler will know that the model has the SoftwareInfoModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { SoftwareInfo } from \"@kos-ui/kos-dispenser-model\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...SoftwareInfo.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The softwareInfo model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const SoftwareInfo: Readonly<\n KosModelRegistrationBean<SoftwareInfoModel, SoftwareInfoOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: SoftwareInfoModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Factory.create<SoftwareInfoModel, SoftwareInfoOptions>(\n MODEL_TYPE\n ),\n};\n","/**\n * @internal\n */\nimport { KosLog, ServiceFactory, resolveServiceUrl } from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"STATE-BEAN_SERVICE\");\nconst { getOne } = ServiceFactory.build({\n basePath: `${URL}/api/kos/state`,\n});\n\nconst log = KosLog.createLogger({\n name: \"state-bean-service\",\n group: \"Services\",\n});\nexport interface StateBeanResponse {\n [k: string]: string | number | boolean;\n}\n\ninterface StateBeanOptions {\n path: string;\n}\n/**\n * @category Service\n * @internal\n * Retrieves the initial state-bean data.\n */\nexport const getStateBeanData = async ({ path }: StateBeanOptions) => {\n log.debug(\"sending GET for state-bean\");\n const response = await getOne<StateBeanResponse>({\n urlOverride: `${URL}/api/kos/state/${path}`,\n });\n return response;\n};\n","import type {\n IKosModelLogger,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core\";\nimport {\n createPropKey,\n kosModel,\n kosObservable,\n kosTopicHandler,\n mapDataToModel,\n} from \"../../../core\";\nimport { isBoolean, isNumber } from \"../../utils/prop-utils\";\nimport { StatePropertyTypes } from \"../types\";\nimport { getStateBeanData, type StateBeanResponse } from \"./services\";\nimport type { StateBeanModel, StateBeanOptions, StatePropsMap } from \"./types\";\n\nexport const MODEL_TYPE = \"state-bean-model\";\nconst PATH_PROP = createPropKey<StateBeanModel>(\"path\");\n@kosModel(MODEL_TYPE)\nexport class StateBeanModelImpl<\n T extends Record<string, StatePropertyTypes> = any\n> implements StateBeanModel<T>, IKosModelLogger\n{\n id: string;\n path!: string;\n props: StatePropsMap<T>;\n logger: KosContextLogger;\n constructor(\n modelId: string,\n options: StateBeanOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.props = kosObservable.map(new Map());\n mapDataToModel(options, this);\n }\n\n updateModel(options: StateBeanOptions): void {\n mapDataToModel(options, this);\n }\n\n /**\n * @category Subscription\n * Updates the Config Bean model when a `/kos/config//update` event\n * is recieved from the server.\n *\n *\n * @param data - the raw callback\n * @param data.body - the Config Bean that was updated.\n * @see ConfigBeanResponse\n */\n @kosTopicHandler({\n topic: `/kos/state/${PATH_PROP}`,\n websocket: true,\n })\n handleConfigBeanUpdated(stateBean: StateBeanResponse) {\n Object.entries(stateBean).forEach(([key, value]) => {\n let val = value;\n\n if (typeof val === \"string\" && isBoolean(val)) {\n val = val.toLowerCase() == \"true\";\n }\n\n if (typeof val === \"string\" && isNumber(val)) {\n val = Number(val);\n }\n\n this.props.set(key, val as any);\n });\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing state-bean ${this.id}`);\n }\n\n updateProps(props: Record<string, StatePropertyTypes>) {\n Object.entries(props).forEach(([key, value]) => {\n this.props.set(key, value);\n });\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading state-bean ${this.id}`);\n const response = await getStateBeanData({ path: this.path });\n if (response?.data) {\n this.updateProps(response.data);\n }\n }\n}\n","import type { KosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport { MODEL_TYPE, StateBeanModelImpl } from \"./state-bean-model\";\nimport type { StateBeanModel, StateBeanOptions } from \"./types\";\n\n/**\n * # StateBean\n *\n * The registration bean includes convenience methods for creating and working with StateBeanModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: StateBean.type, id: \"stateBeanId\"})\n * private stateBeanModel: StateBeanModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new StateBeanModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = StateBean.factory(\"stateBeanId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a StateBeanModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (StateBean.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to StateBeanModel\n * // and the compiler will know that the model has the StateBeanModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { StateBean } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...StateBean.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The stateBean model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const StateBean: Readonly<\n KosModelRegistrationBean<StateBeanModel, StateBeanOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: StateBeanModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Factory.create<StateBeanModel, StateBeanOptions>(MODEL_TYPE),\n};\n","import type {\n IKosModelLogger,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core\";\nimport { createPropKey, kosDependency, kosModel } from \"../../../core\";\nimport { StateBean } from \"../state-bean\";\nimport type { StateBeanModel, StateBeanOptions } from \"../state-bean/types\";\nimport type { StatePropertyTypes } from \"../types\";\nimport type { KosStateProp, StatePropOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"state-prop-model\";\nconst PATH_PROP = createPropKey<StateBeanModel>(\"path\");\n\n@kosModel(MODEL_TYPE)\nexport class StatePropModelImpl<T extends StatePropertyTypes = any>\n implements KosStateProp<T>, IKosModelLogger\n{\n id: string;\n path: string;\n attribute: string;\n logger: KosContextLogger;\n\n @kosDependency<StateBeanOptions>({\n modelType: StateBean.type,\n id: `state-bean-${PATH_PROP}`,\n options: { path: PATH_PROP },\n })\n stateBean!: StateBeanModel;\n\n constructor(\n modelId: string,\n options: StatePropOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.path = options.path;\n this.attribute = options.attribute;\n if (options) {\n // Assign options properties here.\n }\n }\n\n get value(): T | undefined {\n return this.stateBean.props.get(this.attribute) as T;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing state-prop ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading state-prop ${this.id}`);\n }\n\n toString(): string {\n return this.value?.toString() ?? \"\";\n }\n}\n","import type { KosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport { MODEL_TYPE, StatePropModelImpl } from \"./state-prop-model\";\nimport type { KosStateProp, StatePropOptions } from \"./types\";\n\n/**\n * # StateProp\n *\n * The registration bean includes convenience methods for creating and working with StatePropModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: StateProp.type, id: \"statePropId\"})\n * private statePropModel: StatePropModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new StatePropModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = StateProp.factory(\"statePropId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a StatePropModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (StateProp.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to StatePropModel\n * // and the compiler will know that the model has the StatePropModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { StateProp } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...StateProp.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The stateProp model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const StateProp: Readonly<\n KosModelRegistrationBean<KosStateProp, StatePropOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: StatePropModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Factory.create<KosStateProp, StatePropOptions>(MODEL_TYPE),\n};\n","/**\n * @internal\n */\nimport { KosLog, ServiceFactory, resolveServiceUrl } from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"STATE-PROP_SERVICE\");\nconst { getAll } = ServiceFactory.build({\n basePath: `${URL}/api/state-prop`,\n});\n\nconst log = KosLog.createLogger({\n name: \"state-prop-service\",\n group: \"Services\",\n});\ninterface StatePropResponse {\n id: string;\n}\n/**\n * @category Service\n * @internal\n * Retrieves the initial state-prop data.\n */\nexport const getStateProps = async () => {\n log.debug(\"sending GET for state-prop\");\n const response = await getAll<StatePropResponse>({});\n return response;\n};\n","import {\n KosLog,\n ServiceFactory,\n getQueryParams,\n resolveServiceUrl,\n} from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"TRANSLATION_SERVICE\");\nconst { getOne } = ServiceFactory.build({\n basePath: `${URL}/api/translation`,\n});\n\nconst log = KosLog.createLogger({\n name: \"translation-service\",\n group: \"Services\",\n});\nexport type TranslationResponse = Record<string, any>;\n\nexport interface LocaleDescriptor {\n defaultLocale: string;\n file: string;\n fallbacks?: string[];\n}\nexport interface Localization {\n namespaces: {\n [key: string]: {\n locales: {\n [key: string]: LocaleDescriptor;\n };\n basePath: string;\n };\n };\n path: string;\n}\n\nconst getDefaultHost = () => {\n const defaultHost = window.location.origin;\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n const result = hostUrl || defaultHost;\n return result;\n};\n/**\n * @category Service\n * Retrieves the initial translation data.\n */\nexport const getTranslations = async (url: string, root?: string) => {\n log.debug(\"sending GET for translation\");\n const rootUrl = root ?? getDefaultHost();\n try {\n const response = await fetch(`${rootUrl}${url}`);\n\n if (response.status !== 200) {\n log.warn(`Failed to fetch translations at ${url}: ${response.status}`);\n return {};\n }\n const json = await response.json();\n return json;\n } catch (error) {\n log.error(\"Error fetching translations\", error);\n throw error;\n }\n};\n\nexport const getLocalizationDescriptor = async () => {\n log.debug(`getting localization descriptor`);\n const response = await getOne<Localization>({\n urlOverride: `${URL}/api/system/kos/localization`,\n });\n\n if (response?.status !== 200) {\n throw new Error(\n `Failed to get tool localization descriptor ${response?.status}`\n );\n }\n return response.data;\n};\n\nexport const getKosLocalizationDescriptor = (context: string) => async () => {\n log.debug(`getting kos localization descriptor`);\n const response = await getOne<Record<string, Localization>>({\n urlOverride: `${URL}/api/kos/localization/contexts`,\n });\n\n if (response?.status !== 200) {\n throw new Error(\n `Failed to get tool localization descriptor ${response?.status}`\n );\n }\n return response.data[context];\n};\n","export const CONTEXT_LANG_RESOLVER = \"langResolver\";\n","/**\n * @ignore\n * @internal\n */\nimport { IReactionDisposer, reaction } from \"mobx\";\nimport type {\n IKosDataModel,\n IKosIdentifiable,\n KosContext,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core\";\nimport {\n KosContextManager,\n kosAction,\n kosModel,\n kosParentAware,\n} from \"../../../core\";\nimport { CONTEXT_LANG_RESOLVER } from \"./constants\";\nimport {\n LocaleDescriptor,\n TranslationResponse,\n getTranslations,\n} from \"./services\";\nimport { TranslationContainerModel } from \"./translation-container-model\";\nimport type { TranslationOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"translation-model\";\ninterface ResolveTranslationOptionsBase<T = string> {\n context?: string;\n defaultValue?: T;\n}\n\ninterface ResolveTranslationsDataOptions<T = string>\n extends ResolveTranslationOptionsBase<T> {\n data: Record<string, any> | string;\n}\n\ntype ResolveTranslationsOptionsMap<T = string> =\n ResolveTranslationOptionsBase<T> &\n Record<string, string | number | boolean | undefined | null>;\nexport type ResolveTranslationOptions<T = string> =\n | ResolveTranslationsDataOptions<T>\n | ResolveTranslationsOptionsMap<T>;\nexport type TranslationModel = Exclude<\n TranslationModelImpl,\n keyof IKosDataModel\n>;\n\nfunction extractOptions(options: any) {\n const isBasicOptions = typeof options === \"string\";\n const isDataObject = isBasicOptions\n ? false\n : !!options?.data && typeof options?.data !== \"string\";\n const defaultValue = isBasicOptions ? options : options?.defaultValue;\n const context = isBasicOptions ? undefined : options?.context;\n const data = isBasicOptions\n ? undefined\n : isDataObject\n ? options?.data\n : options;\n\n return { isBasicOptions, defaultValue, context, data };\n}\nfunction flattenObject(\n obj: Record<string, any>,\n parentKey = \"\"\n): Record<string, any> {\n return Object.keys(obj).reduce((acc, key) => {\n const newKey = parentKey ? `${parentKey}.${key}` : key;\n if (typeof obj[key] === \"object\" && obj[key] !== null) {\n const flattenedChild = flattenObject(obj[key], newKey);\n return { ...acc, ...flattenedChild };\n } else {\n return { ...acc, [newKey]: obj[key] };\n }\n }, {});\n}\nfunction mergeObjects<T extends Record<string, any>>(\n base: T,\n overlay: Partial<T>\n): T {\n const result: any = { ...base };\n\n for (const key in overlay) {\n if (Object.prototype.hasOwnProperty.call(overlay, key)) {\n if (\n typeof overlay[key] === \"object\" &&\n overlay[key] !== null &&\n typeof base[key] === \"object\" &&\n base[key] !== null\n ) {\n result[key] = mergeObjects(base[key], (overlay as any)[key]);\n } else {\n result[key] = overlay[key];\n }\n }\n }\n\n return result;\n}\n\nexport const expandMacros = (text: string, data: Record<string, any>) => {\n const regex = /__(.*?)__/g;\n\n const replacedText = text.replace(\n regex,\n (match, key) =>\n // Use the key to access the corresponding value in the data object\n Object.prototype.hasOwnProperty.call(data || {}, key.trim())\n ? data?.[key.trim()]\n : match // Replace with the value from the data object or keep the original match if no value found\n );\n\n // If the text hasn't changed, return it\n if (replacedText === text) {\n return replacedText;\n }\n if (regex.test(replacedText)) {\n return expandMacros(replacedText, data);\n }\n return replacedText;\n};\n\nexport const replaceText = (\n text: string,\n data: Record<string, any>,\n context?: Record<string, any>\n) => {\n const regex = /{{(.*?)}}/g;\n\n const expandedText = expandMacros(text, data);\n const replacedText = expandedText.replace(\n regex,\n (match, key) =>\n // Use the key to access the corresponding value in the data object\n Object.prototype.hasOwnProperty.call(context || {}, key.trim())\n ? context?.[key.trim()]\n : match // Replace with the value from the data object or keep the original match if no value found\n );\n\n const result = expandMacros(replacedText, data);\n return result;\n};\n\nconst splitKey = (currentNamespace: string, _key: string) => {\n if (_key.includes(\":\")) {\n const [namespace, key] = _key.split(\":\");\n return { namespace, key };\n } else {\n return { namespace: currentNamespace, key: _key };\n }\n};\n@kosParentAware()\n@kosModel(MODEL_TYPE)\nexport class TranslationModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n namespace: string;\n\n descriptor: Record<string, LocaleDescriptor>;\n defaultLocale: string;\n currentLocale: string;\n bundleResolver?: (\n namespace: string,\n locale: string,\n context?: KosContext\n ) => Promise<TranslationResponse>;\n private data: Record<string, any>;\n private logger: KosContextLogger;\n private resolver: (namespace: string, locale: string) => string;\n private disposer?: IReactionDisposer;\n private context: TranslationContainerModel;\n private rootUrl?: string;\n constructor(\n modelId: string,\n options: TranslationOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.defaultLocale = options.defaultLocale || \"en\";\n this.currentLocale = options.currentLocale || \"en\";\n this.namespace = options.namespace;\n this.descriptor = options.descriptor;\n this.rootUrl = options.rootUrl;\n this.data = {};\n this.resolver =\n options.resolver || context.kosContext.get(CONTEXT_LANG_RESOLVER);\n this.bundleResolver = options.bundleResolver;\n this.logger = context.logger;\n this.context = context.kosContext.parentModel as TranslationContainerModel;\n if (options) {\n // Assign options properties here.\n }\n }\n\n // -------------------LIFECYCLE----------------------------\n\n getTranslationLocales(locale: string) {\n const _locale = this.descriptor[locale];\n if (!locale || !_locale) {\n return [this.defaultLocale];\n }\n\n if (!this.defaultLocale && !_locale.fallbacks) {\n return [locale];\n }\n let langs = _locale.fallbacks || [this.defaultLocale];\n if (!langs.includes(locale)) {\n langs = [locale, ...langs];\n }\n return langs;\n }\n private async loadTranslations() {\n const reversed = this.getTranslationLocales(this.currentLocale).reverse();\n const allTranslations = reversed.map((lang) => {\n if (this.bundleResolver) {\n const context = KosContextManager.getContext(this.id);\n return this.bundleResolver(this.namespace, lang, context);\n }\n try {\n const translationsPath = this.resolver(this.namespace, lang);\n return getTranslations(translationsPath, this.rootUrl);\n } catch {\n return Promise.resolve({});\n }\n });\n const results = await Promise.allSettled(allTranslations);\n\n kosAction(() => {\n const newData = results.reduce<Record<string, any>>(\n (acc, result, index) => {\n if (result.status === \"fulfilled\") {\n this.logger.debug(`resolved ${reversed[index]}`, result.value);\n if (result.value) {\n acc = mergeObjects(acc, result.value);\n }\n } else {\n this.logger.error(\n `failed to load translation ${this.id} for ${reversed[index]}`\n );\n }\n return acc;\n },\n {}\n );\n this.data = flattenObject(newData);\n });\n }\n async init(): Promise<void> {\n this.logger.debug(`initializing translation ${this.id}`);\n }\n\n exists(_key: string) {\n const { namespace, key } = splitKey(this.namespace, _key);\n if (namespace !== this.namespace) {\n const ns = this.context.getModel(namespace);\n if (ns) {\n return ns.exists(key);\n } else {\n return false;\n }\n }\n return !!this.data[key];\n }\n resolveKey<T = string>(\n _key: string,\n options?: ResolveTranslationOptions<T> | string\n ) {\n if (!_key) {\n this.logger.warn(`key is empty`);\n return \"\";\n }\n const { defaultValue, context, data } = extractOptions(options);\n const { namespace, key } = splitKey(this.namespace, _key);\n const contextKey = `${key}_${context}`;\n if (namespace !== this.namespace) {\n const ns = this.context.getModel(namespace);\n if (ns) {\n return ns.resolveKey(key, options);\n } else {\n return key;\n }\n }\n if (context && this.data[contextKey]) {\n const value = this.data[contextKey];\n if (Array.isArray(value)) {\n return value.map((v) => replaceText(v, this.data, data as any));\n }\n return replaceText(this.data[contextKey], this.data, data as any);\n }\n if (this.data[key]) {\n const value = this.data[contextKey];\n if (Array.isArray(value)) {\n return value.map((v) => replaceText(v, this.data, data as any));\n }\n return replaceText(this.data[key], this.data, data as any);\n }\n\n return defaultValue ?? key;\n }\n\n unload(): void {\n this.logger.debug(`unloading translation ${this.id}`);\n if (this.disposer) {\n this.disposer();\n }\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading translation ${this.id}`);\n await this.loadTranslations();\n }\n\n async ready(): Promise<void> {\n this.logger.debug(`ready translation ${this.id}`);\n this.disposer = reaction(\n () => this.currentLocale,\n (value, previous) => {\n this.logger.info(\n `translation langs for namespace ${this.id} changed from ${previous} to ${value}`\n );\n this.loadTranslations();\n }\n );\n }\n}\n","import type { KosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport type { TranslationModel } from \"./translation-model\";\nimport { MODEL_TYPE, TranslationModelImpl } from \"./translation-model\";\nimport type { TranslationOptions } from \"./types\";\n\n/**\n * # Translation\n *\n * The registration bean includes convenience methods for creating and working with TranslationModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: Translation.type, id: \"translationId\"})\n * private translationModel: TranslationModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new TranslationModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = Translation.factory(\"translationId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a TranslationModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (Translation.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to TranslationModel\n * // and the compiler will know that the model has the TranslationModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { Translation } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...Translation.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The translation model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const Translation: Readonly<\n KosModelRegistrationBean<TranslationModel, TranslationOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: TranslationModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Factory.create<TranslationModel, TranslationOptions>(MODEL_TYPE),\n};\n","/**\n * @internal\n * @ignore\n */\nimport type {\n IKosDataModel,\n IKosIdentifiable,\n IKosModelContainer,\n IKosModelHolder,\n KosContextLogger,\n KosCreationContext,\n ReloadAware,\n} from \"../../../core\";\nimport {\n KosModelContainer,\n kosAction,\n kosChild,\n kosModel,\n resetKosModel,\n whenReady,\n} from \"../../../core\";\n\nimport { CONTEXT_LANG_RESOLVER } from \"./constants\";\nimport { Localization } from \"./services\";\nimport type { TranslationModel } from \"./translation-model\";\nimport { Translation } from \"./translation-registration\";\nimport type { TranslationContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"translation-container-model\";\ntype PublicInterface<T> = {\n [P in keyof T]: T[P];\n};\nexport type TranslationContainerModel = PublicInterface<\n Exclude<TranslationContainerModelImpl, keyof IKosDataModel>\n>;\n\nconst pathJoin = (parts, sep = \"/\") =>\n parts.join(sep).replace(new RegExp(sep + \"{1,}\", \"g\"), sep);\n\nfunction defaultResolver(\n this: TranslationContainerModel,\n namespace: string,\n locale: string\n) {\n const namespaceDescriptor = this.descriptor.namespaces[namespace];\n if (!namespaceDescriptor) {\n throw new Error(`namespace ${namespace} not found in descriptor`);\n }\n const basePath = namespaceDescriptor.basePath;\n const localePath = namespaceDescriptor.locales[locale].file;\n return pathJoin([basePath, localePath]);\n}\n\n@kosModel(MODEL_TYPE)\nexport class TranslationContainerModelImpl\n implements\n IKosIdentifiable,\n IKosModelHolder<TranslationModel>,\n IKosDataModel,\n ReloadAware\n{\n id: string;\n lang: string;\n private rootUrl?: string;\n descriptor: Localization;\n private _defaultNamespace?: string;\n private resolver: (\n this: TranslationContainerModel,\n namespace: string,\n locale: string\n ) => string;\n private logger: KosContextLogger;\n private descriptorUrl?: string;\n private namespaces: string[] = [];\n @kosChild private _models: IKosModelContainer<TranslationModel>;\n constructor(\n modelId: string,\n options: TranslationContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.lang = options.lang || \"en\";\n\n this.descriptor = options.descriptor;\n this._defaultNamespace = options.defaultNamespace;\n this.descriptorUrl = options.descriptorUrl;\n this.rootUrl = options.rootUrl;\n this.resolver = options.resolver || defaultResolver.bind(this);\n context.kosContext.set(CONTEXT_LANG_RESOLVER, this.resolver);\n this.logger = context.logger;\n this._models = new KosModelContainer<TranslationModel>({\n parentId: modelId,\n });\n }\n\n set currentLocale(locale: string) {\n this.lang = locale;\n this.models.data.forEach((model) => {\n model.currentLocale = locale;\n });\n }\n get defaultNamespace() {\n return this._defaultNamespace\n ? this.getModel(`translation-${this._defaultNamespace}`)\n : undefined;\n }\n getModel(id: string) {\n this.logger.debug(`getting model ${id}`);\n return this._models.getModel(`translation-${id}`);\n }\n get models() {\n return this._models;\n }\n get data() {\n return this._models.data;\n }\n\n async reload() {\n this._models.clear();\n await resetKosModel(this);\n for (const namespace of this.namespaces) {\n const ns = this.resolveNamespace(namespace);\n await whenReady(ns);\n }\n }\n resolveNamespace(namespace: string) {\n const namespaceDescriptor = this.descriptor.namespaces[namespace];\n\n if (!namespaceDescriptor) {\n this.logger.warn(`namespace ${namespace} not found in descriptor`);\n const translation = Translation.factory(`translation-${namespace}`)({\n kosParentId: this.id,\n namespace,\n rootUrl: this.rootUrl,\n currentLocale: this.lang,\n defaultLocale: this.lang,\n descriptor: {},\n resolver: this.resolver,\n });\n\n this.addModel(translation);\n return translation;\n } else {\n const firstLocale = Object.keys(\n this.descriptor.namespaces[namespace].locales\n )[0];\n const namespaceDefault =\n this.descriptor.namespaces[namespace].locales[firstLocale]\n .defaultLocale;\n const translation = Translation.factory(`translation-${namespace}`)({\n kosParentId: this.id,\n namespace,\n rootUrl: this.rootUrl,\n currentLocale: this.lang,\n defaultLocale: namespaceDefault,\n descriptor: this.descriptor.namespaces[namespace].locales,\n resolver: this.resolver,\n });\n\n this.addModel(translation);\n if (!this.namespaces.includes(namespace)) {\n kosAction(() => {\n this.namespaces.push(namespace);\n });\n }\n return translation;\n }\n }\n\n addModel(model: TranslationModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(\n `initializing translation-container container ${this.id}`\n );\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading translation-container container ${this.id}`);\n }\n}\n","import type { SingletonKosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport type { TranslationContainerModel } from \"./translation-container-model\";\nimport {\n MODEL_TYPE,\n TranslationContainerModelImpl,\n} from \"./translation-container-model\";\nimport type { TranslationContainerOptions } from \"./types\";\n\n/**\n * # TranslationContainer\n *\n * The registration bean includes convenience methods for creating and working with TranslationContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: TranslationContainer.type, id: \"translationContainerId\"})\n * private translationContainerModel: TranslationContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new TranslationContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = TranslationContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a TranslationContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (TranslationContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to TranslationContainerModel\n * // and the compiler will know that the model has the TranslationContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { TranslationContainer } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...TranslationContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The translationContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const TranslationContainer: Readonly<\n SingletonKosModelRegistrationBean<\n TranslationContainerModel,\n TranslationContainerOptions\n >\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: TranslationContainerModelImpl,\n singleton: true,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Singleton.create<\n TranslationContainerModel,\n TranslationContainerOptions\n >(MODEL_TYPE),\n};\n","import { KosContextManager, whenReady } from \"../../../core\";\nimport { TranslationContainer } from \"./translation-container-registration\";\nimport type { TranslationContainerOptions } from \"./types\";\n\nexport const TranslationContext = {\n set(name: string, value: any) {\n const context = KosContextManager.getContext(TranslationContainer.type);\n if (context) {\n context.set(name, value);\n }\n },\n get(name: string) {\n const context = KosContextManager.getContext(TranslationContainer.type);\n return context?.get(name);\n },\n};\n\nexport const KosTranslations = {\n async init(options: TranslationContainerOptions) {\n const tc = TranslationContainer.factory(options);\n await whenReady(tc);\n return { translations: tc };\n },\n};\n","import type { TroubleModel } from \"../types\";\n\nexport const troubleByTypeReducer = (\n acc: Record<string, TroubleModel[]>,\n trouble: TroubleModel\n) => {\n const type = trouble.type;\n if (!acc[type]) {\n acc[type] = [];\n }\n acc[type].push(trouble);\n return acc;\n};\n","import { modelFactory } from \"../../../core\";\nimport type { IWsEvent, WsEventOptions } from \"./types\";\nexport const WS_EVENT_TYPE = \"kos-ws-event\";\nexport const WsEventFactory = modelFactory<IWsEvent, WsEventOptions>(\n WS_EVENT_TYPE\n);\n","import { observable } from \"mobx\";\nimport { KosWsEvents, type ApiCallback } from \"../../../common\";\nimport {\n KosLog,\n kosModel,\n kosTopicHandler,\n type KosInternalEvent,\n} from \"../../../core\";\nimport type { EventData, IWsEvent } from \"./types\";\nimport { WsEventFactory } from \"./ws-event-factory\";\n\nconst stringify = ({ headers, body }: KosInternalEvent) => {\n const headText = Object.entries(headers)\n .map(([key, value]) => `${key}:${value}`)\n .join(\"\\\\n\");\n return headText + \"\\\\n\\\\n\" + body;\n};\n@kosModel(WsEventFactory.type)\nexport class WsEventModel implements IWsEvent {\n id: string;\n events: Map<string, EventData>;\n private _topicMap: Map<string, number>;\n constructor(modelId: string) {\n this.id = modelId;\n this.events = observable.map(new Map<string, EventData>());\n\n this._topicMap = new Map<string, number>();\n }\n\n get websocketEvents() {\n return Array.from(this.events.values());\n }\n\n @kosTopicHandler({\n topic: [KosWsEvents.SEND],\n })\n handleSendEvent(\n _data: KosInternalEvent,\n payload: ApiCallback<KosInternalEvent>\n ) {\n this.processEvent(payload, true);\n }\n\n @kosTopicHandler({\n topic: [KosWsEvents.RECEIVED],\n })\n handleReceiveEvent(\n _data: KosInternalEvent,\n payload: ApiCallback<KosInternalEvent>\n ) {\n this.processEvent(payload);\n }\n\n processEvent(data: ApiCallback<KosInternalEvent>, isSend = false) {\n KosLog.debug(\"kos event received\");\n const { body, headers } = data.body;\n\n const isUnique = headers[\"request-id\"] || headers[\"response-id\"];\n const msgId =\n headers[\"request-id\"] ||\n headers[\"response-id\"] ||\n headers[\"topic\"] ||\n headers[\"type\"];\n\n if (msgId) {\n let rawKey = msgId;\n if (!isUnique) {\n const count = this._topicMap.get(msgId) || 0;\n\n rawKey = `${rawKey}-${count + 1}`;\n this._topicMap.set(msgId, count + 1);\n } else {\n const dir = isSend ? \"send\" : \"receive\";\n rawKey = `${rawKey}-${dir}`;\n }\n const rawData: EventData = {\n msgId: rawKey,\n content: body,\n headers,\n timestamp: Date.now(),\n raw: stringify({ headers, body }),\n direction: isSend ? \"send\" : \"receive\",\n mocked: !!headers[\"mocked\"],\n };\n this.events.set(rawKey, rawData);\n KosLog.debug(`logged ${this.events.size} events`);\n }\n }\n}\n","/**\n * @internal\n */\nimport {\n FetchError,\n KosLog,\n ServiceFactory,\n resolveServiceUrl,\n} from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"DEVICE_SERVICE\");\nconst { getOne } = ServiceFactory.build({\n basePath: `${URL}/api/device`,\n});\n\nconst log = KosLog.createLogger({ name: \"device-service\", group: \"Services\" });\n\ntype SerialNumberResponse = [string | undefined, string | undefined];\n\ntype DeviceResponse = [string, undefined] | [undefined, DevicePayload];\ntype DevicePayload = {\n serialNumber: string;\n name: string;\n nodeId: string;\n};\n/**\n * @category Service\n * @internal\n * Retrieves the device serial number.\n */\nexport const getSerialNumber = async (): Promise<SerialNumberResponse> => {\n log.debug(\"sending GET for device serial number\");\n try {\n const response = await getOne<DevicePayload>({\n urlOverride: `${URL}/api/kos/device/serialNumber`,\n });\n\n return [undefined, response?.data.serialNumber];\n } catch (error) {\n if (error instanceof FetchError) {\n log.error(`Error fetching device serial number: ${error.payload.error}`);\n return [error.payload.error, undefined];\n }\n }\n\n return [\"unknownError\", undefined];\n};\n\n/**\n * @category Service\n * @internal\n * Retrieves the initial device data.\n */\nexport const getDeviceDetails = async (): Promise<DeviceResponse> => {\n log.debug(\"sending GET for device details\");\n try {\n const response = await getOne<DevicePayload>({\n urlOverride: `${URL}/api/kos/device`,\n });\n\n if (!response) {\n return [\"unknownError\", undefined];\n }\n return [undefined, response.data];\n } catch (error) {\n if (error instanceof FetchError) {\n log.error(`Error fetching device serial number: ${error.payload.error}`);\n return [error.payload.error, undefined];\n }\n }\n\n return [\"unknownError\", undefined];\n};\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosModel, kosTopicHandler } from \"../../../core\";\nimport { getDeviceDetails, getSerialNumber } from \"./services\";\nimport type { DeviceOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"device-model\";\nexport const TOPIC_CRITICAL_DATA_CHANGED = \"/kos/criticalData/changed\";\nexport const TOPIC_CRITICAL_DATA_AVAILABLE = \"/kos/criticalData/available\";\nexport const TOPIC_CRITICAL_DATA_UNAVAILABLE = \"/kos/criticalData/unavailable\";\n\n/**\n * A model representing a device.\n * This is an alias for the implementation {@link DeviceModelImpl}.\n *\n * @category Model\n *\n */\nexport type DeviceModel = PublicModelInterface<DeviceModelImpl>;\n\n@kosModel(MODEL_TYPE)\nexport class DeviceModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n private logger: KosContextLogger;\n private _serialNumber: string | \"unassigned\";\n\n get serialNumber(): string | \"unassigned\" {\n return this._serialNumber;\n }\n\n private _name: string | \"unassigned\";\n\n get name(): string | \"unassigned\" {\n return this._name;\n }\n\n private _nodeId: string | \"unassigned\";\n\n get nodeId(): string | \"unassigned\" {\n return this._nodeId;\n }\n\n get nodeType(): string {\n const [nodeType] = this.nodeId.split(\"-\");\n return nodeType;\n }\n\n get nodeName(): string {\n const [, nodeName] = this.nodeId.split(\"-\");\n return nodeName;\n }\n\n constructor(\n modelId: string,\n _options: DeviceOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._serialNumber = \"unassigned\";\n this._name = \"unassigned\";\n this._nodeId = \"unassigned\";\n }\n\n /**\n * Update the model with new options.\n */\n updateModel(options: DeviceOptions): void {\n this._serialNumber = options.serialNumber ?? \"unassigned\";\n this._name = options.name ?? \"unassigned\";\n this._nodeId = options.nodeId ?? \"unassigned\";\n }\n\n private async loadDeviceData() {\n const [error, device] = await getDeviceDetails();\n if (error) {\n this.logger.error(`Error fetching device serial number: ${error}`);\n return;\n }\n if (device) {\n const { name, nodeId } = device;\n this.updateModel({ name, nodeId, serialNumber: this.serialNumber });\n }\n }\n\n private async loadSerialNumber() {\n const [error, serialNumber] = await getSerialNumber();\n if (error) {\n this.logger.error(`Error fetching device serial number: ${error}`);\n return;\n }\n\n this.updateModel({ serialNumber, name: this.name, nodeId: this.nodeId });\n }\n\n /**\n * Handle critical data changes to load the serial number at the appropriate time.\n */\n @kosTopicHandler({\n topic: [TOPIC_CRITICAL_DATA_CHANGED, TOPIC_CRITICAL_DATA_AVAILABLE],\n websocket: true,\n })\n async handleCriticalDataChanged() {\n this.logger.debug(`Critical data changed for device ${this.id}`);\n await this.loadSerialNumber();\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing device ${this.id}`);\n }\n\n /**\n * Load the device data.\n *\n * This method is called when the device model is loaded.\n *\n *\n */\n async load(): Promise<void> {\n this.logger.debug(`loading device ${this.id}`);\n await this.loadDeviceData();\n await this.loadSerialNumber();\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { DeviceModel } from \"./device-model\";\nimport { DeviceModelImpl, MODEL_TYPE } from \"./device-model\";\nimport type { DeviceOptions } from \"./types\";\n\n/**\n * # Device\n *\n * The registration bean includes convenience methods for creating and working with DeviceModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: Device.type, id: \"deviceId\"})\n * private deviceModel: DeviceModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new DeviceModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = Device.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a DeviceModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (Device.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to DeviceModel\n * // and the compiler will know that the model has the DeviceModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { Device } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(Device);\n * ```\n *\n * ## registration.singleton\n \n * The device model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const Device = new SingletonKosModelRegistrationFactory<\n DeviceModel,\n DeviceOptions\n>({\n class: DeviceModelImpl,\n type: MODEL_TYPE,\n});\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosModel } from \"../../../core\";\nimport type {\n EthernetData,\n Ip44Settings,\n NetworkInterfaceCategory,\n NetworkInterfaceData,\n WifiData,\n} from \"./services\";\nimport type { NetworkInterfaceOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"network-interface-model\";\n\nexport type NetworkInterfaceModel =\n PublicModelInterface<NetworkInterfaceModelImpl>;\n\n@kosModel(MODEL_TYPE)\nexport class NetworkInterfaceModelImpl\n implements IKosDataModel, IKosIdentifiable, NetworkInterfaceData\n{\n id: string;\n name: string;\n type: string;\n nmdevicestate: number;\n hwaddress: string;\n mtu: number;\n configured: boolean;\n wifi?: WifiData;\n ethernet?: EthernetData;\n ip4settings?: Ip44Settings;\n category: NetworkInterfaceCategory;\n\n private logger: KosContextLogger;\n\n constructor(\n modelId: string,\n options: NetworkInterfaceOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n this.name = options.name;\n this.type = options.type;\n this.nmdevicestate = options.nmdevicestate;\n this.hwaddress = options.hwaddress;\n this.mtu = options.mtu;\n this.configured = options.configured;\n this.wifi = options.wifi;\n this.ethernet = options.ethernet;\n this.ip4settings = options.ip4settings;\n this.category = options.category;\n }\n\n updateModel(options: NetworkInterfaceOptions): void {\n this.name = options.name;\n this.type = options.type;\n this.nmdevicestate = options.nmdevicestate;\n this.hwaddress = options.hwaddress;\n this.mtu = options.mtu;\n this.configured = options.configured;\n this.wifi = options.wifi;\n this.ethernet = options.ethernet;\n this.ip4settings = options.ip4settings;\n this.category = options.category;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing network-interface ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading network-interface ${this.id}`);\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core\";\nimport type { NetworkInterfaceModel } from \"./network-interface-model\";\nimport {\n MODEL_TYPE,\n NetworkInterfaceModelImpl,\n} from \"./network-interface-model\";\nimport type { NetworkInterfaceOptions } from \"./types\";\n\n/**\n * # NetworkInterface\n *\n * The registration bean includes convenience methods for creating and working with NetworkInterfaceModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: NetworkInterface.type, id: \"networkInterfaceId\"})\n * private networkInterfaceModel: NetworkInterfaceModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new NetworkInterfaceModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = NetworkInterface.factory(\"networkInterfaceId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a NetworkInterfaceModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (NetworkInterface.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to NetworkInterfaceModel\n * // and the compiler will know that the model has the NetworkInterfaceModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { NetworkInterface } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(NetworkInterface);\n * ```\n *\n * ## registration.singleton\n \n * The networkInterface model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const NetworkInterface = new KosModelRegistrationFactory<\n NetworkInterfaceModel,\n NetworkInterfaceOptions\n>({\n class: NetworkInterfaceModelImpl,\n type: MODEL_TYPE,\n});\n","/**\n * @internal\n */\nimport {\n FetchError,\n KosLog,\n ServiceFactory,\n resolveServiceUrl,\n} from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"NETWORK-INTERFACE_SERVICE\");\nconst { getAll } = ServiceFactory.build({\n basePath: `${URL}/api/kos/network/interfaces`,\n});\n\nconst log = KosLog.createLogger({\n name: \"network-interface-service\",\n group: \"Services\",\n});\n\nexport type NetworkInterfaceCategory =\n | \"INTERNAL\"\n | \"INTEGRATION\"\n | \"EXTERNAL\"\n | \"NONE\";\n\nexport interface EthernetData {\n carrier: boolean;\n speed: number;\n duplex: string;\n}\n\nexport interface WifiData {\n apFlags: number;\n bssid: string;\n wpaFlags: number;\n bitrate: number;\n ssid: string;\n signal: number;\n rsnFlags: number;\n lastSeenAgo: number;\n frequency: number;\n}\n\nexport interface Ip44Settings {\n prefix: number;\n addressprefixlist: string[];\n address: string;\n method: string;\n gateway: string;\n dnslist: string[];\n}\n\nexport interface NetworkInterfaceData {\n name: string;\n\n type: string;\n nmdevicestate: number;\n hwaddress: string;\n mtu: number;\n configured: boolean;\n wifi?: WifiData;\n ethernet?: EthernetData;\n ip4settings?: Ip44Settings;\n category: NetworkInterfaceCategory;\n}\n\ntype NetworkInterfaceResponse =\n | [error: string, data: undefined]\n | [error: undefined, data: NetworkInterfaceData[] | undefined];\n/**\n * @category Service\n * @internal\n * Retrieves the initial network-interface data.\n */\n\nexport const getNetworkInterfaces =\n async (): Promise<NetworkInterfaceResponse> => {\n log.debug(\"sending GET for copy-logs\");\n\n try {\n const response = await getAll<NetworkInterfaceData>({});\n\n return [undefined, response?.data];\n } catch (error) {\n if (error instanceof FetchError) {\n log.error(`Error fetching log file size: ${error.payload.error}`);\n return [error.payload.error, undefined];\n }\n }\n\n return [\"unknownError\", undefined];\n };\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n IKosModelContainer,\n IKosModelHolder,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosChild, kosModel, KosModelContainer } from \"../../../core\";\nimport type { NetworkInterfaceModel } from \"./network-interface-model\";\nimport { NetworkInterface } from \"./network-interface-registration\";\nimport { getNetworkInterfaces } from \"./services\";\nimport type { NetworkInterfaceContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"network-interface-container-model\";\n\nexport type NetworkInterfaceContainerModel =\n PublicModelInterface<NetworkInterfaceContainerModelImpl>;\n\n@kosModel(MODEL_TYPE)\nexport class NetworkInterfaceContainerModelImpl\n implements\n IKosIdentifiable,\n IKosModelHolder<NetworkInterfaceModel>,\n IKosDataModel\n{\n id: string;\n private logger: KosContextLogger;\n @kosChild private _models: IKosModelContainer<NetworkInterfaceModel>;\n constructor(\n modelId: string,\n options: NetworkInterfaceContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._models = new KosModelContainer<NetworkInterfaceModel>({\n parentId: modelId,\n indexMap: {\n byCategory: \"category\",\n },\n });\n if (options) {\n // Assign options properties here.\n }\n }\n\n getModel(id: string) {\n return this._models.getModel(id);\n }\n get models() {\n return this._models;\n }\n get data() {\n return this._models.data;\n }\n\n addModel(model: NetworkInterfaceModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(\n `initializing network-interface-container container ${this.id}`\n );\n }\n\n async refreshInterfaces() {\n this.logger.debug(`refreshing interfaces`);\n const [error, networkInterfaces] = await getNetworkInterfaces();\n if (error) {\n this.logger.error(`Error loading network interfaces: ${error}`);\n return;\n }\n\n if (networkInterfaces) {\n networkInterfaces.forEach((networkInterfaceData) => {\n const networkInterfaceModel = NetworkInterface.instance(\n networkInterfaceData.name\n )\n .forceUpdate.options(networkInterfaceData)\n .build();\n this.addModel(networkInterfaceModel);\n });\n }\n }\n\n async load(): Promise<void> {\n this.logger.debug(\n `loading network-interface-container container ${this.id}`\n );\n\n this.refreshInterfaces();\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { NetworkInterfaceContainerModel } from \"./network-interface-container-model\";\nimport {\n MODEL_TYPE,\n NetworkInterfaceContainerModelImpl,\n} from \"./network-interface-container-model\";\nimport { NetworkInterface } from \"./network-interface-registration\";\nimport type { NetworkInterfaceContainerOptions } from \"./types\";\n\n/**\n * # NetworkInterfaceContainer\n *\n * The registration bean includes convenience methods for creating and working with NetworkInterfaceContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: NetworkInterfaceContainer.type, id: \"networkInterfaceContainerId\"})\n * private networkInterfaceContainerModel: NetworkInterfaceContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new NetworkInterfaceContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = NetworkInterfaceContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a NetworkInterfaceContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (NetworkInterfaceContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to NetworkInterfaceContainerModel\n * // and the compiler will know that the model has the NetworkInterfaceContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { NetworkInterfaceContainer } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...NetworkInterfaceContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The networkInterfaceContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const NetworkInterfaceContainer =\n new SingletonKosModelRegistrationFactory<\n NetworkInterfaceContainerModel,\n NetworkInterfaceContainerOptions\n >({\n class: NetworkInterfaceContainerModelImpl,\n type: MODEL_TYPE,\n });\n\nNetworkInterfaceContainer.addRelatedModel(NetworkInterface);\n","/**\n * @internal\n */\n\nimport { KosLog, resolveServiceUrl, ServiceFactory } from \"../../../../core\";\n\nconst { URL } = resolveServiceUrl(\"STORAGE-DEVICE_SERVICE\");\nconst { getAll } = ServiceFactory.build({\n basePath: `${URL}/api/kos/storage/devices`,\n});\n\nconst log = KosLog.createLogger({\n name: \"storage-device-service\",\n group: \"Services\",\n});\n\nexport interface StorageDeviceResponse {\n mountDir: string;\n removed: boolean;\n id: string;\n vendor: string;\n runTimeMs: number;\n model: string;\n nodeId: string;\n local: boolean;\n label: string;\n syspath: string;\n}\n/**\n * @category Service\n * @internal\n * Retrieves the initial storage-device data.\n */\nexport const getStorageDevices = async () => {\n log.debug(\"sending GET for storage-device\");\n const response = await getAll<StorageDeviceResponse>({});\n if (!response?.data || response.status !== 200) {\n log.error(\"Failed to retrieve storage-device data\", response);\n return [];\n }\n return response.data;\n};\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosModel, kosParentAware } from \"../../../core\";\nimport type { StorageDeviceOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"storage-device-model\";\n\nexport type StorageDeviceModel = PublicModelInterface<StorageDeviceModelImpl>;\n\n/**\n * Storage Device Model\n * @category Model\n */\n@kosParentAware()\n@kosModel(MODEL_TYPE)\nexport class StorageDeviceModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n mountDir: string;\n removed: boolean;\n\n vendor: string;\n runTimeMs: number;\n model: string;\n nodeId: string;\n local: boolean;\n label: string;\n syspath: string;\n private logger: KosContextLogger;\n constructor(\n modelId: string,\n options: StorageDeviceOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.mountDir = options.mountDir;\n this.removed = options.removed;\n this.vendor = options.vendor;\n this.runTimeMs = options.runTimeMs;\n this.model = options.model;\n this.nodeId = options.nodeId;\n this.local = options.local;\n this.label = options.label;\n this.syspath = options.syspath;\n }\n\n updateModel(options: StorageDeviceOptions): void {\n this.mountDir = options.mountDir;\n this.removed = options.removed;\n this.vendor = options.vendor;\n this.runTimeMs = options.runTimeMs;\n this.model = options.model;\n this.nodeId = options.nodeId;\n this.local = options.local;\n this.label = options.label;\n this.syspath = options.syspath;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing storage-device ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading storage-device ${this.id}`);\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core\";\nimport type { StorageDeviceModel } from \"./storage-device-model\";\nimport { MODEL_TYPE, StorageDeviceModelImpl } from \"./storage-device-model\";\nimport type { StorageDeviceOptions } from \"./types\";\n\n/**\n * # StorageDevice\n *\n * The registration bean includes convenience methods for creating and working with StorageDeviceModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: StorageDevice.type, id: \"storageDeviceId\"})\n * private storageDeviceModel: StorageDeviceModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new StorageDeviceModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = StorageDevice.factory(\"storageDeviceId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a StorageDeviceModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (StorageDevice.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to StorageDeviceModel\n * // and the compiler will know that the model has the StorageDeviceModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { StorageDevice } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(StorageDevice);\n * ```\n *\n * ## registration.singleton\n \n * The storageDevice model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const StorageDevice = new KosModelRegistrationFactory<\n StorageDeviceModel,\n StorageDeviceOptions\n>({\n class: StorageDeviceModelImpl,\n type: MODEL_TYPE,\n});\n","import {\n type IKosIdentifiable,\n type IKosModelHolder,\n kosChild,\n kosModel,\n kosTopicHandler,\n type PublicModelInterface,\n} from \"../../../core\";\nimport {\n type IKosModelContainer,\n KosModelContainer,\n} from \"../../../core/core/kos-container-model\";\nimport {\n type IKosDataModel,\n KosContextLogger,\n type KosCreationContext,\n} from \"../../../core/core/kosModel\";\n\nimport { getStorageDevices, type StorageDeviceResponse } from \"./services\";\nimport type { StorageDeviceModel } from \"./storage-device-model\";\nimport { StorageDevice } from \"./storage-device-registration\";\nimport type {\n StorageDeviceContainerOptions,\n StorageDeviceOptions,\n} from \"./types\";\n\nexport const MODEL_TYPE = \"storage-device-container-model\";\n\nexport const TOPIC_STORAGE_AVAILABILITY = \"/kos/storage\";\n\nexport type StorageDeviceContainerModel =\n PublicModelInterface<StorageDeviceContainerModelImpl>;\n\n/**\n * Storage Device Container Model\n * @category Model\n */\n@kosModel(MODEL_TYPE)\nexport class StorageDeviceContainerModelImpl\n implements\n IKosIdentifiable,\n IKosModelHolder<StorageDeviceModel>,\n IKosDataModel\n{\n id: string;\n private logger: KosContextLogger;\n @kosChild private _models: IKosModelContainer<StorageDeviceModel>;\n constructor(\n modelId: string,\n options: StorageDeviceContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._models = new KosModelContainer<StorageDeviceModel>({\n parentId: modelId,\n });\n if (options) {\n // Assign options properties here.\n }\n }\n\n getModel(id: string) {\n return this._models.getModel(id);\n }\n get models() {\n return this._models;\n }\n get data() {\n return this._models.data;\n }\n\n addModel(model: StorageDeviceModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(\n `initializing storage-device-container container ${this.id}`\n );\n }\n get isStorageInserted() {\n return this.data.length > 0;\n }\n\n get volumes() {\n return this.data;\n }\n\n @kosTopicHandler({\n topic: TOPIC_STORAGE_AVAILABILITY,\n websocket: true,\n })\n handleStorageAvailability(devices: StorageDeviceResponse[]) {\n const toRemove = this._models.data.filter(\n (model) => !devices.find((device) => device.id === model.id)\n );\n toRemove.forEach((model) => {\n this.removeModel(model.id);\n });\n\n devices.forEach((device) => {\n const model = this.getModel(device.id);\n if (model) {\n const options: StorageDeviceOptions = {\n ...device,\n kosParentId: this.id,\n };\n model.updateModel(options);\n } else {\n const options: StorageDeviceOptions = {\n ...device,\n kosParentId: this.id,\n };\n const model = StorageDevice.instance(device.id)\n .options(options)\n .build();\n this.addModel(model);\n }\n });\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading storage-device-container container ${this.id}`);\n const storageDevices = await getStorageDevices();\n storageDevices.forEach((storageDevice) => {\n const options: StorageDeviceOptions = {\n ...storageDevice,\n kosParentId: this.id,\n };\n const model = StorageDevice.instance(storageDevice.id)\n .options(options)\n .build();\n this.addModel(model);\n });\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { StorageDeviceContainerModel } from \"./storage-device-container-model\";\nimport {\n MODEL_TYPE,\n StorageDeviceContainerModelImpl,\n} from \"./storage-device-container-model\";\nimport { StorageDevice } from \"./storage-device-registration\";\nimport type { StorageDeviceContainerOptions } from \"./types\";\n\n/**\n * # StorageDeviceContainer\n *\n * The registration bean includes convenience methods for creating and working with StorageDeviceContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: StorageDeviceContainer.type, id: \"storageDeviceContainerId\"})\n * private storageDeviceContainerModel: StorageDeviceContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new StorageDeviceContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = StorageDeviceContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a StorageDeviceContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (StorageDeviceContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to StorageDeviceContainerModel\n * // and the compiler will know that the model has the StorageDeviceContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { StorageDeviceContainer } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...StorageDeviceContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The storageDeviceContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const StorageDeviceContainer = new SingletonKosModelRegistrationFactory<\n StorageDeviceContainerModel,\n StorageDeviceContainerOptions\n>({\n class: StorageDeviceContainerModelImpl,\n type: MODEL_TYPE,\n});\n\nStorageDeviceContainer.addRelatedModel(StorageDevice);\n","/**\n * @internal\n */\nimport {\n KosLog,\n ServiceFactory,\n resolveServiceUrl,\n type KosServiceResponse,\n} from \"../../../../core\";\nimport type { FutureResponse } from \"../../../services/future\";\n\nconst { URL } = resolveServiceUrl(\"USB-UPDATE_SERVICE\");\nconst { getAll, postModel } = ServiceFactory.build({\n basePath: `${URL}/api/kos/update/available`,\n});\n\nconst log = KosLog.createLogger({\n name: \"usb-update-service\",\n group: \"Services\",\n});\n\nexport interface UpdateNote {\n summary: string;\n details: string[];\n}\n\nexport interface UsbUpdateResponse {\n active: boolean;\n blocked: boolean;\n createTime: Date;\n deviceId: string;\n manifestId: string;\n notes: UpdateNote[];\n}\n\n/**\n * @category Service\n * @internal\n * Retrieves the initial usb-update data.\n */\nexport const getAvailableUpdates = async () => {\n log.debug(\"sending GET for usb-update\");\n const response = await getAll<UsbUpdateResponse>({\n urlOverride: `${URL}/api/kos/update/available`,\n });\n\n if (!response?.data || response?.status !== 200) {\n log.error(\"Failed to retrieve usb-update data\", response);\n return [];\n }\n\n return response.data;\n};\n\nexport const installUpdate = async (\n manifestId: string,\n deviceId: string,\n tracker: string\n): Promise<FutureResponse> => {\n const response: KosServiceResponse<FutureResponse> | undefined =\n await postModel({\n model: {\n manifestId,\n deviceId,\n },\n tracker,\n urlOverride: `${URL}/api/kos/update/install`,\n });\n\n if (!response?.data) {\n throw new Error(\"No response from server\");\n }\n\n return response.data;\n};\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosModel } from \"../../../core\";\n\nimport { kosFuture } from \"../../decorators/future-service\";\nimport { FutureHandler } from \"../future/future-aware\";\nimport type {\n FutureAwareContainer,\n FutureContainer,\n} from \"../future/future-types\";\nimport { installUpdate, type UpdateNote } from \"./services\";\nimport type { UsbUpdateOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"usb-update-model\";\n\nexport type UsbUpdateModel = PublicModelInterface<UsbUpdateModelImpl>;\n\n/**\n * USB Update Model\n * @category Model\n */\n@kosModel(MODEL_TYPE)\nexport class UsbUpdateModelImpl\n implements IKosDataModel, IKosIdentifiable, FutureContainer\n{\n id: string;\n active: boolean;\n blocked: boolean;\n createTime: Date;\n deviceId: string;\n manifestId: string;\n notes: UpdateNote[];\n futureHandler: FutureAwareContainer<Record<string, unknown>>;\n\n private logger: KosContextLogger;\n\n constructor(\n modelId: string,\n options: UsbUpdateOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.active = options.active;\n this.blocked = options.blocked;\n this.createTime = options.createTime;\n this.deviceId = options.deviceId;\n this.manifestId = options.manifestId;\n this.notes = options.notes;\n this.futureHandler = new FutureHandler(this);\n }\n\n updateModel(options: UsbUpdateOptions): void {\n this.active = options.active;\n this.blocked = options.blocked;\n this.createTime = options.createTime;\n this.deviceId = options.deviceId;\n this.manifestId = options.manifestId;\n this.notes = options.notes;\n }\n\n reset() {\n this.futureHandler.removeFuture();\n }\n\n get future() {\n return this.futureHandler.future;\n }\n\n @kosFuture()\n async install(tracker?: string) {\n // should be handed in by the `kosFuture` decorator\n if (!tracker) {\n throw new Error(\"No tracker provided\");\n }\n\n this.logger.info(\n `Installing update for manifest ${this.manifestId} from device ${this.deviceId}`\n );\n\n return installUpdate(this.manifestId, this.deviceId, tracker);\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing usb-update ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading usb-update ${this.id}`);\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core\";\nimport type { UsbUpdateOptions } from \"./types\";\nimport type { UsbUpdateModel } from \"./usb-update-model\";\nimport { MODEL_TYPE, UsbUpdateModelImpl } from \"./usb-update-model\";\n\n/**\n * # UsbUpdate\n *\n * The registration bean includes convenience methods for creating and working with UsbUpdateModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: UsbUpdate.type, id: \"usbUpdateId\"})\n * private usbUpdateModel: UsbUpdateModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new UsbUpdateModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = UsbUpdate.factory(\"usbUpdateId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a UsbUpdateModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (UsbUpdate.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to UsbUpdateModel\n * // and the compiler will know that the model has the UsbUpdateModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { UsbUpdate } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * import { initKosProvider } from \"@kosdev-code/kos-ui-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(UsbUpdate);\n * ```\n *\n * ## registration.singleton\n \n * The usbUpdate model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const UsbUpdate = new KosModelRegistrationFactory<\n UsbUpdateModel,\n UsbUpdateOptions\n>({\n class: UsbUpdateModelImpl,\n type: MODEL_TYPE,\n});\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n IKosModelContainer,\n IKosModelHolder,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport {\n KosModelContainer,\n kosAction,\n kosChild,\n kosDependency,\n kosModel,\n kosModelEffect,\n} from \"../../../core\";\nimport {\n StorageDeviceContainer,\n type StorageDeviceContainerModel,\n} from \"../storage-device\";\nimport { getAvailableUpdates } from \"./services\";\nimport type { UsbUpdateContainerOptions } from \"./types\";\nimport type { UsbUpdateModel } from \"./usb-update-model\";\nimport { UsbUpdate } from \"./usb-update-registration\";\n\nexport const MODEL_TYPE = \"usb-update-container-model\";\n\nexport type UsbUpdateContainerModel =\n PublicModelInterface<UsbUpdateContainerModelImpl>;\n\n@kosModel(MODEL_TYPE)\nexport class UsbUpdateContainerModelImpl\n implements IKosIdentifiable, IKosModelHolder<UsbUpdateModel>, IKosDataModel\n{\n id: string;\n private disposer?: () => void;\n @kosDependency({ modelType: StorageDeviceContainer.type })\n storageService!: StorageDeviceContainerModel;\n\n private _activeUpdate?: UsbUpdateModel;\n private logger: KosContextLogger;\n @kosChild private _models: IKosModelContainer<UsbUpdateModel>;\n\n constructor(\n modelId: string,\n options: UsbUpdateContainerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._models = new KosModelContainer<UsbUpdateModel>({ parentId: modelId });\n\n if (options) {\n // Assign options properties here.\n }\n }\n\n getModel(id: string) {\n return this._models.getModel(id);\n }\n\n get models() {\n return this._models;\n }\n\n get data() {\n return this._models.data;\n }\n\n addModel(model: UsbUpdateModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n\n get activeUpdate() {\n return this._activeUpdate;\n }\n\n reset() {\n this.clearActiveUpdate();\n }\n\n clearActiveUpdate() {\n this._activeUpdate = undefined;\n }\n\n updateActiveUpdate(update: UsbUpdateModel) {\n this._activeUpdate = update;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n get isUsbInserted(): boolean {\n return this.storageService.isStorageInserted;\n }\n\n get hasAvailableUpdates(): boolean {\n return this._models.data.length > 0;\n }\n\n async syncAvailableUpdates() {\n const updates = await getAvailableUpdates();\n\n kosAction(() => {\n const allKeys = updates.map(\n (update) => `${update.deviceId}-${update.manifestId}`\n );\n\n this._models.data\n .filter((model) => !allKeys.includes(model.id))\n .forEach((model) => this.removeModel(model.id));\n\n updates.forEach((update) => {\n const modelId = `${update.deviceId}-${update.manifestId}`;\n const model = UsbUpdate.instance(modelId)\n .forceUpdate.options({\n ...update,\n createTime: new Date(update.createTime),\n })\n .build();\n\n this.addModel(model);\n });\n\n if (this.data.length === 1) {\n this.updateActiveUpdate(this.data[0]);\n } else {\n this.clearActiveUpdate();\n }\n });\n }\n\n @kosModelEffect({ dependencies: (model) => [model.isUsbInserted] })\n usbInsertedEffect() {\n if (this.isUsbInserted) {\n this.syncAvailableUpdates();\n } else {\n this._models.clear();\n this.clearActiveUpdate();\n }\n }\n\n async init(): Promise<void> {\n this.logger.debug(`initializing usb-update-container container ${this.id}`);\n }\n\n unload(): void {\n this.disposer?.();\n }\n\n async activate(): Promise<void> {\n this.logger.debug(`activating usb-update-container container ${this.id}`);\n\n await this.syncAvailableUpdates();\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading usb-update-container container ${this.id}`);\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { UsbUpdateContainerOptions } from \"./types\";\nimport type { UsbUpdateContainerModel } from \"./usb-update-container-model\";\nimport {\n MODEL_TYPE,\n UsbUpdateContainerModelImpl,\n} from \"./usb-update-container-model\";\nimport { UsbUpdate } from \"./usb-update-registration\";\n\n/**\n * # UsbUpdateContainer\n *\n * The registration bean includes convenience methods for creating and working with UsbUpdateContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: UsbUpdateContainer.type, id: \"usbUpdateContainerId\"})\n * private usbUpdateContainerModel: UsbUpdateContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new UsbUpdateContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = UsbUpdateContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a UsbUpdateContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (UsbUpdateContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to UsbUpdateContainerModel\n * // and the compiler will know that the model has the UsbUpdateContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { UsbUpdateContainer } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...UsbUpdateContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The usbUpdateContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const UsbUpdateContainer = new SingletonKosModelRegistrationFactory<\n UsbUpdateContainerModel,\n UsbUpdateContainerOptions\n>({\n class: UsbUpdateContainerModelImpl,\n type: MODEL_TYPE,\n});\n\nUsbUpdateContainer.addRelatedModel(UsbUpdate);\n","import { FutureFactory, FutureModel } from \"./models/future\";\nimport {\n FutureContainerFactory,\n FutureContainerModel,\n} from \"./models/future-container\";\nimport { KosTime } from \"./models/kos-time/kos-time-registration\";\nimport { StateBean } from \"./models/state-bean/state-bean-registration\";\nimport { StateProp } from \"./models/state-prop/state-prop-registration\";\n// ------- PREPEND IMPORTS --------\n\nimport { KosConfigPropertySpec } from \"./models/config-bean-prop\";\nimport { RegionInfo } from \"./models/region-info\";\nimport { Translation, TranslationContainer } from \"./models/translation\";\nimport { TroubleContainer } from \"./models/trouble-container/trouble-container-registration\";\n\nimport type { IKosRegistry } from \"../core/core/types\";\nimport { WsEventModel } from \"./models/ws-event\";\nimport { WsEventFactory } from \"./models/ws-event/ws-event-factory\";\n\nconst getKosModel = () => {\n const kosModels: IKosRegistry[\"models\"] = {\n [FutureFactory.type]: {\n class: FutureModel,\n },\n [FutureContainerFactory.type]: {\n class: FutureContainerModel,\n singleton: true,\n },\n ...RegionInfo.registration,\n\n ...KosConfigPropertySpec.registration,\n\n ...TroubleContainer.registration,\n ...Translation.registration,\n ...TranslationContainer.registration,\n\n [WsEventFactory.type]: {\n class: WsEventModel,\n singleton: true,\n },\n ...StateBean.registration,\n ...StateProp.registration,\n ...KosTime.registration,\n };\n return { ...kosModels };\n};\n\nexport const CoreModels = getKosModel();\nexport const Registry: IKosRegistry = {\n models: CoreModels,\n preloadModels: [],\n};\n","import {\n RegistrationManager,\n registerKosModel,\n registerLegacyModel,\n type RegistrationResult,\n} from \"../../core\";\nimport { LogStreamContainer } from \"../models\";\nimport { BrowserRouter } from \"../models/browser-router\";\nimport { ConfigBean } from \"../models/config-bean/config-bean-model\";\nimport { Device } from \"../models/device\";\nimport { KeyValue } from \"../models/key-value\";\nimport { NetworkInterfaceContainer } from \"../models/network-interface\";\nimport { Ota } from \"../models/ota/ota-registration\";\nimport { SoftwareInfo } from \"../models/software-info/software-info-registration\";\nimport { StorageDeviceContainer } from \"../models/storage-device\";\nimport { TroubleContainer } from \"../models/trouble-container/trouble-container-registration\";\nimport { Trouble } from \"../models/trouble/trouble-registration\";\nimport { UsbUpdateContainer } from \"../models/usb-update\";\nimport { CoreModels } from \"../registration\";\n\nconst PRELOAD = true;\nexport const registerCoreModels =\n <R>(root: R) =>\n () => {\n const coreModels = CoreModels;\n registerKosModel(KosModelRegistry)(Trouble)\n .model(TroubleContainer)\n .model(StorageDeviceContainer)\n .model(UsbUpdateContainer)\n .model(Device)\n .model(Ota)\n .model(ConfigBean)\n .model(SoftwareInfo)\n .model(KeyValue)\n .model(NetworkInterfaceContainer)\n .model(BrowserRouter, PRELOAD)\n .model(LogStreamContainer);\n\n Object.keys(coreModels).forEach((key) => {\n const model = coreModels[key];\n registerLegacyModel(KosModelRegistry)(key, model);\n });\n\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n };\n };\n\ntype ModelRegistry<R> = {\n core: { models: () => RegistrationResult<R> };\n preload: ReturnType<typeof RegistrationManager.model.preloadModel>;\n model: ReturnType<typeof RegistrationManager.model.register>;\n companion: ReturnType<typeof RegistrationManager.companion.register>;\n};\n\nconst _KosModelRegistry = {};\n\n(_KosModelRegistry as any).core = {\n models: registerCoreModels(_KosModelRegistry),\n};\n(_KosModelRegistry as any).preload =\n RegistrationManager.model.preloadModel(_KosModelRegistry);\n(_KosModelRegistry as any).model =\n RegistrationManager.model.register(_KosModelRegistry);\n(_KosModelRegistry as any).companion =\n RegistrationManager.companion.register(_KosModelRegistry);\n(_KosModelRegistry as any).legacy =\n RegistrationManager.model.registerLegacyModel(_KosModelRegistry);\n\ntype KosModelRegistryType = ModelRegistry<typeof _KosModelRegistry>;\n\nconst KosModelRegistry: KosModelRegistryType = _KosModelRegistry as any;\n\nexport { KosModelRegistry };\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { ExtensionManager, PropertyMapper } from \"../../core\";\nimport { KosCoreModelPropertyMapper } from \"../constants\";\nimport type { TroubleModel } from \"../models/trouble/types\";\n\ntype TroubleRankMapper<AdditionalData extends object = Record<string, any>> =\n PropertyMapper<TroubleModel<AdditionalData>, number, any>;\n\ntype TroubleColorMapper<AdditionalData extends object = Record<string, any>> =\n PropertyMapper<TroubleModel<AdditionalData>, string, any>;\n\ntype TroubleRoleMapper<AdditionalData extends object = Record<string, any>> =\n PropertyMapper<TroubleModel<AdditionalData>, string, any>;\n\nexport class CoreExtensionManager {\n /**\n * Maps the rank property of the trouble into the {@link TroubleModel}\n * */\n registerTroubleRankMapper(troubleRankMapper: TroubleRankMapper) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRank,\n troubleRankMapper\n );\n return this;\n }\n\n /**\n * Maps the role property of the trouble into the {@link TroubleModel}\n * */\n registerTroubleRoleMapper(troubleRoleMapper: TroubleRoleMapper) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRole,\n troubleRoleMapper\n );\n return this;\n }\n\n /**\n * Maps the color property of the trouble into the {@link TroubleModel}\n * */\n registerTroubleColorMapper(troubleColorMapper: TroubleRoleMapper) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleColor,\n troubleColorMapper\n );\n return this;\n }\n}\n","import { destroyKosModel, whenReady } from \"../../core\";\nimport { KeyValue } from \"../models/key-value\";\n\n/**\n * A persistence store that can be used to store data for a given session id and key\n * The store is namespaced by the stateKey and the sessionId allows for multiple instances\n * of data to be created with the same store using the session id as the discriminator.\n * The store is backed by a {@link KeyValue} model.\n * @public\n * @interface\n */\nexport interface PersistenceStoreAware {\n /** The key value data store */\n store: KosPersistenceStore;\n\n /** The sessionId to be used when multiple instances of a persistence store are required for a given namespace */\n sessionId: string;\n\n /** The stateKey used to namespace the store */\n stateKey: string;\n}\nexport interface KosPersistenceStore {\n /**\n * Update the state of the store for a given key. The session id of the store instance\n * will be used to segregate the data. For example, if the session id is \"my-session\" and the\n * key is \"my-key\", the data will be stored as \"my-session-my-key\". However the session id is not\n * externally visible and is managed by the store.\n *\n * @param key - the key to update\n * @param value - the value to update\n *\n */\n updateState(\n key: string,\n value: string | number | boolean | undefined\n ): Promise<void>;\n\n /**\n * Clean all the data from the store for the given session id\n */\n clean(): void;\n\n /**\n * Retrieve the state of the store for a given key. The session id of the store instance\n * will be used to retrieve the data.\n * @param key - the key to retrieve\n * @returns the value of the key or undefined if the key does not exist\n */\n getState(key: string): string | number | boolean | undefined;\n\n /**\n * Unsubscribe from the store. This will remove the store from the persistence layer\n */\n unsubscribe(): void;\n}\n\n/**\n * Subscribe to a kOS Persistence Store or create a new one\n * The store will be namespaced by the stateKey and the sessionId allows\n * for multiple instances of data to be created with the same store using eh session id\n * as the discriminator.\n *\n * If the sessionId is not provided, the store will be global\n *\n * @param stateKey - the namespace of the given persistence store\n * @param sessionId - the data partition with the namespace that the store will operate within\n * @returns a {@link KosPersistenceStore} instance\n */\nexport const subscribeStore = async (\n stateKey: string,\n sessionId?: string\n): Promise<KosPersistenceStore> => {\n const toolState = KeyValue.instance(stateKey).options({}).build();\n const prefix = sessionId ? `${sessionId}-` : \"\";\n await whenReady(toolState);\n return {\n getState: (key: string) => toolState.data[`${prefix}${key}`],\n updateState: async (\n key: string,\n value: string | number | boolean | undefined\n ) => {\n await toolState.updateState(`${prefix}${key}`, value);\n },\n clean: async () => {\n for (const key of toolState.data.keys) {\n await toolState.updateState(`${prefix}${key}`, undefined);\n }\n },\n unsubscribe: () => {\n destroyKosModel(toolState);\n },\n };\n};\n","import { whenReady } from \"../../core\";\nimport { KosConfigPropertySpec } from \"../models/config-bean-prop\";\n\nconst REGION_PATH = \"kos:service:region\";\nconst REGION_ATTRIBUTE = \"regionId\";\nconst REGION_ID = `${REGION_PATH}-${REGION_ATTRIBUTE}`;\n\nexport const updateRegion = async (region: string) => {\n const regionInfo = KosConfigPropertySpec.factory(REGION_ID)({\n path: REGION_PATH,\n attribute: REGION_ATTRIBUTE,\n });\n await whenReady(regionInfo);\n\n regionInfo.updateProperty(region);\n};\n","/// <reference types=\"@types/node/timers\"/>\n/**\n * @module TimerManager\n * @description\n * The TimerManager module provides functionality for managing timers and executing actions at specific intervals.\n * It includes a `KosTimer` class for individual timers and a set of utility functions to interact with timers.\n *\n * @example\n * // Create a timer with a 60-second timeout and default actions\n * const timer = TimerManager.createTimer(\"myTimer\", 60, [{ name: \"customAction\" }]);\n *\n * // Start the timer\n * TimerManager.startTimer(\"myTimer\");\n *\n * // Add a timeout action to the timer\n * TimerManager.addTimeoutAction(\"myTimer\", { name: \"newAction\", remainingTime: 30 });\n *\n * // Reset the timer\n * TimerManager.resetTimer(\"myTimer\");\n */\n\nimport { EventBus } from \"../../common\";\nimport { KosLog, kosAutoEffect } from \"../../core\";\nimport type { KosConfigProperty } from \"../models\";\n\n/**\n * Event name for timer-related events.\n */\nexport const TIMER_EVENT = `/kos-timer-event`;\n\n/**\n * Default action name for timer end event.\n */\nexport const TIMER_END = \"defaultTimerEnd\";\n\n/**\n * Represents a timer event.\n */\nexport interface TimerEvent {\n name: string;\n action: string;\n remainingTime: number;\n}\n\n/**\n * Represents a function that can be executed as a timer action.\n */\ntype TimerActionFn = (name: string, timeRemaining: number) => void;\n\n/**\n * Represents a timer action configuration.\n */\nexport interface TimerAction {\n name: string;\n action?: TimerActionFn;\n remainingTime?: number;\n singleUse?: boolean;\n}\n\nconst log = KosLog.createLogger({ name: \"timer-manager\" });\n\nconst isConfigProperty = (\n value: number | KosConfigProperty<number>\n): value is KosConfigProperty<number> =>\n (value as KosConfigProperty<number>).updateProperty !== undefined;\n/**\n * Manages the behavior of a timer.\n */\nexport class KosTimer {\n private name: string;\n private timeout: number;\n private timer?: NodeJS.Timeout;\n private state: \"inactive\" | \"active\" | \"paused\" | \"complete\" = \"inactive\";\n private decrementValue = 1;\n private remainingTime: number;\n private timeoutActions: Map<number, TimerAction[]> = new Map();\n\n /**\n * Creates a new timer.\n * @param name - The name of the timer.\n * @param timeout - The duration (in seconds) of the timer.\n * @param defaultActions - Optional default timer actions.\n */\n constructor(\n name: string,\n timeout: number | KosConfigProperty<number>,\n defaultActions?: TimerAction[]\n ) {\n this.name = name;\n\n const timeoutValue =\n typeof timeout === \"number\" ? timeout : timeout.value || 60;\n this.timeout = timeoutValue;\n this.state = \"inactive\";\n\n this.remainingTime = timeoutValue;\n\n if (isConfigProperty(timeout)) {\n kosAutoEffect(() => {\n KosLog.info(\n `Updating config value timer ${name} with new timeout value ${timeout.value}`\n );\n const newValue = timeout.value || 60;\n this.updateTimeout(newValue);\n });\n }\n // Add a default timeout action for timer end event.\n this.addTimeoutAction({\n name: TIMER_END,\n });\n\n if (defaultActions) {\n // Add any provided default actions.\n defaultActions.forEach((action) => {\n this.addTimeoutAction(action);\n });\n }\n }\n\n /**\n * Starts the timer.\n */\n public start() {\n if (this.state === \"active\") {\n log.debug(`Timer ${this.name} already started`);\n return;\n }\n\n if (this.state === \"inactive\" || this.state === \"paused\") {\n this.state = \"active\";\n this.timer = setInterval(() => this.updateTimer(), 1000);\n }\n }\n\n /**\n * Pauses the timer.\n */\n public pause() {\n if (this.timer) {\n log.debug(`Pausing timer ${this.name}`);\n this.state = \"paused\";\n clearInterval(this.timer);\n }\n }\n\n /**\n * Restarts the timer. The timer will continue to run from its initial state.\n */\n public restart() {\n this.pause();\n this.remainingTime = this.timeout;\n this.start();\n }\n /**\n * Resets the timer to its initial state. The timer will be stopped and reset to its initial state.\n * The timer will need to be started again to continue running.\n */\n public reset() {\n this.pause();\n this.remainingTime = this.timeout;\n this.state = \"inactive\";\n }\n\n public updateTimeout(timeout: number) {\n this.timeout = timeout;\n this.restart();\n }\n\n /**\n * Adds a timeout action to the timer.\n * @param timerAction - The timer action configuration to add.\n */\n public addTimeoutAction(timerAction: TimerAction) {\n const time = timerAction.remainingTime ?? 0;\n\n if (!this.timeoutActions.has(time)) {\n this.timeoutActions.set(time, []);\n }\n const name = timerAction.name;\n const existingAction = this.timeoutActions\n .get(time)!\n .find((action) => action.name === name);\n if (existingAction) {\n existingAction.action = timerAction.action;\n } else {\n this.timeoutActions.get(time)!.push(timerAction);\n }\n }\n\n /**\n * Removes a timeout action from the timer by action name.\n * @param actionName - The name of the action to remove.\n */\n public removeTimeoutAction(actionName: string) {\n for (const [time, actions] of this.timeoutActions.entries()) {\n const updatedActions = actions.filter(\n (action) => action.name !== actionName\n );\n\n if (updatedActions.length === 0) {\n this.timeoutActions.delete(time);\n } else {\n this.timeoutActions.set(time, updatedActions);\n }\n }\n }\n\n /**\n * Updates the timer's remaining time and executes timeout actions.\n */\n private updateTimer() {\n this.remainingTime =\n Math.round((this.remainingTime - this.decrementValue) * 100) / 100;\n\n if (this.remainingTime <= 0) {\n if (this.state === \"active\") {\n this.executeActions(0);\n }\n\n this.pause();\n return;\n }\n\n if (this.state === \"active\") {\n this.executeActions(this.remainingTime);\n }\n }\n\n /**\n * Executes timeout actions at the specified time.\n * @param time - The remaining time at which to execute actions.\n */\n private executeActions(time: number) {\n if (this.timeoutActions.has(time)) {\n this.timeoutActions.get(time)!.forEach((timerAction) => {\n log.debug(`Executing timer action ${timerAction.name} at ${time}`);\n timerAction.action?.(timerAction.name, time);\n this.notifyTimeoutAction(timerAction);\n if (timerAction.singleUse) {\n log.info(\n `${this.name} Removing single-use action ${timerAction.name}`\n );\n this.removeTimeoutAction(timerAction.name);\n }\n });\n }\n }\n\n /**\n * Notifies a timeout action through the EventBus.\n * @param action - The timeout action to notify.\n */\n private notifyTimeoutAction(action: TimerAction) {\n EventBus.publish(TIMER_EVENT, {\n name: this.name,\n action: action.name,\n remainingTime: this.remainingTime,\n });\n }\n}\n\n// A map to store timer instances.\nconst timers = new Map<string, KosTimer>();\n\n/**\n * Executes a function on a timer with the specified name.\n * @param name - The name of the timer to operate on.\n * @param action - The function to execute on the timer.\n */\nconst executeOnTimer = (name: string, action: (timer: KosTimer) => void) => {\n const timer = timers.get(name);\n if (!timer) {\n log.error(`Timer ${name} not found`);\n return;\n }\n action(timer);\n};\n\n/**\n * The TimerManager provides utility functions to manage timers.\n */\nexport const TimerManager = {\n /**\n * Creates a new timer with a timeout relative to the current date.\n * @param name - The name of the timer\n * @param date - The date to set the timer to\n * @param defaultActions - Optional default timer actions.\n * @returns the time instance\n */\n createRelativeTimer(\n name: string,\n date: Date,\n defaultActions?: TimerAction[]\n ) {\n const now = new Date();\n const timeout = Math.round((date.getTime() - now.getTime()) / 1000);\n return this.createTimer(name, timeout, defaultActions);\n },\n /**\n * Creates a new timer or retrieves an existing one by name.\n * @param name - The name of the timer.\n * @param timeout - The duration (in seconds) of the timer (default: 60 seconds).\n * @param defaultActions - Optional default timer actions.\n * @returns The timer instance.\n */\n createTimer(name: string, timeout = 60, defaultActions?: TimerAction[]) {\n if (timers.has(name)) {\n return timers.get(name);\n }\n const timer = new KosTimer(name, timeout, defaultActions);\n timers.set(name, timer);\n return timer;\n },\n\n /**\n * Gets an existing timer by name.\n * @param name - The name of the timer.\n * @returns The timer instance or `undefined` if not found.\n */\n getTimer(name: string) {\n return timers.get(name);\n },\n\n /**\n * Clears (pauses) an existing timer by name.\n * @param name - The name of the timer.\n */\n clearTimer(name: string) {\n executeOnTimer(name, (timer) => timer.pause());\n },\n\n /**\n * Restarts an existing timer to its initial state by name. The timer will continue to run from its initial state.\n * @param name - The name of the timer.\n */\n restartTimer(name: string) {\n executeOnTimer(name, (timer) => timer.restart());\n },\n\n /**\n * Resets an existing timer to its initial state by name.\n * @param name - The name of the timer.\n */\n resetTimer(name: string) {\n executeOnTimer(name, (timer) => timer.reset());\n },\n\n /**\n * Adds a timeout action to an existing timer by name.\n * @param name - The name of the timer.\n * @param action - The timer action configuration to add.\n */\n addTimeoutAction(name: string, action: TimerAction) {\n executeOnTimer(name, (timer) => timer.addTimeoutAction(action));\n },\n\n /**\n * Removes a timeout action from an existing timer by name and action name.\n * @param name - The name of the timer.\n * @param actionName - The name of the action to remove.\n */\n removeTimeoutAction(name: string, actionName: string) {\n executeOnTimer(name, (timer) => timer.removeTimeoutAction(actionName));\n },\n\n /**\n * Starts an existing timer by name.\n * @param name - The name of the timer.\n */\n startTimer(name: string) {\n executeOnTimer(name, (timer) => timer.start());\n },\n};\n","import { whenReady } from \"../../core\";\nimport { KosConfigPropertySpec } from \"../models/config-bean-prop\";\n\nconst REGION_SETTINGS_PATH = \"kos:service:region:settings\";\nconst TIMEZONE_ATTRIBUTE = \"timeZone\";\nconst REGION_TIMEZONE_ID = `${REGION_SETTINGS_PATH}-${TIMEZONE_ATTRIBUTE}`;\n\nexport const updateTimeZone = async (timezone: string) => {\n const timezoneInfo = KosConfigPropertySpec.factory(REGION_TIMEZONE_ID)({\n path: REGION_SETTINGS_PATH,\n attribute: TIMEZONE_ATTRIBUTE,\n });\n await whenReady(timezoneInfo);\n\n timezoneInfo.updateProperty(timezone);\n};\n","import {\n FutureService,\n kosAction,\n KosLog,\n uuid,\n whenReady,\n type KosServiceResponse,\n} from \"../../core\";\nimport { FUTURE_NOT_ASSIGNED } from \"../constants\";\nimport { mapDtoToFutureModel } from \"../models/future\";\nimport { FutureContainer } from \"../models/future/future-types\";\nimport { FutureResponse } from \"../services\";\nimport { FutureManager } from \"../utils\";\ninterface FutureProps {\n alias?: string;\n namespace?: string;\n}\n\nconst isFutureResponse = (response: any): response is FutureResponse =>\n !response || !response.data;\ntype FutureHandler = (\n this: FutureContainer,\n ...args: Array<unknown>\n) => Promise<KosServiceResponse<FutureResponse> | undefined>;\nexport function kosFuture(props: FutureProps = {}) {\n const { alias, namespace } = props;\n return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n target[FutureService] = target[FutureService] || {};\n\n const original: FutureHandler = descriptor.value;\n\n const handler = async function (\n this: FutureContainer,\n ...args: Array<unknown>\n ): Promise<FutureResponse | undefined> {\n // create a tracker id to track the future\n const tracker = uuid();\n KosLog.debug(\n `Calling future service ${propertyKey} with tracker ${tracker}`\n );\n // initialize a new future placeholder using the tracker id\n const future = FutureManager.initiateFuture({\n tracker,\n id: FUTURE_NOT_ASSIGNED,\n });\n if (namespace) {\n future.namespace = namespace;\n }\n KosLog.debug(`waiting for future ${future.id} to be ready`);\n await whenReady(future);\n KosLog.debug(`future ${future.id} is ready`);\n kosAction(() => {\n // eslint-disable-next-line no-invalid-this\n KosLog.debug(`Adding future ${future.id} to futureHandler`);\n this.futureHandler.addFuture(future, alias);\n });\n\n try {\n const futureResponse:\n | KosServiceResponse<FutureResponse>\n | FutureResponse\n | undefined =\n // eslint-disable-next-line no-invalid-this\n await original.apply(this, [...args, tracker]);\n\n KosLog.debug(`received future response for ${tracker}`, futureResponse);\n const response = isFutureResponse(futureResponse)\n ? futureResponse\n : futureResponse?.data;\n\n if (response) {\n // hack to get the progress to show up immediately. This is a bug in the future model\n\n response.progress = 1;\n\n KosLog.debug(`mapping future response to future model`);\n // map the api response, which is a future response, to the future model\n // only map the response if the model has not already been completed.\n if (!future.endState) {\n mapDtoToFutureModel(response, future);\n } else {\n KosLog.debug(\n `future ${future.id} has already completed. Not updating the model`\n );\n }\n } else {\n this.futureHandler.removeFuture(alias);\n }\n return response;\n } catch (e) {\n KosLog.error(e);\n throw e;\n }\n };\n\n target[FutureService][propertyKey] = {\n handler,\n };\n };\n}\n","import { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { StateBean } from \"../models/state-bean\";\n\ninterface KosStateParams {\n path: string;\n}\n\nexport const kosStateBean =\n ({ path }: KosStateParams) =>\n (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: StateBean.type,\n id: `${StateBean.type}-${path}`,\n options: {\n path,\n },\n lifecycle: DependencyLifecycle.INIT,\n };\n };\n","import { DependencyLifecycle, DependencyModels } from \"../../core\";\n\nimport { StateProp } from \"../models/state-prop\";\nimport { StatePropertyTypes } from \"../models/types\";\n\ntype StateKeys<T extends Record<string, StatePropertyTypes>> = keyof T;\n\ninterface KosStateParams<T extends Record<string, StatePropertyTypes> = any> {\n path: string;\n attribute: `${string & StateKeys<T>}`;\n}\n\nexport function kosStateProp<\n T extends Record<string, StatePropertyTypes> = any\n>(params: KosStateParams<T>) {\n const { path, attribute } = params;\n\n return (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: StateProp.type,\n id: `${path}-${attribute}`,\n options: {\n path,\n attribute,\n },\n\n lifecycle: DependencyLifecycle.INIT,\n };\n };\n}\n","import { BASE_URL, kosFetch, KosLog, KosServiceResponse } from \"../../../core\";\n\nconst log = KosLog.createLogger({ name: \"services\", group: \"Services\" });\n\ninterface LoginResponse {\n token: string;\n}\n\n/**\n * Convienience function to provide Studio specific login functions defaulting the url\n * Studio endpoint.\n * @param username - the username of the user to log in\n * @param password - the password of the user to log in\n * @returns a login response with the token of the logged in user\n *\n * @internal\n * @see login\n */\nexport const studioLogin = async (username: string, password: string) =>\n login(username, password, `${BASE_URL}/api/server/login`);\n\n/**\n * Attempts a log in against the specified URL.\n * @param username - the username of the user to log in\n * @param password - the password of the user to log in\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n *\n * @returns a login response with the token of the logged in user\n */\nexport const login = async (\n username: string,\n password: string,\n url = `${BASE_URL}/api/login`\n) => {\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n email: username,\n password,\n }),\n });\n if (!response.ok) {\n const configResponse = await response.json();\n\n throw Error(`${configResponse?.error}`);\n }\n const configResponse: KosServiceResponse<LoginResponse> | null =\n await response.json();\n return configResponse;\n};\n\n/**\n * Convienience function to provide Studio specific password reset functions defaulting the url\n * Studio endpoint.\n * @param username - the userID of the user to start the password reset process.\n * @returns an API response with no value.\n *\n * @see startPasswordReset\n * @internal\n */\nexport const studioStartPasswordReset = async (userId: string) =>\n startPasswordReset(userId, `${BASE_URL}/api/server/startPasswordReset`, \"\");\n\n/**\n * When a user is first created or if the password is forgotten. A user can request\n * a password reset from thier Organization administrator. The administrator will end\n * up calling this function in order to initiate the request and have reset token sent\n * to the user on thier specified e-mail address (or other method.)\n * The token, received by the user, can be used as part of the reset call to provide a new password.\n *\n * @param userId - the user ID of the suer to start the password reset process.\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n * @returns an API response with no value.\n * @internal\n * @see resetPassword\n */\nexport const startPasswordReset = async (\n userId: string,\n url = `${BASE_URL}/api/startPasswordReset`,\n destinationAddress = \"server\"\n) => {\n const response = await kosFetch(`${url}?email=${userId}`, {\n method: `POST`,\n destinationAddress,\n });\n if (!response.ok) {\n throw Error(\n `There was a problem reseting config; returned status ${response.status}`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n\n/**\n * Convienience function to provide Studio specific password reset functions defaulting the url\n * Studio endpoint.\n * @param token - the reset token recieved as part of the `startPasswordReset` process\n * @param password - the new password to be used by the user specified in the token.\n * @returns an API response with no value.\n * @internal\n * @see startPasswordReset\n */\nexport const studioResetPassword = async (token: string, password: string) =>\n resetPassword(token, password, `${BASE_URL}/api/server/resetPassword`);\n\n/**\n * Resets the password for the user.\n *\n * @param token - the reset token recieved as part of the `startPasswordReset` process\n * @param password - the new password to be used by the user specified in the token.\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n * @returns an API response with no value.\n *\n * @internal\n * @see resetPassword\n */\nexport const resetPassword = async (\n token: string,\n password: string,\n url = `${BASE_URL}/api/resetPassword`\n) => {\n log.debug(\n `resetting password with token ${token} and password ${password.replace(\n /./g,\n \"*\"\n )}`\n );\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n token,\n password,\n }),\n });\n log.debug(`password reset returned status ${response.status}`);\n if (!response.ok) {\n log.error(`password reset failed with message ${response.statusText}`);\n\n const configResponse = await response.json();\n\n throw Error(\n `${configResponse?.error}:There was a problem resetting the password.`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n\nexport const studioAcceptOrgInvitation = async (\n token: string,\n password: string,\n name: string\n) =>\n acceptOrgInvitation(\n token,\n password,\n name,\n `${BASE_URL}/api/server/acceptInvite`\n );\nexport const acceptOrgInvitation = async (\n token: string,\n password: string,\n name: string,\n url = `${BASE_URL}/api/server/acceptInvite`\n) => {\n log.debug(\n `accepting invite with token ${token} and password ${password.replace(\n /./g,\n \"*\"\n )}`\n );\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n token,\n password,\n name,\n }),\n });\n log.debug(`invitation accept returned status ${response.status}`);\n if (!response.ok) {\n log.error(`invite failed with message ${response.statusText}`);\n\n const configResponse = await response.json();\n\n throw Error(\n `${configResponse?.error}:There was a problem accepting the invite.`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n","import { css, keyframes } from \"@emotion/react\";\n\nexport const run = keyframes`\n 0% {\n left: -90px;\n color: #eee;\n }\n 50% {\n color: #666;\n }\n 100% {\n left: 90px;\n color: #eee;\n }\n`;\n\nexport const loadingDot = css`\n font-size: 100px;\n margin-top: -80px;\n position: relative;\n animation: ${run} ease-in-out infinite alternate;\n animation-duration: 1.2s;\n`;\n","import styled from \"@emotion/styled\";\nimport { loadingDot } from \"./loading-message-styles\";\nimport { createPortal } from \"react-dom\";\n\ninterface PortalProps {\n children: React.ReactNode;\n}\n\nexport const Portal = ({ children }: PortalProps) =>\n createPortal(children, document.body);\ninterface Props {\n message?: string;\n}\nfunction LoadingMessage({\n message = \"Wait a moment while we load your app.\",\n}: Props) {\n return (\n <Portal>\n <MessageContainer>\n {message}\n <div css={loadingDot}>.</div>\n </MessageContainer>\n </Portal>\n );\n}\n\nexport default LoadingMessage;\n\nconst MessageContainer = styled.div`\n padding-inline: 20px;\n width: 100%;\n height: 100vh;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n position: fixed;\n font-size: 14px;\n top: 0;\n left: 0;\n z-index: 10000;\n`;\n","import React, { ErrorInfo } from \"react\";\n\nexport interface ErrorBoundaryState {\n error: Error | null;\n errorInfo: ErrorInfo | null;\n}\n\nexport interface ErrorBoundaryProps extends React.PropsWithChildren {\n fallback?: React.ReactNode;\n}\nclass ErrorBoundary extends React.Component<\n ErrorBoundaryProps,\n ErrorBoundaryState\n> {\n constructor(props: ErrorBoundaryProps) {\n super(props);\n this.state = { error: null, errorInfo: null };\n }\n\n override componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n // Catch errors in any components below and re-render with error message\n this.setState({\n error: error,\n errorInfo: errorInfo,\n });\n // You can also log error messages to an error reporting service here\n }\n\n override render() {\n if (this.state.errorInfo) {\n // Error path\n return (\n this.props.fallback || (\n <div>\n <h2>Something went wrong.</h2>\n <details style={{ whiteSpace: `pre-wrap` }}>\n {this.state.error && this.state.error.toString()}\n <br />\n {this.state.errorInfo.componentStack}\n </details>\n </div>\n )\n );\n }\n // Normally, just render children\n return this.props.children;\n }\n}\n\nexport default ErrorBoundary;\n","import { css } from \"@emotion/react\";\ntype Status = \"error\" | \"warn\" | \"normal\";\ninterface Props {\n value: number;\n title?: JSX.Element;\n subtitle?: string;\n status?: Status;\n}\n\nconst statusMap: Record<Status, string> = {\n normal: \"#B5F7F6\",\n warn: \"#F3D78A\",\n error: \"#FC8486\",\n};\nexport const ProgressBar = ({\n value = 0,\n title,\n status = \"normal\",\n subtitle,\n}: Props) => {\n const progressBarContainer = css`\n display: flex;\n flex-direction: column;\n `;\n const progressContainer = css`\n position: relative;\n height: 18px;\n width: 100%;\n background-color: #ddd;\n border-radius: 5px;\n overflow: hidden;\n `;\n\n const titleContainer = css`\n position: absolute;\n top: 50%; /* position the top edge of the element at the middle of the parent */\n left: 50%; /* position the left edge of the element at the middle of the parent */\n z-index: 5;\n transform: translate(-50%, -50%);\n font-size: smaller;\n `;\n\n const progress = css`\n width: ${value}%;\n height: 35px;\n background-color: ${statusMap[status]};\n text-align: center;\n line-height: 32px;\n color: black;\n `;\n\n const indeterminate = css`\n animation: indeterminateAnimation 1s infinite linear;\n transform-origin: 0% 50%;\n @keyframes indeterminateAnimation {\n 0% {\n transform: translateX(0) scaleX(0);\n }\n 40% {\n transform: translateX(0) scaleX(0.4);\n }\n 100% {\n transform: translateX(100%) scaleX(0.5);\n }\n }\n `;\n\n return (\n <div css={progressBarContainer}>\n <div css={progressContainer}>\n <div css={titleContainer}>{title}</div>\n <div css={[progress, value < 0 ? indeterminate : \"\"]}></div>\n </div>\n <div>{subtitle}</div>\n </div>\n );\n};\n","import {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useState,\n} from \"react\";\nimport { IKosDataModel } from \"../../../../core\";\n\ninterface KosModelContextProps {\n model?: IKosDataModel;\n setModel: (model: IKosDataModel) => boolean;\n}\n\nconst defaultProps: KosModelContextProps = {\n setModel: () => false,\n};\n\nexport const KosModelContext =\n createContext<KosModelContextProps>(defaultProps);\n\nexport const useContextModel = <T extends IKosDataModel>(): T | undefined => {\n const context = useContext(KosModelContext);\n if (context == undefined) {\n throw new Error(`useModels must be used within a KosModelProvider`);\n }\n return context.model as T;\n};\n\nexport const KosModelProvider: React.FunctionComponent<PropsWithChildren> = ({\n children,\n}) => {\n const [model, setModel] = useState<IKosDataModel>();\n const setKosModel = useCallback(\n (kosModel: IKosDataModel) => {\n setModel(kosModel);\n return true;\n },\n [setModel]\n );\n return (\n <KosModelContext.Provider value={{ model, setModel: setKosModel }}>\n {children}\n </KosModelContext.Provider>\n );\n};\n","import {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useMemo,\n useState,\n} from \"react\";\nimport { getKosModelSync, IKosDataModel, KosLog } from \"../../../../core\";\n\ninterface KosNestedModelContextProps {\n models: IKosDataModel[];\n addModel: (model: IKosDataModel) => void;\n}\n\nconst log = KosLog.createLogger({ name: \"kos-model-hierarchy-context\" });\nconst defaultNestedProps: KosNestedModelContextProps = {\n models: [],\n addModel: () => {\n log.debug(\"Default implementation being used. Do Nothing.\");\n },\n};\n\nexport const NestedModelContext =\n createContext<KosNestedModelContextProps>(defaultNestedProps);\n\nexport const KosModelCollectionProvider: React.FunctionComponent<\n PropsWithChildren\n> = ({ children }) => {\n const [models, setModels] = useState<IKosDataModel[]>([]);\n const addModel = useCallback(\n (model: IKosDataModel) => {\n if (!models.includes(model)) {\n log.debug(\"adding to hierarchy context\", model.id);\n setModels((prevModels) => [...prevModels, model]);\n }\n },\n [models]\n );\n return (\n <NestedModelContext.Provider value={{ models, addModel }}>\n {children}\n </NestedModelContext.Provider>\n );\n};\n\ninterface ModelHierarchyProps {\n filter?: (model: IKosDataModel) => boolean;\n}\n\nconst DEFAULT_FILTER = () => true;\nexport const useContextModelHierarchy = (\n props?: ModelHierarchyProps\n): IKosDataModel[] => {\n const context = useContext(NestedModelContext);\n if (!context) {\n throw new Error(\n `useContextModelHierarchy must be used within a KosModelCollectionProvider`\n );\n }\n\n const filter = props?.filter || DEFAULT_FILTER;\n const filteredModels = useMemo(\n () => context.models.filter(filter),\n [context.models, filter]\n );\n return filteredModels;\n};\n\nexport const useModelFromHierarchy = <T extends IKosDataModel = IKosDataModel>(\n type: string\n): T | undefined => {\n const context = useContextModelHierarchy({\n filter: (model) => {\n const _model = getKosModelSync(model.id);\n return _model?.type === type;\n },\n });\n return context[0] as T;\n};\n","import {\n PropsWithChildren,\n Suspense,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport { IKosDataModel, KosLog } from \"../../../core\";\nimport { ErrorBoundaryWithFallback } from \"../error-boundary\";\nimport { ErrorBoundaryProps } from \"../error-boundary/error-boundary\";\nimport {\n KosModelContext,\n KosModelProvider,\n} from \"./contexts/kos-model-context\";\nimport { NestedModelContext } from \"./contexts/kos-model-hierarchy-context\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-loader\" });\nexport interface KosModelLoaderProps {\n model?: IKosDataModel;\n ready: boolean;\n error?: string;\n loading?: React.ReactElement;\n}\n\nconst DefaultLoader = () => <div></div>;\n\nexport const KosModelLoader: React.FunctionComponent<\n PropsWithChildren<ErrorBoundaryProps & KosModelLoaderProps>\n> = ({ fallback, children, ...modelProps }) => (\n <KosModelProvider>\n <ErrorBoundaryWithFallback fallback={fallback}>\n <Suspense>\n <KosModelLoaderDisplay {...modelProps}>\n {children}\n </KosModelLoaderDisplay>\n </Suspense>\n </ErrorBoundaryWithFallback>\n </KosModelProvider>\n);\nexport const KosModelLoaderDisplay: React.FunctionComponent<\n PropsWithChildren<KosModelLoaderProps>\n> = (props) => {\n const [model, setCurrentModel] = useState<IKosDataModel>();\n const [isReady, setIsReady] = useState(false);\n const { setModel } = useContext(KosModelContext);\n const hierarchyContext = useContext(NestedModelContext);\n useEffect(() => {\n if (props.model) {\n setCurrentModel(props.model);\n setModel(props.model);\n setIsReady(true);\n if (hierarchyContext) {\n hierarchyContext.addModel(props.model);\n }\n }\n }, [hierarchyContext, props.model, setModel]);\n\n if (props.error) {\n log.error(props.error);\n throw new Error(props.error);\n }\n\n const loader = props.loading || <DefaultLoader></DefaultLoader>;\n return <>{model && isReady ? props.children : loader}</>;\n};\n","import React from \"react\";\n\ninterface HeaderTranslations {\n title: string;\n createLabel: string;\n deleteLabel: string;\n}\ninterface ModalTranslations {\n okText: string;\n cancelText: string;\n title: string;\n}\nexport interface Translations {\n header?: Partial<HeaderTranslations>;\n createModal?: Partial<ModalTranslations>;\n}\nconst DEFAULT_TRANSLATIONS: ContextTranslations = {\n header: {\n title: \"Model\",\n createLabel: \"Create new Model\",\n deleteLabel: \"Delete\",\n },\n createModal: {\n okText: \"OK\",\n cancelText: \"Cancel\",\n title: \"Create New Model\",\n },\n};\n\ninterface ContextTranslations {\n header: HeaderTranslations;\n createModal: ModalTranslations;\n}\ninterface Props {\n translations?: Translations;\n children: React.ReactNode;\n}\nconst CreateModelTranslationsContext =\n React.createContext<ContextTranslations>(DEFAULT_TRANSLATIONS);\n\nconst CreateModelTranslationsProvider: React.FC<Props> = ({\n translations = DEFAULT_TRANSLATIONS,\n children,\n}) => {\n const merged: ContextTranslations = {\n header: { ...DEFAULT_TRANSLATIONS.header, ...translations.header },\n createModal: {\n ...DEFAULT_TRANSLATIONS.createModal,\n ...translations.createModal,\n },\n };\n return (\n <CreateModelTranslationsContext.Provider value={merged}>\n {children}\n </CreateModelTranslationsContext.Provider>\n );\n};\n\nexport { CreateModelTranslationsContext, CreateModelTranslationsProvider };\n","import type { IKosCoreManager, IKosRegistry } from \"../../core\";\nimport { KosCore, wrapPromise } from \"../../core\";\n\nexport function fetchKosCore(registration: IKosRegistry, alias?: string) {\n const kosCore = KosCore.create(registration, false, alias);\n const promise = kosCore.whenReady().then(() => kosCore);\n return wrapPromise<IKosCoreManager>(promise);\n}\n","import { observer } from \"mobx-react-lite\";\nimport React, { useEffect } from \"react\";\nimport { IKosCoreManager, IKosRegistry, kosAutoEffect } from \"../../core\";\nimport { fetchKosCore } from \"./fetch-kos-core\";\n\nexport interface ProviderProps {\n children?: React.ReactNode;\n}\n\ninterface IKosContext {\n kosCore: IKosCoreManager;\n online: boolean;\n}\nconst KosContext = React.createContext<IKosContext | undefined>(undefined);\nconst initKosProvider = (\n registration: IKosRegistry = { models: {}, preloadModels: [] },\n alias?: string\n) => {\n const resource = fetchKosCore(registration, alias);\n\n const KosCoreContextProvider: React.FC<ProviderProps> = ({ children }) => {\n const kosCore = resource.read();\n const [online, setOnline] = React.useState(kosCore.onlineStatus);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setOnline(kosCore.onlineStatus);\n });\n\n return () => {\n disposer();\n };\n }, [kosCore]);\n return (\n <KosContext.Provider value={{ kosCore, online }}>\n {children}\n </KosContext.Provider>\n );\n };\n\n return { KosCoreContextProvider: observer(KosCoreContextProvider) };\n};\n\nexport const useKosCore = () => {\n const context = React.useContext(KosContext);\n if (context === undefined) {\n throw new Error(`useKosCore must be used within a KosCoreContextProvider`);\n }\n\n return context;\n};\n\nexport default initKosProvider;\n","import {\n destroyKosModel,\n IKosCoreManager,\n IKosDataModel,\n kosAutoEffect,\n KosCore,\n ModelFactory,\n} from \"../../core\";\n\nimport { useEffect, useState } from \"react\";\nimport { useKosCore } from \"../contexts/kos-core-context\";\n\nimport type { IReactionDisposer } from \"mobx\";\nimport { KosModelEvents, KosModelState } from \"../../core\";\nimport { KosModelLoader } from \"../components/kos-model-loader\";\ninterface Options<T extends IKosDataModel, O extends Object = {}> {\n modelId?: string;\n factory?: ModelFactory<T, O>;\n modelType?: string;\n options?: O;\n activate?: boolean;\n destroyOnUnmount?: boolean;\n}\n\nconst MAX_RETRIES = 8;\nconst waitForRetry = (depth = 0) =>\n new Promise((resolve) => {\n setTimeout(() => {\n resolve(true);\n }, 2 ** depth * 10);\n });\n\nconst cache = new Map();\n\nfunction fetchData(key, fetcher) {\n // Check if there's already a cached promise or result.\n if (cache.has(key)) {\n const entry = cache.get(key);\n if (entry.status === \"finished\") {\n const kosModel = KosCore.getInstance().modelManager.getModelById(key);\n return { kosModel, model: kosModel?.modelData };\n } else {\n throw entry.promise;\n }\n } else {\n // If no cache exists, create a new promise.\n const promise = fetcher().then(\n () => {\n cache.set(key, { status: \"finished\", key });\n },\n (error) => {\n cache.set(key, { status: \"error\", error });\n throw error;\n }\n );\n\n // Store the promise in the cache with a pending status.\n const entry = { status: \"pending\", promise };\n cache.set(key, entry);\n\n // Suspend by throwing the promise.\n throw promise;\n }\n}\n\nfunction useSuspenseData<T>(\n key: string,\n fetcher: (...args: any[]) => Promise<T>\n) {\n // Attempt to fetch the data (or retrieve from cache), throwing a promise if it's not ready.\n const data = fetchData(key, fetcher) as T;\n\n // If the data is available, return it.\n return data;\n}\n\nasync function fetchModel<T extends IKosDataModel, O extends Object = {}>(\n kosCore: IKosCoreManager,\n modelOptions: Options<T, O>\n) {\n const { modelId, factory, modelType, options, activate } = modelOptions;\n let retryCount = 0;\n await kosCore.whenReady();\n let _model: T;\n if (options) {\n const _factory =\n typeof modelType === \"string\"\n ? kosCore.modelManager.getModelFactory<T>(modelType)\n : factory;\n\n if (!_factory) {\n throw Error(\"No Factory Specified. Cannot create a new instance\");\n }\n // build the model first\n _model = _factory.build(modelId!, options);\n }\n const kosModel = kosCore.modelManager.getModelById<T>(modelId!);\n\n if (!kosModel) {\n if (retryCount > MAX_RETRIES) {\n throw Error(`kOS Model ${modelId} has not been found`);\n }\n\n await waitForRetry(retryCount);\n const count = retryCount + 1;\n retryCount = count;\n }\n await kosModel?.whenReady();\n\n if (kosModel) {\n _model = kosModel.modelData;\n return { kosModel, model: _model };\n }\n\n return { kosModel: undefined, model: undefined };\n}\nexport const useKosModel = <T extends IKosDataModel, O extends Object = {}>(\n modelOptions: Options<T, O>\n) => {\n const { modelId, modelType, activate, destroyOnUnmount } = modelOptions;\n const kosCoreContext = useKosCore();\n const [ready, setReady] = useState(false);\n\n const [error, setError] = useState<string | undefined>();\n\n const { kosModel, model } = useSuspenseData(\n modelId || modelType || \"\",\n () => {\n const response = fetchModel(kosCoreContext.kosCore, modelOptions);\n return response;\n }\n );\n useEffect(() => {\n async function waitForModel() {\n try {\n await kosCoreContext.kosCore.whenReady();\n if (activate) {\n await kosModel?.transition(\n KosModelEvents.GO_ACTIVE,\n KosModelState.ACTIVE\n );\n }\n setReady(true);\n return kosModel;\n } catch (e) {\n setError((e as Error).message);\n }\n return undefined;\n }\n\n let disposer: IReactionDisposer | undefined = undefined;\n if (kosCoreContext.kosCore && modelId) {\n waitForModel()\n .then((kosModel) => {\n disposer = kosAutoEffect(() => {\n const _ready = kosModel?.status === KosModelState.READY;\n setReady(_ready);\n });\n })\n .catch((e) => {\n console.error(e);\n });\n }\n return () => {\n if (activate) {\n if (model?.id) {\n const kosModel = kosCoreContext.kosCore.modelManager.getModelById<T>(\n model.id\n );\n\n kosModel\n ?.transition(KosModelEvents.GO_INACTIVE, KosModelState.INACTIVE)\n .then(() => {\n if (destroyOnUnmount) {\n const modelId = model.id;\n destroyKosModel(model).then(() => {\n cache.delete(modelId);\n disposer?.();\n });\n }\n });\n }\n } else {\n if (destroyOnUnmount && model) {\n destroyKosModel(model).then(() => {\n cache.delete(modelId);\n disposer?.();\n });\n }\n }\n };\n }, [\n activate,\n destroyOnUnmount,\n kosCoreContext.kosCore,\n kosModel,\n model,\n modelId,\n ]);\n\n return {\n model,\n ready,\n error,\n status: {\n model,\n ready,\n error,\n },\n KosModelLoader,\n };\n};\n","import { KosTime, KosTimeModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useKosTime = () => {\n const modelId = KosTime.type;\n const result = useKosModel<KosTimeModel>({\n modelId,\n modelType: KosTime.type,\n options: {},\n });\n\n return result;\n};\n","import { PropsWithChildren, createContext, useContext, useMemo } from \"react\";\nimport { KosTimeModel } from \"../../../models\";\nimport { useKosTime } from \"../../hooks/kos-time/use-kos-time\";\n\ninterface KosTimeType {\n model?: KosTimeModel;\n}\nexport const KosTimeContext = createContext<KosTimeType | undefined>(undefined);\n\ninterface KosTimeProviderProps {}\n\nexport const KosTimeProvider: React.FunctionComponent<\n PropsWithChildren<KosTimeProviderProps>\n> = ({ children }) => {\n const { model, ready } = useKosTime();\n const value: KosTimeType = useMemo(() => {\n if (ready && model) {\n return { model };\n }\n return {};\n }, [ready, model]);\n return (\n <KosTimeContext.Provider value={value}>{children}</KosTimeContext.Provider>\n );\n};\nexport const useKosTimeContext = () => {\n const context = useContext(KosTimeContext);\n if (!context) {\n throw new Error(\"useKosTimeContext must be used within a KosTimeProvider\");\n }\n return context;\n};\n","import { SoftwareInfo, type SoftwareInfoModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useSoftwareInfo = () => {\n const modelId = SoftwareInfo.type;\n const result = useKosModel<SoftwareInfoModel>({\n modelId,\n modelType: SoftwareInfo.type,\n options: {},\n });\n\n return result;\n};\n","import type { SoftwareInfoModel } from \"../../../models\";\nimport { useSoftwareInfo } from \"./use-software-info\";\n\ninterface SoftwareInfoProps {\n softwareInfo: SoftwareInfoModel;\n}\n// react HOC to provide a SoftwareInfo to a component\nexport function withSoftwareInfo<\n T extends SoftwareInfoProps = SoftwareInfoProps\n>(WrappedComponent: React.ComponentType<T>) {\n return () => (props: Omit<T, keyof SoftwareInfoProps>) => {\n const { model, status, KosModelLoader } = useSoftwareInfo();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} softwareInfo={model} />\n </KosModelLoader>\n );\n };\n}\n","import { PropsWithChildren, createContext, useContext, useMemo } from \"react\";\nimport type { SoftwareInfoModel } from \"../../../models\";\nimport { useSoftwareInfo } from \"../../hooks/software-info\";\n\ninterface SoftwareInfoType {\n model?: SoftwareInfoModel;\n}\nexport const SoftwareInfoContext = createContext<SoftwareInfoType | undefined>(\n undefined\n);\n\ninterface SoftwareInfoProviderProps {\n id: string;\n}\n\nexport const SoftwareInfoProvider: React.FunctionComponent<\n PropsWithChildren<SoftwareInfoProviderProps>\n> = ({ children }) => {\n const { model, ready } = useSoftwareInfo();\n const value: SoftwareInfoType = useMemo(() => {\n if (ready && model) {\n return { model };\n }\n return {};\n }, [ready, model]);\n return (\n <SoftwareInfoContext.Provider value={value}>\n {children}\n </SoftwareInfoContext.Provider>\n );\n};\nexport const useSoftwareInfoContext = () => {\n const context = useContext(SoftwareInfoContext);\n if (!context) {\n throw new Error(\n \"useSoftwareInfoContext must be used within a SoftwareInfoProvider\"\n );\n }\n return context;\n};\n","import React from \"react\";\nimport { KosToken } from \"../../core\";\n\nconst token = new KosToken();\nconst TokenContext = React.createContext<KosToken>(token);\n\nfunction TokenProvider({ children }: { children: React.ReactNode }) {\n return (\n <TokenContext.Provider value={token}>{children}</TokenContext.Provider>\n );\n}\nexport { TokenContext, TokenProvider };\n","import { KosLog, getQueryParams } from \"../../../core\";\nimport {\n KosTranslations,\n Localization,\n TranslationContainerModel,\n getKosLocalizationDescriptor,\n} from \"../../../models\";\n\nimport {\n PropsWithChildren,\n createContext,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\n\ninterface TranslationContainerType {\n setLocale: (locale: string) => void;\n}\nexport const TranslationContainerContext = createContext<\n TranslationContainerType | undefined\n>(undefined);\n\ninterface TranslationContainerProviderProps {\n appContext?: string | string[];\n rootUrl?: string;\n locale?: string;\n descriptorResolver?: () => Promise<Localization>;\n resolver?: (\n this: TranslationContainerModel,\n namespace: string,\n locale: string\n ) => string;\n}\n\nconst getDefaultHost = () => {\n const defaultHost = window.location.origin;\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n const result = hostUrl || defaultHost;\n return result;\n};\n\nexport const KosTranslationProvider: React.FunctionComponent<\n PropsWithChildren<TranslationContainerProviderProps>\n> = ({\n children,\n appContext = [\"app/system\"],\n locale = \"en\",\n resolver,\n rootUrl,\n descriptorResolver,\n}) => {\n const [ready, setReady] = useState(false);\n const [localization, setLocalization] = useState<Localization>();\n const [translations, setTranslations] = useState<TranslationContainerModel>();\n const resolvedRootUrl = rootUrl || getDefaultHost();\n useEffect(() => {\n async function initTools() {\n const contexts = Array.isArray(appContext) ? appContext : [appContext];\n\n const descriptorPromises = contexts.map((context) => {\n const localizationResolver =\n descriptorResolver || getKosLocalizationDescriptor(context);\n return localizationResolver();\n });\n\n const descriptorsResults = await Promise.allSettled(descriptorPromises);\n const descriptors: Localization[] = descriptorsResults\n .map((d) => {\n if (d.status === \"rejected\") {\n KosLog.warn(\"Failed to load localization descriptor\", d.reason);\n return undefined;\n }\n return d.value;\n })\n .filter((d) => !!d) as Localization[];\n\n const localizationDescriptor = descriptors\n .reverse()\n .reduce<Localization>((acc, val) => {\n const basePath = val.path;\n Object.keys(val.namespaces).forEach((namespaceKey) => {\n const namespace = val.namespaces[namespaceKey];\n namespace.basePath = basePath;\n });\n return {\n ...acc,\n namespaces: { ...acc.namespaces, ...val.namespaces },\n };\n }, {} as Localization);\n setLocalization(localizationDescriptor);\n }\n initTools();\n }, [appContext, descriptorResolver]);\n\n useEffect(() => {\n async function initLocalization() {\n if (localization) {\n const _rootUrl = resolvedRootUrl;\n const { translations } = await KosTranslations.init({\n lang: locale,\n descriptor: localization,\n defaultNamespace: \"common\",\n resolver: resolver,\n rootUrl: _rootUrl,\n });\n setTranslations(translations);\n setReady(true);\n }\n }\n\n initLocalization();\n }, [appContext, locale, localization, resolver, resolvedRootUrl]);\n\n const value: TranslationContainerType = useMemo(() => {\n if (ready) {\n return {\n setLocale: (locale: string) => {\n if (translations) {\n translations.currentLocale = locale;\n }\n },\n };\n }\n return {\n setLocale: () => {\n throw new Error(\"Translations not ready\");\n },\n };\n }, [ready, translations]);\n\n const content = ready ? children : null;\n return (\n <TranslationContainerContext.Provider value={value}>\n {content}\n </TranslationContainerContext.Provider>\n );\n};\nexport const useKosTranslationContext = () => {\n const context = useContext(TranslationContainerContext);\n if (!context) {\n throw new Error(\n \"useTranslationContainerContext must be used within a TranslationContainerProvider\"\n );\n }\n return context;\n};\n","import { Device, DeviceModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useDevice = () => {\n const modelId = Device.type;\n const result = useKosModel<DeviceModel>({\n modelId,\n modelType: Device.type,\n options: {},\n });\n\n return result;\n};\n","import { DeviceModel } from \"../../../models\";\nimport { useDevice } from \"./use-device\";\n\nexport interface DeviceProps {\n device: DeviceModel;\n}\n\ntype HoCDeviceProps = DeviceProps;\n// react HOC to provide a Device to a component\nexport function withDevice<T extends HoCDeviceProps = HoCDeviceProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof DeviceProps>) => {\n const { model, status, KosModelLoader } = useDevice();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} device={model} />\n </KosModelLoader>\n );\n };\n}\n","import { IKosDataModel, KosCore, wrapPromise } from \"../../core\";\n\nexport default function fetchModel<\n T extends IKosDataModel,\n O extends object = Record<string, unknown>\n>(modelType: string, id?: string, options?: O) {\n const corePromise = new Promise<T>((resolve) => {\n KosCore.getInstance()\n .whenReady()\n .then(() => {\n const { model } =\n KosCore.getInstance().modelManager.createModelInstance<T>(\n modelType,\n id ?? modelType,\n options\n );\n return model.whenReady().then(() => {\n resolve(model.modelData);\n });\n });\n });\n\n return wrapPromise<T>(corePromise);\n}\n","import { KosTimeModel } from \"../../../models\";\nimport { useKosTime } from \"./use-kos-time\";\n\ninterface KosTimeProps {\n kosTime: KosTimeModel;\n}\n// react HOC to provide a KosTime to a component\nexport function withKosTime<T extends KosTimeProps = KosTimeProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof KosTimeProps>) => {\n const { model, status, KosModelLoader } = useKosTime();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} kosTime={model} />\n </KosModelLoader>\n );\n };\n}\n","import {\n NetworkInterfaceContainer,\n NetworkInterfaceContainerModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useNetworkInterfaceContainer = () => {\n const modelId = NetworkInterfaceContainer.type;\n const result = useKosModel<NetworkInterfaceContainerModel>({\n modelId,\n modelType: NetworkInterfaceContainer.type,\n options: {},\n });\n\n return result;\n};\n","import { NetworkInterfaceContainerModel } from \"../../../models\";\nimport { useNetworkInterfaceContainer } from \"./use-network-interface-container\";\n\ninterface NetworkInterfaceContainerProps {\n networkInterfaceContainer: NetworkInterfaceContainerModel;\n}\n\ntype HoCNetworkInterfaceContainerProps = NetworkInterfaceContainerProps;\n// react HOC to provide a NetworkInterfaceContainer to a component\nexport function withNetworkInterfaceContainer<\n T extends HoCNetworkInterfaceContainerProps = HoCNetworkInterfaceContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof NetworkInterfaceContainerProps>) => {\n const { model, status, KosModelLoader } = useNetworkInterfaceContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} networkInterfaceContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { Ota, type OtaModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useOta = () => {\n const modelId = Ota.type;\n const result = useKosModel<OtaModel>({\n modelId,\n modelType: Ota.type,\n options: {},\n });\n\n return result;\n};\n","import type { OtaModel } from \"../../../models\";\nimport { useOta } from \"./use-ota\";\n\ninterface OtaProps {\n oTA: OtaModel;\n}\n\ntype HoCOtaProps = OtaProps;\n// react HOC to provide a Ota to a component\nexport function withOta<T extends HoCOtaProps = HoCOtaProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof OtaProps>) => {\n const { model, status, KosModelLoader } = useOta();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} oTA={model} />\n </KosModelLoader>\n );\n };\n}\n","import { useRef, useEffect, PropsWithChildren } from \"react\";\n\n/**\n * Hook that alerts clicks outside of the passed ref\n */\nfunction useOutsideAlerter(ref, onAction) {\n useEffect(() => {\n /**\n * Alert if clicked on outside of element\n */\n function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n onAction();\n }\n }\n\n function handleEscFunction(event) {\n if (event.key === \"Escape\") {\n onAction();\n }\n }\n // Bind the event listener\n document.addEventListener(\"mousedown\", handleClickOutside);\n document.addEventListener(\"keydown\", handleEscFunction, false);\n return () => {\n // Unbind the event listener on clean up\n document.removeEventListener(\"mousedown\", handleClickOutside);\n document.removeEventListener(\"keydown\", handleEscFunction, false);\n };\n }, [ref, onAction]);\n}\n\ninterface Props {\n onAlert: () => void;\n}\n/**\n * Component that alerts if you click outside of it\n */\nexport default function OutsideAlerter(props: PropsWithChildren<Props>) {\n const wrapperRef = useRef(null);\n const onAction = props.onAlert;\n useOutsideAlerter(wrapperRef, onAction);\n\n return (\n <div ref={wrapperRef} style={{ width: \"100%\" }}>\n {props.children}\n </div>\n );\n}\n","import { KosStateProp, StatePropertyTypes } from \"../../../models\";\n\nimport { useEffect, useState } from \"react\";\nimport { kosAutoEffect, whenReady } from \"../../../core\";\n\ninterface UseStatePropertyProps<T extends StatePropertyTypes = any> {\n stateProp?: KosStateProp<T>;\n}\n\ntype StatePropertyStatus<T extends StatePropertyTypes = any> = [\n value: T | undefined,\n status: { ready: boolean; error?: string }\n];\nexport const useStateProperty = <T extends StatePropertyTypes = any>(\n props: UseStatePropertyProps<T>\n): StatePropertyStatus<T> => {\n const { stateProp } = props;\n const [value, setValue] = useState<T | undefined>(props.stateProp?.value);\n const [ready, setReady] = useState(false);\n const [error, setError] = useState<string | undefined>(undefined);\n\n useEffect(() => {\n async function waitForProp(prop?: KosStateProp) {\n try {\n if (prop) {\n await whenReady(prop);\n setReady(true);\n }\n } catch (e) {\n setError((e as Error).message);\n }\n }\n\n waitForProp(stateProp);\n }, [stateProp]);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (stateProp && ready) {\n setValue(stateProp.value);\n }\n });\n return () => {\n disposer();\n };\n }, [ready, stateProp]);\n\n const status = { ready, error };\n return [value, status];\n};\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport {\n StorageDeviceContainer,\n StorageDeviceContainerModel,\n type StorageDeviceModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useStorageDeviceContainer = () => {\n const [inserted, setInserted] = useState<boolean>(false);\n const [devices, setDevices] = useState<StorageDeviceModel[]>([]);\n const modelId = StorageDeviceContainer.type;\n const result = useKosModel<StorageDeviceContainerModel>({\n modelId,\n modelType: StorageDeviceContainer.type,\n options: {},\n });\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setInserted(result.model?.isStorageInserted ?? false);\n setDevices(result.model?.data ?? []);\n });\n\n return () => {\n disposer();\n };\n }, [result.model]);\n\n return { ...result, inserted, devices };\n};\n","import { StorageDeviceContainerModel } from \"../../../models\";\nimport { useStorageDeviceContainer } from \"./use-storage-device-container\";\n\ninterface StorageDeviceContainerProps {\n storageDeviceContainer: StorageDeviceContainerModel;\n}\n\ntype HoCStorageDeviceContainerProps = StorageDeviceContainerProps;\n// react HOC to provide a StorageDeviceContainer to a component\nexport function withStorageDeviceContainer<\n T extends HoCStorageDeviceContainerProps = HoCStorageDeviceContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof StorageDeviceContainerProps>) => {\n const { model, status, KosModelLoader } = useStorageDeviceContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} storageDeviceContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { useEffect } from \"react\";\nimport { EventBus } from \"../../../common\";\nimport {\n KosTimer,\n TIMER_END,\n TIMER_EVENT,\n TimerEvent,\n TimerManager,\n} from \"../../../models\";\n\ninterface TimerHookProps {\n timerName: string;\n onTimerExpired: (event: TimerHookEvent) => void;\n timerEventActions?: Record<string, (event: TimerHookEvent) => void>;\n autoStart?: boolean;\n}\ntype TimerHookEvent = TimerEvent & { timer: KosTimer };\nexport const useTimer = ({\n timerName,\n onTimerExpired,\n timerEventActions,\n autoStart,\n}: TimerHookProps) => {\n const t = TimerManager.getTimer(timerName);\n\n useEffect(() => {\n const result = EventBus.subscribe(TIMER_EVENT, (data) => {\n const { name, action, remainingTime } =\n data?.body as unknown as TimerEvent;\n if (name === timerName && t) {\n if (action === TIMER_END) {\n onTimerExpired({ name, action, remainingTime, timer: t });\n } else {\n if (timerEventActions?.[action]) {\n timerEventActions[action]({\n name,\n action,\n remainingTime,\n timer: t,\n });\n }\n }\n }\n });\n if (autoStart) {\n t?.start();\n }\n\n return () => {\n result.unsubscribe();\n };\n }, [autoStart, onTimerExpired, t, timerEventActions, timerName]);\n\n return {\n timer: t,\n start: t?.start.bind(t),\n reset: t?.reset.bind(t),\n pause: t?.pause.bind(t),\n };\n};\n","import React, { type ReactNode, type ReactElement } from \"react\";\nimport { TFunction } from \"./use-translation\";\nimport { css } from \"@emotion/react\";\n\nconst escapeRegExp = (toEscape: string) => {\n const escapableChars = /[\\\\^$.*+?()[\\]{}|]/g;\n const hasEscapableChar = RegExp(escapableChars.source);\n\n return hasEscapableChar.test(toEscape)\n ? toEscape.replace(escapableChars, \"\\\\$&\")\n : toEscape;\n};\n\nconst isRegExp = (toTest: string | RegExp): toTest is RegExp =>\n toTest instanceof RegExp;\n\nconst isString = (toTest: string | RegExp | ReactNode): toTest is string =>\n typeof toTest === \"string\";\n\nconst replaceString = (\n source: string,\n _toMatch: string | RegExp,\n callback: (match: string, index: number) => ReactNode\n) => {\n if (source === \"\" || _toMatch === \"\") return source;\n\n let toMatch = _toMatch;\n\n if (!isRegExp(toMatch)) {\n toMatch = new RegExp(\"(\" + escapeRegExp(toMatch) + \")\", \"gi\");\n }\n\n const result: ReactNode[] = source.split(toMatch);\n\n // Matches will be every odd string in the array, iterate over them and\n // call the callback to insert our component for each match.\n for (let i = 1, length = result.length; i < length; i += 2) {\n result[i] = callback(result[i] as string, i);\n }\n\n return result;\n};\n\nexport const stringComponentInsert = (\n _source: string | (string | ReactNode)[],\n toMatch: string | RegExp,\n callback: (match: string, index: number) => string | ReactElement\n) => {\n let source = _source;\n if (!Array.isArray(source)) source = [source];\n\n return source.flatMap((x) =>\n isString(x) ? replaceString(x, toMatch, callback) : x\n );\n};\n\ninterface Components {\n [key: string]: JSX.Element;\n}\n\ntype ComponentArray = JSX.Element[];\n\ntype ComponentMap = Components | ComponentArray;\ninterface TransProps {\n t: TFunction;\n i18nKey: string;\n defaults?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n values?: Record<string, any | undefined>;\n components?: ComponentMap;\n context?: string;\n className?: string;\n}\n\nfunction substituteBlocks(stringValue: string, componentsMap: ComponentMap) {\n let blocks: string | ReactNode[] = stringValue;\n\n Object.entries(componentsMap).forEach(([key, value]) => {\n const regex = new RegExp(`<${key}>(.*?)</${key}>|<${key}/>`, \"g\");\n\n blocks = stringComponentInsert(blocks, regex, (match, index) => {\n if (value.type === \"br\") {\n return <br />;\n }\n return React.cloneElement(value, { key: `${key}-${index}` }, match);\n });\n });\n\n return blocks;\n}\n\nexport const Trans: React.FunctionComponent<TransProps> = (props) => {\n const { i18nKey, t, defaults, components, values = {}, context } = props;\n const translated = t(i18nKey, {\n defaultValue: defaults,\n data: values,\n context,\n returnObjects: true,\n });\n\n const element = substituteBlocks(translated, components || {});\n return <span className={props.className}>{element}</span>;\n};\n","import { useCallback, useMemo } from \"react\";\nimport { KosLog, getKosModel, whenReady } from \"../../../core\";\nimport {\n ResolveTranslationOptions,\n TranslationContainer,\n TranslationContainerModel,\n} from \"../../../models\";\n\nconst cache = new Map();\n\nfunction fetchData(key, fetcher) {\n // Check if there's already a cached promise or result.\n if (cache.has(key)) {\n const entry = cache.get(key);\n if (entry.status === \"finished\") {\n return entry.result;\n } else {\n throw entry.promise;\n }\n } else {\n // If no cache exists, create a new promise.\n const promise = fetcher().then(\n (result) => {\n cache.set(key, { status: \"finished\", result });\n },\n (error) => {\n cache.set(key, { status: \"error\", error });\n throw error;\n }\n );\n\n // Store the promise in the cache with a pending status.\n const entry = { status: \"pending\", promise };\n cache.set(key, entry);\n\n // Suspend by throwing the promise.\n throw promise;\n }\n}\n\nexport function useSuspenseData<T>(\n key: string,\n fetcher: (...args: any[]) => Promise<T>\n) {\n // Attempt to fetch the data (or retrieve from cache), throwing a promise if it's not ready.\n const data = fetchData(key, fetcher) as T;\n\n // If the data is available, return it.\n return data;\n}\n\nconst fetchTranslationContainer = async () => {\n const container = await getKosModel(TranslationContainer.type);\n await whenReady(container.model);\n return container.model as TranslationContainerModel;\n};\nconst fetchTranslations = async (\n parent: TranslationContainerModel,\n namespace: string,\n additionalNamespaces: string[]\n) => {\n const trans = parent.resolveNamespace(namespace);\n await whenReady(trans);\n for (const ns of additionalNamespaces) {\n const additional = parent.resolveNamespace(ns);\n await whenReady(additional);\n\n //TODO: This is a hack to force the model to resolve the translations\n cache.set(ns, { status: \"finished\", result: additional });\n }\n return trans;\n};\n\nexport type TFunction = <T = string>(\n key: string,\n options?: ResolveTranslationOptions<T> | string\n) => T | string;\n\nexport interface UseKosTranslationOptions {\n keyPrefix?: string;\n}\nexport const useKosTranslation = (\n namespace: string | string[],\n baseOptions?: UseKosTranslationOptions\n) => {\n const allNamespaces = [namespace].flat();\n const [defaultNamespace, ...additionalNamespaces] = allNamespaces;\n\n const model = useSuspenseData(\n TranslationContainer.type,\n fetchTranslationContainer\n );\n\n const allKeys = allNamespaces.join(\"__\");\n const translationModel = useSuspenseData(allKeys, () =>\n fetchTranslations(model, defaultNamespace, additionalNamespaces)\n );\n\n const i18n = useMemo(() => {\n return {\n exists: (key: string) => {\n const expandedKey = baseOptions?.keyPrefix\n ? `${baseOptions.keyPrefix}.${key}`\n : key;\n if (translationModel) {\n return translationModel.exists(expandedKey);\n }\n\n return false;\n },\n };\n }, [baseOptions?.keyPrefix, translationModel]);\n const t = useCallback<TFunction>(\n <T = string>(\n key: string,\n options?: ResolveTranslationOptions<T> | string\n ) => {\n const expandedKey = baseOptions?.keyPrefix\n ? `${baseOptions.keyPrefix}.${key}`\n : key;\n if (translationModel) {\n return translationModel.resolveKey(expandedKey, options) as T;\n }\n\n KosLog.debug(\n `Translation model ${namespace} not ready for key: ${expandedKey}`\n );\n return expandedKey;\n },\n [baseOptions?.keyPrefix, namespace, translationModel]\n );\n return { t, i18n };\n};\n","import {\n TranslationContainer,\n type TranslationContainerModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useTranslationContainer = () => {\n const modelId = TranslationContainer.type;\n const result = useKosModel<TranslationContainerModel>({\n modelId,\n modelType: TranslationContainer.type,\n options: {},\n });\n\n return result;\n};\n","import type { TranslationContainerModel } from \"../../../models\";\nimport { useTranslationContainer } from \"./use-translation-container\";\n\ninterface TranslationContainerProps {\n translationContainer: TranslationContainerModel;\n}\n\ntype HoCTranslationContainerProps = TranslationContainerProps;\n// react HOC to provide a TranslationContainer to a component\nexport function withTranslationContainer<\n T extends HoCTranslationContainerProps = HoCTranslationContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof TranslationContainerProps>) => {\n const { model, status, KosModelLoader } = useTranslationContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} translationContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { Trouble, type TroubleModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useTroubleModel = (id: string) => {\n const modelId = id;\n\n const result = useKosModel<TroubleModel>({\n modelId,\n modelType: Trouble.type,\n });\n\n return result;\n};\n","import { TroubleContainer, type TroubleContainerModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useTroubleContainerModel = () => {\n const result = useKosModel<TroubleContainerModel>({\n modelId: TroubleContainer.type,\n modelType: TroubleContainer.type,\n options: {},\n });\n return result;\n};\n","import { useCallback, useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport type { TroubleModel } from \"../../../models/models/trouble\";\nimport type { FutureResponse } from \"../../../models/services/future\";\nimport { useTroubleContainerModel } from \"../trouble/use-trouble-container\";\n\ninterface Props {\n troubleType?: string;\n condition?: (trouble: TroubleModel) => boolean;\n}\n\ntype TroubleVisibility = [\n boolean,\n () => Promise<FutureResponse | undefined>,\n TroubleModel | undefined,\n TroubleModel[]\n];\nexport const useTroublePresence = ({\n troubleType,\n condition,\n}: Props): TroubleVisibility => {\n const { model } = useTroubleContainerModel();\n const [active, setActive] = useState<boolean>(false);\n const [troubles, setTroubles] = useState<TroubleModel[]>([]);\n\n const onComplete = useCallback(() => {\n if (troubles.length > 0 && troubles[0]?.resolvable) {\n return troubles[0]?.resolve();\n }\n return Promise.resolve(undefined);\n }, [troubles]);\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n const troublesByType =\n (troubleType\n ? model?.troubles.getIndexByKey(\"byType\", troubleType)\n : model?.troubles.data) || [];\n const activeTroubles = condition\n ? troublesByType.filter(condition)\n : troublesByType;\n setActive(activeTroubles.length > 0);\n setTroubles(activeTroubles);\n });\n return disposer;\n }, [condition, model, troubleType]);\n\n return [\n active,\n onComplete,\n troubles.length > 0 ? troubles[0] : undefined,\n troubles,\n ];\n};\n","import type { TroubleContainerModel } from \"../../../models\";\nimport { useTroubleContainerModel } from \"./use-trouble-container\";\n\ninterface TroubleContainerProps {\n troubleContainer: TroubleContainerModel;\n}\n// react HOC to provide a BoardContainer to a component\nexport function withTroubleContainer<\n T extends TroubleContainerProps = TroubleContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof TroubleContainerProps>) => {\n const { model, status, KosModelLoader } = useTroubleContainerModel();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} troubleContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport {\n UsbUpdateContainer,\n type UsbUpdateContainerModel,\n type UsbUpdateModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useUsbUpdateContainer = () => {\n const modelId = UsbUpdateContainer.type;\n const result = useKosModel<UsbUpdateContainerModel>({\n modelId,\n modelType: UsbUpdateContainer.type,\n options: {},\n activate: true,\n destroyOnUnmount: true,\n });\n\n const [inserted, setInserted] = useState<boolean>(false);\n const [updateAvailable, setUpdateAvailable] = useState<boolean>(false);\n const [updates, setUpdates] = useState<UsbUpdateModel[]>([]);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setInserted(result.model?.isUsbInserted ?? false);\n setUpdateAvailable(result.model?.hasAvailableUpdates ?? false);\n setUpdates(result.model?.data ?? []);\n });\n\n return () => {\n disposer();\n };\n }, [result.model]);\n\n return { ...result, inserted, updateAvailable, updates };\n};\n","import type { UsbUpdateContainerModel } from \"../../../models\";\nimport { useUsbUpdateContainer } from \"./use-usb-update-container\";\n\ninterface UsbUpdateContainerProps {\n usbUpdateContainer: UsbUpdateContainerModel;\n}\n\ntype HoCUsbUpdateContainerProps = UsbUpdateContainerProps;\n// react HOC to provide a UsbUpdateContainer to a component\nexport function withUsbUpdateContainer<\n T extends HoCUsbUpdateContainerProps = HoCUsbUpdateContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof UsbUpdateContainerProps>) => {\n const { model, status, KosModelLoader } = useUsbUpdateContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} usbUpdateContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { autorun } from \"mobx\";\nimport { useEffect, useState } from \"react\";\nimport type { IConfigBeanModel, IConfigBeanModelOptions } from \"../../models\";\nimport { ConfigBean, ConfigPropertyTypes } from \"../../models\";\nimport { useKosModel } from \"./use-kos-model\";\n\ninterface UseConfigBeanParams {\n path: string;\n propKey?: string;\n}\nexport const useConfigBean = ({ path, propKey }: UseConfigBeanParams) => {\n const { status } = useKosModel<IConfigBeanModel, IConfigBeanModelOptions>({\n modelType: ConfigBean.type,\n modelId: path,\n options: {\n path,\n },\n });\n const [ready, setReady] = useState(false);\n const [config, setConfig] = useState<IConfigBeanModel>();\n const [value, setValue] = useState<ConfigPropertyTypes>(\"\");\n const [error, setError] = useState<string>();\n const updateValue = (val: string) => {\n if (config && propKey) {\n config.updateProperty(propKey, val);\n }\n };\n useEffect(() => {\n if (status.model) {\n setConfig(status.model);\n }\n\n if (status.model && propKey) {\n if (status.model?.props.has(propKey)) {\n setValue(status.model.props[propKey]!);\n } else {\n setError(`property ${propKey} not found`);\n }\n }\n\n if (status.ready) {\n setReady(status.ready);\n }\n }, [status.ready, status.model, propKey]);\n\n useEffect(() => {\n if (propKey) {\n autorun(() => {\n const prop = config?.props[propKey];\n setValue(prop || \"\");\n });\n }\n }, [config, propKey]);\n\n return {\n config,\n ready,\n value,\n error,\n updateValue,\n };\n};\n","import {\n ChangeEvent,\n Reducer,\n useCallback,\n useEffect,\n useReducer,\n useState,\n} from \"react\";\nimport { kosAutoEffect, whenReady } from \"../../core\";\nimport type {\n ConfigPropertyTypes,\n OptionsType,\n SchemaOptionsType,\n} from \"../../models\";\nimport { KosConfigProperty } from \"../../models\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\nexport type OptionsTransformer = (options?: OptionsType[]) => any[];\n\ntype KosConfigProp =\n | KosConfigProperty<ConfigPropertyTypes>\n | KosConfigProperty<string>\n | KosConfigProperty<number>\n | KosConfigProperty<boolean>;\ninterface Props {\n configProperty?: KosConfigProp;\n optionsTransformer?: OptionsTransformer;\n}\n\ninterface UpdateAction<T extends object = any> {\n type: \"UPDATE\";\n payload: Partial<ConfigPropertyState<T>>;\n}\ninterface ConfigPropertyState<O extends object = any> {\n value: string;\n displayValue: string;\n significantValue: any;\n unit: string;\n options: OptionsType[];\n mappedOptions: O[];\n updateProperty?: (value: string) => void;\n displayOptions?: SchemaOptionsType;\n}\nconst reducer = <T extends object = any>(\n state: Partial<ConfigPropertyState<T>>,\n action: UpdateAction\n) => {\n switch (action.type) {\n case \"UPDATE\":\n return action.payload;\n default:\n return state;\n }\n};\nexport const useConfigProperty = <T extends object = any>({\n configProperty,\n optionsTransformer,\n}: Props) => {\n const [ready, setReady] = useState(false);\n const [error, setError] = useState(\"\");\n\n const [state, dispatch] = useReducer<\n Reducer<Partial<ConfigPropertyState<T>>, UpdateAction<T>>\n >(reducer, {\n value: String(configProperty?.value),\n displayValue: configProperty?.displayValue,\n significantValue: configProperty?.significantValue,\n unit: configProperty?.unit,\n options: configProperty?.options,\n mappedOptions: [],\n updateProperty: configProperty?.updateProperty,\n displayOptions: configProperty?.displayOptions,\n });\n\n const handleUpdate = useCallback(\n (e: SelectCallback) => {\n let value = \"factory\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n configProperty?.updateProperty(value);\n }\n },\n [configProperty]\n );\n useEffect(() => {\n async function waitForProp(prop?: KosConfigProp) {\n try {\n if (prop) {\n await whenReady(prop);\n setReady(true);\n }\n } catch (e) {\n setError((e as Error).message);\n }\n }\n\n waitForProp(configProperty);\n }, [configProperty]);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (configProperty && ready) {\n let mapped: any[] = [];\n if (optionsTransformer) {\n mapped = optionsTransformer(configProperty.options);\n }\n dispatch({\n type: \"UPDATE\",\n payload: {\n value: String(configProperty.value),\n displayValue: configProperty.displayValue,\n significantValue: configProperty.significantValue,\n unit: configProperty.unit,\n options: configProperty.options,\n mappedOptions: mapped,\n updateProperty: configProperty.updateProperty,\n displayOptions: configProperty?.displayOptions,\n },\n });\n }\n });\n return () => {\n disposer();\n };\n }, [configProperty, optionsTransformer, ready]);\n\n return {\n ...state,\n configSelectProps: {\n onChange: handleUpdate,\n value: state.value,\n options: optionsTransformer\n ? state.mappedOptions || []\n : state.options || [],\n },\n ready,\n error,\n };\n};\n","/**\n * Type for month represented as zero-based (0 for January, 11 for December).\n */\ntype Month = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11;\n\n/**\n * Utility method to get an array of zero-based month options (0 through 11).\n */\nexport function getMonthOptions(): Month[] {\n return Array.from({ length: 12 }, (_, index) => index as Month);\n}\n\n/**\n * Utility method to determine the number of days in a given month of a particular year.\n * @param month - Zero-based month (0 for January, 11 for December).\n * @param year - The year to account for leap years (optional, default is current year).\n * @returns The number of days in the specified month.\n */\nexport function getDaysInMonth(month: Month, year?: number): number {\n const yearToUse = year ?? new Date().getFullYear();\n const daysInEachMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n // Adjust for leap year\n if (\n month === 1 &&\n ((yearToUse % 4 === 0 && yearToUse % 100 !== 0) || yearToUse % 400 === 0)\n ) {\n return 29;\n }\n\n return daysInEachMonth[month] ?? 0;\n}\n\n/**\n * Utility method to get an array of zero-based day options for a specific month and year.\n * @param month - Zero-based month (0 for January, 11 for December).\n * @param year - The year to account for leap years (optional, default is current year).\n * @returns The array of zero-based day options.\n */\nexport function getDayOptions(month: Month, year?: number): number[] {\n const daysInMonth = getDaysInMonth(month, year);\n return Array.from({ length: daysInMonth }, (_, index) => index);\n}\n\n/**\n * Utility method to get an array of year options.\n * @param startYear - The starting year for the array.\n * @param endYear - The ending year for the array.\n * @returns The array of year options.\n */\nexport function getYearOptions(startYear: number, endYear: number): number[] {\n if (startYear > endYear) {\n throw new Error(\"Start year must be less than or equal to end year\");\n }\n return Array.from(\n { length: endYear - startYear + 1 },\n (_, index) => startYear + index\n );\n}\n","import { getDaysInMonth } from \"./date\";\n\n// Returns the number of days in a given month & year\nexport function getDays(year: number, month: number): number {\n return new Date(year, month, 0).getDate();\n}\n\n// Returns an array of all days in a given month & year\n// TODO: Make numbers locale specific\nexport function getDaysArray(year: number, month: number): number[] {\n const numberOfDays = getDaysInMonth(month as any, year);\n const daysAry: number[] = [];\n for (let i = 1; i <= numberOfDays; i++) {\n daysAry.push(i);\n }\n return daysAry;\n}\n\n// Returns an array of months from 0 - 11\n// Note: The array needs to be 0-11 for date functions\nexport function getMonthsArray(): number[] {\n const months = [...Array(12).keys()].map((key) =>\n new Date(0, key).getMonth()\n );\n return months;\n}\n\n// Returns an array of full years\n// When passed a tupple of numbers, it will generate an array with the\n// provided year range.\nexport function getYearsArray(\n number: [number, number] = [2018, 2028]\n): number[] {\n // Create an array +- number of years from current year\n const yearsArray: number[] = [];\n for (let i = number[0]; i <= number[1]; i++) {\n yearsArray.push(i);\n }\n // Return the array\n return yearsArray;\n}\n\nexport type YearFormat = \"short\" | \"long\";\n\nexport function getFormattedYearsArray(\n format: YearFormat,\n range: [number, number] = [2018, 2028]\n): number[] {\n const fullYearsArray = getYearsArray(range);\n if (format === \"long\") {\n return fullYearsArray;\n }\n // Modify the values of the full years array to only return YY instead\n return fullYearsArray.map((year) => Number(year.toString().substring(2)));\n}\n\nexport type MonthFormat = \"numeric\" | \"short\" | \"long\";\n\nexport function getFormattedMonthsArray(\n monthFormat: MonthFormat = \"numeric\",\n locale = \"en-US\"\n) {\n const format = new Intl.DateTimeFormat(locale, {\n month: monthFormat,\n timeZone: \"UTC\",\n }).format;\n\n return [...Array(12).keys()].map((m) => format(new Date(Date.UTC(0, m, 1))));\n}\n\ninterface GetFormattedDateProps {\n locale?: string;\n year: number;\n month: number;\n day: number;\n formatOptions?: Intl.DateTimeFormatOptions;\n displayOrder?: string;\n}\n\n// Formats a given year, month, date based on an optional local and format options\nexport function getFormattedDate({\n locale = \"en-US\",\n year,\n month,\n day,\n formatOptions = {\n weekday: \"long\",\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n },\n displayOrder,\n}: GetFormattedDateProps): string {\n // Correct the month, due to it being an index in the Date method\n const correctedMonth = month - 1;\n const dateFormat = new Date(year, correctedMonth, day);\n const monthName = new Intl.DateTimeFormat(locale, {\n month: formatOptions.month,\n }).format(dateFormat);\n const yearName = new Intl.DateTimeFormat(locale, {\n year: formatOptions.year,\n }).format(dateFormat);\n const dayName = new Intl.DateTimeFormat(locale, {\n day: formatOptions.day,\n }).format(dateFormat);\n\n if (displayOrder) {\n if (displayOrder == \"MMDDYY\") {\n return `${monthName} ${dayName} ${yearName}`;\n } else if (displayOrder === \"DDMMYY\") {\n return `${dayName} ${monthName} ${yearName}`;\n } else if (displayOrder === \"YYMMDD\") {\n return `${yearName} ${monthName} ${dayName}`;\n } else {\n return `${yearName} ${dayName} ${monthName}`;\n }\n }\n // If a displayOrder override isn't provided, format according to the locale:\n return new Intl.DateTimeFormat(locale, formatOptions).format(dateFormat);\n}\n\n// Formats a year to the full 4 digit year to be used in Date methods\nexport function getFormattedYear(year: number): number {\n const formattedYear =\n year.toString().length === 2\n ? new Date(Date.parse(`01 Jan 20${year}`)).getFullYear()\n : year;\n return formattedYear;\n}\n\n// Formats a month to the 2 digit month code to be used in Date methods\nexport function getFormattedMonth(month: number | string): number {\n const formattedMonth =\n typeof month === \"string\"\n ? new Date(Date.parse(`01 ${month.substring(0, 3)} 2023`)).getMonth() + 1\n : month;\n return formattedMonth;\n}\n\n// Return an array assuming the calendar week starts on Sunday\nexport function getCalendarMonthArray(\n month,\n year,\n dayOptions: { label: string; value: number; disabled: boolean }[]\n): { label: string; value: number; disabled: boolean }[] {\n const formattedYear = getFormattedYear(year);\n const firstDay = new Date(formattedYear, month, 1).getDay();\n const numberOfDays = new Date(formattedYear, month + 1, 0).getDate();\n\n const monthArray = [...Array(42).keys()].map((index) => {\n if (index < firstDay || index > numberOfDays + firstDay - 1) {\n return { label: \"\", value: 0, disabled: true };\n } else {\n return dayOptions[index - firstDay];\n }\n });\n\n return monthArray;\n}\n\n// Returns a boolean value of if a provided month, day and year form a valid date\nexport function isValidDate(year, month, day): boolean {\n const zeroIndexedMonth = month - 1;\n const d = new Date(year, zeroIndexedMonth, day);\n return (\n new Date(d).getMonth() === zeroIndexedMonth && new Date(d).getDate() === day\n );\n}\n\n// Returns the last of the month in a provided month and year\nexport function getLastDayOfMonth(year, month): number {\n const lastDay = new Date(year, month, 0).getDate();\n return lastDay;\n}\n\nexport type DayFormatOptions = \"short\" | \"long\" | \"narrow\" | undefined;\n\nexport function getDayStrings(\n locale = \"en-US\",\n dayFormat: DayFormatOptions = \"short\"\n) {\n const format = new Intl.DateTimeFormat(locale, { weekday: dayFormat }).format;\n return [...Array(7).keys()].map((day) =>\n format(new Date(Date.UTC(2021, 5, day)))\n );\n}\n","import { format, parseISO } from \"date-fns\";\nimport { Dispatch, SetStateAction, useEffect, useMemo, useState } from \"react\";\nimport { RegionInfo, RegionInfoModel, RegionInfoOptions } from \"../../models\";\nimport {\n DayFormatOptions,\n MonthFormat,\n YearFormat,\n getCalendarMonthArray,\n getDayStrings,\n getDaysArray,\n getFormattedMonthsArray,\n getFormattedYear,\n getFormattedYearsArray,\n getLastDayOfMonth,\n getMonthsArray,\n isValidDate,\n} from \"../utils/date-utils\";\nimport { useKosModel } from \"./use-kos-model\";\n\nexport type DaysOfWeekFilter = [\n number?,\n number?,\n number?,\n number?,\n number?,\n number?,\n number?\n];\n\nexport interface UseDateArrayFormatOptions {\n yearFormat?: YearFormat;\n monthFormat?: MonthFormat;\n dayFormat?: DayFormatOptions;\n}\nexport interface UseDateArraysProps {\n locale?: string;\n // TODO: Can we tighten the typing on the number?\n year?: number;\n // TODO: Can we tighten the typing on the number?\n month?: number;\n // TODO: Can we tighten the typing on the number?\n day?: number;\n formatOptions?: UseDateArrayFormatOptions;\n yearRange?: [number, number];\n daysOfWeekFilter?: DaysOfWeekFilter;\n}\n\nexport function useDateArrays({\n locale = \"en-US\",\n year = new Date().getFullYear(),\n month = new Date().getMonth(),\n yearRange = [2018, 2028],\n daysOfWeekFilter = [],\n formatOptions: {\n yearFormat = \"long\",\n monthFormat = \"long\",\n dayFormat = \"short\",\n } = {},\n}: UseDateArraysProps) {\n const yearsArray = useYears(yearFormat, yearRange);\n const yearsOptionsArray = useYearsOptions(yearFormat, yearRange, locale);\n const monthsArray = useMonths(monthFormat, locale);\n const monthsOptionsArray = useMonthsOptions(monthFormat, locale);\n const daysArray = useDays(year, month);\n const daysOptionsArray = useDayOptions(year, month, locale, daysOfWeekFilter);\n const calendarDayArray = useCalendarDayArray(month, year, daysOptionsArray);\n const dayNamesArray = useDayNames(locale, dayFormat);\n\n return {\n daysArray,\n monthsArray,\n yearsArray,\n yearsOptionsArray,\n monthsOptionsArray,\n daysOptionsArray,\n calendarDayArray,\n dayNamesArray,\n };\n}\n\n// TODO: Tighten the range type to only be positive numbers within a range\nexport function useYears(\n format: YearFormat = \"long\",\n range: [number, number] = [2018, 2028]\n): number[] {\n const yearsArray = useMemo(\n () => getFormattedYearsArray(format, range),\n [format, range]\n );\n return yearsArray;\n}\n\nexport function useYearsOptions(\n format: YearFormat = \"long\",\n range: [number, number] = [2018, 2028],\n locale = \"en-US\"\n): { label: string; value: number }[] {\n const rawYearsArray = useYears(format, range);\n const yearsOptionsArray = useMemo(\n () =>\n rawYearsArray.map((year) => {\n return {\n label: year.toLocaleString(locale).replace(\",\", \"\"),\n value: year,\n };\n }),\n [locale, rawYearsArray]\n );\n return yearsOptionsArray;\n}\n\nexport function useMonths(\n format: MonthFormat,\n locale = \"en-US\"\n): number[] | string[] {\n const monthsArray = useMemo(\n () => getFormattedMonthsArray(format, locale),\n [format, locale]\n );\n return monthsArray;\n}\n\nexport function useMonthsOptions(\n format: MonthFormat,\n locale = \"en-US\"\n): { label: string; value: number }[] {\n const monthsArray = useMemo(() => getMonthsArray(), []);\n const monthLabelsArray = useMemo(\n () => getFormattedMonthsArray(format, locale),\n [format, locale]\n );\n const monthsOptionsArray = useMemo(\n () =>\n [...Array(12).keys()].map((index) => {\n return {\n label: monthLabelsArray[index],\n value: Number(monthsArray[index]),\n };\n }),\n [monthLabelsArray, monthsArray]\n );\n\n return monthsOptionsArray;\n}\n\nexport function useDays(year: number, month: number): number[] {\n // Convert year\n const formattedYear = getFormattedYear(year);\n\n const daysArray = useMemo(\n () => getDaysArray(formattedYear, month),\n [month, formattedYear]\n );\n\n return daysArray;\n}\n\nconst isFilteredDayOfWeek = (\n year: number,\n month: number,\n day: number,\n filters: DaysOfWeekFilter = []\n): boolean => {\n const dateToCheck: number = new Date(year, month, day).getDay();\n return filters.length > 0 && filters.includes(dateToCheck);\n};\n\nexport function useDayOptions(\n year: number,\n month: number,\n locale = \"en-US\",\n daysOfWeekFilter: DaysOfWeekFilter = []\n): { label: string; value: number; disabled: boolean }[] {\n // TODO: Refactor to be able to pass in additional metadata\n const rawDaysArray = useDays(year, month);\n\n const daysOptionsArray = useMemo(\n () =>\n rawDaysArray.map((day) => {\n return {\n label: day.toLocaleString(locale),\n value: day,\n disabled: isFilteredDayOfWeek(year, month, day, daysOfWeekFilter),\n };\n }),\n [daysOfWeekFilter, locale, month, rawDaysArray, year]\n );\n\n return daysOptionsArray;\n}\nexport function useDayNames(\n locale = \"en-US\",\n dayFormat: DayFormatOptions = \"short\"\n): string[] {\n const dayNamesArray = useMemo(\n () => getDayStrings(locale, dayFormat),\n [locale, dayFormat]\n );\n return dayNamesArray;\n}\n\ninterface UseFormattedDateProps {\n // TODO: Can we tighten the typing on the number?\n year: number;\n // TODO: Can we tighten the typing on the number?\n month: number;\n // TODO: Can we tighten the typing on the number?\n day: number;\n yearRange?: number;\n formatString: string;\n}\n\nexport function useFormattedDate({\n year = new Date().getFullYear(),\n month = new Date().getMonth(),\n day = new Date().getDate(),\n formatString,\n}: UseFormattedDateProps): { formattedDate: string } {\n const indexedMonth = month;\n const date = new Date(year, indexedMonth, day);\n const formattedDate = format(date, formatString);\n\n return { formattedDate };\n}\n\nexport function useCalendarDayArray(\n month: number,\n year: number,\n dayOptionsArray: { label: string; value: number; disabled: boolean }[]\n): { label: string; value: number; disabled: boolean }[] {\n const calendarDayArray = useMemo(\n () => getCalendarMonthArray(month, year, dayOptionsArray),\n [month, year, dayOptionsArray]\n );\n return calendarDayArray;\n}\n\nexport interface UseDatePropsReturnActions {\n setYear: Dispatch<SetStateAction<number>>;\n setYearRange: Dispatch<SetStateAction<[number, number]>>;\n setMonth: Dispatch<SetStateAction<number>>;\n setDay: Dispatch<SetStateAction<number>>;\n nextMonth: () => void;\n previousMonth: () => void;\n nextYear: () => void;\n previousYear: () => void;\n}\n\nexport interface UseDatePropsReturnState {\n year: number;\n yearRange: [number, number];\n month: number;\n day: number;\n yearsArray: number[];\n yearsOptionsArray: { label: string; value: number; disabled?: boolean }[];\n monthsArray: string[] | number[];\n monthsOptionsArray: {\n label: string | number;\n value: number;\n disabled?: boolean;\n }[];\n daysArray: number[];\n daysOptionsArray: { label: string; value: number; disabled?: boolean }[];\n calendarDayNames: string[];\n calendarDayArray: {\n label: string;\n value: number;\n disabled?: boolean;\n }[];\n formattedDate: string;\n}\n\nexport interface UseDatePropsReturn {\n dateActions: UseDatePropsReturnActions;\n dateState: UseDatePropsReturnState;\n}\n\nexport enum DateDisplayFormat {\n \"MMDDYY\" = \"MMDDYY\",\n \"DDMMYY\" = \"DDMMYY\",\n \"YYMMDD\" = \"YYMMDD\",\n \"YYDDMM\" = \"YYDDMM\",\n}\n\ninterface UseDatePropsFormatOptions extends UseDateArrayFormatOptions {\n formatString?: string;\n}\ninterface UseDatePropsFilterOptions {\n yearsRange?: [number, number];\n daysOfWeekFilter?: DaysOfWeekFilter;\n}\n\ninterface UseDateProps {\n locale?: string;\n date?: { day?: number; month?: number; year?: number };\n formatOptions?: UseDatePropsFormatOptions;\n filterOptions?: UseDatePropsFilterOptions;\n}\n\nexport function useDateProps({\n locale = \"en-US\",\n date: {\n year: yearProp = new Date().getFullYear(),\n month: monthProp = new Date().getMonth(),\n day: dayProp = new Date().getDate(),\n } = {\n year: new Date().getFullYear(),\n month: new Date().getMonth(),\n day: new Date().getDate(),\n },\n formatOptions: {\n yearFormat = \"long\",\n monthFormat = \"long\",\n dayFormat = \"short\",\n formatString = \"yyyy/MM/dd\",\n } = {},\n filterOptions: {\n yearsRange = [2018, 2028] as [number, number],\n daysOfWeekFilter = [] as DaysOfWeekFilter,\n } = {},\n}: UseDateProps): UseDatePropsReturn {\n const [year, setYear] = useState<number>(yearProp);\n const [yearRange, setYearRange] = useState<[number, number]>(yearsRange);\n const [month, setMonth] = useState<number>(monthProp);\n const [day, setDay] = useState<number>(dayProp);\n\n useEffect(() => {\n setYear(yearProp);\n }, [yearProp]);\n\n useEffect(() => {\n setMonth(monthProp);\n }, [monthProp]);\n\n useEffect(() => {\n setDay(dayProp);\n }, [dayProp]);\n\n const {\n yearsArray,\n yearsOptionsArray,\n monthsArray,\n monthsOptionsArray,\n daysArray,\n daysOptionsArray,\n calendarDayArray,\n dayNamesArray,\n } = useDateArrays({\n locale,\n year,\n yearRange,\n month,\n formatOptions: {\n yearFormat,\n monthFormat,\n dayFormat,\n },\n daysOfWeekFilter,\n });\n\n const { formattedDate } = useFormattedDate({\n year,\n month,\n day,\n formatString,\n });\n\n const nextMonth = (): void => {\n // Account for going past December\n const formattedYear =\n month < 11 ? getFormattedYear(year) : getFormattedYear(year + 1);\n const nextMonth = month < 11 ? month + 1 : 0;\n\n // Account for the day and if it's valid in the month\n if (!isValidDate(formattedYear, nextMonth, day)) {\n const lastValidDay = getLastDayOfMonth(formattedYear, nextMonth);\n setDay(lastValidDay);\n }\n if (nextMonth === 0) {\n setYear(formattedYear);\n }\n setMonth(nextMonth);\n };\n\n const previousMonth = (): void => {\n // Account for going before January\n const formattedYear =\n month === 0 ? getFormattedYear(year - 1) : getFormattedYear(year);\n\n const prevMonth = month === 0 ? 11 : month - 1;\n // Account for the day and if it's valid in the month\n if (!isValidDate(formattedYear, prevMonth, day)) {\n const lastValidDay = getLastDayOfMonth(formattedYear, prevMonth);\n setDay(lastValidDay);\n }\n if (prevMonth === 11) {\n setYear(formattedYear);\n }\n setMonth(prevMonth);\n };\n\n const nextYear = (): void => {\n const nextYear = year < yearRange[1] ? year + 1 : yearRange[0];\n // Account for the day and if it's valid in the month\n const formattedYear = getFormattedYear(nextYear);\n\n if (isValidDate(formattedYear, month, day)) {\n setYear(nextYear);\n } else {\n // If it's not a valid day, change the day to the last day of the month\n const lastValidDay = getLastDayOfMonth(getFormattedYear(year + 1), month);\n setDay(lastValidDay);\n setYear(nextYear);\n }\n };\n\n const previousYear = (): void => {\n const prevYear = year > yearRange[0] ? year - 1 : yearRange[0];\n const formattedYear = getFormattedYear(prevYear);\n\n if (isValidDate(formattedYear, month, day)) {\n setYear(prevYear);\n } else {\n // If it's not a valid day, change the day to the last day of the month\n const lastValidDay = getLastDayOfMonth(getFormattedYear(year - 1), month);\n setDay(lastValidDay);\n setYear(prevYear);\n }\n };\n\n return {\n dateActions: {\n setYear,\n setYearRange,\n setMonth,\n setDay,\n nextMonth,\n previousMonth,\n nextYear,\n previousYear,\n },\n dateState: {\n year,\n yearRange,\n month,\n day,\n yearsArray,\n yearsOptionsArray,\n monthsArray,\n monthsOptionsArray,\n daysArray,\n daysOptionsArray,\n calendarDayNames: dayNamesArray,\n calendarDayArray,\n formattedDate,\n },\n };\n}\n\nexport interface UseRegionalFormatProps {\n date?: Date | string;\n dateFormat?: string;\n timeFormat?: string;\n options?: {\n ignoreDateFormat?: boolean;\n };\n}\n\nexport function useRegionalTimeDate({\n date = new Date(),\n dateFormat,\n timeFormat,\n options = {},\n}: UseRegionalFormatProps): { formattedDate: string; formattedTime: string } {\n const [formattedTime, setFormattedTime] = useState(\"Formatting Time...\");\n const [formattedDate, setFormattedDate] = useState(\"Formatting Date...\");\n\n const ignoreDate = !!options.ignoreDateFormat;\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelId: RegionInfo.type,\n modelType: RegionInfo.type,\n options: {},\n });\n const dateToFormat = typeof date === \"string\" ? parseISO(date) : date;\n\n useEffect(() => {\n if (ignoreDate) {\n setFormattedDate(\"\");\n } else if (dateFormat) {\n // Set date according to format string\n setFormattedDate(format(dateToFormat, dateFormat));\n } else {\n // Set date according to model if no date format string provided\n if (ready) {\n setFormattedDate(\n format(\n dateToFormat,\n model?.selectedDateFormat ? model?.selectedDateFormat : \"\"\n )\n );\n }\n }\n }, [ignoreDate, date, dateFormat, dateToFormat, model, ready]);\n\n useEffect(() => {\n if (timeFormat) {\n // Set date according to format string\n setFormattedTime(format(dateToFormat, timeFormat));\n } else {\n // Set date according to model if no time format string provided\n if (ready) {\n setFormattedTime(\n format(\n dateToFormat,\n model?.selectedTimeFormat ? model?.selectedTimeFormat : \"\"\n )\n );\n }\n }\n }, [date, timeFormat, dateToFormat, model, ready]);\n\n return { formattedDate, formattedTime };\n}\n","import { useEffect, useRef, useState } from \"react\";\nimport type { KosConfigProperty } from \"../../models\";\nimport { useConfigProperty } from \"./use-config-property\";\nimport { useRegionalTimeDate } from \"./use-date-props\";\n\ninterface Props {\n configProperty?: KosConfigProperty<number>;\n is24Hr?: boolean;\n}\n\ninterface DateRelative {\n hours: number;\n minutes: number;\n seconds: number;\n formattedTime;\n timeActions: {\n setHours: (hours: number) => void;\n setMinutes: (minutes: number) => void;\n setSeconds: (seconds: number) => void;\n };\n}\ninterface DateRelativeDataProps {\n secondsFromMidnight?: number;\n}\n\n/**\n * Hook to convert seconds from midnight to a human readable time format\n *\n * The hook will use the time format based on the regional settings\n *\n * @param secondsFromMidnight - The number of seconds from midnight\n * @returns The hours, minutes, seconds, formatted time and actions to update the time\n */\nexport const useDateRelativeData = ({\n secondsFromMidnight = 0,\n}: DateRelativeDataProps) => {\n const [hours, setHours] = useState(0);\n const [minutes, setMinutes] = useState(0);\n const [seconds, setSeconds] = useState(0);\n const [date, setDate] = useState(new Date());\n const { formattedTime } = useRegionalTimeDate({\n date,\n options: {\n ignoreDateFormat: true,\n },\n });\n useEffect(() => {\n const numericValue = Number(secondsFromMidnight);\n const _hours = Math.floor(numericValue / 3600);\n const _minutes = Math.floor((numericValue % 3600) / 60);\n const _seconds = numericValue % 60;\n setHours(_hours);\n setMinutes(_minutes);\n setSeconds(_seconds);\n const midnight = new Date();\n midnight.setHours(0, 0, 0, 0);\n\n // Add the seconds to the midnight time\n const time = new Date(midnight.getTime() + numericValue * 1000);\n setDate(new Date(time));\n }, [secondsFromMidnight]);\n\n return {\n hours,\n minutes,\n seconds,\n formattedTime,\n timeActions: {\n setHours,\n setMinutes,\n setSeconds,\n },\n };\n};\n\n/**\n * Hook to translate date relative configuration properties to human readable time\n *\n * @param configProperty - The configuration property to use\n * @returns\n * @see useDateRelativeData\n */\nexport const useDateRelativeConfig = ({\n configProperty,\n}: Props): DateRelative => {\n const { value } = useConfigProperty({ configProperty });\n\n const secondsFromMidnight = parseInt(value || \"0\", 10);\n const { hours, minutes, seconds, formattedTime, timeActions } =\n useDateRelativeData({\n secondsFromMidnight,\n });\n\n const timeoutRef = useRef<NodeJS.Timeout>();\n\n useEffect(() => {\n // Calculate the new value only once per effect run\n const newValue = hours * 3600 + minutes * 60 + seconds;\n\n // Clear any previously set timeout to ensure only the latest update is applied\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n // Set a new timeout to update the property after 100ms\n timeoutRef.current = setTimeout(() => {\n if (configProperty) {\n configProperty.updateProperty(newValue.toString());\n }\n }, 100); // 100 milliseconds delay\n\n // Cleanup function to clear the timeout if the component is unmounted or dependencies change\n return () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n };\n }, [configProperty, hours, minutes, seconds]); // Dependencies list\n return {\n hours,\n minutes,\n seconds,\n formattedTime,\n timeActions,\n };\n};\n","import { RegionInfo } from \"../../models\";\n\nimport { kosAutoEffect } from \"../../core\";\nimport type {\n DateFormatOptions,\n RegionInfoModel,\n RegionInfoOptions,\n} from \"../../models\";\n\nimport { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { useKosModel } from \"./use-kos-model\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype DateFormatMap<T extends {} = any> = (format: DateFormatOptions) => T;\nconst DEFAULT_FORMAT_MAP: DateFormatMap = (format: DateFormatOptions) => (\n <option title={format.id} key={format.id} value={format.format}>\n {format.format}\n </option>\n);\n\n/**\n * The data returned from the useKosRegions hook.\n * @typeParam RegionData - the region data returned from the backend service. The type must extend BaseRegionResponse from the kos-core-model.\n * @typeParam T - the type of the options returned from the regionMap function.\n */\nexport interface KosDateFormatHookData<T extends {} = any> {\n /**the raw region data returned from the backend service. */\n raw: string[];\n\n /**the region model returned from the backend service. */\n regionModel?: RegionInfoModel;\n\n /**the currently selected region. */\n selectedDateFormat: string;\n\n dateFormatId: string;\n /**a function that can be used to update the region. */\n updateDateFormat: (e: SelectCallback) => void;\n\n /**the props that can be spread into a select box component. */\n props: {\n onChange: (e: SelectCallback) => void;\n value: string;\n options: T[];\n };\n}\n\n/**\n * A hook that will help manage the use of region date formats on a dispenser.\n * @param dateFormatMap - a function that maps a region string a structure that can be\n * used as an option in a select box. The default is to return an option element\n * with the date format as the value and label.\n * @returns KosDateFormatHookData - the data returned from the hook.\n * @example\n * In this example the default region map is used to populate a select box with the available regions. If using a third party select box component where the options\n * are passed in as a prop, the options property can be spread into the props for the component. In this case, a region map function could be passed in to map the region\n * to a structure that the component expects.\n *\n *\n * ```typescript\n * interface RegionData extends RegionServices.BaseRegionResponse {\n * rfidRegion: string;\n * }\n * const { regionSelectProps, regionModel, regionData, selectedRegion, updateRegion } = useKosRegions<RegionData>();\n * const { options, ...selectAttributes } = regionSelectProps;\n * ...\n * <div>\n * <label>Select region: </label>\n * <select {...selectAttributes}>{options}</select>\n * </div>\n * <div>Selected Region: {selectedRegion}</div>\n * <div>Region Data: {regionData?.rfidRegion}</div>\n * ```\n */\nexport const useKosDateFormats = <T extends {} = any>(\n dateFormatMap: DateFormatMap<T> = DEFAULT_FORMAT_MAP\n): KosDateFormatHookData<T> => {\n const [dateFormats, setDateFormats] = useState<T[]>([]);\n const [selectedDateFormat, setSelectedDateFormat] = useState<{\n id: string;\n value: string;\n }>();\n\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n options: {},\n });\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setDateFormats(model?.dateFormatOptions.map(dateFormatMap) || []);\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, dateFormatMap]);\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n if (model?.dateFormatId && model?.selectedDateFormat) {\n setSelectedDateFormat({\n id: model?.dateFormatId,\n value: model?.selectedDateFormat,\n });\n }\n });\n\n return () => {\n cleanup();\n };\n }, [model?.selectedDateFormat, model?.dateFormatId]);\n\n const handleDateFormatChange = useCallback(\n (e: SelectCallback) => {\n let value = \"\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n model?.setSelectedDateFormat(value);\n }\n },\n [model]\n );\n\n return {\n raw: model?.dateFormatOptions.map((o) => o.id) ?? [],\n regionModel: model,\n selectedDateFormat: selectedDateFormat?.value || \"\",\n dateFormatId: selectedDateFormat?.id || \"\",\n updateDateFormat: handleDateFormatChange,\n props: {\n onChange: handleDateFormatChange,\n value: selectedDateFormat?.id || \"\",\n options: dateFormats,\n },\n };\n};\n","import { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../core\";\nimport {\n KosConfigProperty,\n KosConfigPropertySpec,\n RegionInfo,\n RegionInfoModel,\n RegionInfoOptions,\n updateTimeZone,\n} from \"../../models\";\nimport { useKosModel } from \"./use-kos-model\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype OptionMap<T extends {} = any> = (option: string) => T;\n\nconst DEFAULT_OPTION_MAP: OptionMap = (option: string) => (\n <option title={option} key={option} value={option}>\n {option}\n </option>\n);\n\nconst REGION_SETTINGS_PATH = \"kos:service:region:settings\";\nconst TIMEZONE_ATTRIBUTE = \"timeZone\";\nconst REGION_TIMEZONE_ID = `${REGION_SETTINGS_PATH}-${TIMEZONE_ATTRIBUTE}`;\n\n/**\n * Custom React hook for managing and interacting with timezone data.\n * It fetches timezone information from the RegionInfoModel and facilitates\n * timezone selection in a React application.\n *\n * @typeparam T The type of the options that the hook will produce for use in UI components.\n * @param optionsMap A function that maps a timezone string to a JSX structure or other specified format.\n * @returns An object containing timezone options, raw timezone data, the selected timezone, and functions to handle updates.\n *\n * @example\n * ```typescript\n * import React from 'react';\n * import { useKosTimeZones } from '@kosdev-code/kos-ui-sdk';\n *\n * const MyComponent: React.FC = () => {\n * // Using the hook with the default option mapper\n * const { selectProps } = useKosTimeZones();\n *\n * return (\n * <div>\n * <label>Select Timezone:</label>\n * <select {...selectProps}>\n * {selectProps.options}\n * </select>\n * </div>\n * );\n * };\n *\n * export default MyComponent;\n * ```\n * @example\n * Using the hook with a custom component and regionMap function:\n *\n * ```typescript\n * import React from 'react';\n * import { useKosTimeZones } from '@kosdev-code/kos-ui-sdk';\n *\n * // Custom component that expects an options prop\n * const CustomSelectComponent: React.FC<{ options: { label: string; value: string }[] }> = ({ options }) => {\n * return (\n * <select>\n * {options.map(option => (\n * <option key={option.value} value={option.value}>{option.label}</option>\n * ))}\n * </select>\n * );\n * };\n *\n * // Custom regionMap function to map timezones to the required format for CustomSelectComponent\n * const customRegionMap = (timezone: string) => ({\n * label: `Timezone: ${timezone}`,\n * value: timezone\n * });\n *\n * const MyComponent: React.FC = () => {\n * // Using the hook with the custom regionMap function\n * const { options } = useKosTimeZones(customRegionMap);\n *\n * return (\n * <div>\n * <label>Select Timezone:</label>\n * <CustomSelectComponent options={options} />\n * </div>\n * );\n * };\n *\n * export default MyComponent;\n * ```\n */\nexport const useKosTimeZones = <T extends {} = any>(\n optionsMap: OptionMap<T> = DEFAULT_OPTION_MAP\n) => {\n const [timeZones, setTimeZones] = useState<T[]>([]);\n const [selectedTimeZone, setSelectedTimeZone] = useState<string>(\"\");\n\n // Fetches the RegionInfoModel using the useKosModel hook.\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n options: {},\n });\n\n // Defines a KosConfigProperty for timezone information.\n const timezoneInfo: KosConfigProperty<string> = KosConfigPropertySpec.factory(\n REGION_TIMEZONE_ID\n )({\n path: REGION_SETTINGS_PATH,\n attribute: TIMEZONE_ATTRIBUTE,\n }) as KosConfigProperty<string>;\n\n // Updates the timeZones state when the model changes.\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setTimeZones(model?.timeZones.map(optionsMap) || []);\n\n if (model?.timeZones.length) {\n updateTimeZone(model?.timeZones[0]);\n }\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, optionsMap]);\n\n // Updates the selectedTimeZone state based on the timezoneInfo value.\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setSelectedTimeZone(timezoneInfo.value || \"\");\n });\n\n return () => {\n cleanup();\n };\n }, [timezoneInfo.value]);\n\n // Callback function to handle timezone updates.\n const handleUpdate = useCallback((e: SelectCallback) => {\n let value = \"factory\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n updateTimeZone(value);\n }\n }, []);\n\n return {\n options: timeZones,\n raw: model?.timeZones ?? [],\n regionModel: model,\n selectedTimeZone,\n timeZones: model?.timeZones ?? [],\n updateTimeZone: handleUpdate,\n selectProps: {\n onChange: handleUpdate,\n value: selectedTimeZone,\n options: timeZones,\n },\n };\n};\n","import { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../core\";\nimport {\n KosConfigPropertySpec,\n type KosConfigProperty,\n} from \"../../models/models/config-bean-prop\";\nimport {\n RegionInfo,\n RegionInfoOptions,\n RegionServices,\n type RegionInfoModel,\n} from \"../../models/models/region-info\";\nimport { updateRegion } from \"../../models/utils/region-utils\";\nimport { useKosModel } from \"./use-kos-model\";\n\nconst REGION_PATH = \"kos:service:region\";\nconst REGION_ATTRIBUTE = \"regionId\";\nconst REGION_ID = `${REGION_PATH}-${REGION_ATTRIBUTE}`;\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype RegionMap<T extends object = any> = (region: string) => T;\nconst DEFAULT_REGION_MAP: RegionMap = (region: string) => (\n <option title={region} key={region} value={region}>\n {region}\n </option>\n);\n\n/**\n * The data returned from the useKosRegions hook.\n * @typeParam RegionData - the region data returned from the backend service. The type must extend BaseRegionResponse from the kos-core-model.\n * @typeParam T - the type of the options returned from the regionMap function.\n */\nexport interface KosRegionHookData<\n RegionData extends RegionServices.BaseRegionResponse = RegionServices.BaseRegionResponse,\n T extends object = any\n> {\n /**the raw region data returned from the backend service. */\n raw: string[];\n\n /**the region model returned from the backend service. */\n regionModel?: RegionInfoModel<RegionData>;\n\n /** the region data returned from the backend service. */\n regionData?: RegionData;\n\n /**the currently selected region. */\n selectedRegion: string;\n\n /**a function that can be used to update the region. */\n updateRegion: (e: SelectCallback) => void;\n\n /**the props that can be spread into a select box component. */\n regionSelectProps: {\n onChange: (e: SelectCallback) => void;\n value: string;\n options: T[];\n };\n}\n\n/**\n * A hook that will help manage the use of region information on a dispenser.\n * @typeParam RegionData - the region data returned from the backend service. The type must extend BaseRegionResponse from the kos-core-model.\n * @param regionMap - a function that maps a region string a structure that can be\n * used as an option in a select box. The default is to return an option element\n * with the region as the value and label.\n * @returns KosRegionHookData - the data returned from the hook.\n * @example\n * In this example the default region map is used to populate a select box with the available regions. If using a third party select box component where the options\n * are passed in as a prop, the options property can be spread into the props for the component. In this case, a region map function could be passed in to map the region\n * to a structure that the component expects.\n *\n *\n * ```typescript\n * interface RegionData extends RegionServices.BaseRegionResponse {\n * rfidRegion: string;\n * }\n * const { regionSelectProps, regionModel, regionData, selectedRegion, updateRegion } = useKosRegions<RegionData>();\n * const { options, ...selectAttributes } = regionSelectProps;\n * ...\n * <div>\n * <label>Select region: </label>\n * <select {...selectAttributes}>{options}</select>\n * </div>\n * <div>Selected Region: {selectedRegion}</div>\n * <div>Region Data: {regionData?.rfidRegion}</div>\n * ```\n */\nexport const useKosRegions = <\n RegionData extends RegionServices.BaseRegionResponse = RegionServices.BaseRegionResponse,\n T extends {} = any\n>(\n regionMap: RegionMap<T> = DEFAULT_REGION_MAP\n): KosRegionHookData<RegionData, T> => {\n const [regions, setRegions] = useState<T[]>([]);\n const [selectedRegion, setSelectedRegion] = useState<string>(\"factory\");\n const { model, ready } = useKosModel<\n RegionInfoModel<RegionData>,\n RegionInfoOptions\n >({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n options: {},\n });\n\n const regionInfo: KosConfigProperty<string> = KosConfigPropertySpec.factory(\n REGION_ID\n )({\n path: REGION_PATH,\n attribute: REGION_ATTRIBUTE,\n }) as KosConfigProperty<string>;\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setRegions(model?.availableRegions.map(regionMap) || []);\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, regionMap]);\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setSelectedRegion(regionInfo.value || \"factory\");\n });\n\n return () => {\n cleanup();\n };\n }, [regionInfo.value]);\n\n const handleUpdate = useCallback((e: SelectCallback) => {\n let value = \"factory\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n updateRegion(value);\n }\n }, []);\n\n return {\n raw: model?.availableRegions ?? [],\n regionModel: model,\n regionData: model?.selectedRegion,\n selectedRegion,\n updateRegion: handleUpdate,\n\n regionSelectProps: {\n onChange: handleUpdate,\n value: selectedRegion,\n options: regions,\n },\n };\n};\n","import { RegionInfo } from \"../../models/models/region-info\";\n\nimport { kosAutoEffect } from \"../../core\";\nimport type {\n RegionInfoModel,\n RegionInfoOptions,\n TimeFormatOptions,\n} from \"../../models/models/region-info\";\n\nimport { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { useKosModel } from \"./use-kos-model\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype TimeFormatMap<T extends {} = any> = (format: TimeFormatOptions) => T;\nconst DEFAULT_FORMAT_MAP: TimeFormatMap = (format: TimeFormatOptions) => (\n <option title={format.id} key={format.id} value={format.format}>\n {format.format}\n </option>\n);\n\n/**\n * The data returned from the useKosRegions hook.\n * @typeParam RegionData - the region data returned from the backend service. The type must extend BaseRegionResponse from the kos-core-model.\n * @typeParam T - the type of the options returned from the regionMap function.\n */\nexport interface KosTimeFormatHookData<T extends {} = any> {\n /**the raw region data returned from the backend service. */\n raw: string[];\n\n /**the region model returned from the backend service. */\n regionModel?: RegionInfoModel;\n\n /**the currently selected region. */\n selectedTimeFormat: string;\n\n timeFormatId: string;\n /**a function that can be used to update the region. */\n updateTimeFormat: (e: SelectCallback) => void;\n\n /**the props that can be spread into a select box component. */\n props: {\n onChange: (e: SelectCallback) => void;\n value: string;\n options: T[];\n };\n}\n\n/**\n * A hook that will help manage the use of region information on a dispenser.\n * @typeParam RegionData - the region data returned from the backend service. The type must extend BaseRegionResponse from the kos-core-model.\n * @param timeFormatMap - a function that maps a region string a structure that can be\n * used as an option in a select box. The default is to return an option element\n * with the region as the value and label.\n * @returns KosRegionHookData - the data returned from the hook.\n * @example\n * In this example the default region map is used to populate a select box with the available regions. If using a third party select box component where the options\n * are passed in as a prop, the options property can be spread into the props for the component. In this case, a region map function could be passed in to map the region\n * to a structure that the component expects.\n *\n *\n * ```typescript\n * interface RegionData extends RegionServices.BaseRegionResponse {\n * rfidRegion: string;\n * }\n * const { regionSelectProps, regionModel, regionData, selectedRegion, updateRegion } = useKosRegions<RegionData>();\n * const { options, ...selectAttributes } = regionSelectProps;\n * ...\n * <div>\n * <label>Select region: </label>\n * <select {...selectAttributes}>{options}</select>\n * </div>\n * <div>Selected Region: {selectedRegion}</div>\n * <div>Region Data: {regionData?.rfidRegion}</div>\n * ```\n */\nexport const useKosTimeFormats = <T extends {} = any>(\n timeFormatMap: TimeFormatMap<T> = DEFAULT_FORMAT_MAP\n): KosTimeFormatHookData<T> => {\n const [timeFormats, setTimeFormats] = useState<T[]>([]);\n const [selectedTimeFormat, setSelectedTimeFormat] = useState<{\n id: string;\n value: string;\n }>();\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n options: {},\n });\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setTimeFormats(model?.timeFormatOptions.map(timeFormatMap) || []);\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, timeFormatMap]);\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n if (model?.timeFormatId && model?.selectedTimeFormat) {\n setSelectedTimeFormat({\n id: model?.timeFormatId,\n value: model?.selectedTimeFormat,\n });\n }\n });\n\n return () => {\n cleanup();\n };\n }, [model?.selectedTimeFormat, model?.timeFormatId]);\n\n const handleTimeFormatChange = useCallback(\n (e: SelectCallback) => {\n let value = \"\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n model?.setSelectedTimeFormat(value);\n }\n },\n [model]\n );\n\n return {\n raw: model?.timeFormatOptions.map((o) => o.id) ?? [],\n regionModel: model,\n selectedTimeFormat: selectedTimeFormat?.value ?? \"\",\n timeFormatId: selectedTimeFormat?.id ?? \"\",\n updateTimeFormat: handleTimeFormatChange,\n props: {\n onChange: handleTimeFormatChange,\n value: selectedTimeFormat?.id ?? \"\",\n options: timeFormats,\n },\n };\n};\n","import { useMemo } from \"react\";\nimport { kosComputed } from \"../../core\";\n\n/**\n * @description An abstraction of React's useMemo for observable dependencies.\n * @param callback A function that returns a desired value.\n * @param dependencies An array of non-observable variables that are required to run the callback.\n */\nexport const useLocalComputed = <T>(\n callback: () => T,\n dependencies: ReadonlyArray<unknown>\n) => useMemo(() => kosComputed(callback), dependencies);\n","import { useEffect, useState } from \"react\";\nimport { KosLog } from \"../../core/core/log\";\n\ninterface MutationObserverOptions {\n config: MutationObserverInit;\n}\n\n// Default options for the MutationObserver\nconst DEFAULT_OPTIONS: MutationObserverOptions = {\n config: { attributes: true, childList: true, subtree: true },\n};\n\n/**\n * A hook that creates a MutationObserver and observes a DOM element for mutations. When a mutation occurs, the callback function is executed.\n *\n * @param targetEl The DOM element to observe\n * @param cb The callback function to execute when a mutation occurs\n * @param options Options to pass to the MutationObserver to configure what mutations to observe\n */\nexport function useMutationObserver<T extends Node>(\n targetEl: T,\n cb: MutationCallback,\n options: MutationObserverOptions = DEFAULT_OPTIONS\n) {\n const [observer, setObserver] = useState<MutationObserver | null>(null);\n useEffect(() => {\n // Validate the callback function\n if (!cb || typeof cb !== \"function\") {\n throw new Error(\"A valid callback function is required\");\n }\n const obs = new MutationObserver(cb);\n setObserver(obs);\n }, [cb, options, setObserver]);\n\n useEffect(() => {\n // Validate the observer\n if (!observer) return () => {};\n\n // Validate the target element\n if (!targetEl) {\n throw new Error(\"A valid DOM element is required\");\n }\n const { config } = options;\n try {\n // Start observing the target element for configured mutations\n observer.observe(targetEl, config);\n } catch (e) {\n KosLog.error(e);\n }\n return () => {\n // Stop observing the target element\n if (observer) {\n observer.disconnect();\n }\n };\n }, [observer, targetEl, options]);\n}\n","import {\n IntersectionStrategy,\n IntersectionStrategyState,\n} from \"./intersection-strategy\";\n\nexport const DomIntersectionStrategy: IntersectionStrategy = {\n validateStart: function (_state: IntersectionStrategyState): boolean {\n return true;\n },\n validateStop: function (state: IntersectionStrategyState): boolean {\n const boundingRect = (\n state.event.currentTarget as HTMLElement\n ).getBoundingClientRect();\n const [clientX, clientY] = state.xy;\n\n const isOutside =\n clientX < boundingRect.left ||\n clientX > boundingRect.right ||\n clientY < boundingRect.top ||\n clientY > boundingRect.bottom;\n\n return isOutside;\n },\n};\n","import { useGesture } from \"@use-gesture/react\";\nimport { useRef } from \"react\";\nimport { KosLog } from \"../../../core/core/log\";\nimport { DomIntersectionStrategy } from \"./strategy/dom-intersection-strategy\";\nimport { IntersectionStrategy } from \"./strategy/intersection-strategy\";\n\ninterface PressHandlers {\n onPressed?: () => void;\n onRelease?: () => void;\n intersectionStrategy?: IntersectionStrategy;\n}\n\nconst logger = KosLog.createLogger({\n name: \"usePressGesture\",\n group: \"kos-hooks\",\n});\nexport function usePressGesture({\n onPressed,\n onRelease,\n intersectionStrategy = DomIntersectionStrategy,\n}: PressHandlers) {\n const isDraggingInside = useRef<boolean>(false);\n\n const bind = useGesture({\n onDragStart: (state) => {\n logger.info(\"onDragStart\", state.type);\n if (!intersectionStrategy.validateStart(state)) return;\n\n if (onPressed) onPressed();\n isDraggingInside.current = true;\n },\n onDrag: (state) => {\n logger.info(\"onDrag\", state.type);\n if (!isDraggingInside.current) return;\n\n if (intersectionStrategy.validateStop(state)) {\n if (onRelease) onRelease();\n isDraggingInside.current = false;\n }\n },\n onDragEnd: (state) => {\n logger.info(\"onDragEnd\", state.type);\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n },\n });\n\n const handlePointerDown = () => {\n if (onPressed) onPressed();\n isDraggingInside.current = true;\n };\n\n const handlePointerUp = () => {\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n };\n\n const handlePointerOut = () => {\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n };\n\n return {\n dom: bind,\n mesh: () => {\n return {\n onPointerDown: handlePointerDown,\n onPointerUp: handlePointerUp,\n onPointerOut: handlePointerOut,\n };\n },\n };\n}\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect, KosCore } from \"../../core\";\nexport const useProjectReload = () => {\n const [reloading, setReloading] = useState(false);\n const core = KosCore.getInstance();\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (!core) return;\n if (core.reloading === reloading) return;\n setReloading(core.reloading);\n });\n\n return () => {\n disposer();\n };\n }, [core, reloading]);\n\n return [reloading];\n};\n","import { useCallback, useMemo, useState } from \"react\";\nimport { format } from \"date-fns\";\n\ntype TimeFormat = \"2-digit\" | \"numeric\";\n\nexport function useHourValues(hour12 = false, format: TimeFormat = \"2-digit\") {\n return useMemo(() => {\n const hours = hour12 ? 12 : 24;\n\n return Array.from({ length: hours }, (_, i) => {\n const hour = hour12 && i === 0 ? 12 : i % hours;\n\n return {\n id: i,\n label:\n format === \"2-digit\"\n ? hour.toString().padStart(2, \"0\")\n : hour.toString(),\n };\n });\n }, [format, hour12]);\n}\n\nexport function useTimeValues(\n length: number,\n format: TimeFormat = \"2-digit\",\n labelOffset = 0,\n valueOffset = 0\n) {\n return useMemo(\n () =>\n Array.from({ length }, (_, i) => {\n const label = String(i + labelOffset);\n\n return {\n id: i + valueOffset,\n label: format === \"2-digit\" ? label.padStart(2, \"0\") : label,\n };\n }),\n [length, labelOffset, valueOffset, format]\n );\n}\n\nexport function useAmPmValues(locale = \"en-US\") {\n return useMemo(\n () =>\n [\"AM\", \"PM\"].map((period) => {\n const formattedPeriod = new Intl.DateTimeFormat(locale, {\n hour: \"2-digit\",\n hour12: true,\n }).formatToParts(new Date().setHours(period === \"AM\" ? 0 : 12))[2]\n .value;\n\n return { id: formattedPeriod, label: formattedPeriod };\n }),\n [locale]\n );\n}\n\nexport interface UseTimeOptionsProps {\n formatOptions?: Intl.DateTimeFormatOptions;\n locale?: string;\n}\n\nexport function useTimeOptions({\n formatOptions: {\n hour12 = true,\n hour = \"2-digit\",\n minute = \"2-digit\",\n second = \"2-digit\",\n } = { hour12: true, hour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\" },\n locale = \"en-US\",\n}: UseTimeOptionsProps) {\n const hourOptions = useHourValues(hour12, hour);\n const minuteOptions = useTimeValues(60, minute);\n const secondOptions = useTimeValues(60, second);\n const amPmOptions = useAmPmValues(locale);\n\n return {\n hourOptions,\n minuteOptions,\n secondOptions,\n amPmOptions,\n };\n}\n\nexport function useFormattedTime(date: Date, formatString: string): string {\n const formattedDate = format(date, formatString);\n\n return formattedDate;\n}\n\nexport interface UseTimeProps {\n formatOptions?: Intl.DateTimeFormatOptions;\n initialDate?: Date;\n locale?: string;\n format?: string;\n}\n\nexport function useTimeProps({\n formatOptions,\n initialDate = new Date(),\n locale = \"en-US\",\n format = \"HH:mm\",\n}: UseTimeProps) {\n const [date, setDate] = useState(initialDate);\n\n const setHours = useCallback((hours: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setHours(Number(hours));\n\n return newDate;\n });\n }, []);\n\n const setMinutes = useCallback((minutes: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setMinutes(Number(minutes));\n\n return newDate;\n });\n }, []);\n\n const setSeconds = useCallback((seconds: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setSeconds(Number(seconds));\n\n return newDate;\n });\n }, []);\n\n const setTime = useCallback((date: Date) => {\n const newDate = new Date(date);\n\n setDate(newDate);\n }, []);\n\n const formattedTime = useFormattedTime(date, format);\n\n const { hourOptions, minuteOptions, secondOptions, amPmOptions } =\n useTimeOptions({\n formatOptions,\n locale,\n });\n\n return {\n amPmOptions,\n formattedTime,\n hourOptions,\n minuteOptions,\n secondOptions,\n setHours,\n setMinutes,\n setSeconds,\n setTime,\n time: new Date(date),\n };\n}\n","import { useMemo } from \"react\";\nimport { useKosRegions } from \"./use-kos-regions\";\nimport { useTimeProps, type UseTimeProps } from \"./use-time-props\";\n\nexport const useRegionTimeProps = (props?: UseTimeProps) => {\n const { regionModel } = useKosRegions();\n\n const formatOptions = useMemo(() => {\n return { hour12: regionModel?.is12HourTimeFormat };\n }, [regionModel?.is12HourTimeFormat]);\n\n return useTimeProps({\n ...props,\n locale: regionModel?.regionId,\n format: regionModel?.selectedTimeFormat,\n formatOptions,\n });\n};\n","import LoadingMessage from \"../components/loading-message\";\nimport { useProjectReload } from \"./use-project-reloading\";\n\ninterface ProjectReloadingProps {\n reloading: boolean;\n}\n// react HOC to provide a NodeTargetContainer to a component\nexport function withProjectReloading<\n T extends ProjectReloadingProps = ProjectReloadingProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof ProjectReloadingProps>) => {\n const [reloading] = useProjectReload();\n\n return reloading ? (\n <LoadingMessage message=\"Wait a moment while your project reloads...\" />\n ) : (\n <WrappedComponent {...(props as T)} />\n );\n };\n}\n"],"names":["HEADER_METHOD","HEADER_TOPIC","HEADER_URL","HEADER_REQUEST_ID","HEADER_RESPONSE_ID","STATUS","HEADER_DESTINATION_ADDR","HEADER_SOURCE_ADDR","HEADER_REQUEST_TYPE","HEADER_ORDERED","HEADER_WORK_TRACKER","HEADER_CONTENT_TYPE","HEADER_CACHE_CONTROL","HEADER_FOS_REQUEST_ID","LOGIN_HOST","PORT","LOGIN_URL","KOS_MODEL_ID","KosWsEvents","KosMockEvents","log","subscriptions","getNextUniqueId","subscribe","eventType","callback","id","publish","msg","headers","count","responseId","response","reset","key","convertFileSizeRaw","bytes","decimals","k","dm","sizes","i","value","scale","wrapPromise","promise","status","suspender","res","err","uuid","c","r","applyMixins","derivedCtor","baseCtors","baseCtor","name","descriptor","deltas","projectedModels","currentModels","newIds","entity","modelId","resolveContainerDeltas","container","onAddItem","onRemoveItem","idMapper","entities","mappedLayers","removedIds","toAdd","resolveListDeltas","resolveItemListDeltas","items","processId","prefix","_id","formatter","DIVISIONS","formatDateSince","date","duration","division","debounce","context","func","timeout","timer","args","FeatureFlagService","initialFlags","__publicField","flag","newFlags","KosFeatureFlags","getQueryParams","query","pair","val","result","hslToHex","h","s","l","a","f","color","hslStringToHex","hsl","match","resolveVariable","element","variable","variableToHex","PROFILE_TOOLS_PREVIEW","PROFILE_RELAX_STORE_VALIDATION","PROFILE_LOG_DEBUG","PROFILE_LOG_INFO","defaultConfig","config","_a","configObj","KosGlobalConfig","resolveKosProfiles","hasKosProfile","profile","isKosLoggingEnabled","defaultMapper","data","_model","parsedData","mapDataToModel","model","mapper","partial","kosAction","deletionMap","KosDeletionManager","timeouts","SubscriptionHandlers","DependencyModels","FutureService","ChildModels","ParentModel","LogConfig","ReferenceConfig","KosModelSymbol","ModelEffects","dataMappers","dataLoaders","propertyMappers","indexExtensions","registerExtensionPoint","extensionPoint","_ExtensionManager","extension","extensions","loader","mappers","_interim","ExtensionManager","DependencyLifecycle","resolveLogLevelProfile","showDebugLogProfile","showInfoLogProfile","getLogLevel","params","profileLogLevel","logLevel","getKosMessageLogging","getLogMessageToStudio","WS_LOG","originalFactory","enableMessageLogging","enableStudioMessageLogging","methodName","loggerName","rawMethod","style","level","_level","wsLog","styles","received","conditionallyLog","fn","KosLog","group","str","createStudioMessage","path","requestId","method","destinationAddress","createFosBaseMessage","ordered","tracker","createBaseMessage","bridge","createMessageBody","body","_msg","createHeaders","_headers","callbackFn","createReadableStream","sent","controller","push","done","createStudioMessageRequest","createKosMessage","requestType","sendKosMessage","options","wrappedMsg","socketTransport","KosCore","createStudioMessageResponse","sendStudioMessageRequest","sendStudioMessage","createBroadcastMessageResponse","topic","createKosHtpMessageResponse","type","sourceAddress","createKosMessageResponse","sendBroadcastMessage","sendKosMessageResponse","sendKosHttpMessageResponse","getMessageBody","payload","skipParse","kosChild","target","createPropKey","createOptionKey","DEFAULT_OPTION_KEY","kosParentAware","constructor","parentId","resolveParameters","modelData","_value","acc","curr","propRegex","_depId","prop","handler1","kosContext","KosContextManager","modelInstance","_b","e","dependencies","dependency","obs","makeAutoObservable","kosModel","kosCompanion","modelType","_target","_propertyKey","originalMethod","ctx","kosLogger","kosModelEffect","props","kosReference","kosDependency","lifecycle","kosSubscribe","handler","websocket","condition","t","action","kosTopicHandler","_payload","transform","fos","KosModelState","KosModelEvents","PROMISE_TIMEOUT","ModelError","message","rejectAfterDelay","ms","timeoutId","_","reject","transitionToActive","transitionToReady","transitionToLoad","transitionToUnload","transitionToInit","Transitions","TransitionMap","createModelDependency","_dataModelId","dataModelId","getDependenciesByLifecycle","dependentModel","readyFn","cancel","p","executeListLifecycle","sourceModel","models","sourceLifecycle","childPromises","modelPromise","failedChildren","timeoutPromise","timeoutCancel","executeChildrenModelLifecycle","child","executeDependentModelLifecycle","failed","isKosDataModel","isKosModelContainer","resolveChild","attribute","ObservableMap","activeMachine","machine","createMachine","state","transition","invoke","interpret","_service","onlineMachine","service","active","online","immediate","fsm","WebSocketBridgeTransport","address","processKosMessage","MESSAGE_SEPARATOR","SEPARATOR","HEADER_SEPARATOR","headerText","line","header","raw","processKosSnifferMessage","BaseTransport","host","port","protocol","alias","onConnectionEstablished","onConnectionLost","Transport","EventBus.subscribe","makeObservable","observable","event","subscriptionTopic","msgBody","msgHeaders","snifferHeaders","snifferBody","EventBus.publish","ex","runInAction","returnData","BridgeTransport","addr","that","BridgeMessageTransport","FosTransport","KosTransport","TransportFactory","fosPort","Logger","KosWSTransportStatus","WebSocketEvents","WebSocketTransport","token","initialize","initialized","computed","reaction","connectionEstablished","ev","connId","dstAddr","_c","socket","_d","unsubscribe","when","logger","MODEL_LOADER","handlerFactory","subscription","resolvedTopic","offlineHandler","resolveTopic","_topic","KosModel","modelTypeName","modelManager","activeStatus","onlineStatus","error","dispose","resolve","kosAutoEffect","transitionStatus","errorDispose","targetDispose","loadedContext","modelEffects","effect","autoRunHandler","disposer","autorun","childrenUnload","unsub","onlineUnsub","offlineUnsub","_subscription","_lifecycle","sub","visitor","decoratedChildren","resolvedChildren","children","uniqueChildren","filtered","isKosCompanionTypeFactory","obj","MODEL_DELETION_DELAY","KosModelManager","registry","modelKey","deleteVistor","activeModel","typeId","modelFilter","modelRegistry","modelFactory","dependencyId","usedBy","uses","index","usesIndex","companionRegistration","modelRegistration","modelCreator","ModelClass","dataInstance","companionSpec","companionModelType","compType","companionId","companionModel","instance","executeLoaderExtension","contextData","executeDataMapperExtension","executePropertyMapperExtension","PLUGIN_EXTENSION_NAME","PluginExtensionManager","component","KosCoreState","KosCoreEvents","coreFsm","core","whenReady","dataModel","destroyKosModel","unloadKosModel","resetKosModel","isKosModelReady","getKosModelType","getKosModel","getKosModelSync","findModels","predicate","m","findModel","getKosCompanionModel","getAllKosCompanionModels","resolveKosCompanion","resolver","isKosModel","KosModelFactory","factory","Kos","coreModels","preloadModels","companionModels","RegistrationManager","root","registration","preload","register","isKosModelRegistration","parentType","companion","companions","registerLegacyModel","registerKosModel","registerCompanionModel","preloadKosModel","isUpdateable","item","KosBaseModelRegistration","KosModelRegistrationFactory","optionsFactory","SingletonKosModelRegistrationFactory","getDefaultProtocol","defaultProtocol","hostUrl","getDefaultHost","defaultHost","envHost","getDefaultPort","defaultPort","envPort","isReloadable","isUnloadable","AuthState","connectionAlias","ws","currentTime","elapsed","promises","transport","dataMapper","propertyMapper","WS_TIMEOUT","delay","fetchMessageFactory","kosFetchWs","url","urlObj","TIMEOUT","messageFactory","responseMsg","BASE_URL","kosFetch","KosModelVisitor","rootModel","stopVisiting","resolveBaseUrl","ERROR_UNKNOWN","clientRequest","endpoint","fullUrl","fetchOptions","createClient","MiddlewareChain","middleware","next","processMiddleware","chain","updateModelRegistration","updateCompanionModelRegistration","KosObservableData","ObservableDataMap","property","createAtom","initialData","createObservableData","BaseClass","ObservableData","od","TOPIC","pairedClientHeartbeat","relationshipId","onAbort","waitTime","beatTime","lastHeartBeat","_waitTime","waitInterval","timeDiff","_beatTime","beatInterval","cleanUpHeartbeat","handleAbort","pipe","fns","x","v","BASE_OPTIONS","retryWithExponentialBackoff","operation","attempt","_options","maxAttempts","baseDelayMs","backoffFactor","delayMs","resolveServiceUrl","deleteModel","_fetch","urlOverride","studio","destinationAddressOverride","addCommonParams","getAll","FetchError","getOne","getModelById","resolvedUrl","add","modifyModel","ServiceFactory","basePath","getAllPath","getOnePath","deleteModelPath","addModelPath","modifyModelPath","mock","_sessionKey","getKosSessionKey","isLocalRefId","waitForRequest","op","sendRequest","requestPromise","refId","syncPublish","_requestId","responsePromise","contextMap","KosContextBean","parent","resolveKosContext","arraysAreEqual","arr1","arr2","item1","KosContainerIndex","map","currentValue","values","existing","set","tempMap","tempData","valueItem","observeComputedProperties","keys","descriptors","isComputedProp","newValue","oldValue","KosModelContainer","extensionOptions","indexMap","tmp","idx","b","sortKey","list","ids","defer","_disposer","_entries","_values","_reverseMap","change","fnIndexs","computedDisposers","observe","d","indexName","indexKey","thisArg","compareFn","callbackfn","KosDataContainer","observableData","isObservable","KosRegistration","childRegistration","KosSingletonRegistration","KosToken","BrowserKosRouter","middlewares","rawReq","req","route","routePath","part","param","paths","requestPath","queryString","routeParts","requestParts","unsubscribeIntentService","intent","fireIntent","intentMap","registerIntentHandler","existingHandlers","KosFetchMethods","kosWhen","kosComputed","kosEffect","kosObservable","FUTURE_NOT_ASSIGNED","EVENT_TROUBLE_ADDED","EVENT_TROUBLE_REMOVED","KosCoreModelPropertyMapper","Topics","URL","hasDecimals","option","postModel","modifyConfigBean","getConfigBean","isBoolean","isNumber","evaluateScopes","scopes","overrides","flattenObject","parentKey","newKey","mapDtoToConfigBeanModel","dto","bean","flattened","mapUpdateDtoToConfigBeanModel","previousValue","mapConfigBeanModelToDto","buildConfigBeanModel","configBeanOptions","matchValue","patterns","pattern","CONFIG_BEAN_MODEL_TYPE","PATH_PROP","ConfigBeanModelImpl","modifyConfigBeanService","getConfigBeanService","schemaResponse","request","configBean","__decorateClass","ConfigBean","kosConfigBean","lazy","serviceBasePath","getRegionInfo","getRegions","UnitTupleKeys","UnitTupleKeys2","timeTuples","unitSystemMapReducer","unitSystem","system","units","unit","unitTuple","measureMapReducer","systemAcc","measures","measure","systemMeasure","defaultMeasureMapReducer","MODEL_TYPE","RegionInfoModelImpl","_timeFormatId","selectedTimeFormatId","resolvedTimeFormatId","_dateFormatId","selectedDateFormatId","timeFormatId","dateFormatId","unitSystemId","_unit","measureUnitSystems","unitSystemUnits","defaultUnit","fromUnit","toUnit","fromOffset","fromScale","toScale","toOffset","from","to","fromName","toName","measureSystems","regions","region","regionInfo","timeFormat","dateFormat","Registration","createUnitSource","source","defaultSystem","defaultMeasure","convert","RegionInfo","defaultToSource","generateEvenlyDistributedArray","start","end","step","generateIntervalArray","interval","conversionMap","configOptionsFactory","schema","displayOptionsFactory","isEnum","convertFormats","format","secondsToFormattedTime","secondsSinceMidnight","formatString","midnight","time","SERVICE_PATH_PROP","KosConfigPropertyImpl","defaultUnitSystem","converter","defaultOptions","backend","display","_val","current","timeFormatString","currentSystem","locale","defaultFormatter","_formatter","formatOptions","globalMeasure","toMeasure","fromMeasure","_e","_measure","_g","_f","_i","_h","toSystem","_k","_j","fromSystem","updateValue","kosConfigProperty","optionsExpander","_converter","KosConfigPropertySpec","MultipleFutureHandler","defaultContext","future","FutureHandler","FUTURE_MODEL_TYPE","FutureFactory","isMock","FutureEndState","addModel","getFutures","deleteFuture","addFuture","modifyFuture","cancelFuture","mapDtoToFutureOptions","mapDtoToFutureModel","buildFutureModel","futureOptions","buildFuture","FutureModel","remaining","milliseconds","parts","FutureModel$1","api","HTTP_REQUEST_TOPIC","HTTP_RESPONSE_TOPIC","BrowserRouterModelImpl","_data","destination","src","code","BrowserRouter","FUTURE_CONTAINER_MODEL_TYPE","FutureContainerFactory","initiateFuture","futureModel","getFuture","FutureManager","FutureContainerModel","deleteFutureService","addFutureService","futureId","newFutureModel","FutureContainerModel$1","deleteKeyValue","namespace","updateKeyValue","getKeyValue","deleteKeyValueNamespace","KeyValueModelImpl","studioState","update","KeyValue","setTime","setDate","setTimezone","timezone","getTimezone","TOPIC_TIME_CHANGE","TOPIC_DAY_CHANGE","TOPIC_TIMEZONE_CHANGE","KosTimeModelImpl","tz","KosTime","LogBlockContainerModelImpl","getKosConnectionId","SERVICE_PATH","getLogStreams","API","subscribeToLogStream","stream","nodeId","unsubscribeFromLogStream","createOverride","getLogStreamBlocks","getLogStreamBlock","blockId","LogBlockModelImpl","blockData","lines","replace","baseLines","LogBlock","LogBlockContainer","LogStreamModelImpl","firstBlock","currentBlockId","block","blockNum","lastBlock","previousBlocks","secondLastBlock","queue","resolveQueue","currentIndex","prev","latestBlock","newLines","LogStream","TOPIC_ADD_BLOCK","TOPIC_UPDATE_BLOCK","TOPIC_REMOVE_BLOCK","TOPIC_LOG_LINES","TOPIC_ADD_STREAM","LogStreamContainerModelImpl","streamName","logStream","streams","LogStreamContainer","isRankedInfo","isRoleAwareInfo","isColorAwareInfo","defaultTroubleRankMapper","trouble","info","defaultTroubleColorMapper","defaultTroubleRoleMapper","getTroubles","resolveTrouble","troubleId","futureResponse","bulkResolveTroubles","troubleIds","EXTENSION_TROUBLE_DATA_MAPPER","troubleMappers","EXTENSION_TROUBLE_MAPPER","troublePathFactory","ifaces","iface","troubleDataFactory","troubleExtension","ResolvableTroubleHandler","BlockPumpTroubleHandler","TroubleHandlerFactory","isDeferAware","TroubleModelImpl","resolvable","tags","clientData","rank","createTime","role","rest","kosFuture","Trouble","troubleRankMapper","troubleColorMapper","troubleRoleMapper","Troubles","TroubleContainerModelImpl","_troubles","newTrouble","removed","TroubleContainer","getArtifacts","getLastRequest","requests","lastRequest","provider","currentConfig","currentLastUpdateTime","mapOTAArtifactResponseToUpdaterItem","otaArtifactResponse","artifactInfo","manifest","OtaModelImpl","artifacts","Ota","getSoftwareInfos","SoftwareInfoModelImpl","arr","cur","nodes","updatedList","el","SoftwareInfo","getStateBeanData","StateBeanModelImpl","stateBean","StateBean","StatePropModelImpl","StateProp","getStateProps","getTranslations","rootUrl","getLocalizationDescriptor","getKosLocalizationDescriptor","CONTEXT_LANG_RESOLVER","extractOptions","isBasicOptions","isDataObject","defaultValue","flattenedChild","mergeObjects","base","overlay","expandMacros","text","regex","replacedText","replaceText","splitKey","currentNamespace","_key","TranslationModelImpl","_locale","langs","reversed","allTranslations","lang","translationsPath","results","newData","ns","contextKey","previous","Translation","pathJoin","sep","defaultResolver","namespaceDescriptor","localePath","TranslationContainerModelImpl","firstLocale","namespaceDefault","translation","TranslationContainer","TranslationContext","KosTranslations","tc","troubleByTypeReducer","WS_EVENT_TYPE","WsEventFactory","stringify","WsEventModel","isSend","isUnique","msgId","rawKey","rawData","getSerialNumber","getDeviceDetails","TOPIC_CRITICAL_DATA_CHANGED","TOPIC_CRITICAL_DATA_AVAILABLE","DeviceModelImpl","nodeType","nodeName","device","serialNumber","Device","NetworkInterfaceModelImpl","NetworkInterface","getNetworkInterfaces","NetworkInterfaceContainerModelImpl","networkInterfaces","networkInterfaceData","networkInterfaceModel","NetworkInterfaceContainer","getStorageDevices","StorageDeviceModelImpl","StorageDevice","TOPIC_STORAGE_AVAILABILITY","StorageDeviceContainerModelImpl","devices","storageDevice","StorageDeviceContainer","getAvailableUpdates","installUpdate","manifestId","deviceId","UsbUpdateModelImpl","UsbUpdate","UsbUpdateContainerModelImpl","updates","allKeys","UsbUpdateContainer","CoreModels","Registry","PRELOAD","registerCoreModels","KosModelRegistry","_KosModelRegistry","CoreExtensionManager","subscribeStore","stateKey","sessionId","toolState","REGION_PATH","REGION_ATTRIBUTE","REGION_ID","updateRegion","TIMER_EVENT","TIMER_END","isConfigProperty","KosTimer","defaultActions","timeoutValue","timerAction","existingAction","actionName","actions","updatedActions","timers","executeOnTimer","TimerManager","now","REGION_SETTINGS_PATH","TIMEZONE_ATTRIBUTE","REGION_TIMEZONE_ID","updateTimeZone","timezoneInfo","isFutureResponse","propertyKey","original","kosStateBean","kosStateProp","studioLogin","username","password","login","configResponse","studioStartPasswordReset","userId","startPasswordReset","studioResetPassword","resetPassword","studioAcceptOrgInvitation","acceptOrgInvitation","run","keyframes","loadingDot","css","Portal","createPortal","LoadingMessage","jsx","jsxs","MessageContainer","styled","ErrorBoundary","React","errorInfo","statusMap","ProgressBar","title","subtitle","progressBarContainer","progressContainer","titleContainer","progress","indeterminate","defaultProps","KosModelContext","createContext","useContextModel","useContext","KosModelProvider","setModel","useState","setKosModel","useCallback","defaultNestedProps","NestedModelContext","KosModelCollectionProvider","setModels","prevModels","DEFAULT_FILTER","useContextModelHierarchy","filter","useMemo","useModelFromHierarchy","DefaultLoader","KosModelLoader","fallback","modelProps","ErrorBoundaryWithFallback","Suspense","KosModelLoaderDisplay","setCurrentModel","isReady","setIsReady","hierarchyContext","useEffect","Fragment","DEFAULT_TRANSLATIONS","CreateModelTranslationsContext","CreateModelTranslationsProvider","translations","merged","fetchKosCore","kosCore","KosContext","initKosProvider","resource","observer","setOnline","useKosCore","MAX_RETRIES","waitForRetry","depth","cache","fetchData","fetcher","entry","useSuspenseData","fetchModel","modelOptions","activate","retryCount","_factory","useKosModel","destroyOnUnmount","kosCoreContext","ready","setReady","setError","waitForModel","_ready","useKosTime","KosTimeContext","KosTimeProvider","useKosTimeContext","useSoftwareInfo","withSoftwareInfo","WrappedComponent","SoftwareInfoContext","SoftwareInfoProvider","useSoftwareInfoContext","TokenContext","TokenProvider","TranslationContainerContext","KosTranslationProvider","appContext","descriptorResolver","localization","setLocalization","setTranslations","resolvedRootUrl","initTools","descriptorPromises","localizationDescriptor","namespaceKey","initLocalization","_rootUrl","content","useKosTranslationContext","useDevice","withDevice","corePromise","withKosTime","useNetworkInterfaceContainer","withNetworkInterfaceContainer","useOta","withOta","useOutsideAlerter","ref","onAction","handleClickOutside","handleEscFunction","OutsideAlerter","wrapperRef","useRef","useStateProperty","stateProp","setValue","waitForProp","useStorageDeviceContainer","inserted","setInserted","setDevices","withStorageDeviceContainer","useTimer","timerName","onTimerExpired","timerEventActions","autoStart","remainingTime","escapeRegExp","toEscape","escapableChars","isRegExp","toTest","isString","replaceString","_toMatch","toMatch","length","stringComponentInsert","_source","substituteBlocks","stringValue","componentsMap","blocks","Trans","i18nKey","defaults","components","translated","fetchTranslationContainer","fetchTranslations","additionalNamespaces","trans","additional","useKosTranslation","baseOptions","allNamespaces","defaultNamespace","translationModel","i18n","expandedKey","useTranslationContainer","withTranslationContainer","useTroubleModel","useTroubleContainerModel","useTroublePresence","troubleType","setActive","troubles","setTroubles","onComplete","troublesByType","activeTroubles","withTroubleContainer","useUsbUpdateContainer","updateAvailable","setUpdateAvailable","setUpdates","withUsbUpdateContainer","useConfigBean","propKey","setConfig","reducer","useConfigProperty","configProperty","optionsTransformer","dispatch","useReducer","handleUpdate","mapped","getDaysInMonth","month","year","yearToUse","daysInEachMonth","getDays","getDaysArray","numberOfDays","daysAry","getMonthsArray","getYearsArray","number","yearsArray","getFormattedYearsArray","range","fullYearsArray","getFormattedMonthsArray","monthFormat","getFormattedDate","day","displayOrder","correctedMonth","monthName","yearName","dayName","getFormattedYear","getFormattedMonth","getCalendarMonthArray","dayOptions","formattedYear","firstDay","isValidDate","zeroIndexedMonth","getLastDayOfMonth","getDayStrings","dayFormat","useDateArrays","yearRange","daysOfWeekFilter","yearFormat","useYears","yearsOptionsArray","useYearsOptions","monthsArray","useMonths","monthsOptionsArray","useMonthsOptions","daysArray","useDays","daysOptionsArray","useDayOptions","calendarDayArray","useCalendarDayArray","dayNamesArray","useDayNames","rawYearsArray","monthLabelsArray","isFilteredDayOfWeek","filters","dateToCheck","rawDaysArray","useFormattedDate","indexedMonth","dayOptionsArray","DateDisplayFormat","useDateProps","yearProp","monthProp","dayProp","yearsRange","setYear","setYearRange","setMonth","setDay","formattedDate","nextMonth","lastValidDay","prevMonth","nextYear","prevYear","useRegionalTimeDate","formattedTime","setFormattedTime","setFormattedDate","ignoreDate","dateToFormat","parseISO","useDateRelativeData","secondsFromMidnight","hours","setHours","minutes","setMinutes","seconds","setSeconds","numericValue","_hours","_minutes","_seconds","useDateRelativeConfig","timeActions","timeoutRef","DEFAULT_FORMAT_MAP","useKosDateFormats","dateFormatMap","dateFormats","setDateFormats","selectedDateFormat","setSelectedDateFormat","cleanup","handleDateFormatChange","o","DEFAULT_OPTION_MAP","useKosTimeZones","optionsMap","timeZones","setTimeZones","selectedTimeZone","setSelectedTimeZone","DEFAULT_REGION_MAP","useKosRegions","regionMap","setRegions","selectedRegion","setSelectedRegion","useKosTimeFormats","timeFormatMap","timeFormats","setTimeFormats","selectedTimeFormat","setSelectedTimeFormat","handleTimeFormatChange","useLocalComputed","DEFAULT_OPTIONS","useMutationObserver","targetEl","cb","setObserver","DomIntersectionStrategy","_state","boundingRect","clientX","clientY","usePressGesture","onPressed","onRelease","intersectionStrategy","isDraggingInside","bind","useGesture","handlePointerDown","handlePointerUp","handlePointerOut","useProjectReload","reloading","setReloading","useHourValues","hour12","hour","useTimeValues","labelOffset","valueOffset","label","useAmPmValues","period","formattedPeriod","useTimeOptions","minute","second","hourOptions","minuteOptions","secondOptions","amPmOptions","useFormattedTime","useTimeProps","initialDate","prevDate","newDate","useRegionTimeProps","regionModel","withProjectReloading"],"mappings":";;;;;;;;;;;;;;;;AAAO,MAAMA,KAAgB,UAChBC,KAAe,SACfC,KAAa,OACbC,KAAoB,cACpBC,KAAqB,eACrBC,KAAS,UACTC,KAA0B,YAC1BC,KAAqB,YACrBC,KAAsB,QACtBC,KAAiB,WACjBC,KAAsB,WACtBC,KAAsB,gBACtBC,KAAuB,iBAEvBC,KAAwB,aACxBC,KAAa,QAAQ,IAAI,iBAAiB,oBAC1CC,KAAO,QAAQ,IAAI,gBAAgB,QAEnCC,KAAY,GAAGF,EAAU,IAAIC,EAAI,IAEjCE,KAAe;AAEhB,IAAAC,uBAAAA,OACVA,EAAA,OAAO,oBACPA,EAAA,WAAW,uBAFDA,IAAAA,MAAA,CAAA,CAAA,GAKAC,uBAAAA,OACVA,EAAA,cAAc,qBADJA,IAAAA,MAAA,CAAA,CAAA;AC1BZC,EAAI,KAAK,wBAAwB;AACjC,WAAW,MAAM,WAAW,OAAO;AACnC,WAAW,IAAI,gBAAgB,WAAW,IAAI,iBAAiB,CAAA;AAC/D,MA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