@kosdev-code/kos-ui-sdk 3.0.26 → 3.0.28

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 (339) hide show
  1. package/.kos.json +2 -1
  2. package/common/events/async-event-bus.d.ts +8 -11
  3. package/common/events/async-event-bus.d.ts.map +1 -1
  4. package/common/events/eventBus.d.ts +1 -18
  5. package/common/events/eventBus.d.ts.map +1 -1
  6. package/core/core/companion-instantiator.d.ts +5 -0
  7. package/core/core/companion-instantiator.d.ts.map +1 -1
  8. package/core/core/decorators/index.d.ts +1 -0
  9. package/core/core/decorators/index.d.ts.map +1 -1
  10. package/core/core/decorators/kos-child.d.ts +2 -3
  11. package/core/core/decorators/kos-child.d.ts.map +1 -1
  12. package/core/core/decorators/kos-companion.d.ts +26 -88
  13. package/core/core/decorators/kos-companion.d.ts.map +1 -1
  14. package/core/core/decorators/kos-container-aware-reconcile.test-d.d.ts +2 -0
  15. package/core/core/decorators/kos-container-aware-reconcile.test-d.d.ts.map +1 -0
  16. package/core/core/decorators/kos-container-aware.d.ts +191 -420
  17. package/core/core/decorators/kos-container-aware.d.ts.map +1 -1
  18. package/core/core/decorators/kos-execute-service-request.d.ts +7 -11
  19. package/core/core/decorators/kos-execute-service-request.d.ts.map +1 -1
  20. package/core/core/decorators/kos-execution-context.d.ts +14 -31
  21. package/core/core/decorators/kos-execution-context.d.ts.map +1 -1
  22. package/core/core/decorators/kos-future-aware.d.ts +21 -74
  23. package/core/core/decorators/kos-future-aware.d.ts.map +1 -1
  24. package/core/core/decorators/kos-http-decorators.d.ts +18 -62
  25. package/core/core/decorators/kos-http-decorators.d.ts.map +1 -1
  26. package/core/core/decorators/kos-logger-aware.d.ts +10 -60
  27. package/core/core/decorators/kos-logger-aware.d.ts.map +1 -1
  28. package/core/core/decorators/kos-mixin.d.ts +69 -0
  29. package/core/core/decorators/kos-mixin.d.ts.map +1 -0
  30. package/core/core/decorators/kos-model-effect.d.ts +10 -9
  31. package/core/core/decorators/kos-model-effect.d.ts.map +1 -1
  32. package/core/core/decorators/kos-multiple-future-aware.d.ts +21 -94
  33. package/core/core/decorators/kos-multiple-future-aware.d.ts.map +1 -1
  34. package/core/core/decorators/kos-reload-aware.d.ts +14 -16
  35. package/core/core/decorators/kos-reload-aware.d.ts.map +1 -1
  36. package/core/core/decorators/kos-service-request.d.ts +80 -238
  37. package/core/core/decorators/kos-service-request.d.ts.map +1 -1
  38. package/core/core/decorators/kos-state-machine.d.ts +35 -275
  39. package/core/core/decorators/kos-state-machine.d.ts.map +1 -1
  40. package/core/core/decorators/kos-topic-handler-flow-control.d.ts +11 -3
  41. package/core/core/decorators/kos-topic-handler-flow-control.d.ts.map +1 -1
  42. package/core/core/decorators/kos-trouble-aware.d.ts +9 -43
  43. package/core/core/decorators/kos-trouble-aware.d.ts.map +1 -1
  44. package/core/core/decorators/kos-view-model.d.ts +20 -100
  45. package/core/core/decorators/kos-view-model.d.ts.map +1 -1
  46. package/core/core/decorators/kosModel.d.ts.map +1 -1
  47. package/core/core/decorators/kosTopicHandler.d.ts +28 -89
  48. package/core/core/decorators/kosTopicHandler.d.ts.map +1 -1
  49. package/core/core/decorators/propKeys.d.ts +1 -0
  50. package/core/core/decorators/propKeys.d.ts.map +1 -1
  51. package/core/core/indexing/index.d.ts +2 -4
  52. package/core/core/indexing/index.d.ts.map +1 -1
  53. package/core/core/indexing/kos-container-index-aware.d.ts +17 -48
  54. package/core/core/indexing/kos-container-index-aware.d.ts.map +1 -1
  55. package/core/core/indexing/kos-index-aware.d.ts +11 -37
  56. package/core/core/indexing/kos-index-aware.d.ts.map +1 -1
  57. package/core/core/kos-container-index.d.ts +11 -0
  58. package/core/core/kos-container-index.d.ts.map +1 -1
  59. package/core/core/kos-container-model.d.ts +11 -32
  60. package/core/core/kos-container-model.d.ts.map +1 -1
  61. package/core/core/kos-data-container.d.ts +6 -6
  62. package/core/core/kos-data-container.d.ts.map +1 -1
  63. package/core/core/kosCore.d.ts +7 -4
  64. package/core/core/kosCore.d.ts.map +1 -1
  65. package/core/core/kosModel.d.ts +16 -8
  66. package/core/core/kosModel.d.ts.map +1 -1
  67. package/core/core/kosModelManager.d.ts +2 -3
  68. package/core/core/kosModelManager.d.ts.map +1 -1
  69. package/core/core/lifecycle/constants.d.ts +6 -2
  70. package/core/core/lifecycle/constants.d.ts.map +1 -1
  71. package/core/core/lifecycle/kosCoreLifecycle.d.ts +11 -1
  72. package/core/core/lifecycle/kosCoreLifecycle.d.ts.map +1 -1
  73. package/core/core/lifecycle/kosModelLifecycle.d.ts +6 -0
  74. package/core/core/lifecycle/kosModelLifecycle.d.ts.map +1 -1
  75. package/core/core/lifecycle/model-machine.d.ts +6 -0
  76. package/core/core/lifecycle/model-machine.d.ts.map +1 -1
  77. package/core/core/model/kos-fsm-manager.d.ts +6 -0
  78. package/core/core/model/kos-fsm-manager.d.ts.map +1 -1
  79. package/core/core/model/kos-offline-queue.d.ts +1 -1
  80. package/core/core/model/kos-subscription-manager.d.ts.map +1 -1
  81. package/core/core/model/service-response-store.d.ts +2 -15
  82. package/core/core/model/service-response-store.d.ts.map +1 -1
  83. package/core/core/reconnect/reconnect-fixture.d.ts +17 -0
  84. package/core/core/reconnect/reconnect-fixture.d.ts.map +1 -0
  85. package/core/core/registration/model-registration.d.ts.map +1 -1
  86. package/core/core/services/app-startup-service.d.ts +5 -13
  87. package/core/core/services/app-startup-service.d.ts.map +1 -1
  88. package/core/core/services/intent-service.d.ts +3 -12
  89. package/core/core/services/intent-service.d.ts.map +1 -1
  90. package/core/core/transport/mock/mock-frames.d.ts +3 -3
  91. package/core/core/transport/transport.d.ts +1 -1
  92. package/core/core/transport/transport.d.ts.map +1 -1
  93. package/core/core/transport/webSocketTransport.d.ts +10 -0
  94. package/core/core/transport/webSocketTransport.d.ts.map +1 -1
  95. package/core/types/model.d.ts +4 -8
  96. package/core/types/model.d.ts.map +1 -1
  97. package/core/types/service-response-store.d.ts +3 -11
  98. package/core/types/service-response-store.d.ts.map +1 -1
  99. package/core/types/utils/kos-fetch.d.ts +25 -37
  100. package/core/types/utils/kos-fetch.d.ts.map +1 -1
  101. package/core/util/abortable-when.d.ts +5 -6
  102. package/core/util/abortable-when.d.ts.map +1 -1
  103. package/core/util/ancestor-path-visitor.d.ts +14 -20
  104. package/core/util/ancestor-path-visitor.d.ts.map +1 -1
  105. package/core/util/container-utils.d.ts +26 -159
  106. package/core/util/container-utils.d.ts.map +1 -1
  107. package/core/util/date-utils.d.ts +9 -58
  108. package/core/util/date-utils.d.ts.map +1 -1
  109. package/core/util/debounce.d.ts +1 -8
  110. package/core/util/debounce.d.ts.map +1 -1
  111. package/core/util/kos-fetch.d.ts +1 -1
  112. package/core/util/kos-fetch.d.ts.map +1 -1
  113. package/core/util/kos-model-utils.d.ts +10 -11
  114. package/core/util/kos-model-utils.d.ts.map +1 -1
  115. package/core/util/model-attribute-utils.d.ts +5 -22
  116. package/core/util/model-attribute-utils.d.ts.map +1 -1
  117. package/core/util/model-type-guards.d.ts.map +1 -1
  118. package/core/util/promise-utils.d.ts +1 -26
  119. package/core/util/promise-utils.d.ts.map +1 -1
  120. package/core/util/service-factory.d.ts +5 -23
  121. package/core/util/service-factory.d.ts.map +1 -1
  122. package/core/util/service-request-error.d.ts +3 -5
  123. package/core/util/service-request-error.d.ts.map +1 -1
  124. package/core/util/service-response.d.ts +12 -67
  125. package/core/util/service-response.d.ts.map +1 -1
  126. package/core/util/transport-not-ready-error.d.ts +11 -13
  127. package/core/util/transport-not-ready-error.d.ts.map +1 -1
  128. package/core/util/when-ready.d.ts +1 -8
  129. package/core/util/when-ready.d.ts.map +1 -1
  130. package/index.cjs +692 -11760
  131. package/index.cjs.map +1 -1
  132. package/index.js +774 -11846
  133. package/index.js.map +1 -1
  134. package/models/decorators/future-service.d.ts +7 -7
  135. package/models/models/browser-router/browser-router-model.d.ts +10 -39
  136. package/models/models/browser-router/browser-router-model.d.ts.map +1 -1
  137. package/models/models/browser-router/browser-router-registration.d.ts +5 -77
  138. package/models/models/browser-router/browser-router-registration.d.ts.map +1 -1
  139. package/models/models/browser-router/types/index.d.ts +2 -16
  140. package/models/models/canvas-dispatcher/canvas-dispatcher-registration.d.ts +5 -77
  141. package/models/models/canvas-dispatcher/canvas-dispatcher-registration.d.ts.map +1 -1
  142. package/models/models/canvas-renderer/canvas-renderer-registration.d.ts +5 -75
  143. package/models/models/canvas-renderer/canvas-renderer-registration.d.ts.map +1 -1
  144. package/models/models/config-bean/config-bean-model-builder.d.ts +4 -11
  145. package/models/models/config-bean/config-bean-model-builder.d.ts.map +1 -1
  146. package/models/models/config-bean/config-bean-model.d.ts +23 -66
  147. package/models/models/config-bean/config-bean-model.d.ts.map +1 -1
  148. package/models/models/config-bean-prop/config-bean-prop-model.d.ts +15 -62
  149. package/models/models/config-bean-prop/config-bean-prop-model.d.ts.map +1 -1
  150. package/models/models/config-bean-prop/types/index.d.ts +34 -215
  151. package/models/models/device/device-model.d.ts +20 -199
  152. package/models/models/device/device-model.d.ts.map +1 -1
  153. package/models/models/device/device-registration.d.ts +7 -87
  154. package/models/models/device/device-registration.d.ts.map +1 -1
  155. package/models/models/device/types/index.d.ts +5 -34
  156. package/models/models/future/future-aware.d.ts +7 -71
  157. package/models/models/future/future-aware.d.ts.map +1 -1
  158. package/models/models/future/future-model-builder.d.ts +2 -2
  159. package/models/models/future/future-model.d.ts +3 -23
  160. package/models/models/future/future-model.d.ts.map +1 -1
  161. package/models/models/future/future-types.d.ts +28 -145
  162. package/models/models/future/future-types.d.ts.map +1 -1
  163. package/models/models/gpio-chip/gpio-chip-builders.d.ts +14 -0
  164. package/models/models/gpio-chip/gpio-chip-builders.d.ts.map +1 -0
  165. package/models/models/gpio-chip/gpio-chip-container-model.d.ts +2 -1
  166. package/models/models/gpio-chip/gpio-chip-container-model.d.ts.map +1 -1
  167. package/models/models/key-value/key-value-model.d.ts +12 -72
  168. package/models/models/key-value/key-value-model.d.ts.map +1 -1
  169. package/models/models/key-value/key-value-registration.d.ts +5 -77
  170. package/models/models/key-value/key-value-registration.d.ts.map +1 -1
  171. package/models/models/key-value/services/key-value-services.d.ts +13 -72
  172. package/models/models/key-value/services/key-value-services.d.ts.map +1 -1
  173. package/models/models/key-value/types/index.d.ts +3 -46
  174. package/models/models/kos-expression-evaluator/expression-parse-cache.d.ts +29 -0
  175. package/models/models/kos-expression-evaluator/expression-parse-cache.d.ts.map +1 -0
  176. package/models/models/kos-expression-evaluator/index.d.ts +1 -0
  177. package/models/models/kos-expression-evaluator/index.d.ts.map +1 -1
  178. package/models/models/kos-expression-evaluator/kos-expression-evaluator-model.d.ts +73 -105
  179. package/models/models/kos-expression-evaluator/kos-expression-evaluator-model.d.ts.map +1 -1
  180. package/models/models/kos-expression-evaluator/services/kos-expression-evaluator-services.d.ts +2 -12
  181. package/models/models/kos-expression-evaluator/services/kos-expression-evaluator-services.d.ts.map +1 -1
  182. package/models/models/kos-log-manager/kos-log-manager-model.d.ts +7 -46
  183. package/models/models/kos-log-manager/kos-log-manager-model.d.ts.map +1 -1
  184. package/models/models/kos-log-manager/kos-log-manager-registration.d.ts +5 -80
  185. package/models/models/kos-log-manager/kos-log-manager-registration.d.ts.map +1 -1
  186. package/models/models/kos-log-manager/types/index.d.ts +13 -156
  187. package/models/models/kos-time/kos-time-model.d.ts +8 -39
  188. package/models/models/kos-time/kos-time-model.d.ts.map +1 -1
  189. package/models/models/kos-time/kos-time-registration.d.ts +6 -73
  190. package/models/models/kos-time/kos-time-registration.d.ts.map +1 -1
  191. package/models/models/kos-time/types/index.d.ts +3 -58
  192. package/models/models/log-block/log-block-container-model.d.ts +2 -118
  193. package/models/models/log-block/log-block-container-model.d.ts.map +1 -1
  194. package/models/models/log-block/log-block-container-registration.d.ts +5 -75
  195. package/models/models/log-block/log-block-container-registration.d.ts.map +1 -1
  196. package/models/models/log-block/log-block-model.d.ts +5 -168
  197. package/models/models/log-block/log-block-model.d.ts.map +1 -1
  198. package/models/models/log-block/log-block-registration.d.ts +5 -75
  199. package/models/models/log-block/log-block-registration.d.ts.map +1 -1
  200. package/models/models/log-block/types/index.d.ts +14 -81
  201. package/models/models/log-stream/log-stream-container-model.d.ts +8 -35
  202. package/models/models/log-stream/log-stream-container-model.d.ts.map +1 -1
  203. package/models/models/log-stream/log-stream-container-registration.d.ts +5 -75
  204. package/models/models/log-stream/log-stream-container-registration.d.ts.map +1 -1
  205. package/models/models/log-stream/log-stream-model.d.ts +8 -29
  206. package/models/models/log-stream/log-stream-model.d.ts.map +1 -1
  207. package/models/models/log-stream/log-stream-registration.d.ts +5 -75
  208. package/models/models/log-stream/log-stream-registration.d.ts.map +1 -1
  209. package/models/models/log-stream/types/index.d.ts +5 -60
  210. package/models/models/network-interface/network-interface-container-model.d.ts +6 -35
  211. package/models/models/network-interface/network-interface-container-model.d.ts.map +1 -1
  212. package/models/models/network-interface/network-interface-container-registration.d.ts +5 -73
  213. package/models/models/network-interface/network-interface-container-registration.d.ts.map +1 -1
  214. package/models/models/network-interface/network-interface-model.d.ts +5 -43
  215. package/models/models/network-interface/network-interface-model.d.ts.map +1 -1
  216. package/models/models/network-interface/network-interface-registration.d.ts +5 -73
  217. package/models/models/network-interface/network-interface-registration.d.ts.map +1 -1
  218. package/models/models/network-interface/types/index.d.ts +2 -16
  219. package/models/models/ota/ota-model.d.ts +11 -39
  220. package/models/models/ota/ota-model.d.ts.map +1 -1
  221. package/models/models/ota/ota-registration.d.ts +5 -77
  222. package/models/models/ota/ota-registration.d.ts.map +1 -1
  223. package/models/models/ota/types/index.d.ts +2 -141
  224. package/models/models/region-info/types/index.d.ts +19 -99
  225. package/models/models/region-info/types/index.d.ts.map +1 -1
  226. package/models/models/software-info/services/software-info-services.d.ts +2 -14
  227. package/models/models/software-info/services/software-info-services.d.ts.map +1 -1
  228. package/models/models/software-info/software-info-model.d.ts +3 -39
  229. package/models/models/software-info/software-info-model.d.ts.map +1 -1
  230. package/models/models/software-info/software-info-registration.d.ts +6 -73
  231. package/models/models/software-info/software-info-registration.d.ts.map +1 -1
  232. package/models/models/software-info/types/index.d.ts +6 -20
  233. package/models/models/state-bean/state-bean-model.d.ts +10 -41
  234. package/models/models/state-bean/state-bean-model.d.ts.map +1 -1
  235. package/models/models/state-bean/state-bean-registration.d.ts +6 -73
  236. package/models/models/state-bean/state-bean-registration.d.ts.map +1 -1
  237. package/models/models/state-bean/types/index.d.ts +4 -84
  238. package/models/models/state-prop/state-prop-model.d.ts +6 -40
  239. package/models/models/state-prop/state-prop-model.d.ts.map +1 -1
  240. package/models/models/state-prop/state-prop-registration.d.ts +6 -73
  241. package/models/models/state-prop/state-prop-registration.d.ts.map +1 -1
  242. package/models/models/state-prop/types/index.d.ts +5 -37
  243. package/models/models/storage-device/storage-device-container-model.d.ts +7 -273
  244. package/models/models/storage-device/storage-device-container-model.d.ts.map +1 -1
  245. package/models/models/storage-device/storage-device-container-registration.d.ts +5 -75
  246. package/models/models/storage-device/storage-device-container-registration.d.ts.map +1 -1
  247. package/models/models/storage-device/storage-device-model.d.ts +3 -49
  248. package/models/models/storage-device/storage-device-model.d.ts.map +1 -1
  249. package/models/models/storage-device/storage-device-registration.d.ts +5 -75
  250. package/models/models/storage-device/storage-device-registration.d.ts.map +1 -1
  251. package/models/models/storage-device/types/index.d.ts +13 -82
  252. package/models/models/studio-properties/studio-properties-model.d.ts +13 -36
  253. package/models/models/studio-properties/studio-properties-model.d.ts.map +1 -1
  254. package/models/models/studio-properties/studio-properties-registration.d.ts +5 -75
  255. package/models/models/studio-properties/studio-properties-registration.d.ts.map +1 -1
  256. package/models/models/studio-properties/types/index.d.ts +2 -24
  257. package/models/models/translation/descriptor-merge.d.ts +13 -17
  258. package/models/models/translation/descriptor-merge.d.ts.map +1 -1
  259. package/models/models/translation/services/translation-services.d.ts +19 -77
  260. package/models/models/translation/services/translation-services.d.ts.map +1 -1
  261. package/models/models/translation/test-harness.d.ts +6 -8
  262. package/models/models/translation/test-harness.d.ts.map +1 -1
  263. package/models/models/translation/translation-container-model.d.ts +7 -59
  264. package/models/models/translation/translation-container-model.d.ts.map +1 -1
  265. package/models/models/translation/translation-container-registration.d.ts +6 -73
  266. package/models/models/translation/translation-container-registration.d.ts.map +1 -1
  267. package/models/models/translation/translation-model.d.ts +17 -50
  268. package/models/models/translation/translation-model.d.ts.map +1 -1
  269. package/models/models/translation/translation-registration.d.ts +6 -73
  270. package/models/models/translation/translation-registration.d.ts.map +1 -1
  271. package/models/models/translation/types/index.d.ts +51 -276
  272. package/models/models/trouble/trouble-registration.d.ts +6 -73
  273. package/models/models/trouble/trouble-registration.d.ts.map +1 -1
  274. package/models/models/trouble/types/index.d.ts +17 -188
  275. package/models/models/trouble/utils/is-trouble-aware.d.ts +4 -85
  276. package/models/models/trouble/utils/is-trouble-aware.d.ts.map +1 -1
  277. package/models/models/trouble-container/trouble-builders.d.ts +11 -0
  278. package/models/models/trouble-container/trouble-builders.d.ts.map +1 -0
  279. package/models/models/trouble-container/trouble-container-model.d.ts +2 -1
  280. package/models/models/trouble-container/trouble-container-model.d.ts.map +1 -1
  281. package/models/models/usb-update/usb-update-container-registration.d.ts +5 -75
  282. package/models/models/usb-update/usb-update-container-registration.d.ts.map +1 -1
  283. package/models/models/usb-update/usb-update-registration.d.ts +5 -75
  284. package/models/models/usb-update/usb-update-registration.d.ts.map +1 -1
  285. package/models/types/cancellable-promise.d.ts +6 -9
  286. package/models/types/cancellable-promise.d.ts.map +1 -1
  287. package/models/utils/await-future-call.d.ts +9 -21
  288. package/models/utils/await-future-call.d.ts.map +1 -1
  289. package/models/utils/cancellable-future-call.d.ts +8 -19
  290. package/models/utils/cancellable-future-call.d.ts.map +1 -1
  291. package/models/utils/cancellable-service.d.ts +14 -23
  292. package/models/utils/cancellable-service.d.ts.map +1 -1
  293. package/models/utils/conversion-utils.d.ts +8 -48
  294. package/models/utils/conversion-utils.d.ts.map +1 -1
  295. package/models/utils/persistence-store.d.ts +1 -1
  296. package/models/utils/service.d.ts +14 -48
  297. package/models/utils/service.d.ts.map +1 -1
  298. package/models/utils/services/kos/daily/service.d.ts +4 -4
  299. package/models/utils/services/vfs/daily/service.d.ts +4 -4
  300. package/models/utils/timer-manager.d.ts.map +1 -1
  301. package/package.json +2 -2
  302. package/{index-D52vEGXT.cjs → software-info-registration-Le3V0a6v.cjs} +11906 -416
  303. package/software-info-registration-Le3V0a6v.cjs.map +1 -0
  304. package/{index-Csq0zQtb.js → software-info-registration-kSGacOka.js} +12116 -625
  305. package/software-info-registration-kSGacOka.js.map +1 -0
  306. package/testing/index.d.ts +32 -34
  307. package/testing/index.d.ts.map +1 -1
  308. package/testing.cjs +2 -1
  309. package/testing.cjs.map +1 -1
  310. package/testing.js +2 -1
  311. package/testing.js.map +1 -1
  312. package/ui/components/connection-dev-button/connection-dev-button-styles.d.ts +9 -0
  313. package/ui/components/connection-dev-button/connection-dev-button-styles.d.ts.map +1 -0
  314. package/ui/components/connection-dev-button/index.d.ts +36 -0
  315. package/ui/components/connection-dev-button/index.d.ts.map +1 -0
  316. package/ui/components/connection-dev-button/use-connection-dev-state.d.ts +29 -0
  317. package/ui/components/connection-dev-button/use-connection-dev-state.d.ts.map +1 -0
  318. package/ui/components/index.d.ts +1 -0
  319. package/ui/components/index.d.ts.map +1 -1
  320. package/ui/features/canvas/hooks/use-image-renderer.d.ts +5 -4
  321. package/ui/features/canvas/hooks/use-image-renderer.d.ts.map +1 -1
  322. package/ui/hooks/use-function-warmup.d.ts +4 -14
  323. package/ui/hooks/use-function-warmup.d.ts.map +1 -1
  324. package/ui/hooks/use-kos-date-formats.d.ts +15 -29
  325. package/ui/hooks/use-kos-date-formats.d.ts.map +1 -1
  326. package/ui/hooks/use-kos-region-timezones.d.ts +4 -55
  327. package/ui/hooks/use-kos-region-timezones.d.ts.map +1 -1
  328. package/ui/hooks/use-kos-regions.d.ts +11 -23
  329. package/ui/hooks/use-kos-regions.d.ts.map +1 -1
  330. package/ui/hooks/use-kos-time-formats.d.ts +16 -31
  331. package/ui/hooks/use-kos-time-formats.d.ts.map +1 -1
  332. package/ui/hooks/use-kos-unit-systems.d.ts +13 -27
  333. package/ui/hooks/use-kos-unit-systems.d.ts.map +1 -1
  334. package/ui/hooks/view-model/use-view-model.d.ts +6 -31
  335. package/ui/hooks/view-model/use-view-model.d.ts.map +1 -1
  336. package/ui/policies/reload-on-disconnect-policy.d.ts +5 -6
  337. package/ui/policies/reload-on-disconnect-policy.d.ts.map +1 -1
  338. package/index-Csq0zQtb.js.map +0 -1
  339. package/index-D52vEGXT.cjs.map +0 -1
package/index.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../../packages/kos-api-levels/src/deprecation.ts","../../../packages/kos-api-levels/src/registry.ts","../../../packages/kos-ui-sdk/src/common/events/eventBus.functional.ts","../../../packages/kos-ui-sdk/src/common/file-utils.ts","../../../packages/kos-ui-sdk/src/core/core/api/wrapPromise.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-child.ts","../../../packages/kos-ui-sdk/src/core/util/model-attribute-utils.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-parent.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-companion.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-container-aware.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-context.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-execute-service-request.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-future-aware.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-multiple-future-aware.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-log.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-logger-aware.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-model-effect.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-reference.ts","../../../packages/kos-ui-sdk/src/core/types/utils/kos-fetch.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-trouble-aware.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kosDependency.ts","../../../packages/kos-ui-sdk/src/core/core/extension/initialize-extension.ts","../../../packages/kos-ui-sdk/src/core/core/extension/plugin-extension-manager.ts","../../../packages/kos-ui-sdk/src/core/util/debounce.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kosSubscribe.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-view-model.ts","../../../packages/kos-ui-sdk/src/core/util/ancestor-path-visitor.ts","../../../packages/kos-ui-sdk/src/core/util/apply-mixins.ts","../../../packages/kos-ui-sdk/src/core/util/array-utils.ts","../../../packages/kos-ui-sdk/src/core/util/container-utils.ts","../../../packages/kos-ui-sdk/src/core/util/date-utils.ts","../../../packages/kos-ui-sdk/src/core/util/hsl-to-hex.ts","../../../packages/kos-ui-sdk/src/core/util/kos-data-mapper-utils.ts","../../../packages/kos-ui-sdk/src/core/util/middleware.ts","../../../packages/kos-ui-sdk/src/core/util/model-registration-utils.ts","../../../packages/kos-ui-sdk/src/core/util/paired-client-heartbeat.ts","../../../packages/kos-ui-sdk/src/core/util/pipe.ts","../../../packages/kos-ui-sdk/src/core/util/retry-with-exponential-backoff.ts","../../../packages/kos-ui-sdk/src/core/util/service-response.ts","../../../packages/kos-ui-sdk/src/core/util/wait-for-request.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/kos-index-aware.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/kos-container-index-aware.ts","../../../packages/kos-ui-sdk/src/core/core/kos-registration.ts","../../../packages/kos-ui-sdk/src/core/core/kos-singleton-registration.ts","../../../packages/kos-ui-sdk/src/core/core/models/kos-token/index.ts","../../../packages/kos-ui-sdk/src/core/core/services/browser-router.ts","../../../packages/kos-ui-sdk/src/models/constants/index.ts","../../../packages/kos-ui-sdk/src/models/services/config-bean/index.ts","../../../packages/kos-ui-sdk/src/models/utils/prop-utils.ts","../../../packages/kos-ui-sdk/src/models/models/config-bean/config-bean-model-builder.ts","../../../packages/kos-ui-sdk/src/models/models/config-bean/config-bean-model.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-config-bean.ts","../../../packages/kos-ui-sdk/src/models/models/region-info/services/region-info-services.ts","../../../packages/kos-ui-sdk/src/models/models/region-info/types/index.ts","../../../packages/kos-ui-sdk/src/models/models/region-info/utils/unit-system-utils.ts","../../../packages/kos-ui-sdk/src/models/models/region-info/region-info-model.ts","../../../packages/kos-ui-sdk/src/models/utils/conversion-utils.ts","../../../packages/kos-ui-sdk/src/models/models/config-bean-prop/config-options-factory.ts","../../../packages/kos-ui-sdk/src/models/models/config-bean-prop/config-bean-prop-model.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-config-bean-prop.ts","../../../packages/kos-ui-sdk/src/models/models/future/future-model-builder.ts","../../../packages/kos-ui-sdk/src/models/services/future/index.ts","../../../packages/kos-ui-sdk/src/models/models/future/future-factory.ts","../../../packages/kos-ui-sdk/src/models/models/future-container/future-container-factory.ts","../../../packages/kos-ui-sdk/src/models/utils/future-manager/index.ts","../../../packages/kos-ui-sdk/src/models/decorators/future-service.ts","../../../packages/kos-ui-sdk/src/models/models/state-bean/services/state-bean-services.ts","../../../packages/kos-ui-sdk/src/models/models/state-bean/state-bean-model.ts","../../../packages/kos-ui-sdk/src/models/models/state-bean/state-bean-registration.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-state-bean.ts","../../../packages/kos-ui-sdk/src/models/models/state-prop/state-prop-model.ts","../../../packages/kos-ui-sdk/src/models/models/state-prop/state-prop-registration.ts","../../../packages/kos-ui-sdk/src/models/models/state-prop/services/state-prop-services.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-state-prop.ts","../../../packages/kos-ui-sdk/src/models/models/browser-router/browser-router-model.ts","../../../packages/kos-ui-sdk/src/models/models/browser-router/browser-router-registration.ts","../../../packages/kos-ui-sdk/src/models/models/future/future-model.ts","../../../packages/kos-ui-sdk/src/models/models/future-container/future-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/key-value/services/key-value-services.ts","../../../packages/kos-ui-sdk/src/models/models/key-value/key-value-model.ts","../../../packages/kos-ui-sdk/src/models/models/key-value/key-value-registration.ts","../../../node_modules/expr-eval/dist/index.mjs","../../../packages/kos-ui-sdk/src/models/models/kos-expression-evaluator/kos-expression-evaluator-model.ts","../../../packages/kos-ui-sdk/src/models/models/kos-expression-evaluator/index.ts","../../../packages/kos-ui-sdk/src/models/models/kos-log-manager/services/kos-log-manager-services.ts","../../../packages/kos-ui-sdk/src/models/models/kos-log-manager/kos-log-manager-model.ts","../../../packages/kos-ui-sdk/src/models/models/kos-log-manager/kos-log-manager-registration.ts","../../../packages/kos-ui-sdk/src/models/models/kos-time/services/kos-time-services.ts","../../../packages/kos-ui-sdk/src/models/models/kos-time/kos-time-model.ts","../../../packages/kos-ui-sdk/src/models/models/kos-time/kos-time-registration.ts","../../../packages/kos-ui-sdk/src/models/models/log-block/log-block-container-model.ts","../../../packages/kos-ui-sdk/src/models/utils/get-kos-connection-id.ts","../../../packages/kos-ui-sdk/src/models/models/log-stream/services/log-stream-services.ts","../../../packages/kos-ui-sdk/src/models/models/log-block/log-block-model.ts","../../../packages/kos-ui-sdk/src/models/models/log-block/log-block-registration.ts","../../../packages/kos-ui-sdk/src/models/models/log-block/log-block-container-registration.ts","../../../packages/kos-ui-sdk/src/models/models/log-stream/log-stream-model.ts","../../../packages/kos-ui-sdk/src/models/models/log-stream/log-stream-registration.ts","../../../packages/kos-ui-sdk/src/models/models/log-stream/log-stream-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/log-stream/log-stream-container-registration.ts","../../../packages/kos-ui-sdk/src/models/utils/trouble-utils.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/services/trouble-services.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/utils/trouble-data-extension.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/utils/trouble-extension.ts","../../../packages/kos-ui-sdk/src/models/models/trouble-container/trouble-utils.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/handlers/resolvable-trouble-handler.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/trouble-model.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/trouble-registration.ts","../../../packages/kos-ui-sdk/src/models/models/trouble-container/trouble-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/trouble-container/index.ts","../../../packages/kos-ui-sdk/src/models/models/ota/services/ota-services.ts","../../../packages/kos-ui-sdk/src/models/models/ota/ota-model.ts","../../../packages/kos-ui-sdk/src/models/models/ota/ota-registration.ts","../../../packages/kos-ui-sdk/src/models/utils/await-future-call.ts","../../../packages/kos-ui-sdk/src/models/types/cancellable-promise.ts","../../../packages/kos-ui-sdk/src/models/utils/cancellable-future-call.ts","../../../packages/kos-ui-sdk/src/models/utils/cancellable-service.ts","../../../packages/kos-ui-sdk/src/models/utils/client.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/services/canvas-dispatcher-services.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/encode-frame.tsx","../../../packages/kos-ui-sdk/src/models/models/canvas-renderer/canvas-renderer-model.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-renderer/canvas-renderer-registration.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/base/video-base-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/base/webgl-base-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/drop-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/base/canvas-2d-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/mixins/one-shot-renderer-mixin.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/gradient-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/image-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/looping-video-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/color-utils.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/matrix-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/overlay-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/scrolling-image-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/scrolling-text-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/sequence-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/solid-color-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/sweep-renderer.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/renderer-factory.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/canvas-dispatcher-model.ts","../../../packages/kos-ui-sdk/src/models/models/canvas-dispatcher/canvas-dispatcher-registration.ts","../../../packages/kos-ui-sdk/src/models/models/device/services/device-services.ts","../../../packages/kos-ui-sdk/src/models/models/device/device-model.ts","../../../packages/kos-ui-sdk/src/models/models/device/device-registration.ts","../../../packages/kos-ui-sdk/src/models/models/network-interface/network-interface-model.ts","../../../packages/kos-ui-sdk/src/models/models/network-interface/network-interface-registration.ts","../../../packages/kos-ui-sdk/src/models/models/network-interface/services/network-interface-services.ts","../../../packages/kos-ui-sdk/src/models/models/network-interface/network-interface-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/network-interface/network-interface-container-registration.ts","../../../packages/kos-ui-sdk/src/models/models/storage-device/services/storage-device-services.ts","../../../packages/kos-ui-sdk/src/models/models/storage-device/storage-device-model.ts","../../../packages/kos-ui-sdk/src/models/models/storage-device/storage-device-registration.ts","../../../packages/kos-ui-sdk/src/models/models/storage-device/storage-device-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/storage-device/storage-device-container-registration.ts","../../../packages/kos-ui-sdk/src/models/models/usb-update/services/usb-update-services.ts","../../../packages/kos-ui-sdk/src/models/models/usb-update/usb-update-model.ts","../../../packages/kos-ui-sdk/src/models/models/usb-update/usb-update-registration.ts","../../../packages/kos-ui-sdk/src/models/models/usb-update/usb-update-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/usb-update/usb-update-container-registration.ts","../../../packages/kos-ui-sdk/src/models/models/translation/services/translation-services.ts","../../../packages/kos-ui-sdk/src/models/models/translation/descriptor-merge.ts","../../../packages/kos-ui-sdk/src/models/models/translation/constants.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-model.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-registration.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-container-registration.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-context.ts","../../../packages/kos-ui-sdk/src/models/models/ws-event/ws-event-factory.ts","../../../packages/kos-ui-sdk/src/models/models/ws-event/ws-event-model.ts","../../../packages/kos-ui-sdk/src/models/registration.ts","../../../packages/kos-ui-sdk/src/models/utils/core-registration-manager.ts","../../../packages/kos-ui-sdk/src/models/utils/extension-manager.ts","../../../packages/kos-ui-sdk/src/models/utils/persistence-store.ts","../../../packages/kos-ui-sdk/src/models/utils/region-utils.ts","../../../packages/kos-ui-sdk/src/models/utils/service-accessor.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/daily/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.6.5/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.8.1/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.9.x/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/daily/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.6.5/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.8.1/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.9.x/service.ts","../../../packages/kos-ui-sdk/src/models/utils/timer-manager.ts","../../../packages/kos-ui-sdk/src/models/utils/timezone-utils.ts","../../../packages/kos-ui-sdk/src/models/models/software-info/services/software-info-services.ts","../../../packages/kos-ui-sdk/src/models/models/software-info/software-info-model.ts","../../../packages/kos-ui-sdk/src/models/models/software-info/software-info-registration.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/utils/is-trouble-aware.ts","../../../packages/kos-ui-sdk/src/models/services/login/index.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-pin/gpio-pin-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-pin/gpio-pin-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/gpio-chip-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/services/gpio-chip-services.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/gpio-chip-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/services/studio-properties-services.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/studio-properties-model.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/studio-properties-registration.ts","../../../packages/kos-ui-sdk/src/ui/components/loading-message/loading-message-styles.ts","../../../packages/kos-ui-sdk/src/ui/components/loading-message/index.tsx","../../../packages/kos-ui-sdk/src/ui/components/error-boundary/error-boundary.tsx","../../../packages/kos-ui-sdk/src/ui/components/progress-bar/progress-bar.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-context.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-hierarchy-context.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/kos-model-loader.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/fetch-kos-core.ts","../../../packages/kos-ui-sdk/src/ui/contexts/kos-core-context.tsx","../../../packages/kos-ui-sdk/src/ui/policies/constants.ts","../../../packages/kos-ui-sdk/src/ui/policies/reload-on-disconnect-policy.tsx","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/use-reconnecting-overlay-state.ts","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/reconnecting-overlay-styles.ts","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/index.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/create-model-context.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/kos-time/use-kos-time.ts","../../../packages/kos-ui-sdk/src/ui/contexts/kos-time/kos-time-provider.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/software-info/use-software-info.ts","../../../packages/kos-ui-sdk/src/ui/hooks/software-info/with-software-info.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/software-info/software-info-provider.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/token-context.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/translation-container/kos-translations-provider.tsx","../../../packages/kos-ui-sdk/src/ui/features/canvas/hooks/canvas-dispatcher/use-canvas-dispatcher.ts","../../../packages/kos-ui-sdk/src/ui/features/canvas/hooks/canvas-dispatcher/with-canvas-dispatcher.tsx","../../../packages/kos-ui-sdk/src/ui/features/canvas/utils/preview-decoder.ts","../../../packages/kos-ui-sdk/src/ui/features/canvas/components/canvas-streamer/canvas-streamer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/device/use-device.ts","../../../packages/kos-ui-sdk/src/ui/hooks/device/with-device.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/fetch-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/kos-time/with-kos-time.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/network-interface-container/use-network-interface-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/network-interface-container/with-network-interface-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/ota/use-ota.ts","../../../packages/kos-ui-sdk/src/ui/hooks/ota/with-ota.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/outside-alerter.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/state-prop/use-state-prop.ts","../../../packages/kos-ui-sdk/src/ui/hooks/storage-device-container/use-storage-device-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/storage-device-container/with-storage-device-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/timer/use-timer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/trans.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/use-translation.ts","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/use-translation-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/with-translation-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-visibility.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/with-trouble-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/usb-update-container/use-usb-update-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/usb-update-container/with-usb-update-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-config-bean.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-config-property.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-connection-state.ts","../../../packages/kos-ui-sdk/src/ui/utils/date.ts","../../../packages/kos-ui-sdk/src/ui/utils/date-utils.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-date-props.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-date-relative-prop.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-function-warmup.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-date-formats.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-region-timezones.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-regions.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-time-formats.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-local-computed.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-mutation-observer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-press-gesture/strategy/dom-intersection-strategy.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-press-gesture/use-press-gesture.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-project-reloading.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-time-props.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-region-time-props.ts","../../../packages/kos-ui-sdk/src/ui/hooks/view-model/use-view-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/with-project-reload.tsx","../../../packages/kos-ui-sdk/src/index.ts"],"sourcesContent":["const _warned = new Set<string>();\n\n/**\n * Emits a one-time console warning in non-production environments when a\n * deprecated API is used.\n *\n * @param apiName - The name of the deprecated API (e.g. `@kosSubscribe`)\n * @param serviceId - The service the API belongs to (e.g. `core.subscribe`)\n * @param deprecatedAtLevel - The API level at which this API was deprecated\n * @param replacement - The recommended replacement (e.g. `@kosTopicHandler`)\n * @param removeAtLevel - The API level at which this API will be removed\n */\nexport function warnDeprecated(\n apiName: string,\n serviceId: string,\n deprecatedAtLevel: number,\n replacement: string,\n removeAtLevel: number\n): void {\n if (\n typeof process !== \"undefined\" &&\n process.env[\"NODE_ENV\"] === \"production\"\n ) {\n return;\n }\n if (_warned.has(apiName)) return;\n _warned.add(apiName);\n console.warn(\n `[KOS] \"${apiName}\" is deprecated since ${serviceId} level ${deprecatedAtLevel}. ` +\n `Use \"${replacement}\" instead. Will be removed at level ${removeAtLevel}.`\n );\n}\n","import type { ApiLevelMap } from \"./types\";\n\nconst _registry: ApiLevelMap = {};\n\n/**\n * Registers API levels for an SDK package. Each SDK package calls this on\n * import to populate the in-memory registry. Works in browser and Node.js.\n *\n * Phase 1: called manually from each package's index.ts.\n * Phase 2: generated automatically by the JSDoc scanner at build time.\n */\nexport function registerApiLevels(levels: ApiLevelMap): void {\n Object.assign(_registry, levels);\n}\n\nexport function getRegistry(): Readonly<ApiLevelMap> {\n return _registry;\n}\n","/**\n * Functional programming utilities for the EventBus\n * Provides reactive and promise-based patterns for event handling\n */\n\nimport { ApiCallback, EventCallback, publish, subscribe } from \"./eventBus\";\n\n/**\n * Subscribe to an event that will automatically unsubscribe after the first occurrence\n *\n * @param eventType - The event type to listen for\n * @param callback - The callback to execute once\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function once<T = ApiCallback>(\n eventType: string,\n callback: EventCallback<T>\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n // Unsubscribe immediately after first call\n subscription.unsubscribe();\n callback(msg);\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Wait for a specific event to occur, returning a Promise\n *\n * @param eventType - The event type to wait for\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the event data\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function waitFor<T = ApiCallback>(\n eventType: string,\n timeout?: number\n): Promise<T> {\n return new Promise((resolve, reject) => {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const unsubscribe = once(eventType, (msg?: T) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n resolve(msg!);\n });\n\n if (timeout) {\n timeoutId = setTimeout(() => {\n unsubscribe();\n reject(new Error(`Timeout waiting for event: ${eventType}`));\n }, timeout);\n }\n });\n}\n\n/**\n * Wait for multiple events to occur (Promise.all pattern)\n *\n * @param eventTypes - Array of event types to wait for\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves when all events have occurred\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function waitForAll<T = ApiCallback>(\n eventTypes: string[],\n timeout?: number\n): Promise<T[]> {\n const promises = eventTypes.map((eventType) =>\n waitFor<T>(eventType, timeout)\n );\n return Promise.all(promises);\n}\n\n/**\n * Wait for the first event to occur from a list (Promise.race pattern)\n *\n * @param eventTypes - Array of event types to race\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the first event\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function race<T = ApiCallback>(\n eventTypes: string[],\n timeout?: number\n): Promise<{ eventType: string; data: T }> {\n return new Promise((resolve, reject) => {\n const unsubscribers: (() => void)[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n let resolved = false;\n\n const cleanup = () => {\n unsubscribers.forEach((unsub) => unsub());\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n };\n\n eventTypes.forEach((eventType) => {\n const unsubscribe = once(eventType, (msg?: T) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n resolve({ eventType, data: msg! });\n }\n });\n unsubscribers.push(unsubscribe);\n });\n\n if (timeout) {\n timeoutId = setTimeout(() => {\n if (!resolved) {\n resolved = true;\n cleanup();\n reject(\n new Error(`Timeout waiting for any event: ${eventTypes.join(\", \")}`)\n );\n }\n }, timeout);\n }\n });\n}\n\n/**\n * Filter events based on a predicate function\n *\n * @param eventType - The event type to filter\n * @param predicate - Function to test each event\n * @param callback - Callback for events that pass the filter\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function filter<T = ApiCallback>(\n eventType: string,\n predicate: (msg: T) => boolean,\n callback: EventCallback<T>\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg && predicate(msg)) {\n callback(msg);\n }\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Transform events using a map function\n *\n * @param eventType - The event type to transform\n * @param transform - Function to transform the event data\n * @param callback - Callback for transformed events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function map<T = ApiCallback, R = any>(\n eventType: string,\n transform: (msg: T) => R,\n callback: (msg: R) => void\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n const transformed = transform(msg);\n callback(transformed);\n }\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Debounce events - only emit after a period of inactivity\n *\n * @param eventType - The event type to debounce\n * @param delay - Delay in milliseconds\n * @param callback - Callback for debounced events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function debounce<T = ApiCallback>(\n eventType: string,\n delay: number,\n callback: EventCallback<T>\n): () => void {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n callback(msg);\n }, delay);\n });\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Throttle events - limit emissions to once per interval\n *\n * @param eventType - The event type to throttle\n * @param interval - Minimum interval between emissions in milliseconds\n * @param callback - Callback for throttled events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function throttle<T = ApiCallback>(\n eventType: string,\n interval: number,\n callback: EventCallback<T>\n): () => void {\n let lastEmit = 0;\n let pendingTimeout: NodeJS.Timeout | null = null;\n\n const subscription = subscribe(eventType, (msg?: T) => {\n const now = Date.now();\n const timeSinceLastEmit = now - lastEmit;\n\n if (timeSinceLastEmit >= interval) {\n lastEmit = now;\n callback(msg);\n } else if (!pendingTimeout) {\n // Schedule emission for the remaining time\n pendingTimeout = setTimeout(() => {\n lastEmit = Date.now();\n callback(msg);\n pendingTimeout = null;\n }, interval - timeSinceLastEmit);\n }\n });\n\n return () => {\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Buffer events and emit them as an array\n *\n * @param eventType - The event type to buffer\n * @param bufferTime - Time window to collect events in milliseconds\n * @param callback - Callback for buffered events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function buffer<T = ApiCallback>(\n eventType: string,\n bufferTime: number,\n callback: (events: T[]) => void\n): () => void {\n let buffer: T[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n\n const flush = () => {\n if (buffer.length > 0) {\n callback([...buffer]);\n buffer = [];\n }\n };\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n buffer.push(msg);\n\n if (!timeoutId) {\n timeoutId = setTimeout(() => {\n flush();\n timeoutId = null;\n }, bufferTime);\n }\n }\n });\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n flush(); // Emit any remaining buffered events\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Create a replay subject that remembers the last N events\n *\n * @param eventType - The event type to replay\n * @param bufferSize - Number of events to remember\n * @returns Object with subscribe method that replays buffered events\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function replay<T = ApiCallback>(eventType: string, bufferSize = 1) {\n const buffer: T[] = [];\n\n // Subscribe to capture events\n subscribe(eventType, (msg?: T) => {\n if (msg) {\n buffer.push(msg);\n if (buffer.length > bufferSize) {\n buffer.shift();\n }\n }\n });\n\n return {\n subscribe: (callback: EventCallback<T>) => {\n // Replay buffered events immediately\n buffer.forEach((event) => callback(event));\n\n // Then subscribe for future events\n return subscribe(eventType, callback);\n },\n };\n}\n\n/**\n * Merge multiple event streams into one\n *\n * @param eventTypes - Array of event types to merge\n * @param callback - Callback for all merged events\n * @returns Unsubscribe function for all subscriptions\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function merge<T = ApiCallback>(\n eventTypes: string[],\n callback: (eventType: string, msg: T) => void\n): () => void {\n const subscriptions = eventTypes.map((eventType) =>\n subscribe(eventType, (msg?: T) => {\n if (msg) {\n callback(eventType, msg);\n }\n })\n );\n\n return () => {\n subscriptions.forEach((sub) => sub.unsubscribe());\n };\n}\n\n/**\n * Create a state machine that transitions based on events\n *\n * @param initialState - The initial state\n * @param transitions - Object mapping states to event handlers\n * @returns Object with current state and unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function stateMachine<TState extends string, T = ApiCallback>(\n initialState: TState,\n transitions: Record<TState, Record<string, (msg: T) => TState>>\n) {\n let currentState = initialState;\n const subscriptions: (() => void)[] = [];\n\n // Subscribe to all events mentioned in transitions\n const allEvents = new Set<string>();\n Object.values(transitions).forEach((stateTransitions) => {\n Object.keys(stateTransitions as Record<string, any>).forEach((event) => {\n allEvents.add(event);\n });\n });\n\n allEvents.forEach((eventType) => {\n const { unsubscribe } = subscribe(eventType, (msg?: T) => {\n const stateTransitions = transitions[currentState];\n if (stateTransitions && stateTransitions[eventType]) {\n const nextState = stateTransitions[eventType](msg!);\n currentState = nextState;\n }\n });\n subscriptions.push(unsubscribe);\n });\n\n return {\n get state() {\n return currentState;\n },\n unsubscribe: () => {\n subscriptions.forEach((unsub) => unsub());\n },\n };\n}\n\n/**\n * Utility to create a promise that can be resolved by publishing an event\n *\n * @param requestEvent - Event type to publish the request\n * @param responseEvent - Event type to wait for the response\n * @param request - The request data to publish\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the response\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function request<TRequest = any, TResponse = ApiCallback>(\n requestEvent: string,\n responseEvent: string,\n request: TRequest,\n timeout?: number\n): Promise<TResponse> {\n const responsePromise = waitFor<TResponse>(responseEvent, timeout);\n publish(requestEvent, request);\n return responsePromise;\n}\n\n/**\n * Create an async iterator for events\n *\n * @param eventType - The event type to iterate\n * @returns Async iterator for use with for-await-of\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport async function* eventIterator<T = ApiCallback>(\n eventType: string\n): AsyncIterableIterator<T> {\n const queue: T[] = [];\n const waiters: ((value: T) => void)[] = [];\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n if (waiters.length > 0) {\n const waiter = waiters.shift()!;\n waiter(msg);\n } else {\n queue.push(msg);\n }\n }\n });\n\n try {\n while (true) {\n if (queue.length > 0) {\n yield queue.shift()!;\n } else {\n yield await new Promise<T>((resolve) => {\n waiters.push(resolve);\n });\n }\n }\n } finally {\n subscription.unsubscribe();\n }\n}\n\n/**\n * Namespace collecting all functional event bus utilities.\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport const EventBusFunctional = {\n once,\n waitFor,\n waitForAll,\n race,\n filter,\n map,\n debounce,\n throttle,\n buffer,\n replay,\n merge,\n stateMachine,\n request,\n eventIterator,\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","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 * @kosService core.child\n * @kosApiLevel 2\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 *\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport const createPropKey = <R extends IKosDataModel>(key: keyof R) =>\n `{PROP_${String(key)}}`;\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\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 { OptionsRequired, ParentModel } from \"./propKeys\";\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\n/**\n * @kosService core.parent\n * @kosApiLevel 2\n */\nexport interface KosParentProps {\n parentId?: string;\n}\n\n/**\n * Decorator for declaring that a KOS model should be aware of its 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 * **Note**: This decorator automatically sets the model's `optionsRequired` flag to true since\n * parent-aware models require at least the parent ID to be provided in options.\n *\n * @category KOS Model Decorator\n * @kosService core.parent\n * @kosApiLevel 2\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 // Parent-aware models require options (at minimum the parent ID)\n constructor.prototype[OptionsRequired] = true;\n };\n","/* eslint-disable no-param-reassign */\nimport type { DependencyLifecycle } from \"../../types\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport { kosParentAware } from \"./kos-parent\";\nimport { CompanionParentModel } from \"./propKeys\";\n\n/**\n * @kosService core.companion\n * @kosApiLevel 13\n */\nexport interface KosCompanionOptions {\n /**\n * Pattern mode:\n * - 'decorator': Proxy all parent properties transparently (default)\n * - 'composition': Only provide getCompanionParent() method\n */\n mode?: \"decorator\" | \"composition\";\n /** Properties to exclude from proxying (only applies in decorator mode). Default: [] */\n excludeProperties?: string[];\n /** Custom parent property name. Default: 'companionParent' */\n parentProperty?: string;\n /**\n * Lifecycle phase at which this companion should be created.\n * Defaults to INIT (created immediately during parent instantiation).\n * Use LOAD to create after parent's load() completes, READY for after ready(), etc.\n *\n * @example\n * ```typescript\n * @kosCompanion({ lifecycle: DependencyLifecycle.LOAD })\n * class CarbAgitatorModel implements IKosDataModel {\n * // Created after assembly.load() completes\n * }\n * ```\n * @kosApiLevel 15\n */\n lifecycle?: DependencyLifecycle;\n}\n\n/**\n * Base interface for all companion models.\n * Provides the getCompanionParent() method available in both decorator and composition modes.\n *\n * @kosService core.companion\n * @kosApiLevel 13\n */\nexport interface KosCompanionAware<\n TParent extends IKosDataModel = IKosDataModel\n> {\n /**\n * Gets the companion's parent model instance.\n * Available in both decorator and composition modes.\n * Provides access to the model this companion extends.\n *\n * @returns The parent model instance that this companion enhances\n */\n getCompanionParent(): TParent;\n}\n\n/**\n * Interface for models using @kosCompanion in composition mode.\n * Use TypeScript interface merging to add companion capabilities to your model class.\n *\n * @example\n * ```typescript\n * interface ServiceCompanionModelImpl extends KosCompanionComposition<ServiceModel> {}\n *\n * @kosCompanion({ mode: 'composition' })\n * class ServiceCompanionModelImpl implements IKosDataModel {\n * // Only getCompanionParent() is available\n * get serviceInfo() {\n * const parent = this.getCompanionParent();\n * return `Service: ${parent.serviceName}`;\n * }\n * }\n * ```\n *\n * @kosService core.companion\n */\nexport type KosCompanionComposition<\n TParent extends IKosDataModel = IKosDataModel\n> = KosCompanionAware<TParent>;\n\n/**\n * Interface for models using @kosCompanion in decorator mode (default).\n * Use TypeScript interface merging to add full parent transparency to your model class.\n *\n * @example\n * ```typescript\n * interface BrandCompanionModelImpl extends KosCompanionDecorator<AvailabilityModel> {}\n *\n * @kosCompanion() // defaults to decorator mode\n * class BrandCompanionModelImpl implements IKosDataModel {\n * // All parent properties are available directly\n * get brandSpecificProperty() {\n * return this.name; // 'name' from parent AvailabilityModel\n * }\n * }\n * ```\n *\n * @kosService core.companion\n */\nexport type KosCompanionDecorator<\n TParent extends IKosDataModel = IKosDataModel\n> = KosCompanionAware<TParent>;\n\n/**\n * Class decorator that adds companion model capabilities to a KOS model.\n *\n * Supports two patterns:\n * 1. **Decorator Pattern** (default): Transparently proxies all parent properties,\n * making the companion a drop-in replacement for the parent\n * 2. **Composition Pattern**: Only provides getCompanionParent() method,\n * keeping parent encapsulated\n *\n * **Important**: Use TypeScript interface merging to get proper type information:\n *\n * ```typescript\n * // Decorator pattern - full transparency\n * interface BrandCompanionModelImpl extends KosCompanionAware<AvailabilityModel> {}\n *\n * @kosModel(\"brand-companion\")\n * @kosCompanion() // defaults to decorator mode\n * class BrandCompanionModelImpl implements IKosDataModel {\n * // All parent properties are available\n * get brandSpecificProperty() {\n * return this.name; // 'name' from parent AvailabilityModel\n * }\n * }\n *\n * // Composition pattern - encapsulated parent\n * interface ServiceCompanionModelImpl extends KosCompanionAware<ServiceModel> {}\n *\n * @kosModel(\"service-companion\")\n * @kosCompanion({ mode: 'composition' })\n * class ServiceCompanionModelImpl implements IKosDataModel {\n * // Parent is only accessible via getCompanionParent()\n * get serviceInfo() {\n * const parent = this.getCompanionParent();\n * return `Service: ${parent.serviceName}`;\n * }\n * }\n * ```\n *\n * @param options Configuration options for the companion decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * // Decorator mode - all parent properties proxied\n * @kosCompanion()\n * class MyCompanion { }\n *\n * // Composition mode - only getCompanionParent() available\n * @kosCompanion({ mode: 'composition' })\n * class MyCompanion { }\n *\n * // Decorator mode with exclusions\n * @kosCompanion({ mode: 'decorator', excludeProperties: ['internalState'] })\n * class MyCompanion { }\n *\n * // Lifecycle-deferred companion creation\n * @kosCompanion({ lifecycle: DependencyLifecycle.LOAD })\n * class DataDrivenCompanion { }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.1.0\n * @kosService core.companion\n * @kosApiLevel 2\n */\nexport function kosCompanion(options?: KosCompanionOptions): ClassDecorator {\n return (target: any) => {\n const mode = options?.mode || \"decorator\";\n const parentProperty = options?.parentProperty || \"companionParent\";\n const excludeProperties = options?.excludeProperties || [];\n const lifecycle = options?.lifecycle;\n\n // Companions by definition have parent relationships - automatically apply kosParentAware\n kosParentAware()(target);\n\n // Add the companion configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[CompanionParentModel] = {\n mode,\n parentProperty,\n excludeProperties,\n lifecycle,\n };\n\n return target;\n };\n}\n","/* eslint-disable no-param-reassign */\nimport type { IKosModelContainer } from \"../kos-container-model\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport { ContainerAwareSetup } from \"./propKeys\";\ntype MaybePromise<T> = T | Promise<T>;\n/**\n * Configuration options for the @kosContainerAware decorator.\n *\n * @template T The type of models contained in the container (must extend IKosDataModel)\n *\n * @kosService core.container-aware\n * @kosApiLevel 13\n */\nexport interface KosContainerAwareOptions<\n T extends IKosDataModel = IKosDataModel\n> {\n /**\n * Container property name on the model instance.\n *\n * @default \"container\"\n * @example\n * ```typescript\n * @kosContainerAware({ containerProperty: \"devices\" })\n * class DeviceContainer {\n * // Access via: this.devices.addModel(...)\n * }\n * ```\n */\n containerProperty?: string;\n\n /**\n * Whether to include convenience methods (getModel, addModel, removeModel, addAll, removeAll,\n * removeAndDestroy, removeAndDestroyAll).\n *\n * @default true\n * @example\n * ```typescript\n * @kosContainerAware({ includeMethods: false })\n * class Container {\n * // Only this.container property available, no convenience methods\n * }\n * ```\n */\n includeMethods?: boolean;\n\n /**\n * Whether to include reactive getters (models, data).\n *\n * @default true\n * @example\n * ```typescript\n * @kosContainerAware({ includeGetters: false })\n * class Container {\n * // No this.models or this.data getters, use this.container.data directly\n * }\n * ```\n */\n includeGetters?: boolean;\n\n /**\n * Container-specific configuration options passed to KosModelContainer constructor.\n *\n * @example\n * ```typescript\n * @kosContainerAware({\n * containerOptions: {\n * sortKey: \"name\",\n * indexMap: {\n * byType: \"deviceType\",\n * active: (device) => device.isOnline\n * },\n * parentId: \"custom-parent\", // Overrides automatic inference\n * extensionId: \"device-manager\",\n * maxCapacity: 1000, // Safety net for unbounded growth\n * evictionStrategy: \"fifo\"\n * }\n * })\n * ```\n */\n containerOptions?: {\n /** Default property to sort models by */\n sortKey?: keyof T;\n\n /**\n * Index mapping for efficient queries. Keys are index names, values are either:\n * - Property names (string keys) for simple property-based indexing\n * - Functions that return index keys for complex logic\n *\n * @example\n * ```typescript\n * indexMap: {\n * byStatus: \"connectionStatus\", // Property-based\n * byType: (device) => device.type.toLowerCase(), // Function-based\n * needsUpdate: (device) => device.version < \"2.0\" // Boolean logic\n * }\n * ```\n */\n indexMap?: Record<\n string,\n keyof T | ((model: T) => MaybePromise<string | string[] | undefined>)\n >;\n\n /**\n * Parent model ID for the container. If not provided, automatically uses\n * the modelId parameter from the model's constructor.\n *\n * @default Inferred from constructor modelId parameter\n */\n parentId?: string;\n\n /** Extension identifier for the container */\n extensionId?: string;\n\n /**\n * SAFETY NET: Maximum number of models this container can hold.\n * When exceeded, models are automatically evicted and destroyed based on evictionStrategy.\n *\n * **Primary use case**: Prevent memory overflow when cleanup handlers are missing or\n * data becomes inconsistent. Set higher than normal usage to catch edge cases.\n *\n * @example\n * ```typescript\n * containerOptions: {\n * maxCapacity: 10000, // Safety net: expect ~100-1000 normally\n * evictionStrategy: 'fifo'\n * }\n * ```\n */\n maxCapacity?: number;\n\n /**\n * Strategy for selecting which models to evict when maxCapacity is exceeded.\n *\n * - **fifo** (default): Remove oldest models first - best for event streams, logs\n * - **lru**: Remove least recently accessed models - best for caches\n * - **custom**: Use customEvictionFilter to determine eviction candidates\n *\n * @default 'fifo'\n */\n evictionStrategy?: \"fifo\" | \"lru\" | \"custom\";\n\n /**\n * Number of models to evict when maxCapacity is exceeded.\n * @default Math.max(10, Math.ceil(maxCapacity * 0.1))\n */\n evictionBatchSize?: number;\n\n /**\n * Custom filter function for 'custom' eviction strategy.\n * Should return models that are candidates for eviction.\n *\n * @example\n * ```typescript\n * customEvictionFilter: (models) => {\n * return models.filter(m =>\n * m.status === 'resolved' &&\n * Date.now() - m.resolvedAt > 3600000\n * );\n * }\n * ```\n */\n customEvictionFilter?: (models: T[]) => T[];\n };\n\n /**\n * Custom name for the reactive models array getter.\n *\n * @default \"models\"\n * @example\n * ```typescript\n * @kosContainerAware({ modelsProperty: \"items\" })\n * class Container {\n * get items() { return this.container.data; } // Instead of 'models'\n * }\n * ```\n */\n modelsProperty?: string;\n\n /**\n * Legacy compatibility mode. Uses '_models' as the container property name\n * instead of 'container' for backward compatibility with existing code.\n *\n * @default false\n * @deprecated Use containerProperty instead for new code\n */\n legacy?: boolean;\n}\n\n/**\n * Interface for models using @kosContainerAware decorator.\n *\n * **IMPORTANT**: Use TypeScript interface merging to add container management properties to your model class.\n * This provides full type safety and IntelliSense support for all injected container functionality.\n *\n * ## Interface Merging Pattern\n *\n * ```typescript\n * // 1. Declare interface merging BEFORE the class\n * interface MyContainerModelImpl extends KosContainerAware<ItemModel> {}\n *\n * // 2. Apply decorator and implement the class\n * @kosModel(\"my-container-model\")\n * @kosContainerAware<ItemModel>()\n * export class MyContainerModelImpl implements IKosDataModel {\n * // All container properties are now available with full type safety\n * }\n * ```\n *\n * ## Custom Container Property Name\n *\n * When using a custom `containerProperty` name, use `KosContainerAwareWithProp`:\n *\n * ```typescript\n * // For custom container property name\n * interface DeviceManagerImpl extends KosContainerAwareWithProp<DeviceModel, \"devices\"> {}\n *\n * @kosContainerAware<DeviceModel>({ containerProperty: \"devices\" })\n * class DeviceManagerImpl implements IKosDataModel {\n * // Access via: this.devices instead of this.container\n * }\n * ```\n *\n * ## Injected Properties and Methods\n *\n * The decorator automatically injects the following members (configurable via options):\n *\n * - **`container`**: Core KosModelContainer instance for direct access (or custom name via `containerProperty`)\n * - **`getModel(id)`**: Retrieve a model by ID from the container\n * - **`addModel(model)`**: Add a model to the container\n * - **`removeModel(id)`**: Remove a model from the container by ID (does not destroy)\n * - **`addAll(models)`**: Add multiple models to the container at once\n * - **`removeAll(ids)`**: Remove multiple models from the container by IDs (does not destroy)\n * - **`removeAndDestroy(id)`**: Remove a model from the container and destroy it\n * - **`removeAndDestroyAll(ids)`**: Remove multiple models from the container and destroy them\n * - **`models`**: Readonly KosModelContainer instance (compatible with IKosModelHolder)\n * - **`data`**: Reactive array of all model instances (compatible with IKosModelHolder)\n *\n * All injected getters are reactive and will automatically update UI components when container contents change.\n *\n * @template T The type of models contained in the container (must extend IKosDataModel)\n *\n * @example\n * ```typescript\n * // Basic usage with minimal configuration\n * interface DeviceContainerModelImpl extends KosContainerAware<DeviceModel> {}\n *\n * @kosModel(\"device-container-model\")\n * @kosContainerAware<DeviceModel>()\n * class DeviceContainerModelImpl implements IKosDataModel {\n * constructor(modelId: string, options: ContainerOptions, context: KosCreationContext) {\n * this.id = modelId;\n * // Container automatically injected with parentId: modelId\n * }\n *\n * // Use injected methods\n * addDevice(device: DeviceModel): void {\n * this.addModel(device); // Method injected by decorator\n * }\n *\n * // Use injected reactive getters\n * get deviceCount(): number {\n * return this.data.length; // Reactive array getter injected by decorator\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Advanced usage with indexing and custom configuration\n * interface UserContainerModelImpl extends KosContainerAware<UserModel> {}\n *\n * @kosModel(\"user-container-model\")\n * @kosContainerAware<UserModel>({\n * containerOptions: {\n * indexMap: {\n * byRole: \"role\",\n * byDepartment: \"department\",\n * active: (user) => user.status === \"active\"\n * },\n * sortKey: \"lastName\"\n * }\n * })\n * class UserContainerModelImpl implements IKosDataModel {\n * // Access indexed data via injected container\n * getActiveUsers(): UserModel[] {\n * return this.container.getIndexByKey(\"active\", true);\n * }\n *\n * getUsersByRole(role: string): UserModel[] {\n * return this.container.getIndexByKey(\"byRole\", role);\n * }\n * }\n * ```\n *\n * @see {@link kosContainerAware} - The decorator function\n * @see {@link KosContainerAwareOptions} - Configuration options\n *\n * @kosService core.container-aware\n * @kosApiLevel 13\n */\nexport interface KosContainerAware<T extends IKosDataModel = IKosDataModel> {\n /**\n * Core container that manages the collection of models.\n * Provides methods to add, remove, and query model instances.\n * Automatically injected by @kosContainerAware decorator.\n */\n container: IKosModelContainer<T>;\n\n /**\n * Retrieves a model from the container by its ID.\n * @param id - The unique identifier of the model to retrieve\n * @returns The model instance if found, undefined otherwise\n */\n getModel(id: string): T | undefined;\n\n /**\n * Adds a model to the container.\n * @param model - The model instance to add\n */\n addModel(model: T): void;\n\n /**\n * Removes a model from the container by its ID.\n * @param id - The unique identifier of the model to remove\n */\n removeModel(id: string): void;\n\n /**\n * Adds multiple models to the container at once.\n * @param models - Array of model instances to add\n * @kosApiLevel 19\n */\n addAll(models: T[]): void;\n\n /**\n * Removes multiple models from the container by their IDs.\n * @param ids - Array of unique identifiers of the models to remove\n * @kosApiLevel 19\n */\n removeAll(ids: string[]): void;\n\n /**\n * Removes a model from the container and destroys it.\n * Convenience method that combines removeModel() and destroyKosModel().\n * @param id - The unique identifier of the model to remove and destroy\n * @kosApiLevel 19\n */\n removeAndDestroy(id: string): Promise<void>;\n\n /**\n * Removes multiple models from the container and destroys them.\n * Convenience method that combines removeAll() and destroyKosModel().\n * @param ids - Array of unique identifiers of the models to remove and destroy\n * @kosApiLevel 19\n */\n removeAndDestroyAll(ids: string[]): Promise<void>;\n\n /**\n * The container instance managing the models.\n * Readonly property that provides access to the KosModelContainer.\n * Compatible with IKosModelHolder interface.\n * Updates automatically when models are added or removed.\n */\n readonly models: IKosModelContainer<T>;\n\n /**\n * Reactive array of all model instances in the container.\n * This is the actual array of models, compatible with IKosModelHolder interface.\n * Updates automatically when models are added or removed.\n */\n data: T[];\n}\n\n/**\n * Base interface providing common container-aware methods and properties.\n * Used internally by both KosContainerAware and KosContainerAwareWithProp.\n *\n * @template T The type of models contained in the container\n *\n * @kosService core.container-aware\n * @kosApiLevel 13\n */\nexport interface KosContainerAwareBase<\n T extends IKosDataModel = IKosDataModel\n> {\n /**\n * Retrieves a model from the container by its ID.\n * @param id - The unique identifier of the model to retrieve\n * @returns The model instance if found, undefined otherwise\n */\n getModel(id: string): T | undefined;\n\n /**\n * Adds a model to the container.\n * @param model - The model instance to add\n */\n addModel(model: T): void;\n\n /**\n * Removes a model from the container by its ID.\n * @param id - The unique identifier of the model to remove\n */\n removeModel(id: string): void;\n\n /**\n * Adds multiple models to the container at once.\n * @param models - Array of model instances to add\n * @kosApiLevel 19\n */\n addAll(models: T[]): void;\n\n /**\n * Removes multiple models from the container by their IDs.\n * @param ids - Array of unique identifiers of the models to remove\n * @kosApiLevel 19\n */\n removeAll(ids: string[]): void;\n\n /**\n * Removes a model from the container and destroys it.\n * Convenience method that combines removeModel() and destroyKosModel().\n * @param id - The unique identifier of the model to remove and destroy\n * @kosApiLevel 19\n */\n removeAndDestroy(id: string): Promise<void>;\n\n /**\n * Removes multiple models from the container and destroys them.\n * Convenience method that combines removeAll() and destroyKosModel().\n * @param ids - Array of unique identifiers of the models to remove and destroy\n * @kosApiLevel 19\n */\n removeAndDestroyAll(ids: string[]): Promise<void>;\n\n /**\n * The container instance managing the models.\n * Readonly property that provides access to the KosModelContainer.\n * Compatible with IKosModelHolder interface.\n * Updates automatically when models are added or removed.\n */\n readonly models: IKosModelContainer<T>;\n\n /**\n * Reactive array of all model instances in the container.\n * This is the actual array of models, compatible with IKosModelHolder interface.\n * Updates automatically when models are added or removed.\n */\n data: T[];\n}\n\n/**\n * Interface for models using @kosContainerAware decorator with a custom container property name.\n *\n * Use this interface when you specify a custom `containerProperty` in the decorator options\n * to get proper type safety for the custom property name.\n *\n * @template T The type of models contained in the container\n * @template P The custom property name for the container (string literal type)\n *\n * @example\n * ```typescript\n * // Specify the custom property name \"devices\" in both the interface and decorator\n * interface DeviceManagerImpl extends KosContainerAwareWithProp<DeviceModel, \"devices\"> {}\n *\n * @kosModel(\"device-manager\")\n * @kosContainerAware<DeviceModel>({ containerProperty: \"devices\" })\n * class DeviceManagerImpl implements IKosDataModel {\n * constructor(modelId: string, options: ContainerOptions, context: KosCreationContext) {\n * this.id = modelId;\n * }\n *\n * addDevice(device: DeviceModel): void {\n * // Access container via custom property name\n * this.devices.addModel(device);\n * }\n *\n * getDeviceCount(): number {\n * // The 'data' property is still available\n * return this.data.length;\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Custom property for user management\n * interface UserManagerImpl extends KosContainerAwareWithProp<UserModel, \"users\"> {}\n *\n * @kosContainerAware<UserModel>({\n * containerProperty: \"users\",\n * containerOptions: {\n * indexMap: {\n * byRole: \"role\"\n * }\n * }\n * })\n * class UserManagerImpl implements IKosDataModel {\n * getUsersByRole(role: string): UserModel[] {\n * // Access via this.users instead of this.container\n * return this.users.getIndexByKey(\"byRole\", role);\n * }\n * }\n * ```\n *\n * @kosService core.container-aware\n */\nexport type KosContainerAwareWithProp<\n T extends IKosDataModel = IKosDataModel,\n P extends string = \"container\"\n> = KosContainerAwareBase<T> & {\n [K in P]: IKosModelContainer<T>;\n};\n\n/**\n * Class decorator that automatically adds container management capabilities to a KOS model.\n *\n * This decorator eliminates the need for manual container setup by:\n * - **Adding a container property** (default: `container`) for managing model collections\n * - **Adding convenience methods** (`getModel`, `addModel`, `removeModel`, `addAll`, `removeAll`, `removeAndDestroy`, `removeAndDestroyAll`) if `includeMethods` is true (default)\n * - **Adding reactive getters** (`models`, `data`) if `includeGetters` is true (default)\n * - **Automatically inferring parentId** from the model's constructor `modelId` parameter\n * - **Registering container as @kosChild** for proper lifecycle management and cleanup\n * - **Supporting custom indexing** via `containerOptions.indexMap` for efficient queries\n *\n * ## Automatic Hierarchy Integration\n *\n * The decorator automatically registers the container as a `@kosChild`, ensuring:\n * - Proper lifecycle management (init, load, destroy)\n * - Automatic cleanup when parent model is destroyed\n * - Participation in the KOS reactive system\n * - Memory management and observer disposal\n *\n * ## TypeScript Usage\n *\n * **IMPORTANT**: Use TypeScript interface merging to get proper type information:\n *\n * ```typescript\n * interface MyContainerModelImpl extends KosContainerAware<MyItemModel> {}\n *\n * @kosContainerAware<MyItemModel>()\n * class MyContainerModelImpl implements IKosDataModel {\n * // All container properties are now available with full type safety\n * }\n * ```\n *\n * ## Model Lifecycle: removeModel vs removeAndDestroy\n *\n * The decorator provides both removal and destruction methods with different purposes:\n *\n * **removeModel(id) / removeAll(ids)** - Removes from container WITHOUT destroying:\n * - Use when moving models between containers\n * - Use when temporarily hiding models that may be re-added\n * - Use when model lifecycle is managed elsewhere\n * - Container handles cleanup of observers and metadata\n * - Model remains in memory and can be used elsewhere\n *\n * **removeAndDestroy(id) / removeAndDestroyAll(ids)** - Removes AND destroys:\n * - Use when permanently removing models from the system\n * - Use when models should be fully cleaned up and disposed\n * - Calls destroyKosModel() automatically after removal\n * - Ensures proper cleanup of all model resources\n * - Model is removed from framework and memory\n *\n * ```typescript\n * // Example: Explicit lifecycle control\n * @kosTopicHandler({ topic: \"/device/sensor/removed\" })\n * handleSensorRemoved(id: string) {\n * // Permanently remove - sensor is gone from system\n * await this.removeAndDestroy(id);\n * }\n *\n * // Example: Reorganization without destruction\n * moveSensorToArchive(id: string) {\n * const sensor = this.getModel(id);\n * if (sensor) {\n * this.removeModel(id); // Remove from active container\n * this.archive.addModel(sensor); // Add to archive container\n * }\n * }\n * ```\n *\n * ## Configuration Options\n *\n * ```typescript\n * @kosContainerAware<UserModel>({\n * containerProperty: \"users\", // Custom property name (default: \"container\")\n * includeMethods: true, // Include convenience methods (default: true)\n * includeGetters: true, // Include reactive getters (default: true)\n * modelsProperty: \"userList\", // Custom models getter name (default: \"models\")\n * legacy: false, // Use \"_models\" property name (default: false)\n * containerOptions: {\n * parentId: \"custom-parent\", // Override automatic parentId inference\n * sortKey: \"name\", // Default sorting key\n * extensionId: \"my-extension\", // Extension identifier\n * indexMap: { // Automatic indexing for efficient queries\n * byRole: \"role\", // Property-based index\n * byStatus: (user) => user.active ? \"active\" : \"inactive\", // Function-based index\n * admins: (user) => user.role === \"admin\" // Boolean index\n * }\n * }\n * })\n * ```\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator that modifies the target class prototype\n *\n * @see {@link KosContainerAware} - Interface for TypeScript merging\n * @see {@link KosContainerAwareOptions} - Configuration options interface\n *\n * @example\n * ```typescript\n * // Minimal configuration - parentId automatically inferred\n * interface ItemContainerModelImpl extends KosContainerAware<ItemModel> {}\n *\n * @kosContainerAware<ItemModel>()\n * class ItemContainerModelImpl implements IKosDataModel {\n * id: string;\n *\n * constructor(modelId: string, options: ContainerOptions, context: KosCreationContext) {\n * this.id = modelId;\n * // Container automatically created with parentId: modelId\n * }\n * }\n *\n * // With index configuration\n * interface UserContainerModelImpl extends KosContainerAware<UserModel> {}\n *\n * @kosContainerAware<UserModel>({\n * containerOptions: {\n * indexMap: {\n * byRole: \"role\",\n * byStatus: (user) => user.status\n * }\n * }\n * })\n * class UserContainerModelImpl implements IKosDataModel {\n * constructor(modelId: string, options: ContainerOptions, context: KosCreationContext) {\n * this.id = modelId;\n * }\n * }\n *\n * // Legacy mode for backward compatibility\n * interface LegacyContainerModelImpl extends KosContainerAware<LegacyModel> {}\n *\n * @kosContainerAware<LegacyModel>({\n * legacy: true, // Uses '_models' as property name\n * containerOptions: {\n * sortKey: \"name\"\n * }\n * })\n * class LegacyContainerModelImpl implements IKosDataModel {\n * // Container available as this._models for backward compatibility\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.1.0\n * @kosService core.container-aware\n * @kosApiLevel 13\n */\nexport function kosContainerAware<T extends IKosDataModel = IKosDataModel>(\n options?: KosContainerAwareOptions<T>\n): ClassDecorator {\n return (target: any) => {\n const containerProperty = options?.legacy\n ? \"_models\"\n : options?.containerProperty || \"container\";\n const includeMethods = options?.includeMethods !== false;\n const includeGetters = options?.includeGetters !== false;\n const modelsProperty = options?.modelsProperty || \"models\";\n const containerOptions = options?.containerOptions || {};\n\n // Add the ContainerAwareSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[ContainerAwareSetup] = {\n containerProperty,\n includeMethods,\n includeGetters,\n modelsProperty,\n containerOptions,\n legacy: options?.legacy || false,\n };\n\n return target;\n };\n}\n","/**\n * @internal\n */\nimport { KosContextManager } from \"../context/kos-context-manager\";\n\n/**\n * Method decorator that injects the current KOS execution context into a method call.\n *\n * @kosService core.context\n * @kosApiLevel 2\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","import type { ClientResponse } from \"../../util/kos-service-request\";\nimport type { KosExecutionContext } from \"./kos-execution-context\";\nimport type { KosLoggerAware } from \"./kos-logger-aware\";\nimport type { HttpMethod, ServiceRequestExecutor } from \"./kos-service-request\";\n\n/**\n * Run a METHOD-DRIVEN service request, collapsing the four steps every such\n * method repeats: guard the injected context, await the error-first tuple, log\n * a failure, and reject an empty body. Callers are left with the success path:\n *\n * ```typescript\n * const data = await executeServiceRequest(this, $ctx, {\n * body: { id: cartridgeId },\n * });\n * if (!data) return;\n * ```\n *\n * Failures are attributed to the method through `$ctx.$name`, which the\n * decorator injects — nothing to pass, and nothing to leave stale at the next\n * rename.\n *\n * ONLY for the method-driven form — a `@kosServiceRequest` WITHOUT `lifecycle`.\n * The decorator injects `$ctx.$request` only on that branch; a lifecycle\n * handler is invoked by the ServiceRequestManager with the request already\n * performed, error-first as `(error, data)`, and never receives a context. See\n * `KosExecutionContext`.\n *\n * @param host Model the request belongs to; supplies the logger.\n * @param $ctx Context the decorator injected as the method's last parameter.\n * @param params `pathParams` / `queryParams` / `body` / `requestOptions`.\n * @returns The response body, or `undefined` when the request could not run,\n * failed, or came back empty.\n *\n * @kosService core.service-request\n * @kosApiLevel 24\n */\nexport async function executeServiceRequest<\n Paths extends Record<string, any>,\n Path extends keyof Paths,\n Method extends HttpMethod = \"get\",\n Transformed = ClientResponse<Paths, Path, Method>\n>(\n host: KosLoggerAware,\n $ctx: KosExecutionContext<Paths, Path, Method, Transformed> | undefined,\n params?: Parameters<ServiceRequestExecutor<Paths, Path, Method>>[0]\n): Promise<NonNullable<Transformed> | undefined> {\n // Only the no-context branch has no name to report — by definition.\n const name = $ctx?.$name ?? \"service request\";\n if (!$ctx?.$request) {\n // Reaching this almost always means the decorator declared a `lifecycle`,\n // which suppresses context injection entirely — name that, because the\n // symptom (a method that silently does nothing) points nowhere useful.\n host.logger.error(\n `${name}: missing execution context — executeServiceRequest is for method-driven requests; ` +\n `a @kosServiceRequest with a lifecycle receives (error, data) instead and needs no helper`\n );\n return undefined;\n }\n\n const [error, data] = await $ctx.$request(params);\n if (error) {\n host.logger.error(`${name}: request failed`, error);\n return undefined;\n }\n if (data == null) {\n host.logger.error(`${name}: no data returned`);\n return undefined;\n }\n // The context carries what the request actually yields — the raw response, or\n // the transform's output when the decorator declared one.\n return data as NonNullable<Transformed>;\n}\n","/* eslint-disable no-param-reassign */\nimport type {\n FutureAwareContainer,\n IFutureModel,\n} from \"../../../models/models/future/future-types\";\nimport { FutureContainerSetup } from \"./propKeys\";\n\n/**\n * @kosService core.future-aware\n * @kosApiLevel 13\n */\nexport interface KosFutureAwareOptions {\n /** Setup mode: 'full' includes all UI properties, 'minimal' only futureHandler. Default: 'full' */\n mode?: \"full\" | \"minimal\";\n /** Custom futureHandler property name. Default: 'futureHandler' */\n handlerProperty?: string;\n}\n\n/**\n * Interface for models using @kosFutureAware in minimal mode.\n * Use TypeScript interface merging to add the futureHandler property to your model class.\n *\n * @example\n * Add ESLint disable comment at top of file, then:\n * ```typescript\n * interface BackgroundServiceModelImpl extends KosFutureAwareMinimal {}\n *\n * kosFutureAware({ mode: 'minimal' })\n * class BackgroundServiceModelImpl implements IKosDataModel {\n * // futureHandler is now available via interface merging\n * }\n * ```\n *\n * @kosService core.future-aware\n * @kosApiLevel 13\n */\nexport interface KosFutureAwareMinimal<\n T extends object = Record<string, unknown>\n> {\n /**\n * Core future management container that handles Future lifecycle operations.\n * Provides methods to add, remove, and query Future instances.\n * Automatically injected by @kosFutureAware decorator.\n */\n futureHandler: FutureAwareContainer<T>;\n}\n\n/**\n * Interface for models using @kosFutureAware in full mode (default).\n * Use TypeScript interface merging to add all Future Container properties to your model class.\n *\n * @example\n * Add ESLint disable comment at top of file, then:\n * ```typescript\n * interface CopyLogsModelImpl extends KosFutureAwareFull<CopyProgress> {}\n *\n * kosFutureAware() // defaults to full mode\n * class CopyLogsModelImpl implements IKosDataModel {\n * // All Future Container properties are now available automatically\n *\n * onFutureUpdate?(future: IFutureModel<CopyProgress>): void {\n * // Access typed clientData\n * }\n * }\n * ```\n *\n * @kosService core.future-aware\n * @kosApiLevel 13\n */\nexport interface KosFutureAwareFull<T extends object = Record<string, unknown>>\n extends KosFutureAwareMinimal<T> {\n /**\n * Current active Future model instance containing operation details.\n * Undefined when no operation is active. Automatically updated when\n * operations start, progress, complete, or fail.\n */\n future?: IFutureModel<T>;\n\n /**\n * Current operation progress as a percentage (0-100).\n * Returns 0 when no Future is active. Updates automatically as the\n * Future operation progresses via WebSocket events.\n */\n progress: number;\n\n /**\n * Current operation status string representation.\n * Common values: \"IDLE\", \"IN_PROGRESS\", \"SUCCESS\", \"ERROR\", \"CANCELLED\".\n * Returns \"IDLE\" when no Future is active.\n */\n status: string;\n\n /**\n * Whether an operation is currently actively executing.\n * True when Future exists and has not reached an end state.\n * False when no Future exists or operation has completed/failed/cancelled.\n */\n isRunning: boolean;\n\n /**\n * Whether the current or most recent operation was cancelled.\n * Remains true after cancellation for status tracking until a new\n * operation starts. False if operation completed normally or failed.\n */\n isCancelled: boolean;\n\n /**\n * Cancels the currently running Future operation.\n * Sends cancellation request to the backend service managing the Future.\n * No-op if no Future is currently active.\n * @returns Promise that resolves when cancellation is acknowledged\n * @throws Error if cancellation request fails\n */\n cancelFuture(): Promise<void>;\n}\n\n/**\n * Class decorator that automatically adds Future Container capabilities to a KOS model.\n *\n * This decorator eliminates the need for manual Future Container setup by:\n * - Adding a futureHandler property for managing Future operations\n * - Adding reactive getters for future, progress, status, isRunning, isCancelled (in full mode)\n * - Adding cancelFuture method for canceling operations (in full mode)\n *\n * **Important**: Use TypeScript interface merging to get proper type information:\n *\n * ```typescript\n * // Add ESLint disable comment at top of file, then:\n * interface MyModelImpl extends KosFutureAwareFull<MyDataType> {}\n *\n * kosFutureAware()\n * class MyModelImpl implements IKosDataModel {\n * // All Future properties are now available with full type safety\n * }\n * ```\n *\n * Note: This decorator supports single Future operations. For models that need to manage\n * multiple concurrent Futures, use @kosMultiFutureAware (coming soon).\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * // Full mode example\n * interface DeviceOperationsModelImpl extends KosFutureAwareFull<OperationData> {}\n *\n * kosFutureAware()\n * class DeviceOperationsModelImpl implements IKosDataModel {\n * onFutureUpdate?(future: IFutureModel<OperationData>): void {\n * // Handle Future updates\n * }\n *\n * kosFuture()\n * async performOperation(): Promise<OperationData> {\n * return { result: \"done\" };\n * }\n * }\n *\n * // Minimal mode example\n * interface BackgroundServiceModelImpl extends KosFutureAwareMinimal {}\n *\n * kosFutureAware({ mode: 'minimal' })\n * class BackgroundServiceModelImpl implements IKosDataModel {\n * kosFuture()\n * async backgroundTask() {\n * return \"done\";\n * }\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.0.0\n * @kosService core.future-aware\n * @kosApiLevel 13\n */\nexport function kosFutureAware(\n options?: KosFutureAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const mode = options?.mode || \"full\";\n const handlerProperty = options?.handlerProperty || \"futureHandler\";\n\n // Add the FutureContainerSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[FutureContainerSetup] = {\n mode,\n handlerProperty,\n };\n\n return target;\n };\n}\n","/* eslint-disable no-param-reassign */\nimport type { MultipleFutureHandler } from \"../../../models/models/future/future-aware\";\nimport type { IFutureModel } from \"../../../models/models/future/future-types\";\nimport { MultipleFutureContainerSetup } from \"./propKeys\";\n\n/**\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport interface KosMultipleFutureAwareOptions {\n /** Setup mode: 'full' includes all UI properties, 'minimal' only futureHandler. Default: 'full' */\n mode?: \"full\" | \"minimal\";\n /** Custom futureHandler property name. Default: 'futureHandler' */\n handlerProperty?: string;\n}\n\n/**\n * Interface for models using @kosMultipleFutureAware in minimal mode.\n * Use TypeScript interface merging to add the futureHandler property and named futures to your model class.\n *\n * @example\n * Add ESLint disable comment at top of file, then:\n * ```typescript\n * interface MaintenanceModelImpl extends KosMultipleFutureAwareMinimal {\n * // Add your specific named futures manually for strong typing:\n * calibrationFuture?: IFutureModel;\n * cleaningFuture?: IFutureModel;\n * }\n *\n * @kosMultipleFutureAware({ mode: 'minimal' })\n * class MaintenanceModelImpl implements IKosDataModel {\n * // futureHandler and named futures are now available via interface merging\n * }\n * ```\n *\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport interface KosMultipleFutureAwareMinimal {\n /**\n * Core multiple future management container that handles concurrent Future lifecycle operations.\n * Provides methods to add, remove, and query multiple Future instances.\n * Automatically injected by @kosMultipleFutureAware decorator.\n */\n futureHandler: MultipleFutureHandler;\n}\n\n/**\n * Utility types to generate future property names for multiple futures (for internal use)\n */\ntype FutureGetters<T extends string> = {\n readonly [K in T as `${K}Future`]?: IFutureModel;\n};\n\ntype ProgressGetters<T extends string> = {\n readonly [K in T as `${K}Progress`]: number;\n};\n\ntype StatusGetters<T extends string> = {\n readonly [K in T as `${K}Status`]: string;\n};\n\ntype IsRunningGetters<T extends string> = {\n readonly [K in T as `${K}IsRunning`]: boolean;\n};\n\ntype IsCancelledGetters<T extends string> = {\n readonly [K in T as `${K}IsCancelled`]: boolean;\n};\n\ntype CancelMethods<T extends string> = {\n readonly [K in T as `cancel${Capitalize<K>}`]: () => Promise<void>;\n};\n\n/**\n * @kosService core.future-aware\n */\nexport type MultipleFutureProperties<T extends string> = FutureGetters<T> &\n ProgressGetters<T> &\n StatusGetters<T> &\n IsRunningGetters<T> &\n IsCancelledGetters<T> &\n CancelMethods<T>;\n\n/**\n * Interface for models using @kosMultipleFutureAware in full mode (default).\n * Use TypeScript interface merging to add all Future Container properties and named futures to your model class.\n *\n * @example\n * Add ESLint disable comment at top of file, then:\n * ```typescript\n * interface IceAgitatorModelImpl extends KosMultipleFutureAwareFull<\"pour\" | \"agitate\" | \"gate\"> {}\n *\n * @kosMultipleFutureAware() // defaults to full mode\n * class IceAgitatorModelImpl implements IKosDataModel {\n * // Each alias gets its own members, e.g. this.pourFuture, this.pourProgress,\n * // this.pourStatus, this.pourIsRunning, this.cancelPour()\n *\n * onFutureUpdate?(future: IFutureModel, alias?: string): void {\n * // Handle updates from any managed Future\n * // Use alias to identify which future triggered the update\n * if (alias === 'pour') {\n * console.log(`Pour operation: ${future.progress}%`);\n * }\n * }\n * }\n * ```\n *\n * @kosService core.future-aware\n */\nexport type KosMultipleFutureAwareFull<T extends string = string> =\n KosMultipleFutureAwareMinimal & MultipleFutureProperties<T>;\n\n/**\n * Class decorator that automatically adds Multiple Future Container capabilities to a KOS model.\n *\n * This decorator eliminates the need for manual MultipleFutureHandler setup by:\n * - Adding a futureHandler property for managing multiple concurrent Future operations\n * - Adding `<alias>Future` for each @kosFuture alias, plus `<alias>Progress`, `<alias>Status`,\n * `<alias>IsRunning`, `<alias>IsCancelled` and `cancel<Alias>()` in full mode\n *\n * **Important**: Use TypeScript interface merging to get proper type information:\n *\n * ```typescript\n * // Add ESLint disable comment at top of file, then:\n * interface MyModelImpl extends KosMultipleFutureAwareFull<\"operation1\" | \"operation2\"> {}\n *\n * @kosMultipleFutureAware()\n * class MyModelImpl implements IKosDataModel {\n * // All Future properties and named futures are now available with full type safety\n * }\n * ```\n *\n * Note: This decorator supports multiple concurrent Future operations. For models that only need\n * single Future support, use @kosFutureAware instead.\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * // Full mode example with multiple futures\n * interface IceAgitatorModelImpl extends KosMultipleFutureAwareFull<\"pour\" | \"agitate\" | \"gate\"> {}\n *\n * @kosMultipleFutureAware()\n * class IceAgitatorModelImpl implements IKosDataModel {\n * get isPouring() {\n * return !!(this.pourFuture && !this.pourFuture?.endState);\n * }\n *\n * onFutureUpdate?(future: IFutureModel, alias?: string): void {\n * // Handle Future updates from any operation\n * // Use alias to discriminate between different future types\n * if (alias === 'pour') {\n * console.log(`Pouring ice: ${future.progress}%`);\n * } else if (alias === 'agitate') {\n * console.log(`Agitating: ${future.progress}%`);\n * }\n * }\n *\n * @kosFuture({ alias: \"pour\" })\n * async pourIce(): Promise<void> {\n * // Pour operation\n * }\n *\n * @kosFuture({ alias: \"agitate\" })\n * async testAgitate(): Promise<void> {\n * // Agitation operation\n * }\n * }\n *\n * // Minimal mode example: declare the alias futures you read\n * interface BackgroundServiceModelImpl extends KosMultipleFutureAwareMinimal {\n * task1Future?: IFutureModel;\n * task2Future?: IFutureModel;\n * }\n *\n * @kosMultipleFutureAware({ mode: 'minimal' })\n * class BackgroundServiceModelImpl implements IKosDataModel {\n * @kosFuture({ alias: \"task1\" })\n * async backgroundTask1() {\n * return \"done\";\n * }\n *\n * @kosFuture({ alias: \"task2\" })\n * async backgroundTask2() {\n * return \"done\";\n * }\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.0.0\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport function kosMultipleFutureAware(\n options?: KosMultipleFutureAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const mode = options?.mode || \"full\";\n const handlerProperty = options?.handlerProperty || \"futureHandler\";\n\n // Add the MultipleFutureContainerSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[MultipleFutureContainerSetup] = {\n mode,\n handlerProperty,\n };\n\n return target;\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}\n/**\n * @kosService core.logging\n * @kosApiLevel 2\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 type { KosContextLogger } from \"../kosModel\";\nimport { KosLoggerFactory } from \"../model/kos-logger-factory\";\nimport { KosViewModelSymbol, LoggerSetup } from \"./propKeys\";\n\n/**\n * @kosService core.logger-aware\n * @kosApiLevel 13\n */\nexport interface KosLoggerAwareOptions {\n /** Logger property name. Default: 'logger' */\n loggerProperty?: string;\n /** Logger context/group name. If not provided, uses model type */\n loggerContext?: string;\n}\n\n/**\n * Interface for models using @kosLoggerAware decorator.\n * Use TypeScript interface merging to add the logger property to your model class.\n *\n * @example\n * ```typescript\n * interface MyModelImpl extends KosLoggerAware {}\n *\n * @kosModel(\"my-model\")\n * @kosLoggerAware()\n * export class MyModelImpl implements IKosDataModel {\n * id: string;\n *\n * constructor(modelId: string, options: any, context: KosCreationContext) {\n * this.id = modelId;\n * // No logger setup needed - automatically injected!\n * }\n *\n * async performOperation() {\n * this.logger.info(\"Starting operation\"); // Direct access to logger\n * }\n * }\n * ```\n *\n * @kosService core.logger-aware\n * @kosApiLevel 13\n */\nexport interface KosLoggerAware {\n /**\n * KOS context logger for this model instance.\n * Automatically injected by the @kosLoggerAware decorator.\n * Shared across all instances of the same model type for optimal performance.\n * Provides structured logging with debug(), info(), warn(), and error() methods.\n * Logger context is automatically set to the model type name unless overridden.\n */\n logger: KosContextLogger;\n}\n\n/**\n * Class decorator that automatically injects a shared logger into a KOS model.\n *\n * This decorator eliminates the need for manual logger setup in constructors by:\n * - Creating a single shared logger per model type (not per instance)\n * - Using the KosLoggerFactory for consistent logger creation\n * - Following KOS naming conventions for logger context\n * - Providing optimal performance through logger reuse\n *\n * **Performance Note**: Creates one logger per model type, shared across all instances\n * of that type. This is much more efficient than per-instance logger creation.\n *\n * **Important**: Use TypeScript interface merging to get proper type information:\n *\n * ```typescript\n * interface MyModelImpl extends KosLoggerAware {}\n *\n * @kosModel(\"my-model\")\n * @kosLoggerAware()\n * export class MyModelImpl implements IKosDataModel {\n * // logger property is now available with full type safety\n * async doSomething() {\n * this.logger.debug(\"Doing something...\");\n * }\n * }\n * ```\n *\n * @param options Configuration options for the logger injection\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * // Basic usage with default logger property\n * @kosLoggerAware()\n * class MyModel { }\n *\n * // Custom logger property name\n * @kosLoggerAware({ loggerProperty: 'log' })\n * class MyModel {\n * // this.log is available instead of this.logger\n * }\n *\n * // Custom logger context for specialized logging\n * @kosLoggerAware({ loggerContext: 'analytics' })\n * class AnalyticsModel {\n * // Logger uses \"analytics\" context instead of model type\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.1.0\n * @kosService core.logger-aware\n * @kosApiLevel 13\n */\nexport function kosLoggerAware(\n options?: KosLoggerAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const loggerProperty = options?.loggerProperty || \"logger\";\n const loggerContext = options?.loggerContext;\n\n // Store configuration on prototype so kosModel.ts can detect it\n target.prototype[LoggerSetup] = {\n loggerProperty,\n loggerContext,\n };\n\n // @kosModel sets modelTypeId; @kosViewModel stores its type under KosViewModelSymbol.\n const getModelType = () =>\n target.prototype.modelTypeId ??\n target.prototype[KosViewModelSymbol]?.type;\n\n // Create logger once per model type (not per instance)\n let sharedLogger: KosContextLogger;\n\n // Define getter that creates logger lazily when first accessed\n Object.defineProperty(target.prototype, loggerProperty, {\n get() {\n if (!sharedLogger) {\n const modelType = getModelType();\n sharedLogger = KosLoggerFactory.create({\n modelTypeName: loggerContext || modelType,\n component: \"kos-model\",\n });\n }\n return sharedLogger;\n },\n enumerable: false,\n configurable: false,\n });\n\n return target;\n };\n}\n","/* eslint-disable no-param-reassign */\nimport { ModelEffects } from \"./propKeys\";\n\n/**\n * @kosService core.model-effect\n * @kosApiLevel 2\n */\ninterface KosModelEffectProps<T = any> {\n dependencies: (model: T) => any[];\n /**\n * @kosApiLevel 3\n */\n options?: {\n fireImmediately?: boolean;\n };\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 * @kosService core.model-effect\n * @kosApiLevel 2\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 options: props?.options,\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 { warnDeprecated } from \"@kosdev-code/kos-api-levels\";\nimport { ReferenceConfig } from \"./propKeys\";\n\n/**\n * @kosService core.reference\n * @kosApiLevel 2\n */\ninterface ReferenceProps {\n modelType: string;\n}\n\n/**\n * @kosService core.reference\n * @kosApiLevel 2\n * @kosDeprecated {replacement: @kosDependency, removeAt: 3}\n */\nexport const kosReference =\n (props: ReferenceProps) =>\n (target: {} | any, name: PropertyKey): any => {\n warnDeprecated(\"@kosReference\", \"core.reference\", 1, \"@kosDependency\", 3);\n target[ReferenceConfig] = target[ReferenceConfig] || {};\n target[ReferenceConfig][name] = props;\n };\n","/**\n * @kosService core.fetch\n * @kosApiLevel 1\n */\nexport enum KosFetchMethods {\n GET = `GET`,\n PUT = `PUT`,\n POST = `POST`,\n DELETE = `DELETE`,\n}\n\ntype FetchMethodStrings = keyof typeof KosFetchMethods;\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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 * Configuration for automatic retry with exponential backoff.\n *\n * @kosService core.fetch\n *\n * When `retry` is set to `true` on {@link KosFetchOptions}, these defaults apply.\n * When set to a partial `RetryConfig`, unspecified fields use these defaults:\n * - `maxAttempts`: 3\n * - `baseDelayMs`: 350\n * - `backoffFactor`: 2\n * - `retryMutations`: false (POST, PUT, DELETE, PATCH are NOT retried)\n * - `retryOn`: retries on any error (return `true` to retry, `false` to stop)\n *\n * @example\n * ```typescript\n * // Use all defaults\n * retry: true\n *\n * // Custom config\n * retry: {\n * maxAttempts: 5,\n * retryOn: (response) => response.status === 503 || response.status === 429,\n * }\n * ```\n *\n * @category Service Request\n * @kosApiLevel 22\n */\nexport interface RetryConfig {\n /** Maximum number of attempts (including the initial request). @default 3 */\n maxAttempts?: number;\n\n /** Base delay in milliseconds before the first retry. @default 350 */\n baseDelayMs?: number;\n\n /** Multiplier applied to the delay after each attempt. @default 2 */\n backoffFactor?: number;\n\n /**\n * Whether to retry mutating methods (POST, PUT, DELETE, PATCH).\n * Set to `true` only if the endpoint is idempotent.\n * @default false\n */\n retryMutations?: boolean;\n\n /**\n * Predicate called with the {@link Response} to decide if a failed request\n * should be retried. Return `true` to retry, `false` to stop immediately.\n *\n * If not provided, all errors are retried (up to `maxAttempts`).\n *\n * @example\n * ```typescript\n * retryOn: (response) => response.status >= 500\n * ```\n */\n retryOn?: (response: Response) => boolean;\n}\n\n/**\n * Represents the configuration options for performing a Kos WebSocket fetch operation.\n *\n * @kosService core.fetch\n * @kosApiLevel 2\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 - can be string, ArrayBuffer, Blob, or FormData.\n */\n body?: string | ArrayBuffer | Blob | FormData | Uint8Array;\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 /**\n * Timeout budget for the **entire call**, in milliseconds: waiting for the\n * transport to become ready plus the request itself.\n *\n * A request issued while the socket is down or reconnecting settles within\n * this budget — it rejects with a `TransportNotReadyError` if the transport\n * never becomes ready — rather than queuing indefinitely. If the transport\n * becomes ready with budget remaining, the remainder applies to the request,\n * which then rejects with a `TimeoutError` `DOMException`. The two errors are\n * distinct so callers can tell \"service is slow\" from \"transport is down\".\n *\n * Defaults to the `KOS_WS_TIMEOUT` environment value, or 30000.\n *\n * Pass `0` or `Infinity` to opt out of the budget entirely and queue until\n * the transport recovers — a request that does this can never settle while\n * the socket is down.\n */\n timeout?: number;\n\n /**\n * @kosApiLevel 5\n */\n headers?: Record<string, string>;\n\n /**\n * Enable streaming mode for large responses\n * @kosApiLevel 11\n */\n stream?: boolean;\n\n /**\n * Response type hint for binary data handling\n * @kosApiLevel 11\n */\n responseType?: \"text\" | \"json\" | \"arraybuffer\" | \"blob\";\n\n /**\n * Retry configuration for transient failures.\n *\n * - `true`: enable retry with all defaults\n * - `RetryConfig`: partial overrides (unspecified fields use defaults)\n * - `undefined` / omitted: no retry (current behavior)\n *\n * Mutating methods (POST, PUT, DELETE, PATCH) are NOT retried by default.\n * Set `retryMutations: true` to opt in.\n * @kosApiLevel 22\n */\n retry?: boolean | RetryConfig;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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 * @kosApiLevel 5\n */\n headers?: Record<string, string | number | boolean>;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosMessageRequest\n extends Omit<KosFetchReqeust, \"method\" | \"path\" | \"requestId\"> {\n requestType: string;\n requestId?: string;\n headers?: Record<string, string>;\n}\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosBroadcastRequest {\n topic: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosMessageOptions extends KosBroadcastRequest {\n destinationAddress?: string;\n responseId?: string;\n type?: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosHttpMessageOptions {\n destinationAddress: string;\n sourceAddress: string;\n responseId: string;\n status: number;\n type: string;\n contentType?: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchResponseParams {\n path: string;\n responseId?: string;\n destinationAddress: string;\n status: string | number | boolean;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchPostReqeust extends KosFetchReqeust {\n body?: string;\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { DependencyModels, TroubleAwareSetup } from \"./propKeys\";\n\n/**\n * @kosService core.trouble-aware\n * @kosApiLevel 13\n */\nexport interface KosTroubleAwareOptions {\n /** Path property name to use for trouble resolution. Default: 'path' */\n pathProperty?: string;\n}\n\n/**\n * Class decorator that automatically adds TroubleAware capabilities to a KOS model.\n *\n * This decorator eliminates the need for manual TroubleAware interface implementation by:\n * - Adding troubleContainer dependency injection (internal, not exposed)\n * - Adding troubles getter that filters by model path\n * - Adding troubleStatus getter (returns empty string by default)\n * - Adding troublesByType getter that groups troubles by type\n *\n * **Important**: Use TypeScript interface merging to get proper type information:\n *\n * ```typescript\n * // Add ESLint disable comment at top of file, then:\n * interface MyModelImpl extends TroubleAware {}\n *\n * @kosTroubleAware()\n * class MyModelImpl implements IKosDataModel {\n * path: string; // Required for trouble resolution\n *\n * constructor(modelId: string, options: MyOptions) {\n * this.path = options.path;\n * // All TroubleAware properties are now available with full type safety\n * }\n * }\n * ```\n *\n * The decorator requires the model to have a path property (default) or specify\n * a custom path property via options.\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * // Default usage - uses this.path\n * interface HolderModelImpl extends TroubleAware {}\n *\n * @kosTroubleAware()\n * class HolderModelImpl implements IKosDataModel {\n * path: string; // Required for trouble path resolution\n *\n * constructor(modelId: string, options: HolderOptions) {\n * this.path = options.path;\n * }\n * }\n *\n * // Custom path property\n * interface CustomModelImpl extends TroubleAware {}\n *\n * @kosTroubleAware({ pathProperty: 'devicePath' })\n * class CustomModelImpl implements IKosDataModel {\n * devicePath: string; // Custom path property\n *\n * constructor(modelId: string, options: CustomOptions) {\n * this.devicePath = options.devicePath;\n * }\n * }\n *\n * // Type-safe external interface\n * export type HolderModel = PublicModelInterface<HolderModelImpl> & TroubleAware;\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.0.0\n * @kosService core.trouble-aware\n * @kosApiLevel 13\n */\nexport function kosTroubleAware(\n options?: KosTroubleAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const pathProperty = options?.pathProperty || \"path\";\n\n // Add the TroubleAwareSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[TroubleAwareSetup] = {\n pathProperty,\n };\n\n // Add troubleContainer as a managed dependency\n target.prototype[DependencyModels] =\n target.prototype[DependencyModels] || {};\n target.prototype[DependencyModels][\"troubleContainer\"] = {\n modelType: \"trouble-container-model\",\n id: \"trouble-container-model\", // TroubleContainer is a singleton\n options: {},\n lazy: false, // Ensure it's created immediately\n };\n\n return target;\n };\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 phase that resolves the dependency and waits for it\n * to be ready (default INIT). ACTIVATE and ONLINE resolve again each time the phase repeats.\n * @param params.resolutionPolicy What to do when no model with the id exists: CREATE (default)\n * creates it, CONTINUE leaves the property undefined, FAIL fails the dependent at the phase.\n *\n * @category KOS Model Decorator\n * @kosService core.dependency\n * @kosApiLevel 2\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 resolutionPolicy,\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 resolutionPolicy,\n };\n };\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { KosContext } from \"../context\";\nimport { ExtensionManager } from \"../extension\";\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport interface ExtensionPointOptions {\n extension: string;\n}\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport interface InitializeContextExtensionPointOptions\n extends ExtensionPointOptions {\n context?: KosContext;\n}\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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 * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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 * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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 * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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","/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const PLUGIN_EXTENSION_NAME = \"Extensions\";\n\n/**\n * Represents the type for the extensions.\n */\n/**\n * @kosService core.extension\n */\nexport interface PluginExtensionsType {\n [k: string]: {\n [k: string]: {\n component?: string;\n remote?: string;\n };\n };\n}\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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","/**\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 *\n * @kosService core.utils\n * @kosApiLevel 2\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","/**\n * @deprecated\n * @internal\n */\nimport { warnDeprecated } from \"@kosdev-code/kos-api-levels\";\nimport { action } from \"mobx\";\nimport debounce from \"../../util/debounce\";\nimport { SubscriptionHandlers } from \"./propKeys\";\n\n/**\n * @kosService core.subscribe\n * @kosApiLevel 2\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\n/**\n * @kosService core.subscribe\n * @kosApiLevel 2\n * @kosDeprecated {replacement: @kosTopicHandler, removeAt: 3}\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 warnDeprecated(\"@kosSubscribe\", \"core.subscribe\", 1, \"@kosTopicHandler\", 3);\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 { autorun, makeAutoObservable, reaction, runInAction } from \"mobx\";\nimport { DependencyLifecycle } from \"../../types\";\nimport type { KosContextLogger } from \"../kosModel\";\nimport {\n initializeStateMachine,\n injectStateMachineSupport,\n} from \"./fsm-injection-utils\";\nimport {\n KosViewModelSymbol,\n ModelEffects,\n StateMachineSetup,\n ViewModelConfig,\n} from \"./propKeys\";\n\n/**\n * Configuration options for the @kosViewModel decorator.\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface KosViewModelOptions {\n /**\n * Optional type identifier for this ViewModel.\n * Used for logging, debugging, and optional DevTools registration.\n * If not provided, defaults to the class name.\n */\n typeId?: string;\n\n /**\n * When true, registers this ViewModel with KOS DevTools for inspection.\n * Default: false (ViewModels are not tracked by default)\n */\n devToolsEnabled?: boolean;\n}\n\n/**\n * Interface for ViewModels that support cleanup.\n * Implement this to have automatic disposal when using useViewModel.\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface IKosViewModelDisposable {\n dispose(): void | Promise<void>;\n}\n\n/**\n * Interface for ViewModels that require async initialization.\n * Implement this to await model readiness or perform async setup.\n *\n * When a ViewModel implements this interface, the useViewModel hook will:\n * - Call ready() after construction\n * - Track ready state and any errors\n * - Return { viewModel, ready, error } instead of just the viewModel\n *\n * @example\n * ```typescript\n * @kosViewModel({ typeId: 'order-summary' })\n * class OrderSummaryViewModel implements IKosViewModelReady {\n * constructor(\n * private order: IOrderModel,\n * private inventory: IInventoryModel\n * ) {}\n *\n * async ready(): Promise<void> {\n * // Await model readiness before ViewModel is considered ready\n * await Promise.all([\n * this.order.whenReady?.(),\n * this.inventory.whenReady?.()\n * ]);\n * }\n * }\n * ```\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface IKosViewModelReady {\n ready(): Promise<void>;\n}\n\n/**\n * Type guard to check if an object implements IKosViewModelReady.\n */\nexport function hasReadyHook(obj: unknown): obj is IKosViewModelReady {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"ready\" in obj &&\n typeof (obj as IKosViewModelReady).ready === \"function\"\n );\n}\n\n/**\n * Interface for models using @kosLoggerAware decorator with @kosViewModel.\n * Use TypeScript interface merging to add the logger property to your ViewModel class.\n *\n * @example\n * ```typescript\n * interface MyViewModel extends KosLoggerAware {}\n *\n * @kosViewModel({ typeId: 'my-view-model' })\n * @kosLoggerAware()\n * export class MyViewModel {\n * constructor(private readonly model: IMyModel) {}\n *\n * doSomething() {\n * this.logger.info('Doing something');\n * }\n * }\n * ```\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface KosViewModelLoggerAware {\n logger: KosContextLogger;\n}\n\n/**\n * Type guard to check if an object implements IKosViewModelDisposable.\n */\nexport function isDisposable(obj: unknown): obj is IKosViewModelDisposable {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"dispose\" in obj &&\n typeof (obj as IKosViewModelDisposable).dispose === \"function\"\n );\n}\n\n// Counter for generating unique instance IDs\nlet viewModelCounter = 0;\n\n// Symbol for storing effect disposers on ViewModel instances\nconst ViewModelEffectDisposers = Symbol(\"ViewModelEffectDisposers\");\n\n/**\n * Checks if a ViewModel has model effects defined.\n */\nfunction hasViewModelEffects(instance: Record<string, unknown>): boolean {\n const effects = instance[ModelEffects as unknown as string];\n return !!effects && Object.keys(effects as object).length > 0;\n}\n\n/**\n * Injects model effect support into a ViewModel instance.\n * Effects are set up immediately and disposers are stored for cleanup.\n */\nfunction injectViewModelEffects(\n instance: Record<string, unknown>,\n typeId: string\n): void {\n if (!hasViewModelEffects(instance)) return;\n\n const modelEffects = instance[ModelEffects as unknown as string] as Record<\n string,\n {\n value: (...args: unknown[]) => void;\n dependencies?: (model: unknown) => unknown[];\n options?: { fireImmediately?: boolean };\n }\n >;\n\n const disposers: VoidFunction[] = [];\n\n for (const effectName of Object.keys(modelEffects)) {\n const { value, dependencies, options } = modelEffects[effectName];\n const handler = value.bind(instance);\n\n const effectHandler = () => {\n runInAction(() => handler());\n };\n\n const disposer = dependencies\n ? reaction(() => dependencies(instance), effectHandler, {\n fireImmediately: !!options?.fireImmediately,\n })\n : autorun(effectHandler);\n\n disposers.push(disposer);\n }\n\n // Store disposers for cleanup\n // Must be configurable: true to allow MobX makeAutoObservable to work\n Object.defineProperty(instance, ViewModelEffectDisposers, {\n value: disposers,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n // Cast to any for dynamic property access\n const inst = instance as unknown as Record<string, unknown>;\n const originalDispose = inst[\"dispose\"] as\n | ((...args: unknown[]) => void | Promise<void>)\n | undefined;\n\n // Create effect disposal function\n const disposeEffects = () => {\n for (const dispose of disposers) {\n try {\n dispose();\n } catch (e) {\n console.warn(\n `[kosViewModel] Failed to dispose effect for ${typeId}:`,\n e\n );\n }\n }\n };\n\n // If the instance already has a dispose method, wrap it to also dispose effects\n if (typeof originalDispose === \"function\") {\n inst[\"dispose\"] = function (this: unknown) {\n disposeEffects();\n return originalDispose.call(this);\n };\n } else {\n // Add a dispose method that cleans up effects\n inst[\"dispose\"] = disposeEffects;\n }\n}\n\n/**\n * Injects state machine support into a ViewModel instance and initializes it.\n * ViewModels have no lifecycle phases, so the FSM initializes at construction:\n * the state property holds `initial`, `isFsmInitialized` is true, and the\n * entry handler for `initial` runs once.\n * Logs a warning if initializeAt was given explicitly with a value other than\n * INIT, since it has no effect on a ViewModel.\n */\nfunction injectViewModelStateMachine(\n instance: Record<string, unknown>,\n typeId: string\n): void {\n const fsmSetup = instance[StateMachineSetup as unknown as string] as\n | {\n config: { initializeAt?: DependencyLifecycle };\n initializeAtExplicit?: boolean;\n }\n | undefined;\n if (!fsmSetup) return;\n\n const { config, initializeAtExplicit } = fsmSetup;\n\n if (\n initializeAtExplicit &&\n config.initializeAt !== DependencyLifecycle.INIT\n ) {\n console.warn(\n `[kosViewModel] ViewModel \"${typeId}\" has @kosStateMachine with ` +\n `initializeAt: ${config.initializeAt}. ViewModels do not have lifecycle phases, ` +\n `so the FSM will initialize immediately. Consider removing initializeAt or using ` +\n `@kosModel if lifecycle-aware FSM initialization is required.`\n );\n }\n\n injectStateMachineSupport(instance);\n initializeStateMachine(instance, config.initializeAt as string);\n}\n\n/**\n * Safely wraps makeAutoObservable with error handling.\n */\nfunction makeSafeObservable<T extends object>(instance: T): T {\n try {\n return makeAutoObservable(instance);\n } catch (e) {\n console.error(\"[kosViewModel] Failed to make observable:\", e);\n return instance;\n }\n}\n\n/**\n * Proxy handler for ViewModel construction.\n * Intercepts new() calls to inject observability.\n */\nconst viewModelConstructorProxy: ProxyHandler<any> = {\n construct(TargetClass, args) {\n const config = (TargetClass.prototype[ViewModelConfig] ||\n {}) as KosViewModelOptions;\n const typeId = config.typeId || TargetClass.name;\n const instanceId = `${typeId}-${++viewModelCounter}`;\n\n // Create the instance\n const instance = new TargetClass(...args);\n\n // Inject state machine support if @kosStateMachine is stacked\n injectViewModelStateMachine(instance, typeId);\n\n // Inject model effect support if @kosModelEffect is used\n injectViewModelEffects(instance, typeId);\n\n // Store metadata as non-enumerable properties for debugging\n // Must be configurable: true to allow MobX makeAutoObservable to work\n Object.defineProperty(instance, \"__viewModelTypeId\", {\n value: typeId,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n Object.defineProperty(instance, \"__viewModelInstanceId\", {\n value: instanceId,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n // Make the instance observable\n const observableInstance = makeSafeObservable(instance);\n\n // Optional DevTools registration\n if (\n config.devToolsEnabled &&\n (globalThis as any).__KOS_DEVTOOLS__?.registerViewModel\n ) {\n (globalThis as any).__KOS_DEVTOOLS__.registerViewModel(\n instanceId,\n observableInstance\n );\n }\n\n return observableInstance;\n },\n};\n\n/**\n * Lightweight model decorator that provides observability without\n * the full KOS model lifecycle machinery.\n *\n * Use @kosViewModel when:\n * - You need observable state for React components\n * - Dependencies are passed directly via constructor (no @kosDependency resolution)\n * - You don't need lifecycle methods (init, load, ready, activate)\n * - You want to instantiate with `new` rather than through factories\n *\n * @param options Configuration options for the ViewModel\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * // Basic usage\n * @kosViewModel({ typeId: 'counter' })\n * export class CounterViewModel {\n * count = 0;\n *\n * increment() {\n * this.count++;\n * }\n * }\n *\n * // With logger support\n * interface OrderSummaryViewModel extends KosViewModelLoggerAware {}\n *\n * @kosViewModel({ typeId: 'order-summary' })\n * @kosLoggerAware()\n * export class OrderSummaryViewModel implements IKosViewModelDisposable {\n * constructor(\n * private readonly order: IOrderModel,\n * private readonly inventory: IInventoryModel\n * ) {\n * this.logger.info('ViewModel created');\n * }\n *\n * get total(): number {\n * return this.order.items.reduce((sum, i) => sum + i.price, 0);\n * }\n *\n * get hasStockIssues(): boolean {\n * return this.order.items.some(item =>\n * this.inventory.getStock(item.productId) < item.quantity\n * );\n * }\n *\n * dispose(): void {\n * this.logger.info('ViewModel disposed');\n * }\n * }\n *\n * // Usage in React component\n * function OrderSummary({ orderId }: Props) {\n * const { model: order } = useKosModel<IOrderModel>({ modelId: orderId });\n * const { model: inventory } = useKosModel<IInventoryModel>({ modelId: 'inventory' });\n *\n * const vm = useViewModel(\n * () => new OrderSummaryViewModel(order!, inventory!),\n * [order, inventory]\n * );\n *\n * return (\n * <div>\n * <p>Total: ${vm.total}</p>\n * {vm.hasStockIssues && <Warning>Some items may be unavailable</Warning>}\n * </div>\n * );\n * }\n * ```\n *\n * @category KOS ViewModel Decorator\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport function kosViewModel(options?: KosViewModelOptions): ClassDecorator {\n return (target: any) => {\n const config = options || {};\n const typeId = config.typeId || target.name;\n\n // Store configuration on prototype for the proxy to access\n // Use same structure as KosModelSymbol for @kosLoggerAware compatibility\n target.prototype[KosViewModelSymbol] = { type: typeId };\n target.prototype[ViewModelConfig] = config;\n\n // Preserve class name for debugging\n const ProxiedClass = new Proxy(target, viewModelConstructorProxy);\n Object.defineProperty(ProxiedClass, \"name\", { value: target.name });\n\n return ProxiedClass;\n };\n}\n","/**\n * (C) Copyright 2025, TCCC, All rights reserved.\n */\n\nimport type { IKosDataModel, IKosModel } from \"../core/kosModel\";\nimport { KosModelVisitor } from \"./kos-model-visitor\";\n\n/**\n * Generic visitor that finds the ancestor path to a target item.\n * Works with any KOS model hierarchy that implements the visitor pattern.\n *\n * Uses depth-first traversal, tracking the path as it goes.\n * When the target is found, the accumulated path IS the ancestor list.\n *\n * Backtracking logic is entirely self-contained - no model changes needed.\n * Works well for Studio's typical model sizes (dozens to ~100 items).\n *\n * @example\n * ```typescript\n * const visitor = new AncestorPathVisitor('target-item-id');\n * visitor.start(rootContainerModel);\n * const ancestors = visitor.getAncestorPath(); // ['root', 'parent', 'grandparent']\n * ```\n *\n * @category Core\n * @kosService core.utils\n * @kosApiLevel 20\n */\nexport class AncestorPathVisitor extends KosModelVisitor {\n private targetId: string;\n private currentPath: string[] = [];\n private foundPath: string[] | null = null;\n\n constructor(targetId: string) {\n super();\n this.targetId = targetId;\n }\n\n /**\n * Override visit() to wrap the entire visit lifecycle with path tracking.\n *\n * Flow:\n * 1. Check cycle detection (skip if already visited)\n * 2. Push model to path\n * 3. Call visitModel() to check if this is target\n * 4. If not target, visit children\n * 5. Pop from path if target not found in this subtree (backtrack)\n *\n * Note: We inline the base class logic rather than calling super.visit()\n * because we need to control exactly when push/pop happens relative to\n * the cycle detection and child traversal.\n */\n override visit(model: IKosModel): void {\n // Cycle detection from base class\n if (this.visitedModels.has(model.modelId)) {\n return;\n }\n\n // Push to path BEFORE processing\n this.currentPath.push(model.modelId);\n\n // Mark as visited\n this.visitedModels.add(model.modelId);\n\n // Check if this is the target\n const stopVisiting = !!this.visitModel(model.modelData);\n\n if (!stopVisiting) {\n // Visit children (depth-first)\n model.getChildren?.().forEach((child) => {\n // Early exit if target was found in a sibling subtree\n if (this.foundPath) {\n return;\n }\n child.accept?.(this);\n });\n }\n\n // Backtrack: pop from path if target not found in this subtree\n if (!this.foundPath) {\n this.currentPath.pop();\n }\n }\n\n /**\n * Called for each model during traversal.\n * Returns true to stop traversal when target is found.\n */\n visitModel<T extends IKosDataModel>(model: T): boolean | void {\n // Check if this is the target\n if (model.id === this.targetId) {\n // Save ancestor path (everything except the target itself)\n this.foundPath = this.currentPath.slice(0, -1);\n return true; // Stop traversal\n }\n\n // Continue depth-first traversal\n return false;\n }\n\n /**\n * Get the ancestor path (IDs from root to parent, not including target).\n * Returns empty array if target not found or target is at root level.\n */\n getAncestorPath(): string[] {\n return this.foundPath ?? [];\n }\n\n /**\n * Check if target was found during traversal.\n */\n wasFound(): boolean {\n return this.foundPath !== null;\n }\n}\n","/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport 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","/**\n * @kosService core.utils\n * @kosApiLevel 5\n */\nexport function arraysEqual(_a?: any[], _b?: any[]): boolean {\n const a = _a ?? [];\n const b = _b ?? [];\n if (a.length !== b.length) return false;\n return a.every((val, index) => val === b[index]);\n}\n","/**\n * Container synchronization utilities for KOS model containers.\n *\n * This module provides utilities for efficiently synchronizing KOS containers with external data sources\n * (e.g., API responses, WebSocket updates). The core pattern uses delta resolution to determine which\n * items need to be added, updated, or removed to keep containers in sync with incoming data.\n *\n * Key capabilities:\n * - Delta-based synchronization (add/update/remove)\n * - ID transformation for compound model IDs\n * - Preservation of backend IDs for server communication\n * - Update-in-place to maintain object identity\n * - Support for nested container hierarchies\n *\n * @module container-utils\n * @author KOS Team\n * @version 1.0.0\n *\n * @example Basic container synchronization\n * ```typescript\n * const syncUsers = resolveContainerDeltas({\n * container: userContainer,\n * onAddItem: (user) => User.instance(user.id).options(user).build(),\n * onUpdateItem: (user, existing) => {\n * existing.updateModel(user);\n * return null; // Don't add, just updated in place\n * },\n * onRemoveItem: (id) => id\n * });\n * syncUsers(newUserList);\n * ```\n *\n * @example ID transformation with compound IDs\n * ```typescript\n * type WithRawId<T> = T & { rawId: string };\n *\n * const syncCandidates = resolveContainerDeltas<\n * typeof version.candidates,\n * CandidateResponse,\n * WithRawId<CandidateResponse>\n * >({\n * container: version.candidates,\n * idMapper: (data) => ({\n * ...data,\n * rawId: data.id, // Preserve backend ID\n * id: `release-candidate-${versionId}-${data.id}` // Compound model ID\n * }),\n * onAddItem: (data) =>\n * Candidate.instance(data.id)\n * .options({ rawId: data.rawId, ...otherProps })\n * .build(),\n * onUpdateItem: (data, existing) => {\n * existing.updateModel({ rawId: data.rawId, ...otherProps });\n * return null;\n * }\n * })(candidatesData);\n * ```\n */\nimport { 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\n/**\n * Function that transforms an entity's ID before container synchronization.\n *\n * The IdMapper pattern enables two critical capabilities:\n *\n * 1. **Compound Model IDs**: Transform simple backend IDs into compound IDs that include\n * parent context (e.g., `\"123\"` → `\"release-version-abc-123\"`). This ensures unique\n * model IDs even when backend IDs are only unique within their parent scope.\n *\n * 2. **Backend ID Preservation**: Add a `rawId` property to preserve the original backend ID\n * for server communication while using compound IDs for model identity.\n *\n * @template D - Input entity type (data from backend)\n * @template M - Mapped entity type (data after transformation, defaults to D if no transformation)\n *\n * @example Simple ID prefix transformation\n * ```typescript\n * const idMapper: IdMapper<User, User & { rawId: string }> = (user) => ({\n * ...user,\n * rawId: user.id,\n * id: `user-${user.id}`\n * });\n * ```\n *\n * @example Compound ID with parent context\n * ```typescript\n * type WithRawId<T> = T & { rawId: string };\n *\n * const idMapper: IdMapper<VersionResponse, WithRawId<VersionResponse>> = (version) => ({\n * ...version,\n * rawId: version.id,\n * id: `release-version-${templateId}-${version.id}`\n * });\n * ```\n *\n * @example Multi-level compound ID\n * ```typescript\n * const idMapper: IdMapper<CandidateResponse, WithRawId<CandidateResponse>> = (candidate) => ({\n * ...candidate,\n * rawId: candidate.id,\n * id: `release-candidate-${templateId}-${versionId}-${candidate.id}`\n * });\n * ```\n *\n * @kosService core.container-utils\n */\nexport type IdMapper<\n D extends Identifiable = Identifiable,\n M extends Identifiable = D\n> = (entity: D) => M;\n\ntype Container = IKosContainerModel<any, any> | IKosModelContainer<any>;\n\n/**\n * Parameters for resolving container deltas.\n * @template T - The container type\n * @template D - The input entity type with an id property\n * @template M - The mapped entity type (after idMapper transformation)\n */\ninterface ResolveParams<\n T extends Container,\n D extends Identifiable,\n M extends Identifiable = D\n> {\n /** The container to synchronize */\n container: T;\n /** Callback to create a new item when an entity is added */\n onAddItem: (entity: M) => any;\n /** Optional callback when an item is removed, receives the id to remove */\n onRemoveItem?: (id: string) => any;\n /** Optional callback when an existing item needs updating */\n onUpdateItem?: (entity: M, existingModel: any) => any;\n /** Optional mapper to transform entity ids before processing */\n idMapper?: IdMapper<D, M>;\n}\n\nconst DEFAULT_REMOVE_MAPPER = (id: string) => id;\nconst DEFAULT_ID_MAPPER = <T extends Identifiable>(entity: T) => entity;\n\n/**\n * Creates a function that synchronizes a container with a new list of entities.\n *\n * This is the primary utility for delta-based container synchronization. It compares incoming\n * data against the current container state and performs minimal operations (add/update/remove)\n * to achieve synchronization.\n *\n * Key features:\n * - **Delta resolution**: Only processes actual changes (add/update/remove)\n * - **ID transformation**: Optional `idMapper` transforms backend IDs to model IDs\n * - **Update-in-place**: `onUpdateItem` can update existing models without recreating\n * - **Type safety**: Generic type parameters ensure type consistency through transformation\n *\n * Workflow:\n * 1. Apply `idMapper` to transform entity IDs (if provided)\n * 2. Calculate deltas: which IDs are missing from new data (removals)\n * 3. Invoke `onRemoveItem` for each ID to remove\n * 4. For each entity in new data:\n * - If model exists: invoke `onUpdateItem` (if provided) or `onAddItem`\n * - If model doesn't exist: invoke `onAddItem`\n * 5. Add all new models to container in batch\n *\n * @template T - Container type implementing IKosModelContainer\n * @template D - Input entity type (data from backend)\n * @template M - Mapped entity type (after idMapper transformation, defaults to D)\n *\n * @param params - Configuration for resolving deltas\n * @param params.container - The container to synchronize\n * @param params.onAddItem - Callback to create a new model from entity data\n * @param params.onUpdateItem - Optional callback to update existing model (return null to skip adding)\n * @param params.onRemoveItem - Optional callback invoked with each ID to remove (default: identity function)\n * @param params.idMapper - Optional function to transform entity IDs before processing\n *\n * @returns A function that accepts entities and synchronizes the container\n *\n * @kosService core.container-utils\n *\n * @example Basic synchronization without ID transformation\n * ```typescript\n * const syncUsers = resolveContainerDeltas({\n * container: userContainer,\n * onAddItem: (user) => User.instance(user.id).options(user).build(),\n * onUpdateItem: (user, existing) => {\n * existing.updateModel(user);\n * return null; // Don't add, just updated in place\n * },\n * onRemoveItem: (id) => id\n * });\n * syncUsers(newUserList);\n * ```\n *\n * @example ID transformation with compound IDs and rawId preservation\n * ```typescript\n * type WithRawId<T> = T & { rawId: string };\n *\n * const syncVersions = resolveContainerDeltas<\n * typeof template.versions,\n * VersionResponse,\n * WithRawId<VersionResponse>\n * >({\n * container: template.versions,\n * idMapper: (versionData) => ({\n * ...versionData,\n * rawId: versionData.id, // Preserve backend ID\n * id: ReleaseIdFactory.version(templateId, versionData.id) // Compound model ID\n * }),\n * onAddItem: (data) => {\n * const model = ReleaseVersion.instance(data.id)\n * .options({\n * rawId: data.rawId, // Store backend ID for server communication\n * version: data.version,\n * // ... other options\n * })\n * .build();\n * // Recursively sync nested containers\n * syncCandidates(model, data.candidates || []);\n * return model;\n * },\n * onUpdateItem: (data, existingVersion) => {\n * existingVersion.updateModel({\n * rawId: data.rawId || existingVersion.rawId,\n * version: data.version,\n * // ... other updates\n * });\n * // Recursively sync nested containers\n * syncCandidates(existingVersion, data.candidates || []);\n * return null; // Don't add, just updated in place\n * },\n * onRemoveItem: (id) => id\n * })(versionsData);\n * ```\n *\n * @example Nested container synchronization\n * ```typescript\n * // Parent level\n * syncTemplates(containerModel, templatesData);\n *\n * // Within onAddItem and onUpdateItem, sync children\n * function syncTemplates(container, templates) {\n * resolveContainerDeltas({\n * container: container.container,\n * idMapper: (template) => ({\n * ...template,\n * rawId: template.id,\n * id: ReleaseIdFactory.template(template.id)\n * }),\n * onAddItem: (template) => {\n * const model = createTemplateModel(template);\n * syncQueues(model, template.queues); // Nested sync\n * syncVersions(model, template.versions); // Nested sync\n * return model;\n * },\n * onUpdateItem: (template, existing) => {\n * existing.updateModel(template);\n * syncQueues(existing, template.queues); // Nested sync\n * syncVersions(existing, template.versions); // Nested sync\n * return null;\n * }\n * })(templates);\n * }\n * ```\n * @kosApiLevel 2\n */\nexport const resolveContainerDeltas =\n <\n T extends IKosModelContainer<any>,\n D extends Identifiable,\n M extends Identifiable = D\n >({\n container,\n onAddItem,\n onUpdateItem,\n onRemoveItem = DEFAULT_REMOVE_MAPPER,\n idMapper = DEFAULT_ID_MAPPER as unknown as IdMapper<D, M>,\n }: ResolveParams<T, D, M>) =>\n (entities: D[]) => {\n const mappedEntities = entities.map(idMapper) as M[];\n const toRemove = deltas(mappedEntities, container.data);\n const removedIds = toRemove.map(onRemoveItem).filter(Boolean);\n container.removeAll(removedIds);\n const toAdd = mappedEntities\n .map((entity: M) => {\n const existing = container.getModel(entity.id);\n if (!existing) {\n return onAddItem(entity);\n } else if (onUpdateItem) {\n return onUpdateItem(entity, existing);\n } else {\n return onAddItem(entity);\n }\n })\n .filter(Boolean);\n container.addAll(toAdd);\n };\n\n/**\n * Creates a function that synchronizes a container model's list with new entities.\n * Simpler alternative to resolveContainerDeltas that directly invokes callbacks for each addition and removal.\n *\n * @template T - Container model type implementing IKosContainerModel\n * @template D - Input entity type with an id property\n * @template M - Mapped entity type (after idMapper transformation)\n * @param params - Configuration for resolving deltas\n * @returns A function that accepts entities and synchronizes by invoking callbacks\n *\n * @kosService core.container-utils\n *\n * @example\n * const syncLayers = resolveListDeltas({\n * container: layerContainer,\n * onAddItem: (layer) => addLayer(layer),\n * onRemoveItem: (id) => removeLayer(id)\n * });\n * syncLayers(newLayerList);\n * @kosApiLevel 2\n */\nexport const resolveListDeltas =\n <\n T extends IKosContainerModel<any, any>,\n D extends Identifiable,\n M extends Identifiable = D\n >({\n container,\n onAddItem,\n onRemoveItem = DEFAULT_REMOVE_MAPPER,\n idMapper = DEFAULT_ID_MAPPER as unknown as IdMapper<D, M>,\n }: ResolveParams<T, D, M>) =>\n (entities: D[]) => {\n const mappedLayers = entities.map(idMapper) as M[];\n const toRemove = deltas(mappedLayers, container.models);\n toRemove.forEach(onRemoveItem);\n mappedLayers.forEach(onAddItem);\n };\n\n/**\n * Parameters for resolving deltas on plain item arrays (not container models).\n * @template T - Current item type with an id property\n * @template D - Input entity type with an id property\n * @template M - Mapped entity type (after idMapper transformation)\n */\ninterface ResolveItemsParams<\n T extends Identifiable,\n D extends Identifiable,\n M extends Identifiable = D\n> {\n /** The current array of items to synchronize */\n items: T[];\n /** Callback invoked for each entity to add */\n onAddItem: (entity: M) => void;\n /** Callback invoked for each id to remove */\n onRemoveItem: (id: string) => void;\n /** Optional mapper to transform entity ids before processing */\n idMapper?: IdMapper<D, M>;\n}\n\n/**\n * Creates a function that synchronizes a plain array of items with new entities.\n * Does not require a container model - works with any array of identifiable items.\n *\n * @template T - Current item type with an id property\n * @template D - Input entity type with an id property\n * @template M - Mapped entity type (after idMapper transformation)\n * @param params - Configuration including the items array and callbacks\n * @returns A function that accepts entities and synchronizes the array\n *\n * @kosService core.container-utils\n *\n * @example\n * const currentItems = [{ id: '1', name: 'Item 1' }];\n * const syncItems = resolveItemListDeltas({\n * items: currentItems,\n * onAddItem: (item) => currentItems.push(item),\n * onRemoveItem: (id) => {\n * const index = currentItems.findIndex(i => i.id === id);\n * if (index >= 0) currentItems.splice(index, 1);\n * }\n * });\n * syncItems(newItems);\n * @kosApiLevel 2\n */\nexport const resolveItemListDeltas =\n <T extends Identifiable, D extends Identifiable, M extends Identifiable = D>({\n items,\n onAddItem,\n onRemoveItem,\n idMapper = DEFAULT_ID_MAPPER as unknown as IdMapper<D, M>,\n }: ResolveItemsParams<T, D, M>) =>\n (entities: D[]) => {\n const mappedLayers = entities.map(idMapper) as M[];\n const toRemove = deltas(mappedLayers, items);\n toRemove.forEach(onRemoveItem);\n mappedLayers.forEach(onAddItem);\n };\n\n/**\n * Removes a prefix from an id string if present.\n * Useful for normalizing ids that may have parent or namespace prefixes.\n *\n * @param id - The id string to process\n * @param prefix - The prefix to remove (defaults to \"parent-\")\n * @returns The id with the prefix removed, or the original id if prefix not found\n *\n * @example\n * processId(\"parent-123\") // returns \"123\"\n * processId(\"parent-abc\", \"parent-\") // returns \"abc\"\n * processId(\"child-456\", \"parent-\") // returns \"child-456\"\n *\n * @kosService core.container-utils\n * @kosApiLevel 2\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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const isLeapYear = (year: number): boolean =>\n (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const getDaysInMonth = (year: number, month: number): number =>\n [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][\n month\n ];\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const addMonthsToDate = (date: Date, value: number) => {\n const d = new Date(date),\n n = date.getDate();\n d.setDate(1);\n d.setMonth(d.getMonth() + value);\n d.setDate(Math.min(n, getDaysInMonth(d.getFullYear(), d.getMonth())));\n return d;\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const addDaysToDate = (date: Date, value: number) => {\n const d = new Date(date);\n d.setDate(d.getDate() + value);\n return d;\n};\n\nconst DEFAULT_LOCALE = \"en-US\";\n\ninterface FormatDateOptions {\n dateStyle?: \"short\" | \"medium\" | \"long\" | \"full\";\n locales?: string | string[];\n}\n\ninterface FormatTimeOptions {\n timeStyle?: \"short\" | \"medium\" | \"long\" | \"full\";\n locales?: string | string[];\n}\n\ninterface FormatDateTimeOptions extends FormatDateOptions, FormatTimeOptions {}\n\ninterface FormatOptions {\n year?: \"numeric\" | \"2-digit\";\n month?: \"short\" | \"long\" | \"numeric\" | \"2-digit\" | \"narrow\";\n day?: \"numeric\" | \"2-digit\";\n weekday?: \"short\" | \"long\" | \"narrow\";\n hour?: \"numeric\" | \"2-digit\";\n minute?: \"numeric\" | \"2-digit\";\n second?: \"numeric\" | \"2-digit\";\n hour12?: boolean;\n timeZoneName?:\n | \"short\"\n | \"long\"\n | \"shortOffset\"\n | \"longOffset\"\n | \"shortGeneric\"\n | \"longGeneric\";\n}\n\nconst dateStyleMap: Record<\n NonNullable<FormatDateTimeOptions[\"dateStyle\"]>,\n Partial<FormatOptions>\n> = {\n short: { year: \"numeric\", month: \"2-digit\", day: \"2-digit\" },\n medium: { year: \"numeric\", month: \"short\", day: \"2-digit\" },\n long: { year: \"numeric\", month: \"long\", day: \"numeric\" },\n full: {\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n weekday: \"long\",\n },\n};\n\nconst timeStyleMap: Record<\n NonNullable<FormatDateTimeOptions[\"timeStyle\"]>,\n Partial<FormatOptions>\n> = {\n short: { hour: \"2-digit\", minute: \"2-digit\", hour12: true },\n medium: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: true,\n },\n long: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: true,\n timeZoneName: \"short\",\n },\n full: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: true,\n timeZoneName: \"long\",\n },\n};\n\n/**\n * Formats a date according to the specified `dateStyle` and locale.\n *\n * Uses `Intl.DateTimeFormat` internally.\n *\n * - `\"short\"` uses a custom format: `dd/mm/yyyy` (e.g., `31/12/2025`)\n * - Other styles use built-in `Intl` formatting\n *\n * ### Example Output\n * ```ts\n * formatDate(new Date(\"2025-12-31\"), { dateStyle: \"short\" }); // \"31/12/2025\"\n * formatDate(new Date(\"2025-12-31\"), { dateStyle: \"medium\" }); // \"Dec 31, 2025\"\n * formatDate(new Date(\"2025-12-31\"), { dateStyle: \"long\" }); // \"December 31, 2025\"\n * formatDate(new Date(\"2025-12-31\"), { dateStyle: \"full\" }); // \"Wednesday, December 31, 2025\"\n * ```\n *\n * @param date - The date object or timestamp to format.\n * @param options - Options to customize formatting.\n * @param options.dateStyle - One of `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or array of locale strings.\n * @returns A formatted date string.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatDate = (\n date?: Date | number,\n { dateStyle = \"short\", locales = DEFAULT_LOCALE }: FormatDateOptions = {\n dateStyle: \"short\",\n locales: DEFAULT_LOCALE,\n }\n) => {\n const options = dateStyle === \"short\" ? dateStyleMap.short : { dateStyle }; // Let Intl handle medium/long/full\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n\n/**\n * Formats a time according to the specified `timeStyle` and locale.\n *\n * Uses `Intl.DateTimeFormat` internally.\n *\n * ### Example Output\n * ```ts\n * formatTime(new Date(\"2025-12-31T23:59:59\"), { timeStyle: \"short\" }); // \"11:59 PM\"\n * formatTime(new Date(\"2025-12-31T23:59:59\"), { timeStyle: \"medium\" }); // \"11:59:59 PM\"\n * formatTime(new Date(\"2025-12-31T23:59:59\"), { timeStyle: \"long\" }); // \"11:59:59 PM EST\"\n * formatTime(new Date(\"2025-12-31T23:59:59\"), { timeStyle: \"full\" }); // \"11:59 PM Eastern Standard Time\"\n * ```\n *\n * @param date - The date object or timestamp to extract the time from.\n * @param options - Options to customize time formatting.\n * @param options.timeStyle - One of `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or locale array.\n * @returns A formatted time string.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatTime = (\n date?: Date | number,\n { locales = DEFAULT_LOCALE, timeStyle = \"short\" }: FormatTimeOptions = {\n locales: DEFAULT_LOCALE,\n timeStyle: \"short\",\n }\n) => {\n const options = timeStyleMap[timeStyle];\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n\n/**\n * Formats a date and/or time using custom formatting logic based on `dateStyle` and `timeStyle`.\n *\n * Uses explicit `Intl.DateTimeFormat` options for full control over the output format.\n *\n * - `\"short\"` date is always `dd/mm/yyyy`\n * - `\"short\"` time is always 12-hour format (e.g., `11:59 PM`)\n * - Supports combining both formats into a single string\n *\n * ### Example Output\n * ```ts\n * formatDateTime(new Date(\"2025-12-31T23:59:59\"), {\n * dateStyle: \"short\",\n * timeStyle: \"short\"\n * }); // \"31/12/2025, 11:59 PM\"\n *\n * formatDateTime(new Date(\"2025-12-31T23:59:59\"), {\n * dateStyle: \"medium\",\n * timeStyle: \"medium\"\n * }); // \"Dec 31, 2025, 11:59:59 PM\"\n *\n * formatDateTime(new Date(\"2025-12-31T23:59:59\"), {\n * dateStyle: \"long\",\n * timeStyle: \"long\"\n * }); // \"December 31, 2025, 11:59:59 PM EST\"\n *\n * formatDateTime(new Date(\"2025-12-31T23:59:59\"), {\n * dateStyle: \"full\",\n * timeStyle: \"full\"\n * }); // \"Wednesday, December 31, 2025, 11:59 PM Eastern Standard Time\"\n *\n * formatDateTime(new Date(\"2025-12-31T23:59:59\"), {\n * timeStyle: \"short\"\n * }); // \"11:59 PM\"\n * ```\n *\n * @param date - The `Date` object or timestamp to format.\n * @param options - Formatting options.\n * @param options.dateStyle - Custom date format: `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.timeStyle - Custom time format: `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or locale array.\n * @returns A string representing the formatted date and/or time.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatDateTime = (\n date?: Date | number,\n {\n dateStyle = \"short\",\n locales = DEFAULT_LOCALE,\n timeStyle = \"short\",\n }: FormatDateTimeOptions = {\n dateStyle: \"short\",\n locales: DEFAULT_LOCALE,\n timeStyle: \"short\",\n }\n) => {\n const options: FormatOptions = {\n ...(dateStyle && dateStyleMap[dateStyle]),\n ...(timeStyle && timeStyleMap[timeStyle]),\n };\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n","/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport 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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const resolveVariable = (element: Element, variable: string) =>\n getComputedStyle(element).getPropertyValue(variable);\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const variableToHex = (element: Element, variable: string) =>\n hslStringToHex(resolveVariable(element, variable));\n","import { runInAction as kosAction } from \"mobx\";\nimport { IKosDataModel } from \"../core/kosModel\";\n\n/**\n * @kosService core.utils\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\n/**\n * @kosService core.utils\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 *\n * @kosService core.utils\n * @kosApiLevel 2\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","/**\n * @kosService core.middleware\n */\nexport 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\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\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;\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\n */\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\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\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 { KosCore } from \"../core/kosCore\";\nimport type { KosCompanionModelType } from \"../core/types/registration\";\nimport type { BaseKosModelRegistrationBean } from \"../types/model\";\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport const updateModelRegistration = <\n T extends BaseKosModelRegistrationBean<any, any>\n>(\n modelRegistration: T\n): void => {\n KosCore.getInstance().modelManager.registerModel(modelRegistration);\n};\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\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 { 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 * @kosService core.utils\n * @kosApiLevel 2\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;\n/**\n * @kosService core.pipe\n * @kosApiLevel 2\n */\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 *\n * @kosService core.fetch\n * @kosApiLevel 2\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","import type {\n ApiPath,\n HttpMethod,\n} from \"../core/decorators/kos-service-request\";\nimport type { IKosDataModel } from \"../core/kosModel\";\n\n/**\n * Utility functions for accessing cached service responses from ServiceResponseStore\n *\n * These functions provide type-safe access to responses stored by @kosServiceRequest\n * decorated methods, eliminating the need for \"magic last parameter\" patterns.\n *\n * @example\n * ```typescript\n * @kosServiceRequest({\n * path: PATH_INGREDIENTS,\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onIngredientsLoaded(): void {\n * const response = getServiceResponse(this, PATH_INGREDIENTS, 'get');\n * this.processIngredients(response.data.ingredients);\n * }\n * ```\n */\n\n/**\n * Get cached service response by path and method\n *\n * Returns the response data cached by @kosServiceRequest decorated methods.\n * TypeScript will infer types from your OpenAPI schema when using typed path constants.\n *\n * For cross-package scenarios where OpenAPI specs differ, you can optionally\n * provide an explicit type parameter.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n * @returns The cached response data, or undefined if not found/expired\n *\n * @kosService core.service-response\n *\n * @example Standard usage (types inferred from OpenAPI)\n * ```typescript\n * const status = getServiceResponse(this, PATH_DEVICE_STATUS, 'get');\n * // TypeScript infers the type from PATH_DEVICE_STATUS\n * ```\n *\n * @example Cross-package usage with explicit type (when OpenAPI schemas differ)\n * ```typescript\n * // Studio models using different OpenAPI than main SDK\n * const vms = getServiceResponse<StudioVMResponse>(this, PATH_VMS, 'get');\n * ```\n * @kosApiLevel 15\n */\nexport function getServiceResponse<T = any>(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): T | undefined {\n const store = (model as any).serviceResponses;\n if (!store) {\n return undefined;\n }\n\n return store.getByPath(path, method);\n}\n\n/**\n * Check if a cached response exists for the given path and method\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n * @returns true if a valid cached response exists\n *\n * @kosService core.service-response\n *\n * @example\n * ```typescript\n * if (hasCachedResponse(this, PATH_DEVICE_STATUS, 'get')) {\n * // Use cached data\n * const status = getServiceResponse(this, PATH_DEVICE_STATUS, 'get');\n * } else {\n * // Fetch fresh data\n * await this.refreshStatus();\n * }\n * ```\n * @kosApiLevel 15\n */\nexport function hasCachedResponse(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): boolean {\n const store = (model as any).serviceResponses;\n if (!store) {\n return false;\n }\n\n return store.has(`${method.toUpperCase()}:${path}`);\n}\n\n/**\n * Manually clear a cached service response\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n *\n * @kosService core.service-response\n *\n * @example\n * ```typescript\n * // Clear cached response to force refresh on next request\n * clearServiceResponse(this, PATH_TEMP_DATA, 'post');\n * ```\n * @kosApiLevel 15\n */\nexport function clearServiceResponse(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.delete(`${method.toUpperCase()}:${path}`);\n}\n\n/**\n * Clear all cached responses for a specific path (all methods)\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n *\n * @kosService core.service-response\n *\n * @example\n * ```typescript\n * // Clear all cached responses for this endpoint\n * clearPath(this, PATH_INGREDIENTS);\n * // Clears GET, POST, PUT, DELETE responses for this path\n * ```\n * @kosApiLevel 15\n */\nexport function clearPath(model: IKosDataModel, path: ApiPath): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.clearPath(path);\n}\n\n/**\n * Clear all cached service responses in the model\n *\n * @param model - The KOS model instance\n *\n * @kosService core.service-response\n *\n * @example\n * ```typescript\n * // Clear all cached responses (typically during model cleanup)\n * clearAllServiceResponses(this);\n * ```\n * @kosApiLevel 15\n */\nexport function clearAllServiceResponses(model: IKosDataModel): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.clear();\n}\n","import log from \"loglevel\";\nimport { EventBus } from \"../../common\";\n\nimport { uuid } from \"./api-request-id\";\nimport { KosServiceResponse } from \"./kos-fetch\";\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport interface ErrorResponse {\n error?: string;\n}\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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}\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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","/* eslint-disable no-param-reassign */\n/**\n * Item-level decorator that makes a model contribute to the kos-ui-sdk\n * container indexing system.\n *\n * Two responsibilities:\n *\n * 1. Installs a symbol-keyed accessor at `INDEX_RECORD_SYMBOL` that\n * returns the current index record for the instance.\n * `KosModelContainer` reads this when publishing ADDED, and\n * consumers re-read it on REQUEST_SEED.\n *\n * 2. Registers a `ModelEffects` entry that fires only on changes\n * to the declared `fields` and publishes CHANGED. Narrowly\n * scoped to the index-relevant fields — no `_optionsMap`\n * entries, no new `KosContainerIndex` instances, no observation\n * of unrelated property changes.\n *\n * Modeled on `kos-logger-aware` / `kos-studio-state-aware`: class\n * decorator, options object, paired `KosIndexAware` interface for\n * TypeScript merging.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\n\nimport * as EventBus from \"../../../common/events/eventBus\";\nimport { KosContextManager } from \"../context/kos-context-manager\";\nimport { ModelEffects } from \"../decorators/propKeys\";\n\nimport { KosContainerIndexEvents } from \"./topics\";\nimport {\n INDEX_COLLECTION_KEY,\n INDEX_RECORD_SYMBOL,\n type IndexChangedEvent,\n type IndexRecordContribution,\n} from \"./types\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Options\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface KosIndexAwareOptions {\n /**\n * Per-item collection tag. May be:\n *\n * - A static string.\n * - A function called with the instance, returning the tag\n * (heterogeneous case where one container holds items belonging\n * to multiple collections, distinguished by some item property).\n * - Undefined — the item resolves its collection from its\n * `KosContext` (auto-walks the parent chain). When the item\n * lives under a `@kosContainerIndexAware`-decorated container,\n * that container has already written its declared collection\n * onto its own context, so this resolves transparently with no\n * per-item declaration needed.\n */\n collection?: string | ((self: any) => string | undefined);\n\n /**\n * Field names projected into the index record and watched for\n * change. Empty/absent means no CHANGED events are emitted; the\n * record still exposes `id`, `modelType`, and `collection`.\n */\n fields?: string[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Companion interface for TS interface merging\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Use TypeScript interface merging to attach the indexable contract\n * to your model class:\n *\n * ```ts\n * interface MyItemModelImpl extends KosIndexAware {}\n *\n * @kosModel(\"my-item-model\")\n * @kosIndexAware({ collection: \"items\", fields: [\"name\"] })\n * class MyItemModelImpl implements IKosDataModel { ... }\n * ```\n *\n * Mirrors the `KosLoggerAware` / `KosContainerAware` pattern.\n */\nexport interface KosIndexAware {\n readonly [INDEX_RECORD_SYMBOL]: IndexRecordContribution;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Decorator\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Class decorator that registers a model as a publisher of index\n * records.\n *\n * Reads `id` and `modelTypeId` off the instance at record-construction\n * time. Both are part of the standard kos-model surface — `id` from\n * `IKosIdentifiable`, `modelTypeId` from `@kosModel`. No author\n * duplication needed.\n *\n * @example Heterogeneous container — collection resolved per item\n * ```ts\n * interface VirtualMachineModelImpl extends KosIndexAware {}\n *\n * @kosModel(\"virtual-machine-model\")\n * @kosIndexAware({\n * collection: (self) => self.type,\n * fields: [\"name\", \"desc\"],\n * })\n * class VirtualMachineModelImpl implements IKosDataModel { ... }\n * ```\n *\n * @example Homogeneous — collection declared on the container instead\n * ```ts\n * @kosModel(\"image-model\")\n * @kosIndexAware({ fields: [\"name\"] })\n * class ImageModelImpl implements IKosDataModel { ... }\n *\n * @kosContainerIndexAware({ itemsProperty: \"images\", collection: \"images\" })\n * class ImageContainerModelImpl ...\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.indexing\n * @kosApiLevel 22\n */\nexport function kosIndexAware(options?: KosIndexAwareOptions): ClassDecorator {\n return (target: any) => {\n const collection = options?.collection;\n const fields = options?.fields ?? [];\n\n installRecordAccessor(target, collection, fields);\n if (fields.length > 0) {\n installChangeEffect(target, fields);\n }\n\n return target;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction installRecordAccessor(\n target: any,\n collection: KosIndexAwareOptions[\"collection\"],\n fields: string[]\n): void {\n Object.defineProperty(target.prototype, INDEX_RECORD_SYMBOL, {\n get(): IndexRecordContribution {\n const record: IndexRecordContribution = {\n id: this.id,\n modelType: this.modelTypeId,\n };\n const resolved =\n typeof collection === \"function\" ? collection(this) : collection;\n // Fall back to the inherited context value when the item\n // declared nothing of its own. `KosContextManager.getContext`\n // looks up the bean by id; `.get` auto-walks the parent chain,\n // so a container-declared collection is visible here without\n // any explicit plumbing.\n const inherited =\n resolved === undefined\n ? (KosContextManager.getContext(this.id)?.get(\n INDEX_COLLECTION_KEY\n ) as string | undefined)\n : undefined;\n const finalCollection = resolved ?? inherited;\n if (finalCollection !== undefined) {\n record.collection = finalCollection;\n }\n for (const field of fields) {\n record[field] = this[field];\n }\n return record;\n },\n enumerable: false,\n configurable: true,\n });\n}\n\nfunction installChangeEffect(target: any, fields: string[]): void {\n target.prototype[ModelEffects] = target.prototype[ModelEffects] || {};\n target.prototype[ModelEffects].handleIndexFieldChange = {\n dependencies: (model: any) => fields.map((field) => model[field]),\n value: function (this: any) {\n const record: IndexRecordContribution = this[INDEX_RECORD_SYMBOL];\n // Skip if no collection resolved — neither item-declared nor\n // inherited from a container's context. Without a collection\n // the consumer can't route the record.\n if (!record.collection) {\n return;\n }\n const payload: IndexChangedEvent = {\n record: record as IndexChangedEvent[\"record\"],\n };\n EventBus.publish(KosContainerIndexEvents.CHANGED, payload);\n },\n };\n}\n","/* eslint-disable no-param-reassign */\n/**\n * Container-level decorator that wires up the kos-ui-sdk container\n * indexing system. Composes with the upstream `@kosContainerAware`\n * (or with legacy `@kosChild`-based containers) — it only needs an\n * `itemsProperty` pointing at the array of items the container\n * exposes.\n *\n * Three responsibilities:\n *\n * 1. Wraps `init` so the decorator-declared collection is written\n * onto the container's own `KosContext`. Items resolve the\n * value via `KosContext.get(INDEX_COLLECTION_KEY)`, which\n * auto-walks the parent chain.\n *\n * 2. Registers a `SubscriptionHandlers` entry for\n * `KosContainerIndexEvents.REQUEST_SEED`. When a consumer\n * publishes that topic, the container reads its current items,\n * maps them via `INDEX_RECORD_SYMBOL`, and emits one SEED\n * event. Lets subscribe order stop mattering.\n *\n * 3. Wraps `unload` to emit one PURGE per distinct collection in\n * the current items, so consumers can drop the collection's\n * records at container teardown.\n *\n * Membership detection (ADDED, REMOVED) is owned by\n * `KosModelContainer` itself, not this decorator — the events fire\n * at the moment of mutation, with no diffing or property-watching\n * involved.\n *\n * Modeled on `kos-studio-state-aware`: class decorator, options\n * object, `target.prototype[ModelEffects]` / `[SubscriptionHandlers]`\n * registration pattern.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\n\nimport * as EventBus from \"../../../common/events/eventBus\";\nimport type { KosContext } from \"../context/kos-context-manager\";\nimport { SubscriptionHandlers } from \"../decorators/propKeys\";\n\nimport { KosContainerIndexEvents } from \"./topics\";\nimport {\n INDEX_COLLECTION_KEY,\n INDEX_RECORD_SYMBOL,\n isIndexableItem,\n type IndexPurgeEvent,\n type IndexRecord,\n type IndexRecordContribution,\n type IndexSeedEvent,\n} from \"./types\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Options\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface KosContainerIndexAwareOptions {\n /**\n * Name of the property on the container that exposes its items\n * as an array. May be a `@kosContainerAware`-injected `data` /\n * `models` getter, or a legacy custom getter (e.g.\n * `virtualMachines` on a container with a `@kosChild`-managed\n * collection).\n *\n * Used for SEED re-emission and PURGE. Membership add/remove\n * events come from `KosModelContainer` directly and do not\n * depend on this property.\n */\n itemsProperty: string;\n\n /**\n * Collection tag written onto the container's own `KosContext`\n * so child items can resolve it via auto-walk. Optional when\n * items declare their own `collection` via `@kosIndexAware`\n * (heterogeneous containers).\n */\n collection?: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Decorator\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Class decorator that wires a container model into the kos-ui-sdk\n * indexing system.\n *\n * @example Homogeneous container — single collection\n * ```ts\n * @kosModel(\"image-container-model\")\n * @kosContainerAware<IImageModel>()\n * @kosContainerIndexAware({ itemsProperty: \"data\", collection: \"images\" })\n * class ImageContainerModelImpl implements IKosDataModel { ... }\n * ```\n *\n * @example Heterogeneous container — items declare their own collection\n * ```ts\n * @kosModel(\"virtual-machine-container-model\")\n * @kosContainerIndexAware({ itemsProperty: \"virtualMachines\" })\n * class VirtualMachineContainerModelImpl implements IKosDataModel { ... }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.indexing\n * @kosApiLevel 22\n */\nexport function kosContainerIndexAware(\n options: KosContainerIndexAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const itemsProperty = options.itemsProperty;\n const declaredCollection = options.collection;\n\n installContextWriter(target, declaredCollection);\n installRequestSeedHandler(target, itemsProperty);\n installPurgeOnUnload(target, itemsProperty);\n\n return target;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction installContextWriter(\n target: any,\n declaredCollection: string | undefined\n): void {\n if (declaredCollection === undefined) return;\n\n const originalInit = target.prototype.init;\n target.prototype.init = async function (context?: KosContext) {\n context?.set(INDEX_COLLECTION_KEY, declaredCollection);\n if (originalInit) {\n await originalInit.call(this, context);\n }\n };\n}\n\nfunction installRequestSeedHandler(target: any, itemsProperty: string): void {\n target.prototype[SubscriptionHandlers] =\n target.prototype[SubscriptionHandlers] || {};\n target.prototype[SubscriptionHandlers][KosContainerIndexEvents.REQUEST_SEED] =\n {\n websocket: false,\n skipParse: true,\n // The subscription manager calls transform(body) before\n // condition/handler. For an internal EventBus event with a\n // plain object payload we just want to pass it through\n // untouched.\n transform: (payload: unknown) => payload,\n condition: () => true,\n handler: function (this: any) {\n const items = (this[itemsProperty] ?? []) as unknown[];\n const records = collectRecords(items);\n if (records.size === 0) return;\n const payload: IndexSeedEvent = {\n modelType: this.modelTypeId,\n items: Array.from(records.values()),\n };\n EventBus.publish(KosContainerIndexEvents.SEED, payload);\n },\n };\n}\n\nfunction installPurgeOnUnload(target: any, itemsProperty: string): void {\n const originalUnload = target.prototype.unload;\n target.prototype.unload = function (context?: KosContext) {\n const items = (this[itemsProperty] ?? []) as unknown[];\n const collections = new Set<string>();\n for (const item of items) {\n if (!isIndexableItem(item)) continue;\n const contribution: IndexRecordContribution = item[INDEX_RECORD_SYMBOL];\n if (contribution.collection) {\n collections.add(contribution.collection);\n }\n }\n for (const collection of collections) {\n const payload: IndexPurgeEvent = {\n modelType: this.modelTypeId,\n collection,\n };\n EventBus.publish(KosContainerIndexEvents.PURGE, payload);\n }\n if (originalUnload) {\n return originalUnload.call(this, context);\n }\n return undefined;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Record collection (shared with the request-seed handler)\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction collectRecords(items: unknown[]): Map<string, IndexRecord> {\n const result = new Map<string, IndexRecord>();\n for (const item of items) {\n if (!isIndexableItem(item)) continue;\n const contribution: IndexRecordContribution = item[INDEX_RECORD_SYMBOL];\n if (!contribution.collection) continue;\n result.set(contribution.id, contribution as IndexRecord);\n }\n return result;\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 type { 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 type { 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 headers?: Record<string, string>;\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 /**\n * Remove routes matching the given method and path\n * @param method HTTP method (GET, POST, etc.)\n * @param path Route path pattern\n * @returns Number of routes removed\n */\n remove(method: string, path: string): number {\n const initialRoutesLength = this.routes.length;\n\n // Remove from routes array\n this.routes = this.routes.filter(\n (route) => !(route.method === method && route.path === path)\n );\n\n // Remove from OpenAPI routes\n this.openApiRoutes = this.openApiRoutes.filter(\n (route) => !(route.method === method && route.path === path)\n );\n\n return initialRoutesLength - this.routes.length;\n }\n\n /**\n * Remove all routes matching a path pattern (regardless of method)\n * @param path Route path pattern\n * @returns Number of routes removed\n */\n removeAllForPath(path: string): number {\n const initialRoutesLength = this.routes.length;\n\n // Remove from routes array\n this.routes = this.routes.filter((route) => route.path !== path);\n\n // Remove from OpenAPI routes\n this.openApiRoutes = this.openApiRoutes.filter(\n (route) => route.path !== path\n );\n\n return initialRoutesLength - this.routes.length;\n }\n\n /**\n * Get all registered routes (for debugging/monitoring)\n */\n getRoutes(): Array<{ method: string; path: string }> {\n return this.routes.map((route) => {\n return {\n method: route.method,\n path: route.path,\n };\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","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 RegionServicePath = \"kos.region.service_path.mapper\",\n ConfigServicePath = \"kos.config.service_path.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\nexport interface ConfigBeanUpdateRecord {\n attr: string;\n currentValue: string;\n previousValue: string;\n}\n\nexport interface ConfigBeanUpdateResponse {\n changes: ConfigBeanUpdateRecord[];\n scopedChanges: 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 destinationAddress = \"\"\n) => {\n log.debug(`sending modify request for ConfigBean: ${id}`);\n const response = postModel({\n model,\n urlOverride: `${URL}${path}/${id}`,\n destinationAddress,\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 (\n id: string,\n path = `/api/kos/config`,\n destinationAddress = \"\"\n) => {\n log.debug(`sending get request for ConfigBean: ${id}`);\n const response = await getOne<ConfigBeanResponse>({\n urlOverride: `${URL}${path}/details/${id}/15`,\n destinationAddress,\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 ConfigBeanUpdateRecord,\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 const changesMap = dto.changes.reduce<\n Record<string, ConfigBeanUpdateRecord>\n >((acc, change) => {\n acc[change.attr] = change;\n return acc;\n }, {});\n\n const scopedChangesMap = dto.scopedChanges.reduce<\n Record<string, ConfigBeanUpdateRecord>\n >((acc, change) => {\n const c = acc[change.attr];\n if (c) {\n // If there's already a change for this attribute, we need to merge them\n acc[change.attr] = {\n ...c,\n currentValue: change.currentValue ?? c.currentValue, // The most recent value should be the current value\n previousValue: change.previousValue ?? c.previousValue, // The original previous value should be preserved\n };\n }\n return acc;\n }, changesMap);\n const allChanges = Object.values(scopedChangesMap);\n allChanges.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 * @group KOS Model\n * @category Configuration\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 * @group KOS Model\n * @category Configuration\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 ExtensionManager,\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 { KosCoreModelPropertyMapper } from \"../../constants\";\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\n/**\n * ConfigBean - Reactive hierarchical configuration management for KOS devices.\n *\n * The ConfigBean model provides reactive access to hierarchical configuration data from KOS devices\n * with real-time synchronization via WebSocket topics, schema-based validation, and transactional\n * updates. Essential for building configuration interfaces and managing device operational parameters.\n *\n * ## Key Features\n * - **Hierarchical Configuration** - Access nested configuration structures using path notation\n * - **Real-Time Synchronization** - Automatic updates via `/kos/config/{path}` WebSocket topic\n * - **Schema-Based Validation** - Built-in validation using device configuration schemas\n * - **Transactional Updates** - Atomic configuration changes with rollback support\n * - **Type-Safe Access** - Strongly typed property access with TypeScript support\n * - **Reactive Properties** - Automatic UI updates when configuration changes\n *\n * ## Configuration Path Patterns\n * ConfigBean supports hierarchical paths that mirror device system organization:\n * - **System Level**: `system:app` - Machine identity, operational modes\n * - **Service Level**: `kos:service:CANPumpMgr` - KOS service configurations\n * - **Hardware Level**: `assembly:core:board:macro:pump:water` - Component settings\n * - **Application Level**: `app:scheduling:dayWiseLockConfigMap` - Application-specific settings\n *\n * ## Common Use Cases\n * - **Configuration Interfaces** - Build reactive configuration management screens\n * - **Operational Parameter Control** - Real-time adjustment of device behavior\n * - **Schema-Driven Forms** - Generate configuration UIs from device schemas\n * - **System Administration** - Centralized device configuration management\n * - **Bulk Configuration Updates** - Transactional updates across multiple properties\n *\n * @example Basic Configuration Management\n * ```typescript\n * const systemConfig = ConfigBean.instance('system-config')\n * .options({ path: 'system:app' })\n * .build();\n *\n * // Access current configuration values\n * const machineId = systemConfig.values.machineId;\n * const debugMode = systemConfig.values.debugMode;\n *\n * // Update configuration properties\n * await systemConfig.updateProperty('debugMode', true);\n * await systemConfig.updateProperty('machineId', 'MACHINE-001');\n * ```\n *\n * @interface\n * @group KOS Model\n * @category Configuration\n * @useDeclaredType\n *\n * @see {@link IConfigBeanModelOptions} - Configuration options for ConfigBean instances\n * @see {@link ConfigBeanKeys} - Type-safe property key access\n * @see {@link ConfigPropertyTypes} - Supported configuration property types\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\");\nconst DESTINATION_PROP = createPropKey<IConfigBeanModel>(\"destinationAddress\");\n\n/**\n * Model id of the bean for a config path; the destination is part of the id\n * so the same path on two devices never shares one bean.\n * @ignore\n * @internal\n */\nexport function configBeanModelId(\n path: string,\n destinationAddress?: string\n): string {\n return destinationAddress\n ? `${CONFIG_BEAN_MODEL_TYPE}-${destinationAddress}-${path}`\n : `${CONFIG_BEAN_MODEL_TYPE}-${path}`;\n}\n\nfunction servicePathMapper<T extends {}>(\n configBeanModel: IConfigBeanModel<T>\n): string {\n const hasMapper = ExtensionManager.propertyMapper.hasMapper(\n KosCoreModelPropertyMapper.ConfigServicePath\n );\n if (hasMapper) {\n return ExtensionManager.propertyMapper.executeMapper(\n KosCoreModelPropertyMapper.ConfigServicePath,\n configBeanModel\n );\n }\n return \"/api/kos/config\";\n}\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(CONFIG_BEAN_MODEL_TYPE)\nclass ConfigBeanModelImpl<T extends {} = any> implements IKosDataModel {\n /** Service function for modifying configuration beans */\n private _modifyConfigBean: typeof modifyConfigBeanService;\n\n /** Service function for retrieving configuration beans */\n private _getConfigBean: typeof getConfigBeanService;\n\n /** Schema response containing configuration property definitions */\n private _schema?: SchemaResponse;\n /** Unique identifier for this configuration model instance */\n id: string;\n /** Hierarchical configuration path (e.g., 'system:app', 'kos:service:CANPumpMgr') */\n path: string;\n /** Observable configuration properties with current values */\n props: KosData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>;\n\n /** Observable configuration properties with previous values (before last update) */\n prevProps: KosData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>;\n\n /** Optional custom base path for configuration service endpoints */\n serviceBasePath?: string;\n /** Connection the bean's requests and topic subscription are routed to */\n destinationAddress?: 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 || servicePathMapper(this);\n this.destinationAddress = options.destinationAddress;\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 /**\n * Gets current configuration property values.\n *\n * @returns Object containing all configuration properties with their current values\n *\n * @example Access Configuration Values\n * ```typescript\n * const currentValues = systemConfig.values;\n * console.log('Machine ID:', currentValues.machineId);\n * console.log('Debug Mode:', currentValues.debugMode);\n * ```\n */\n get values() {\n return this.props.values;\n }\n\n /**\n * @internal\n */\n async ready() {\n log.debug(`readying config bean ${this.path}`);\n log.debug(`complete readying config bean ${this.path}`);\n }\n /**\n * @internal\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 config bean ${this.path}`);\n const response = await this._getConfigBean(\n this.path,\n this.serviceBasePath,\n this.destinationAddress\n );\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 /**\n * Gets all available schema property keys.\n *\n * @returns Array of property keys from the configuration schema\n */\n get schemaKeys() {\n return Object.keys(this._schema?.schema || {});\n }\n\n /**\n * Retrieves schema definition for a specific property.\n *\n * @param key - Property key to get schema for\n * @returns Schema definition if found, undefined otherwise\n *\n * @example Get Property Schema\n * ```typescript\n * const schema = systemConfig.getSchemaForProperty('debugMode');\n * if (schema) {\n * console.log('Type:', schema.type);\n * console.log('Description:', schema.description);\n * }\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 /**\n * Updates a specific configuration property value.\n *\n * @category Action\n *\n * @param key - The configuration property key to update\n * @param value - The new value to set for the property\n *\n * @example Update Configuration Property\n * ```typescript\n * await systemConfig.updateProperty('debugMode', true);\n * await systemConfig.updateProperty('machineId', 'MACHINE-001');\n * ```\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(\n this.path,\n request,\n this.serviceBasePath,\n this.destinationAddress\n );\n }\n\n // ------------------SUBSCRIPTIONS----------------------\n\n /**\n * @category Subscription\n * Updates the Config Bean model when a `/kos/config/{path}` event\n * is received from the server.\n *\n * @param configBean - the Config Bean that was updated.\n * @see ConfigBeanResponse\n */\n @kosTopicHandler({\n topic: `/kos/config/${PATH_PROP}`,\n websocket: true,\n destinationAddress: DESTINATION_PROP,\n explicitDestination: 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\";\nimport { configBeanModelId } from \"../models/config-bean/config-bean-model\";\n\ninterface KosConfigParams {\n path: string;\n lazy?: boolean;\n serviceBasePath?: string;\n /**\n * Connection the bean's requests and topic subscription are routed to.\n * Accepts a prop key so a host model can bind it per device.\n * When set, the bean's model id includes it so beans never collide across devices.\n */\n destinationAddress?: string;\n}\n\nexport const kosConfigBean =\n ({ path, lazy, serviceBasePath, destinationAddress }: 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: configBeanModelId(path, destinationAddress),\n options: {\n path,\n serviceBasePath,\n destinationAddress,\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 baseServicePath: string,\n destinationAddress = \"\"\n) => {\n try {\n const response = await getOne<RegionInfoResponse>({\n urlOverride: `${URL}${baseServicePath}/info`,\n destinationAddress,\n });\n return response;\n } catch (error) {\n return undefined;\n }\n};\n\nexport const getRegions = async (\n baseServicePath: string,\n destinationAddress = \"\"\n) => {\n try {\n const response = await getAll<RegionsResponse>({\n urlOverride: `${URL}${baseServicePath}`,\n destinationAddress,\n });\n return response;\n } catch (error) {\n return undefined;\n }\n};\n","import { IKosDataModel } from \"../../../../core\";\nimport { BaseRegionResponse, RegionsResponse, Unit } from \"../services\";\n\n/**\n * Unit conversion source specification for the conversion system.\n *\n * Flexible specification allowing conversion by specific unit name or by\n * measurement system with automatic unit selection. The conversion system\n * intelligently selects appropriate default units when only system/measure is provided.\n *\n * @example Specific Unit Conversion\n * ```typescript\n * const fahrenheitSource: UnitSource = { unit: 'fahrenheit' };\n * const celsiusSource: UnitSource = { unit: 'celsius' };\n *\n * const result = regionModel.convert(72, fahrenheitSource, celsiusSource);\n * console.log(result); // '22.22'\n * ```\n *\n * @example System-Based Conversion (Auto Unit Selection)\n * ```typescript\n * const imperialLength: UnitSource = { measure: 'length', system: 'imperial' };\n * const metricLength: UnitSource = { measure: 'length', system: 'metric' };\n *\n * // Automatically uses miles → kilometers\n * const result = regionModel.convert(5, imperialLength, metricLength);\n * console.log(result); // '8.047'\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n * @kosApiLevel 2\n */\nexport interface UnitSource {\n /** Measurement system identifier (e.g., 'metric', 'imperial', 'us') */\n system?: string;\n /** Type of measurement (e.g., 'length', 'weight', 'temperature', 'volume') */\n measure?: string;\n /** Specific unit name (e.g., 'meter', 'kilogram', 'fahrenheit') */\n unit?: string;\n}\n\n/**\n * Key type for measure maps — a string or the literal 'default'.\n *\n * @kosService core.region-info\n */\nexport type MeasureMapKeys = string | \"default\";\n\n/**\n * Record mapping MeasureMapKeys to Unit, defining units for each measurement system.\n *\n * @kosService core.region-info\n */\nexport type SystemMeasureMap = Record<MeasureMapKeys, Unit>;\n\n/**\n * Record mapping measurement types to their respective SystemMeasureMap.\n *\n * @kosService core.region-info\n */\nexport type MeasureMap = Record<string, SystemMeasureMap>;\n\n/**\n * Record mapping strings, typically used for default settings.\n *\n * @kosService core.region-info\n */\nexport type SystemDefaultMap = Record<string, string>;\n\n/**\n * Record mapping unit systems to their default settings.\n *\n * @kosService core.region-info\n */\nexport type DefaultMeasureMap = Record<string, SystemDefaultMap>;\n\n/**\n * Configuration options for creating RegionInfoModel instances.\n *\n * Currently an empty interface but reserved for future regional configuration\n * options such as default locale preferences, custom unit mappings, or\n * regional API endpoints.\n *\n * @example\n * ```typescript\n * const options: RegionInfoOptions = {\n * // Future options will be defined here\n * };\n * const regionModel = RegionInfo.instance().options(options).build();\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface RegionInfoOptions {\n /**\n * Connection the region services and settings beans are routed to.\n *\n * Set it when one window shows several devices; the instance is then keyed\n * by device and the default, unrouted instance is left untouched.\n */\n readonly destinationAddress?: string;\n}\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 * Time format configuration options for regional time display.\n *\n * Defines available time formats including 12-hour (AM/PM) and 24-hour formats\n * with their display patterns and behavior.\n *\n * @example\n * ```typescript\n * const timeFormats: TimeFormatOptions[] = [\n * { id: '12h', format: 'hh:mm:ss a', ampm: true }, // 3:45:30 PM\n * { id: '24h', format: 'HH:mm:ss', ampm: false } // 15:45:30\n * ];\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n * @kosApiLevel 2\n */\nexport interface TimeFormatOptions extends FormatOptions {\n /** True if using 12-hour format with AM/PM, false for 24-hour format */\n ampm: boolean;\n}\n\n/**\n * Date format configuration options for regional date display.\n *\n * Defines available date formats including different component ordering\n * (Day/Month/Year vs Month/Day/Year) and display patterns.\n *\n * @example\n * ```typescript\n * const dateFormats: DateFormatOptions[] = [\n * { id: 'us', format: 'MM/DD/YYYY', order: 'MDY' }, // 03/15/2024\n * { id: 'eu', format: 'DD/MM/YYYY', order: 'DMY' }, // 15/03/2024\n * { id: 'iso', format: 'YYYY-MM-DD', order: 'YMD' } // 2024-03-15\n * ];\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n * @kosApiLevel 2\n */\nexport interface DateFormatOptions extends FormatOptions {\n /** Order of date components: 'MDY', 'DMY', 'YMD', etc. */\n order: string;\n}\n\n/**\n * Unit system configuration options for measurement standards.\n *\n * Defines available unit systems (metric, imperial, etc.) with their\n * display names and identification.\n *\n * @example\n * ```typescript\n * const unitSystems: UnitSystemOptions[] = [\n * { id: 'metric', name: 'Metric System' },\n * { id: 'imperial', name: 'Imperial System' },\n * { id: 'us', name: 'US Customary System' }\n * ];\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n * @kosApiLevel 2\n */\nexport interface UnitSystemOptions extends BaseOptions {\n /** Display name of the unit system (e.g., 'Metric System', 'Imperial System') */\n name: string;\n}\n\n/**\n * Region Info Model - Comprehensive regional localization and unit conversion system for KOS applications.\n *\n * This singleton model provides centralized management of regional settings including time formats,\n * date formats, unit systems, time zones, and intelligent unit conversion. Essential for building\n * internationally-aware applications that adapt to local preferences and measurement standards.\n *\n * ## Key Features\n * - **Time & Date Formatting** - Configurable 12/24-hour time and various date order formats\n * - **Unit System Management** - Complete metric/imperial conversion with precision control\n * - **Time Zone Support** - Full time zone management with regional associations\n * - **Dynamic Configuration** - Live updates through KOS configuration system\n * - **Type Safety** - Generic support for additional regional data\n * - **Singleton Pattern** - Single instance manages all regional settings\n *\n * ## Unit Conversion System\n * The model provides intelligent unit conversion between different measurement systems:\n * - **Automatic scaling** - Handles complex conversions with proper scaling factors\n * - **Precision control** - Configurable decimal places per unit type\n * - **Family validation** - Prevents invalid conversions (e.g., length to weight)\n * - **Default unit resolution** - Automatic selection of appropriate units per system\n *\n * @template AdditionalData - Extends BaseRegionResponse for custom regional data requirements\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const regionModel = RegionInfo.instance().build();\n *\n * // Unit conversion and regional settings\n * const celsius = regionModel.convert(72, { unit: 'fahrenheit' }, { unit: 'celsius' });\n * console.log(regionModel.selectedCountry); // 'us'\n * ```\n *\n * @kosService core.region-info\n * @group KOS Model\n * @category Region Info\n * @useDeclaredType\n *\n * @see {@link UnitSource} - Unit conversion source specification\n * @see {@link RegionInfoOptions} - Configuration options for RegionInfoModel instances\n * @kosApiLevel 2\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 * @kosApiLevel 22\n */\n readonly serviceBasePath: 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/**\n * Enum for keys used in UnitTuple.\n *\n * @kosService core.region-info\n */\nexport enum UnitTupleKeys {\n family,\n scale,\n offset,\n decimals,\n alias,\n system,\n}\n\n/**\n * Tuple type for unit properties: family, scale, offset, decimals, alias.\n *\n * @kosService core.region-info\n */\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 (unit.alias) {\n systemMeasure[unit.alias] = unitTuple;\n }\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\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 {\n createPropKey,\n ExtensionManager,\n Kos,\n kosDependency,\n KosLog,\n kosModel,\n} from \"../../../core\";\nimport { KosCoreModelPropertyMapper } from \"../../constants\";\n\nimport { ConfigBean } from \"../config-bean\";\nimport {\n configBeanModelId,\n type IConfigBeanModel,\n} 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\nfunction servicePathMapper(regionInfoModel: RegionInfoModel): string {\n const hasMapper = ExtensionManager.propertyMapper.hasMapper(\n KosCoreModelPropertyMapper.RegionServicePath\n );\n if (hasMapper) {\n return ExtensionManager.propertyMapper.executeMapper<\n RegionInfoModel,\n string\n >(KosCoreModelPropertyMapper.RegionServicePath, regionInfoModel);\n }\n return \"/api/kos/regions\";\n}\n\nconst REGION_SETTINGS_PATH = \"kos:service:region:settings\";\nconst REGION_PATH = \"kos:service:region\";\nconst DESTINATION_PROP =\n createPropKey<RegionInfoModelImpl>(\"destinationAddress\");\nconst REGION_SETTINGS_BEAN_ID_PROP = createPropKey<RegionInfoModelImpl>(\n \"regionSettingsBeanId\"\n);\nconst REGION_BEAN_ID_PROP = createPropKey<RegionInfoModelImpl>(\"regionBeanId\");\n\n/**\n * Model id of the region info for a destination; the default instance keeps\n * the type as its id, so existing lookups by type are unchanged.\n * @ignore\n * @internal\n */\nexport function regionInfoModelId(destinationAddress?: string): string {\n return destinationAddress\n ? `${MODEL_TYPE}-${destinationAddress}`\n : MODEL_TYPE;\n}\n/**\n * @ignore\n * @internal\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 serviceBasePath: string;\n /** Connection the region services and beans are routed to */\n destinationAddress?: string;\n // An unset destination must keep the legacy bean ids, and a dependency id\n // template cannot drop a segment, so the bean ids are computed per instance.\n readonly regionSettingsBeanId: string;\n readonly regionBeanId: string;\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 @kosDependency({\n modelType: ConfigBean.type,\n id: REGION_SETTINGS_BEAN_ID_PROP,\n options: {\n path: REGION_SETTINGS_PATH,\n destinationAddress: DESTINATION_PROP,\n },\n })\n regionSource!: RegionSettingsConfigBean;\n\n @kosDependency({\n modelType: ConfigBean.type,\n id: REGION_BEAN_ID_PROP,\n options: { path: REGION_PATH, destinationAddress: DESTINATION_PROP },\n })\n private region!: RegionConfigBean;\n\n private regions: string[] = [];\n private timeZoneMap: Record<string, string[]> = {};\n\n constructor(modelId: string, options?: RegionInfoOptions) {\n this.id = modelId;\n this.destinationAddress = options?.destinationAddress;\n this.regionSettingsBeanId = configBeanModelId(\n REGION_SETTINGS_PATH,\n this.destinationAddress\n );\n this.regionBeanId = configBeanModelId(REGION_PATH, this.destinationAddress);\n\n this.serviceBasePath = servicePathMapper(this);\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 this.serviceBasePath,\n this.destinationAddress\n );\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 this.serviceBasePath,\n this.destinationAddress\n );\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: false,\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\nfunction formatUnit(\n value: any,\n unit: string,\n format?: {\n mode: \"short\" | \"long\";\n minDecimals?: number;\n maxDecimals?: number;\n }\n) {\n const normalized = unit.toLowerCase().replace(/_/g, \"-\").replace(/s$/, \"\"); // naive singularization\n const locale = new Intl.NumberFormat().resolvedOptions().locale ?? \"en-US\";\n try {\n const mode = format?.mode || \"long\";\n const maxDecimals = format?.maxDecimals ?? 2;\n const minDecimals = format?.minDecimals ?? 0;\n return new Intl.NumberFormat(locale, {\n style: \"unit\",\n unit: normalized,\n unitDisplay: mode,\n minimumFractionDigits: minDecimals,\n maximumFractionDigits: maxDecimals,\n }).format(value);\n } catch (e) {\n // fallback\n return unit;\n }\n}\n/**\n * Converts a numeric value from one unit to another, formats the result, and returns\n * an object containing the converted value, display strings, and the unit.\n *\n * @example\n * convert and format a value, letting the region determine the target unit:\n *\n * ```typescript\n * import { convertWithUnits } from \"@kosdev-code/kos-ui-sdk\";\n *\n * // If the region is set to US, the value is converted to fluid ounces.\n * const result = convertWithUnits(1000, \"milliliter\");\n * // result.value -> the converted numeric value as a string\n * // result.display -> \"33.81 fluid ounces\" (long form)\n * // result.shortDisplay -> \"33.81 fl oz\" (short form)\n * // result.unit -> \"fluid-ounce\"\n * ```\n *\n * @example\n * specify the target unit and control the number of decimal places:\n *\n * ```typescript\n * import { convertWithUnits } from \"@kosdev-code/kos-ui-sdk\";\n *\n * const result = convertWithUnits(1000, \"milliliter\", \"fluid-ounce\", {\n * minDecimals: 1,\n * maxDecimals: 1,\n * });\n * ```\n *\n * @param value - The numeric value to convert.\n * @param from - The source unit or unit system to convert from.\n * @param to - (Optional) The target unit or unit system to convert to. If not provided, uses the default unit system.\n * @param format - (Optional) Formatting options for the output, including minimum and maximum decimal places.\n * @param format.minDecimals - (Optional) Minimum number of decimal places in the formatted output.\n * @param format.maxDecimals - (Optional) Maximum number of decimal places in the formatted output.\n * @returns An object containing:\n * - `value`: The converted value as a string.\n * - `display`: The formatted value with unit in long form.\n * - `shortDisplay`: The formatted value with unit in short form.\n * - `unit`: The unit used for the converted value.\n * @throws If the RegionInfo model is not found.\n */\nexport const convertWithUnits = (\n value: number,\n from: UnitConversionSource,\n to?: UnitConversionSource,\n format?: {\n minDecimals?: number;\n maxDecimals?: number;\n }\n): { value: string; display: string; shortDisplay: string; unit: string } => {\n const convertedValue = convert(value, from, to);\n const fromUnit = createUnitSource({ source: from });\n const { model: regionInfo } = getKosModelSync<RegionInfoModel>(\n RegionInfo.type\n );\n if (!regionInfo) {\n throw new Error(\"RegionInfo model not found\");\n }\n\n const measure = regionInfo.getUnitMeasure(fromUnit.unit || \"\");\n\n const defaultToSource = { system: regionInfo.defaultUnitSystem };\n\n const toUnit: UnitSource = createUnitSource({\n source: to || defaultToSource,\n defaultMeasure: regionInfo.getUnitMeasure(fromUnit.unit || \"\"),\n });\n\n const unit = regionInfo.getDefaultUnitForMeasure(measure, toUnit.system!);\n const defaultDecimals = regionInfo.getDefaultUnitDecimalPlaces(\n measure,\n toUnit.system!\n );\n\n const _format = {\n ...format,\n\n minDecimals: format?.minDecimals ?? defaultDecimals,\n maxDecimals: format?.maxDecimals ?? defaultDecimals,\n };\n return {\n value: convertedValue,\n unit: unit || fromUnit.unit || \"\",\n display: formatUnit(convertedValue as any, unit || fromUnit.unit || \"\", {\n ..._format,\n mode: \"long\",\n }),\n shortDisplay: formatUnit(\n convertedValue as any,\n unit || fromUnit.unit || \"\",\n { ..._format, mode: \"short\" }\n ),\n };\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 { ConfigBean } from \"../config-bean\";\nimport { configBeanModelId } from \"../config-bean/config-bean-model\";\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 { regionInfoModelId } from \"../region-info/region-info-model\";\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\");\nconst DESTINATION_PROP = createPropKey<KosConfigProperty>(\"destinationAddress\");\nconst BEAN_ID_PROP = createPropKey<KosConfigPropertyImpl>(\"configBeanId\");\nconst REGION_INFO_ID_PROP =\n createPropKey<KosConfigPropertyImpl>(\"regionInfoId\");\n\n/**\n * @ignore\n * @internal\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 destinationAddress?: string;\n // An unset destination must keep the legacy bean id, and a dependency id\n // template cannot drop a segment, so the bean id is computed per instance.\n readonly configBeanId: string;\n readonly regionInfoId: string;\n @kosDependency({\n modelType: RegionInfo.type,\n id: REGION_INFO_ID_PROP,\n options: { destinationAddress: DESTINATION_PROP },\n })\n regionInfo!: RegionInfoModel;\n\n @kosDependency({\n modelType: ConfigBean.type,\n id: BEAN_ID_PROP,\n options: {\n path: PATH_PROP,\n serviceBasePath: SERVICE_PATH_PROP,\n destinationAddress: DESTINATION_PROP,\n },\n })\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.destinationAddress = options.destinationAddress;\n this.optionsExpander = options.optionsExpander;\n this.configBeanId = configBeanModelId(this.path, this.destinationAddress);\n this.regionInfoId = regionInfoModelId(this.destinationAddress);\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 /**\n * Gets the schema data type for this property.\n *\n * @returns Schema type string (e.g., \"String\", \"Number\", \"Boolean\", \"enum\")\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 /**\n * Gets the schema format hint for this property.\n *\n * @returns Format string (e.g., \"second\", \"milliliter\", \"hour\") or empty string if not specified\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 /**\n * Gets available options for enumerated properties.\n *\n * @returns Array of options with label/value pairs for dropdowns and selection controls\n *\n * @example Get Property Options\n * ```typescript\n * const options = statusProperty.options;\n * // Returns: [\n * // { label: \"Active\", value: \"active\" },\n * // { label: \"Inactive\", value: \"inactive\" }\n * // ]\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 /**\n * Sets the configuration property value with automatic unit conversion.\n *\n * @param value - The new value to set (in regional units)\n *\n * @example Update Property Value\n * ```typescript\n * pumpRateProperty.value = 1.2; // Sets rate to 1.2 mL/s (converted to backend units)\n * ```\n */\n set value(value: ConfigPropertyTypes) {\n this.updateProperty(value);\n }\n\n /**\n * Gets the configuration property value converted to regional units.\n *\n * @returns Property value in regional display units\n *\n * @example Get Property Value\n * ```typescript\n * const currentRate = pumpRateProperty.value; // Gets rate in mL/s (regional units)\n * ```\n */\n get value() {\n return this.getValue(true);\n }\n\n /**\n * Gets the raw backend value without unit conversion.\n *\n * @returns Raw property value as stored in backend (typically SI units)\n */\n get rawValue() {\n return this.bean.props[this.attribute];\n }\n\n /**\n * Gets the property value with appropriate decimal precision for display.\n *\n * @returns Property value formatted with significant digits based on regional settings\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 converter?.to?.system || 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 /**\n * Gets the previous property value before the last update.\n *\n * @returns Previous property value in regional display units\n *\n * @example Track Value Changes\n * ```typescript\n * const oldValue = pumpRateProperty.previousValue; // Previous rate value\n * const newValue = pumpRateProperty.value; // Current rate value\n * console.log(`Rate changed from ${oldValue} to ${newValue}`);\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 /**\n * @internal\n */\n async activate() {\n log.debug(`activating config bean ${this.id}`);\n }\n\n /**\n * Gets the formatted display string with units and localization.\n *\n * @returns Localized string representation with appropriate units (e.g., \"1.2 mL/s\", \"150 °F\")\n *\n * @example Display Formatted Value\n * ```typescript\n * const display = temperatureProperty.displayValue; // \"72.5 °F\"\n * const rate = pumpRateProperty.displayValue; // \"1.2 mL/s\"\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 /**\n * Gets the unit of measure for the property value.\n *\n * @returns Unit string (e.g., \"°F\", \"mL/s\", \"seconds\") or empty string for unitless properties\n *\n * @example Get Property Unit\n * ```typescript\n * const unit = temperatureProperty.unit; // \"°F\" or \"°C\" based on regional settings\n * const rateUnit = pumpRateProperty.unit; // \"mL/s\"\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 /**\n * Gets display formatting options from the backend schema.\n *\n * @returns Display options object with formatting preferences (decimals, style, etc.)\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\n // DRT is a display format, not a convertible unit\n if (this.schemaFormat === \"drt\") return undefined;\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 toUnitMeasure = this.converter?.to?.unit\n ? this.regionInfo.getUnitMeasure(this.converter.to.unit)\n : undefined;\n const _measure =\n globalMeasure || toMeasure || fromMeasure || toUnitMeasure || 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 /**\n * Updates the configuration property value with automatic unit conversion.\n *\n * @param value - The new value to set (in regional display units)\n *\n * @example Update Property\n * ```typescript\n * // Set temperature in Fahrenheit (regional unit)\n * await temperatureProperty.updateProperty(75.5);\n *\n * // Set pump rate in mL/s (regional unit)\n * await pumpRateProperty.updateProperty(1.2);\n * ```\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 /**\n * Connection the property's bean is routed to. Accepts a prop key so a host\n * model can bind it per device; the property and bean ids include it.\n */\n destinationAddress?: 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 destinationAddress,\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: destinationAddress\n ? `${destinationAddress}-${path}-${attribute}`\n : `${path}-${attribute}`,\n options: {\n path,\n attribute,\n serviceBasePath,\n destinationAddress,\n converter: _converter,\n formatter,\n optionsExpander,\n },\n\n lifecycle: DependencyLifecycle.INIT,\n lazy,\n };\n };\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","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 { 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 { 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","import {\n EXTENSION_FUTURE_LIFECYCLE_WRAPPER,\n FutureAliases,\n FutureContainerSetup,\n FutureService,\n isKosExecutionContext,\n KOS_EXECUTION_CONTEXT,\n kosAction,\n kosAutoEffect,\n KosLog,\n MultipleFutureContainerSetup,\n registerExtensionPoint,\n uuid,\n whenReady,\n type KosServiceResponse,\n} from \"../../core\";\nimport { FUTURE_NOT_ASSIGNED } from \"../constants\";\nimport { mapDtoToFutureModel } from \"../models/future/future-model-builder\";\nimport {\n FutureAwareContainer,\n FutureContainer,\n} from \"../models/future/future-types\";\nimport { FutureResponse } from \"../services\";\nimport { FutureEndState } from \"../services/future\";\nimport { FutureManager } from \"../utils/future-manager\";\nexport interface FutureProps {\n alias?: string;\n namespace?: string;\n /**\n * Enable automatic AbortController integration\n * When true, the decorator will inject an AbortSignal as the last parameter\n * and set up bi-directional cancellation between Future and HTTP requests\n * @default true\n */\n abortController?: boolean;\n /**\n * Tracker injection policy\n * - 'id': Inject tracker ID as last string parameter (default, preserves existing behavior)\n * - 'context': Inject tracker ID into execution context object as $tracker property\n * @default 'id'\n */\n trackerPolicy?: \"id\" | \"context\";\n}\n\nconst isFutureResponse = (response: any): response is FutureResponse =>\n !response || !response.data;\n\n/**\n * Resolve the model's future handler by the property name it was injected\n * under.\n *\n * `@kosFutureAware` and `@kosMultipleFutureAware` accept `handlerProperty` and\n * record the chosen name on the model; `futureHandler` is only the default, so\n * the name has to be read back rather than assumed. Multiple-future setup wins\n * when a model carries both, matching the order kosModel injects them.\n */\nconst resolveFutureHandler = (model: any): FutureAwareContainer => {\n const handlerProperty =\n model?.[MultipleFutureContainerSetup]?.handlerProperty ??\n model?.[FutureContainerSetup]?.handlerProperty ??\n \"futureHandler\";\n\n return model[handlerProperty];\n};\ntype FutureHandler = (\n this: FutureContainer,\n ...args: Array<unknown>\n) => Promise<KosServiceResponse<FutureResponse> | undefined>;\n\n/**\n * Wrap an async function with Future lifecycle management.\n *\n * This is the core wrapper logic shared by the `@kosFuture` decorator\n * and the declarative model factory. It handles:\n * - Tracker ID generation and injection\n * - Future placeholder creation and readiness waiting\n * - AbortController integration (bi-directional cancellation)\n * - Future model mapping from the service response\n *\n * @param original - The raw async function to wrap.\n * @param methodName - Name of the method (used for logging).\n * @param props - Future configuration properties.\n * @returns A wrapped handler function suitable for the FutureService Symbol.\n */\nexport function wrapWithFutureLifecycle(\n original: (...args: any[]) => Promise<any>,\n methodName: string,\n props: FutureProps = {}\n): (\n this: FutureContainer,\n ...args: Array<unknown>\n) => Promise<FutureResponse | undefined> {\n const {\n alias,\n namespace,\n abortController = false,\n trackerPolicy = \"id\",\n } = props;\n\n return 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 ${methodName} with tracker ${tracker}`\n );\n\n // Set up AbortController if enabled\n let abortControllerInstance: AbortController | undefined;\n let effectDisposer: (() => void) | undefined;\n\n if (abortController) {\n abortControllerInstance = new AbortController();\n }\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 resolveFutureHandler(this).addFuture(future, alias);\n });\n\n // Set up bi-directional cancellation if AbortController is enabled\n if (abortController && abortControllerInstance) {\n // 1. Future → AbortController: React to future cancellation\n effectDisposer = kosAutoEffect(() => {\n if (\n future.status === \"CANCELLED\" ||\n future.endState === FutureEndState.Canceled\n ) {\n KosLog.debug(`Future ${future.id} cancelled, aborting request`);\n abortControllerInstance?.abort();\n }\n });\n\n // 2. AbortController → Future: Listen for abort and cancel future\n abortControllerInstance.signal.addEventListener(\n \"abort\",\n async () => {\n if (\n future.status !== \"CANCELLED\" &&\n future.endState !== FutureEndState.Canceled &&\n !future.endState\n ) {\n KosLog.debug(\n `AbortController aborted, cancelling future ${future.id}`\n );\n try {\n await future.cancelFuture();\n } catch (error: any) {\n KosLog.error(`Failed to cancel future ${future.id}:`, error);\n }\n }\n },\n { once: true }\n );\n }\n\n const cleanup = () => {\n if (effectDisposer) {\n effectDisposer();\n effectDisposer = undefined;\n }\n };\n\n try {\n // Prepare arguments - inject AbortSignal if enabled\n const enhancedArgs = [...args];\n if (abortController && abortControllerInstance) {\n // Check if last argument is already an AbortSignal\n const lastArg = enhancedArgs[enhancedArgs.length - 1];\n if (lastArg && typeof lastArg === \"object\" && \"aborted\" in lastArg) {\n // Replace existing signal with our managed one\n enhancedArgs[enhancedArgs.length - 1] =\n abortControllerInstance.signal;\n } else {\n // Add signal as new parameter\n enhancedArgs.push(abortControllerInstance.signal);\n }\n }\n\n // Inject tracker based on policy\n if (trackerPolicy === \"context\") {\n // Check if last parameter is already a KosExecutionContext\n const lastArg = enhancedArgs[enhancedArgs.length - 1];\n\n if (isKosExecutionContext(lastArg)) {\n // Inject $tracker into existing context\n lastArg.$tracker = tracker;\n } else {\n // Create new context with $tracker\n const context: any = {\n [KOS_EXECUTION_CONTEXT]: true,\n $tracker: tracker,\n };\n enhancedArgs.push(context);\n }\n } else {\n // Default 'id' policy: Add tracker as final parameter (preserves existing behavior)\n enhancedArgs.push(tracker);\n }\n\n const futureResponse:\n | KosServiceResponse<FutureResponse>\n | FutureResponse\n | undefined =\n // eslint-disable-next-line no-invalid-this\n await original.apply(this, enhancedArgs);\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 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 resolveFutureHandler(this).removeFuture(alias);\n }\n\n cleanup();\n return response;\n } catch (e) {\n cleanup();\n\n // Convert abort errors to more user-friendly messages\n if (abortController && abortControllerInstance?.signal.aborted) {\n const cancelledError = new Error(\"Operation cancelled\");\n KosLog.debug(`Operation ${methodName} was cancelled`);\n throw cancelledError;\n }\n\n KosLog.error(e);\n throw e;\n }\n };\n}\n\n// Register wrapWithFutureLifecycle as an extension point so the\n// declarative model package can retrieve it without a direct import\n// (which would create a circular / wrong-direction dependency).\nregisterExtensionPoint(EXTENSION_FUTURE_LIFECYCLE_WRAPPER, {\n register: () => {\n /* single implementation, no dynamic registration needed */\n },\n execute: () => wrapWithFutureLifecycle,\n});\n\nexport function kosFuture(props: FutureProps = {}) {\n const { alias } = props;\n return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n target[FutureService] = target[FutureService] || {};\n\n // Store alias metadata for @kosMultipleFutureAware decorator\n if (alias) {\n target[FutureAliases] = target[FutureAliases] || new Map();\n target[FutureAliases].set(propertyKey, alias);\n }\n\n const original: FutureHandler = descriptor.value;\n const handler = wrapWithFutureLifecycle(original, propertyKey, props);\n\n target[FutureService][propertyKey] = {\n handler,\n };\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 type { PublicModelInterface } from \"../../../core/types\";\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\";\n\n/**\n * StateBean - Reactive state management for KOS device state properties.\n *\n * The StateBean model provides real-time access to KOS device state information through\n * reactive properties that automatically synchronize with device state changes via WebSocket\n * topics. This model is essential for applications that need to monitor device state,\n * track property changes, or build reactive UIs that respond to device status updates.\n *\n * ## Key Features\n * - **Real-time Synchronization** - Automatic updates via `/kos/state/{path}` WebSocket topics\n * - **Type-safe Properties** - Strongly typed state properties with automatic type conversion\n * - **Observable State Map** - Reactive Map-based property storage for efficient updates\n * - **Automatic Type Conversion** - Smart conversion of string values to boolean/number types\n * - **Path-based Organization** - Hierarchical state organization using dot-notation paths\n * - **Lifecycle Management** - Proper initialization and loading of state data\n *\n * ## Topic-Based Reactivity\n * The model listens to KOS topics for real-time synchronization:\n * - **`/kos/state/{path}`** - Receives state updates for the specified path, triggering automatic property updates across all connected clients\n *\n * ## State Property Types\n * Supports all common KOS state property types:\n * - **string** - Text values, configuration strings, identifiers\n * - **number** - Numeric values, counters, measurements, percentages\n * - **boolean** - Status flags, enabled/disabled states, operational flags\n * - **object** - Complex state objects, nested configurations\n *\n * ## Common Use Cases\n * - **Device Status Monitoring** - Track operational states, error conditions, health metrics\n * - **Configuration State** - Monitor dynamic configuration changes and feature flags\n * - **System Status Dashboards** - Build real-time status displays and monitoring interfaces\n * - **Conditional UI Logic** - Show/hide UI elements based on device state\n * - **State-dependent Operations** - Enable/disable functionality based on device state\n * - **Multi-client Synchronization** - Keep multiple clients in sync with device state\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const deviceState = StateBean.instance('device-status')\n * .options({ path: 'device.operational.status' })\n * .build();\n *\n * // Access reactive state properties\n * const isOnline = deviceState.props.get('online') as boolean;\n * const temperature = deviceState.props.get('temperature') as number;\n * ```\n *\n * @group KOS Model\n * @category State Management\n * @useDeclaredType\n *\n * @see {@link StateBeanOptions} - Configuration options for StateBean model\n * @see {@link StatePropertyTypes} - Supported state property value types\n * @see {@link StateProp} - Individual property access model\n * @see {@link getStateBeanData} - Service function for loading state data\n */\nexport type StateBean<\n T extends Record<string, StatePropertyTypes> = Record<\n string,\n StatePropertyTypes\n >\n> = PublicModelInterface<StateBeanModelImpl<T>>;\n\nconst PATH_PROP = createPropKey<StateBeanModel>(\"path\");\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class StateBeanModelImpl<\n T extends Record<string, StatePropertyTypes> = Record<\n string,\n StatePropertyTypes\n >\n> implements StateBeanModel<T>, IKosModelLogger\n{\n /** Unique identifier for the model instance */\n id: string;\n /** State path being monitored for updates */\n path!: string;\n /** Reactive Map of state properties with automatic type conversion */\n props: StatePropsMap<T>;\n /** Context logger for debugging and diagnostics */\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 /**\n * Updates the model configuration with new options.\n * @param options New configuration options to apply\n */\n updateModel(options: StateBeanOptions): void {\n mapDataToModel(options, this);\n }\n\n /**\n * Handles WebSocket state updates from the KOS topic system.\n * Automatically converts string values to appropriate types (boolean, number).\n * @param stateBean State data received from WebSocket topic\n * @internal\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 T[keyof T]);\n });\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing state-bean ${this.id}`);\n }\n\n /**\n * Updates multiple properties at once with type conversion.\n * @param props Properties to update\n * @private\n */\n updateProps(props: Record<string, StatePropertyTypes>) {\n Object.entries(props).forEach(([key, value]) => {\n this.props.set(key, value);\n });\n }\n\n /**\n * @internal\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 { 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 type {\n IKosModelLogger,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core\";\nimport { createPropKey, kosDependency, kosModel } from \"../../../core\";\nimport type { PublicModelInterface } from \"../../../core/types\";\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\";\n\n/**\n * StateProp - Focused access to individual state properties with dependency on StateBean.\n *\n * The StateProp model provides targeted access to a single property within a StateBean,\n * offering a focused interface for components or services that only need to monitor\n * specific state values. This model automatically manages its dependency on the underlying\n * StateBean and provides reactive access to individual property values.\n *\n * ## Key Features\n * - **Single Property Focus** - Access one specific property from a StateBean path\n * - **Automatic StateBean Dependency** - Manages StateBean dependency transparently\n * - **Type-safe Value Access** - Strongly typed property value with generic support\n * - **Reactive Updates** - Automatically updates when underlying StateBean changes\n * - **Simplified Interface** - Clean `.value` accessor for property values\n * - **String Conversion** - Built-in `toString()` method for display purposes\n *\n * ## StateBean Integration\n * StateProp models automatically create and manage dependencies on StateBean models:\n * - **Automatic Dependency** - Creates StateBean with matching path automatically\n * - **Shared StateBean** - Multiple StateProp models can share the same StateBean\n * - **Lifecycle Management** - Proper initialization and cleanup of dependencies\n * - **Real-time Synchronization** - Inherits WebSocket updates from StateBean\n *\n * ## Common Use Cases\n * - **Single Value Components** - React components that only need one state property\n * - **Conditional Logic** - Enable/disable functionality based on specific state\n * - **Status Indicators** - Display individual status flags or measurements\n * - **Property Validation** - Monitor specific properties for validation rules\n * - **Focused Updates** - Reduce re-renders by tracking only needed properties\n * - **Service Dependencies** - Services that depend on specific state values\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const deviceOnline = StateProp.instance('device-online')\n * .options({\n * path: 'device.operational.status',\n * attribute: 'online'\n * })\n * .build();\n *\n * // Access focused property value with type safety\n * const isOnline = deviceOnline.value as boolean;\n * console.log(`Status: ${deviceOnline.toString()}`);\n * ```\n *\n * @group KOS Model\n * @category State Management\n * @useDeclaredType\n *\n * @see {@link StatePropOptions} - Configuration options for StateProp model\n * @see {@link StatePropertyTypes} - Supported property value types\n * @see {@link StateBean} - Underlying state collection model\n * @see {@link StateBeanOptions} - StateBean configuration options\n */\nexport type StateProp<T extends StatePropertyTypes = StatePropertyTypes> =\n PublicModelInterface<StatePropModelImpl<T>>;\n\nconst PATH_PROP = createPropKey<StateBeanModel>(\"path\");\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class StatePropModelImpl<\n T extends StatePropertyTypes = StatePropertyTypes\n> implements KosStateProp<T>, IKosModelLogger\n{\n /** Unique identifier for the model instance */\n id: string;\n /** State path being monitored (same as dependent StateBean) */\n path: string;\n /** Specific attribute name to access within the state path */\n attribute: string;\n /** Context logger for debugging and diagnostics */\n logger: KosContextLogger;\n\n /** Automatic dependency on StateBean for the specified path */\n @kosDependency<StateBeanOptions>({\n modelType: StateBean.type,\n id: `${StateBean.type}-${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 /** The current value of the specific attribute, with type safety */\n get value(): T | undefined {\n return this.stateBean.props.get(this.attribute) as T;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing state-prop ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading state-prop ${this.id}`);\n }\n\n /**\n * Converts the current property value to string for display purposes.\n * @returns String representation of the property value, or empty string if undefined\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 { 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 {\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\";\n\n/**\n * BrowserRouter - HTTP routing and middleware management for KOS web services.\n *\n * The BrowserRouter model provides a comprehensive HTTP routing system that handles incoming\n * requests via WebSocket topics and routes them through registered middleware and handlers.\n * It enables KOS applications to expose REST APIs, handle device communication, and manage\n * HTTP-based integrations with automatic OpenAPI specification generation.\n *\n * ## Key Features\n * - **Topic-Based HTTP Handling** - Processes HTTP requests via `kos.http.request` topic\n * - **Middleware Support** - Chain multiple middleware functions for request processing\n * - **Route Management** - Dynamic registration, removal, and inspection of routes\n * - **OpenAPI Generation** - Automatic API documentation at `/openapi.json`\n * - **Request/Response Abstraction** - Familiar Express.js-style request/response objects\n * - **Method Support** - Full HTTP method support (GET, POST, PUT, DELETE, PATCH)\n *\n * ## Topic-Based Reactivity\n * The model listens to these KOS topics for HTTP request handling:\n * - **`kos.http.request`** - Incoming HTTP requests from clients or other services\n * - **`kos.http.response`** - Outgoing HTTP responses with status codes and data\n *\n * ## Common Use Cases\n * - **REST API Endpoints** - Expose device data and control APIs\n * - **Webhook Handlers** - Process incoming webhooks from external services\n * - **Inter-Service Communication** - Handle requests between KOS services\n * - **Device Integration** - Bridge HTTP protocols with KOS messaging\n * - **API Gateway** - Route and transform requests to downstream services\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const router = KosBrowserRouter.instance('main-router')\n * .options({})\n * .build();\n *\n * // Register HTTP endpoints with middleware support\n * router.use('GET', '/api/status', async (req, res) => {\n * res.send({ status: 'online' });\n * });\n *\n * router.use('POST', '/api/commands', validateAuth, async (req, res) => {\n * res.status(200).send({ success: true });\n * });\n * ```\n *\n * @group KOS Model\n * @category Browser Router\n * @category Service Integration\n * @useDeclaredType\n *\n * @see {@link BrowserRouterOptions} - Configuration options for BrowserRouter instances\n */\nexport type KosBrowserRouter = Omit<\n PublicModelInterface<BrowserRouterModelImpl>,\n \"load\" | \"init\"\n>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class BrowserRouterModelImpl implements IKosDataModel, IKosIdentifiable {\n /** Unique identifier for the router model instance */\n private _id: string;\n /** Context logger for debugging HTTP requests and routing */\n private logger: KosContextLogger;\n /** Internal HTTP router instance handling middleware chains */\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 /** Model instance identifier */\n get id(): string {\n return this._id;\n }\n\n /**\n * Handles incoming HTTP requests from WebSocket topics.\n * @param data Request body data\n * @param payload Request headers and metadata\n * @internal\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 body: data,\n headers: payload.headers,\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 /**\n * Registers a route with optional middleware chain.\n * @param method HTTP method (GET, POST, PUT, DELETE, PATCH)\n * @param path Route path pattern with parameter support\n * @param middlewares Middleware functions and final handler\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\n /**\n * Remove routes matching the given method and path\n * @param method HTTP method (GET, POST, etc.)\n * @param path Route path pattern\n * @returns Number of routes removed\n */\n remove(method: KosMethodTypes, path: string): number {\n return this.router.remove(method, path);\n }\n\n /**\n * Remove all routes matching a path pattern (regardless of method)\n * @param path Route path pattern\n * @returns Number of routes removed\n */\n removeAllForPath(path: string): number {\n return this.router.removeAllForPath(path);\n }\n\n /**\n * Gets all registered routes for debugging and monitoring.\n * @returns Array of route objects with method and path\n */\n getRoutes(): Array<{ method: string; path: string }> {\n return this.router.getRoutes();\n }\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing browser-router ${this.id}`);\n }\n\n /**\n * @internal\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","/* 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 * @internal\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 /**\n * @internal\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 const response = await this._cancelFuture(this.futureId, path);\n if (response?.status !== 200) {\n log.error(\n `Failed to cancel Future ${this.id}. Response: ${JSON.stringify(\n response\n )}`\n );\n }\n }\n\n /**\n * Gets the current status of the future operation.\n *\n * @returns Status string: \"NOT_ACTIVE\", \"IN_PROGRESS\", \"Success\", or \"Fail\"\n *\n * @example Monitor Status\n * ```typescript\n * if (future.status === \"IN_PROGRESS\") {\n * console.log(`Operation running: ${future.progress}% complete`);\n * } else if (future.status === \"Success\") {\n * console.log(\"Operation completed successfully!\");\n * }\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 /**\n * Gets human-readable time remaining for the operation.\n *\n * @returns Formatted time string (e.g., \"5 minutes\", \"30 seconds\") or empty string if unknown\n *\n * @example Display Time Remaining\n * ```typescript\n * const timeLeft = future.timeRemaining;\n * if (timeLeft) {\n * console.log(`${timeLeft} remaining`);\n * }\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 * @internal\n * @category Subscription\n * Updates the Future model when a `kos.future/{ID}` event\n * is received from the server.\n *\n * @param future - 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","/**\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 * @group 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 * @group 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","/**\n * @fileoverview Key-Value service functions for persistent data storage and retrieval.\n *\n * This module provides service functions for managing key-value pairs in KOS device storage.\n * Supports namespaced storage, CRUD operations, and typed value handling for configuration\n * data, user preferences, and application state persistence.\n *\n * @module KeyValueServices\n */\n\nimport { KosLog, ServiceFactory, resolveServiceUrl } from \"../../../../core\";\n\n/** Base URL for key-value service endpoints */\nconst { URL } = resolveServiceUrl(\"KEY_VALUE_SERVICE\");\n\n/** Pre-configured service methods for key-value operations */\nconst { getOne, postModel, deleteModel } = ServiceFactory.build({\n basePath: `${URL}/api/keyVal`,\n});\n\n/** Logger instance for key-value service operations */\nconst log = KosLog.createLogger({\n name: \"key-value-service\",\n group: \"Services\",\n});\n\n/**\n * Response format for key-value data retrieval.\n *\n * Represents the structure of data returned from key-value service endpoints,\n * supporting primitive types commonly used for configuration and state data.\n *\n * @group KOS Model\n * @category Key-Value Store\n */\ninterface KeyValueResponse {\n /** Key-value pairs with primitive values */\n [key: string]: string | number | boolean;\n}\n\n/**\n * Update request format for key-value operations.\n *\n * Defines the structure for updating individual key-value pairs within\n * specific namespaces, supporting targeted updates without affecting\n * other stored data.\n *\n * @group KOS Model\n * @category Key-Value Store\n */\nexport interface KeyValueUpdate {\n /** Namespace identifier for data organization */\n namespace: string;\n /** Specific key within the namespace */\n key: string;\n /** Value to store (as string for API compatibility) */\n value: string;\n}\n\n/**\n * Removes a specific key-value pair from storage.\n *\n * Permanently deletes a key and its associated value from the specified namespace.\n * This operation cannot be undone, so use with caution for critical data.\n *\n * @param namespace - Namespace containing the key to delete\n * @param key - Specific key to remove from storage\n *\n * @throws {Error} When deletion request fails or service is unavailable\n *\n * @example Delete User Preference\n * ```typescript\n * await deleteKeyValue('user-preferences', 'theme-mode');\n * console.log('Theme preference cleared');\n * ```\n *\n * @group KOS Model\n * @category Key-Value Store\n */\nexport const deleteKeyValue = async (namespace: string, key: string) => {\n await deleteModel({\n urlOverride: `${URL}/api/keyVal/${namespace}/${key}`,\n id: key,\n });\n};\n/**\n * Creates or updates a key-value pair in persistent storage.\n *\n * Stores a value under the specified key within the given namespace. If the key\n * already exists, its value will be overwritten. Supports primitive types with\n * automatic string conversion for API compatibility.\n *\n * @param namespace - Namespace for organizing related key-value pairs\n * @param key - Unique identifier within the namespace\n * @param value - Value to store (primitive types supported)\n * @returns Promise resolving to the stored value\n *\n * @throws {Error} When update request fails or service returns non-200 status\n *\n * @example Store Configuration Setting\n * ```typescript\n * await updateKeyValue('device-config', 'maxRetries', 5);\n * await updateKeyValue('user-prefs', 'darkMode', true);\n * await updateKeyValue('app-state', 'lastLogin', '2024-01-15');\n * ```\n *\n * @group KOS Model\n * @category Key-Value Store\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 key-value data\", response);\n throw new Error(\n `Failed to update key-value data for namespace ${namespace}`\n );\n }\n return response.data;\n};\n/**\n * Retrieves all key-value pairs from a specified namespace.\n *\n * Fetches all stored data within the given namespace as a complete object.\n * Useful for loading configuration sets, user preferences, or application\n * state data in bulk operations.\n *\n * @param namespace - Namespace to retrieve data from (defaults to \"studio\")\n * @returns Promise resolving to object containing all key-value pairs in namespace\n *\n * @throws {Error} When retrieval fails or service returns non-200 status\n *\n * @example Load Application Configuration\n * ```typescript\n * const appConfig = await getKeyValue('app-config');\n * console.log('Max retries:', appConfig.maxRetries);\n * console.log('Debug mode:', appConfig.debugMode);\n *\n * const userPrefs = await getKeyValue('user-preferences');\n * const theme = userPrefs.themeMode || 'light';\n * ```\n *\n * @group KOS Model\n * @category Key-Value Store\n */\nexport const getKeyValue = async (namespace = \"studio\") => {\n log.debug(`Retrieving all key-value data for namespace: ${namespace}`);\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 key-value data\", response);\n throw new Error(\n `Failed to retrieve key-value data for namespace ${namespace}`\n );\n }\n return response.data;\n};\n\n/**\n * Removes an entire namespace and all its key-value pairs.\n *\n * Permanently deletes all data within the specified namespace. This is a\n * destructive operation that cannot be undone. Use with extreme caution\n * for critical data or production systems.\n *\n * @param namespace - Namespace to completely remove from storage\n *\n * @throws {Error} When deletion request fails or service is unavailable\n *\n * @example Clear All User Preferences\n * ```typescript\n * // Warning: This removes ALL user preferences permanently\n * await deleteKeyValueNamespace('user-preferences');\n * console.log('All user preferences cleared');\n *\n * // Better: Clear specific preferences individually\n * await deleteKeyValue('user-preferences', 'theme-mode');\n * await deleteKeyValue('user-preferences', 'language');\n * ```\n *\n * @group KOS Model\n * @category Key-Value Store\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\n/**\n * Key-Value Model - Persistent, reactive state storage with real-time synchronization across KOS applications.\n *\n * This model provides a namespaced key-value store that automatically persists data and synchronizes\n * changes across all connected clients in real-time. Perfect for storing user preferences, application\n * state, feature flags, or any data that needs to persist between sessions and sync across instances.\n *\n * ## Key Features\n * - **Persistent Storage** - Data survives application restarts and browser refreshes\n * - **Real-time Synchronization** - Changes propagate instantly to all connected clients\n * - **Namespace Isolation** - Multiple stores can coexist without key collisions\n * - **Type-Safe Values** - Supports string, number, boolean, and undefined types\n * - **Reactive Updates** - Automatic UI updates when values change (locally or remotely)\n * - **Topic-Based Sync** - Uses KOS event system for distributed state management\n *\n * ## Topic-Based Reactivity\n * The model listens to two KOS topics for real-time synchronization:\n * - **`/keyVal/set`** - Fired when any key-value pair is updated or added\n * - **`/keyVal/remove`** - Fired when a key is deleted from the store\n *\n * These topics ensure that all instances of the model with the same namespace stay\n * synchronized across browser tabs, windows, and even different client applications.\n * The model automatically filters events by namespace to ensure isolation.\n *\n * @interface\n *\n * @example Basic Usage\n * ```typescript\n * const preferences = KeyValue.instance('user-prefs')\n * .options({ namespace: 'preferences' })\n * .build();\n *\n * // Store values\n * await preferences.updateState('theme', 'dark');\n * await preferences.updateState('fontSize', 14);\n *\n * // Access reactive data\n * console.log(preferences.data.theme); // 'dark'\n * console.log(preferences.data.fontSize); // 14\n * ```\n *\n * @example React Integration\n * ```typescript\n * const UserSettings: React.FC = kosComponent(() => {\n * const settings = useModel(KeyValue, 'app-settings');\n *\n * return (\n * <div>\n * <p>Theme: {settings.data.theme || 'light'}</p>\n * <button onClick={() => settings.updateState('theme', 'dark')}>\n * Set Dark Theme\n * </button>\n * </div>\n * );\n * });\n * ```\n *\n * @group KOS Model\n * @category State Management\n * @category Key-Value Store\n * @useDeclaredType\n * @see {@link KeyValueOptions} - Configuration options for key-value stores\n * @see {@link KeyValueUpdate} - Update event structure for synchronization\n */\nexport type KeyValueModel = PublicModelInterface<KeyValueModelImpl>;\n\n/**\n * @ignore\n * @internal\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 /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing studio-state ${this.id}`);\n }\n\n /**\n * Update or delete a key-value pair in the store.\n *\n * Changes are automatically persisted and synchronized across all instances\n * with the same namespace via KOS topics.\n *\n * @param key - The key to update or delete\n * @param value - The value to set (string | number | boolean), or undefined to delete the key\n * @returns Promise that resolves when the operation completes\n *\n * @example\n * ```typescript\n * // Set a value\n * await keyValue.updateState('theme', 'dark');\n *\n * // Delete a key\n * await keyValue.updateState('theme', undefined);\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 /**\n * Load initial data from persistent storage.\n *\n * @internal\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 /**\n * Topic handler for `/keyVal/set` events to sync updates across instances.\n *\n * Automatically called when any KeyValue model instance updates a value,\n * ensuring all instances with the same namespace stay synchronized.\n *\n * @param update - The key-value update event containing namespace, key, and new value\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 /**\n * Topic handler for `/keyVal/remove` events to sync deletions across instances.\n *\n * Automatically called when any KeyValue model instance deletes a key,\n * ensuring all instances with the same namespace stay synchronized.\n *\n * @param update - The key-value update event containing namespace and deleted key\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","var INUMBER = 'INUMBER';\nvar IOP1 = 'IOP1';\nvar IOP2 = 'IOP2';\nvar IOP3 = 'IOP3';\nvar IVAR = 'IVAR';\nvar IVARNAME = 'IVARNAME';\nvar IFUNCALL = 'IFUNCALL';\nvar IFUNDEF = 'IFUNDEF';\nvar IEXPR = 'IEXPR';\nvar IEXPREVAL = 'IEXPREVAL';\nvar IMEMBER = 'IMEMBER';\nvar IENDSTATEMENT = 'IENDSTATEMENT';\nvar IARRAY = 'IARRAY';\n\nfunction Instruction(type, value) {\n this.type = type;\n this.value = (value !== undefined && value !== null) ? value : 0;\n}\n\nInstruction.prototype.toString = function () {\n switch (this.type) {\n case INUMBER:\n case IOP1:\n case IOP2:\n case IOP3:\n case IVAR:\n case IVARNAME:\n case IENDSTATEMENT:\n return this.value;\n case IFUNCALL:\n return 'CALL ' + this.value;\n case IFUNDEF:\n return 'DEF ' + this.value;\n case IARRAY:\n return 'ARRAY ' + this.value;\n case IMEMBER:\n return '.' + this.value;\n default:\n return 'Invalid Instruction';\n }\n};\n\nfunction unaryInstruction(value) {\n return new Instruction(IOP1, value);\n}\n\nfunction binaryInstruction(value) {\n return new Instruction(IOP2, value);\n}\n\nfunction ternaryInstruction(value) {\n return new Instruction(IOP3, value);\n}\n\nfunction simplify(tokens, unaryOps, binaryOps, ternaryOps, values) {\n var nstack = [];\n var newexpression = [];\n var n1, n2, n3;\n var f;\n for (var i = 0; i < tokens.length; i++) {\n var item = tokens[i];\n var type = item.type;\n if (type === INUMBER || type === IVARNAME) {\n if (Array.isArray(item.value)) {\n nstack.push.apply(nstack, simplify(item.value.map(function (x) {\n return new Instruction(INUMBER, x);\n }).concat(new Instruction(IARRAY, item.value.length)), unaryOps, binaryOps, ternaryOps, values));\n } else {\n nstack.push(item);\n }\n } else if (type === IVAR && values.hasOwnProperty(item.value)) {\n item = new Instruction(INUMBER, values[item.value]);\n nstack.push(item);\n } else if (type === IOP2 && nstack.length > 1) {\n n2 = nstack.pop();\n n1 = nstack.pop();\n f = binaryOps[item.value];\n item = new Instruction(INUMBER, f(n1.value, n2.value));\n nstack.push(item);\n } else if (type === IOP3 && nstack.length > 2) {\n n3 = nstack.pop();\n n2 = nstack.pop();\n n1 = nstack.pop();\n if (item.value === '?') {\n nstack.push(n1.value ? n2.value : n3.value);\n } else {\n f = ternaryOps[item.value];\n item = new Instruction(INUMBER, f(n1.value, n2.value, n3.value));\n nstack.push(item);\n }\n } else if (type === IOP1 && nstack.length > 0) {\n n1 = nstack.pop();\n f = unaryOps[item.value];\n item = new Instruction(INUMBER, f(n1.value));\n nstack.push(item);\n } else if (type === IEXPR) {\n while (nstack.length > 0) {\n newexpression.push(nstack.shift());\n }\n newexpression.push(new Instruction(IEXPR, simplify(item.value, unaryOps, binaryOps, ternaryOps, values)));\n } else if (type === IMEMBER && nstack.length > 0) {\n n1 = nstack.pop();\n nstack.push(new Instruction(INUMBER, n1.value[item.value]));\n } /* else if (type === IARRAY && nstack.length >= item.value) {\n var length = item.value;\n while (length-- > 0) {\n newexpression.push(nstack.pop());\n }\n newexpression.push(new Instruction(IARRAY, item.value));\n } */ else {\n while (nstack.length > 0) {\n newexpression.push(nstack.shift());\n }\n newexpression.push(item);\n }\n }\n while (nstack.length > 0) {\n newexpression.push(nstack.shift());\n }\n return newexpression;\n}\n\nfunction substitute(tokens, variable, expr) {\n var newexpression = [];\n for (var i = 0; i < tokens.length; i++) {\n var item = tokens[i];\n var type = item.type;\n if (type === IVAR && item.value === variable) {\n for (var j = 0; j < expr.tokens.length; j++) {\n var expritem = expr.tokens[j];\n var replitem;\n if (expritem.type === IOP1) {\n replitem = unaryInstruction(expritem.value);\n } else if (expritem.type === IOP2) {\n replitem = binaryInstruction(expritem.value);\n } else if (expritem.type === IOP3) {\n replitem = ternaryInstruction(expritem.value);\n } else {\n replitem = new Instruction(expritem.type, expritem.value);\n }\n newexpression.push(replitem);\n }\n } else if (type === IEXPR) {\n newexpression.push(new Instruction(IEXPR, substitute(item.value, variable, expr)));\n } else {\n newexpression.push(item);\n }\n }\n return newexpression;\n}\n\nfunction evaluate(tokens, expr, values) {\n var nstack = [];\n var n1, n2, n3;\n var f, args, argCount;\n\n if (isExpressionEvaluator(tokens)) {\n return resolveExpression(tokens, values);\n }\n\n var numTokens = tokens.length;\n\n for (var i = 0; i < numTokens; i++) {\n var item = tokens[i];\n var type = item.type;\n if (type === INUMBER || type === IVARNAME) {\n nstack.push(item.value);\n } else if (type === IOP2) {\n n2 = nstack.pop();\n n1 = nstack.pop();\n if (item.value === 'and') {\n nstack.push(n1 ? !!evaluate(n2, expr, values) : false);\n } else if (item.value === 'or') {\n nstack.push(n1 ? true : !!evaluate(n2, expr, values));\n } else if (item.value === '=') {\n f = expr.binaryOps[item.value];\n nstack.push(f(n1, evaluate(n2, expr, values), values));\n } else {\n f = expr.binaryOps[item.value];\n nstack.push(f(resolveExpression(n1, values), resolveExpression(n2, values)));\n }\n } else if (type === IOP3) {\n n3 = nstack.pop();\n n2 = nstack.pop();\n n1 = nstack.pop();\n if (item.value === '?') {\n nstack.push(evaluate(n1 ? n2 : n3, expr, values));\n } else {\n f = expr.ternaryOps[item.value];\n nstack.push(f(resolveExpression(n1, values), resolveExpression(n2, values), resolveExpression(n3, values)));\n }\n } else if (type === IVAR) {\n if (item.value in expr.functions) {\n nstack.push(expr.functions[item.value]);\n } else if (item.value in expr.unaryOps && expr.parser.isOperatorEnabled(item.value)) {\n nstack.push(expr.unaryOps[item.value]);\n } else {\n var v = values[item.value];\n if (v !== undefined) {\n nstack.push(v);\n } else {\n throw new Error('undefined variable: ' + item.value);\n }\n }\n } else if (type === IOP1) {\n n1 = nstack.pop();\n f = expr.unaryOps[item.value];\n nstack.push(f(resolveExpression(n1, values)));\n } else if (type === IFUNCALL) {\n argCount = item.value;\n args = [];\n while (argCount-- > 0) {\n args.unshift(resolveExpression(nstack.pop(), values));\n }\n f = nstack.pop();\n if (f.apply && f.call) {\n nstack.push(f.apply(undefined, args));\n } else {\n throw new Error(f + ' is not a function');\n }\n } else if (type === IFUNDEF) {\n // Create closure to keep references to arguments and expression\n nstack.push((function () {\n var n2 = nstack.pop();\n var args = [];\n var argCount = item.value;\n while (argCount-- > 0) {\n args.unshift(nstack.pop());\n }\n var n1 = nstack.pop();\n var f = function () {\n var scope = Object.assign({}, values);\n for (var i = 0, len = args.length; i < len; i++) {\n scope[args[i]] = arguments[i];\n }\n return evaluate(n2, expr, scope);\n };\n // f.name = n1\n Object.defineProperty(f, 'name', {\n value: n1,\n writable: false\n });\n values[n1] = f;\n return f;\n })());\n } else if (type === IEXPR) {\n nstack.push(createExpressionEvaluator(item, expr));\n } else if (type === IEXPREVAL) {\n nstack.push(item);\n } else if (type === IMEMBER) {\n n1 = nstack.pop();\n nstack.push(n1[item.value]);\n } else if (type === IENDSTATEMENT) {\n nstack.pop();\n } else if (type === IARRAY) {\n argCount = item.value;\n args = [];\n while (argCount-- > 0) {\n args.unshift(nstack.pop());\n }\n nstack.push(args);\n } else {\n throw new Error('invalid Expression');\n }\n }\n if (nstack.length > 1) {\n throw new Error('invalid Expression (parity)');\n }\n // Explicitly return zero to avoid test issues caused by -0\n return nstack[0] === 0 ? 0 : resolveExpression(nstack[0], values);\n}\n\nfunction createExpressionEvaluator(token, expr, values) {\n if (isExpressionEvaluator(token)) return token;\n return {\n type: IEXPREVAL,\n value: function (scope) {\n return evaluate(token.value, expr, scope);\n }\n };\n}\n\nfunction isExpressionEvaluator(n) {\n return n && n.type === IEXPREVAL;\n}\n\nfunction resolveExpression(n, values) {\n return isExpressionEvaluator(n) ? n.value(values) : n;\n}\n\nfunction expressionToString(tokens, toJS) {\n var nstack = [];\n var n1, n2, n3;\n var f, args, argCount;\n for (var i = 0; i < tokens.length; i++) {\n var item = tokens[i];\n var type = item.type;\n if (type === INUMBER) {\n if (typeof item.value === 'number' && item.value < 0) {\n nstack.push('(' + item.value + ')');\n } else if (Array.isArray(item.value)) {\n nstack.push('[' + item.value.map(escapeValue).join(', ') + ']');\n } else {\n nstack.push(escapeValue(item.value));\n }\n } else if (type === IOP2) {\n n2 = nstack.pop();\n n1 = nstack.pop();\n f = item.value;\n if (toJS) {\n if (f === '^') {\n nstack.push('Math.pow(' + n1 + ', ' + n2 + ')');\n } else if (f === 'and') {\n nstack.push('(!!' + n1 + ' && !!' + n2 + ')');\n } else if (f === 'or') {\n nstack.push('(!!' + n1 + ' || !!' + n2 + ')');\n } else if (f === '||') {\n nstack.push('(function(a,b){ return Array.isArray(a) && Array.isArray(b) ? a.concat(b) : String(a) + String(b); }((' + n1 + '),(' + n2 + ')))');\n } else if (f === '==') {\n nstack.push('(' + n1 + ' === ' + n2 + ')');\n } else if (f === '!=') {\n nstack.push('(' + n1 + ' !== ' + n2 + ')');\n } else if (f === '[') {\n nstack.push(n1 + '[(' + n2 + ') | 0]');\n } else {\n nstack.push('(' + n1 + ' ' + f + ' ' + n2 + ')');\n }\n } else {\n if (f === '[') {\n nstack.push(n1 + '[' + n2 + ']');\n } else {\n nstack.push('(' + n1 + ' ' + f + ' ' + n2 + ')');\n }\n }\n } else if (type === IOP3) {\n n3 = nstack.pop();\n n2 = nstack.pop();\n n1 = nstack.pop();\n f = item.value;\n if (f === '?') {\n nstack.push('(' + n1 + ' ? ' + n2 + ' : ' + n3 + ')');\n } else {\n throw new Error('invalid Expression');\n }\n } else if (type === IVAR || type === IVARNAME) {\n nstack.push(item.value);\n } else if (type === IOP1) {\n n1 = nstack.pop();\n f = item.value;\n if (f === '-' || f === '+') {\n nstack.push('(' + f + n1 + ')');\n } else if (toJS) {\n if (f === 'not') {\n nstack.push('(' + '!' + n1 + ')');\n } else if (f === '!') {\n nstack.push('fac(' + n1 + ')');\n } else {\n nstack.push(f + '(' + n1 + ')');\n }\n } else if (f === '!') {\n nstack.push('(' + n1 + '!)');\n } else {\n nstack.push('(' + f + ' ' + n1 + ')');\n }\n } else if (type === IFUNCALL) {\n argCount = item.value;\n args = [];\n while (argCount-- > 0) {\n args.unshift(nstack.pop());\n }\n f = nstack.pop();\n nstack.push(f + '(' + args.join(', ') + ')');\n } else if (type === IFUNDEF) {\n n2 = nstack.pop();\n argCount = item.value;\n args = [];\n while (argCount-- > 0) {\n args.unshift(nstack.pop());\n }\n n1 = nstack.pop();\n if (toJS) {\n nstack.push('(' + n1 + ' = function(' + args.join(', ') + ') { return ' + n2 + ' })');\n } else {\n nstack.push('(' + n1 + '(' + args.join(', ') + ') = ' + n2 + ')');\n }\n } else if (type === IMEMBER) {\n n1 = nstack.pop();\n nstack.push(n1 + '.' + item.value);\n } else if (type === IARRAY) {\n argCount = item.value;\n args = [];\n while (argCount-- > 0) {\n args.unshift(nstack.pop());\n }\n nstack.push('[' + args.join(', ') + ']');\n } else if (type === IEXPR) {\n nstack.push('(' + expressionToString(item.value, toJS) + ')');\n } else if (type === IENDSTATEMENT) ; else {\n throw new Error('invalid Expression');\n }\n }\n if (nstack.length > 1) {\n if (toJS) {\n nstack = [ nstack.join(',') ];\n } else {\n nstack = [ nstack.join(';') ];\n }\n }\n return String(nstack[0]);\n}\n\nfunction escapeValue(v) {\n if (typeof v === 'string') {\n return JSON.stringify(v).replace(/\\u2028/g, '\\\\u2028').replace(/\\u2029/g, '\\\\u2029');\n }\n return v;\n}\n\nfunction contains(array, obj) {\n for (var i = 0; i < array.length; i++) {\n if (array[i] === obj) {\n return true;\n }\n }\n return false;\n}\n\nfunction getSymbols(tokens, symbols, options) {\n options = options || {};\n var withMembers = !!options.withMembers;\n var prevVar = null;\n\n for (var i = 0; i < tokens.length; i++) {\n var item = tokens[i];\n if (item.type === IVAR || item.type === IVARNAME) {\n if (!withMembers && !contains(symbols, item.value)) {\n symbols.push(item.value);\n } else if (prevVar !== null) {\n if (!contains(symbols, prevVar)) {\n symbols.push(prevVar);\n }\n prevVar = item.value;\n } else {\n prevVar = item.value;\n }\n } else if (item.type === IMEMBER && withMembers && prevVar !== null) {\n prevVar += '.' + item.value;\n } else if (item.type === IEXPR) {\n getSymbols(item.value, symbols, options);\n } else if (prevVar !== null) {\n if (!contains(symbols, prevVar)) {\n symbols.push(prevVar);\n }\n prevVar = null;\n }\n }\n\n if (prevVar !== null && !contains(symbols, prevVar)) {\n symbols.push(prevVar);\n }\n}\n\nfunction Expression(tokens, parser) {\n this.tokens = tokens;\n this.parser = parser;\n this.unaryOps = parser.unaryOps;\n this.binaryOps = parser.binaryOps;\n this.ternaryOps = parser.ternaryOps;\n this.functions = parser.functions;\n}\n\nExpression.prototype.simplify = function (values) {\n values = values || {};\n return new Expression(simplify(this.tokens, this.unaryOps, this.binaryOps, this.ternaryOps, values), this.parser);\n};\n\nExpression.prototype.substitute = function (variable, expr) {\n if (!(expr instanceof Expression)) {\n expr = this.parser.parse(String(expr));\n }\n\n return new Expression(substitute(this.tokens, variable, expr), this.parser);\n};\n\nExpression.prototype.evaluate = function (values) {\n values = values || {};\n return evaluate(this.tokens, this, values);\n};\n\nExpression.prototype.toString = function () {\n return expressionToString(this.tokens, false);\n};\n\nExpression.prototype.symbols = function (options) {\n options = options || {};\n var vars = [];\n getSymbols(this.tokens, vars, options);\n return vars;\n};\n\nExpression.prototype.variables = function (options) {\n options = options || {};\n var vars = [];\n getSymbols(this.tokens, vars, options);\n var functions = this.functions;\n return vars.filter(function (name) {\n return !(name in functions);\n });\n};\n\nExpression.prototype.toJSFunction = function (param, variables) {\n var expr = this;\n var f = new Function(param, 'with(this.functions) with (this.ternaryOps) with (this.binaryOps) with (this.unaryOps) { return ' + expressionToString(this.simplify(variables).tokens, true) + '; }'); // eslint-disable-line no-new-func\n return function () {\n return f.apply(expr, arguments);\n };\n};\n\nvar TEOF = 'TEOF';\nvar TOP = 'TOP';\nvar TNUMBER = 'TNUMBER';\nvar TSTRING = 'TSTRING';\nvar TPAREN = 'TPAREN';\nvar TBRACKET = 'TBRACKET';\nvar TCOMMA = 'TCOMMA';\nvar TNAME = 'TNAME';\nvar TSEMICOLON = 'TSEMICOLON';\n\nfunction Token(type, value, index) {\n this.type = type;\n this.value = value;\n this.index = index;\n}\n\nToken.prototype.toString = function () {\n return this.type + ': ' + this.value;\n};\n\nfunction TokenStream(parser, expression) {\n this.pos = 0;\n this.current = null;\n this.unaryOps = parser.unaryOps;\n this.binaryOps = parser.binaryOps;\n this.ternaryOps = parser.ternaryOps;\n this.consts = parser.consts;\n this.expression = expression;\n this.savedPosition = 0;\n this.savedCurrent = null;\n this.options = parser.options;\n this.parser = parser;\n}\n\nTokenStream.prototype.newToken = function (type, value, pos) {\n return new Token(type, value, pos != null ? pos : this.pos);\n};\n\nTokenStream.prototype.save = function () {\n this.savedPosition = this.pos;\n this.savedCurrent = this.current;\n};\n\nTokenStream.prototype.restore = function () {\n this.pos = this.savedPosition;\n this.current = this.savedCurrent;\n};\n\nTokenStream.prototype.next = function () {\n if (this.pos >= this.expression.length) {\n return this.newToken(TEOF, 'EOF');\n }\n\n if (this.isWhitespace() || this.isComment()) {\n return this.next();\n } else if (this.isRadixInteger() ||\n this.isNumber() ||\n this.isOperator() ||\n this.isString() ||\n this.isParen() ||\n this.isBracket() ||\n this.isComma() ||\n this.isSemicolon() ||\n this.isNamedOp() ||\n this.isConst() ||\n this.isName()) {\n return this.current;\n } else {\n this.parseError('Unknown character \"' + this.expression.charAt(this.pos) + '\"');\n }\n};\n\nTokenStream.prototype.isString = function () {\n var r = false;\n var startPos = this.pos;\n var quote = this.expression.charAt(startPos);\n\n if (quote === '\\'' || quote === '\"') {\n var index = this.expression.indexOf(quote, startPos + 1);\n while (index >= 0 && this.pos < this.expression.length) {\n this.pos = index + 1;\n if (this.expression.charAt(index - 1) !== '\\\\') {\n var rawString = this.expression.substring(startPos + 1, index);\n this.current = this.newToken(TSTRING, this.unescape(rawString), startPos);\n r = true;\n break;\n }\n index = this.expression.indexOf(quote, index + 1);\n }\n }\n return r;\n};\n\nTokenStream.prototype.isParen = function () {\n var c = this.expression.charAt(this.pos);\n if (c === '(' || c === ')') {\n this.current = this.newToken(TPAREN, c);\n this.pos++;\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isBracket = function () {\n var c = this.expression.charAt(this.pos);\n if ((c === '[' || c === ']') && this.isOperatorEnabled('[')) {\n this.current = this.newToken(TBRACKET, c);\n this.pos++;\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isComma = function () {\n var c = this.expression.charAt(this.pos);\n if (c === ',') {\n this.current = this.newToken(TCOMMA, ',');\n this.pos++;\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isSemicolon = function () {\n var c = this.expression.charAt(this.pos);\n if (c === ';') {\n this.current = this.newToken(TSEMICOLON, ';');\n this.pos++;\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isConst = function () {\n var startPos = this.pos;\n var i = startPos;\n for (; i < this.expression.length; i++) {\n var c = this.expression.charAt(i);\n if (c.toUpperCase() === c.toLowerCase()) {\n if (i === this.pos || (c !== '_' && c !== '.' && (c < '0' || c > '9'))) {\n break;\n }\n }\n }\n if (i > startPos) {\n var str = this.expression.substring(startPos, i);\n if (str in this.consts) {\n this.current = this.newToken(TNUMBER, this.consts[str]);\n this.pos += str.length;\n return true;\n }\n }\n return false;\n};\n\nTokenStream.prototype.isNamedOp = function () {\n var startPos = this.pos;\n var i = startPos;\n for (; i < this.expression.length; i++) {\n var c = this.expression.charAt(i);\n if (c.toUpperCase() === c.toLowerCase()) {\n if (i === this.pos || (c !== '_' && (c < '0' || c > '9'))) {\n break;\n }\n }\n }\n if (i > startPos) {\n var str = this.expression.substring(startPos, i);\n if (this.isOperatorEnabled(str) && (str in this.binaryOps || str in this.unaryOps || str in this.ternaryOps)) {\n this.current = this.newToken(TOP, str);\n this.pos += str.length;\n return true;\n }\n }\n return false;\n};\n\nTokenStream.prototype.isName = function () {\n var startPos = this.pos;\n var i = startPos;\n var hasLetter = false;\n for (; i < this.expression.length; i++) {\n var c = this.expression.charAt(i);\n if (c.toUpperCase() === c.toLowerCase()) {\n if (i === this.pos && (c === '$' || c === '_')) {\n if (c === '_') {\n hasLetter = true;\n }\n continue;\n } else if (i === this.pos || !hasLetter || (c !== '_' && (c < '0' || c > '9'))) {\n break;\n }\n } else {\n hasLetter = true;\n }\n }\n if (hasLetter) {\n var str = this.expression.substring(startPos, i);\n this.current = this.newToken(TNAME, str);\n this.pos += str.length;\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isWhitespace = function () {\n var r = false;\n var c = this.expression.charAt(this.pos);\n while (c === ' ' || c === '\\t' || c === '\\n' || c === '\\r') {\n r = true;\n this.pos++;\n if (this.pos >= this.expression.length) {\n break;\n }\n c = this.expression.charAt(this.pos);\n }\n return r;\n};\n\nvar codePointPattern = /^[0-9a-f]{4}$/i;\n\nTokenStream.prototype.unescape = function (v) {\n var index = v.indexOf('\\\\');\n if (index < 0) {\n return v;\n }\n\n var buffer = v.substring(0, index);\n while (index >= 0) {\n var c = v.charAt(++index);\n switch (c) {\n case '\\'':\n buffer += '\\'';\n break;\n case '\"':\n buffer += '\"';\n break;\n case '\\\\':\n buffer += '\\\\';\n break;\n case '/':\n buffer += '/';\n break;\n case 'b':\n buffer += '\\b';\n break;\n case 'f':\n buffer += '\\f';\n break;\n case 'n':\n buffer += '\\n';\n break;\n case 'r':\n buffer += '\\r';\n break;\n case 't':\n buffer += '\\t';\n break;\n case 'u':\n // interpret the following 4 characters as the hex of the unicode code point\n var codePoint = v.substring(index + 1, index + 5);\n if (!codePointPattern.test(codePoint)) {\n this.parseError('Illegal escape sequence: \\\\u' + codePoint);\n }\n buffer += String.fromCharCode(parseInt(codePoint, 16));\n index += 4;\n break;\n default:\n throw this.parseError('Illegal escape sequence: \"\\\\' + c + '\"');\n }\n ++index;\n var backslash = v.indexOf('\\\\', index);\n buffer += v.substring(index, backslash < 0 ? v.length : backslash);\n index = backslash;\n }\n\n return buffer;\n};\n\nTokenStream.prototype.isComment = function () {\n var c = this.expression.charAt(this.pos);\n if (c === '/' && this.expression.charAt(this.pos + 1) === '*') {\n this.pos = this.expression.indexOf('*/', this.pos) + 2;\n if (this.pos === 1) {\n this.pos = this.expression.length;\n }\n return true;\n }\n return false;\n};\n\nTokenStream.prototype.isRadixInteger = function () {\n var pos = this.pos;\n\n if (pos >= this.expression.length - 2 || this.expression.charAt(pos) !== '0') {\n return false;\n }\n ++pos;\n\n var radix;\n var validDigit;\n if (this.expression.charAt(pos) === 'x') {\n radix = 16;\n validDigit = /^[0-9a-f]$/i;\n ++pos;\n } else if (this.expression.charAt(pos) === 'b') {\n radix = 2;\n validDigit = /^[01]$/i;\n ++pos;\n } else {\n return false;\n }\n\n var valid = false;\n var startPos = pos;\n\n while (pos < this.expression.length) {\n var c = this.expression.charAt(pos);\n if (validDigit.test(c)) {\n pos++;\n valid = true;\n } else {\n break;\n }\n }\n\n if (valid) {\n this.current = this.newToken(TNUMBER, parseInt(this.expression.substring(startPos, pos), radix));\n this.pos = pos;\n }\n return valid;\n};\n\nTokenStream.prototype.isNumber = function () {\n var valid = false;\n var pos = this.pos;\n var startPos = pos;\n var resetPos = pos;\n var foundDot = false;\n var foundDigits = false;\n var c;\n\n while (pos < this.expression.length) {\n c = this.expression.charAt(pos);\n if ((c >= '0' && c <= '9') || (!foundDot && c === '.')) {\n if (c === '.') {\n foundDot = true;\n } else {\n foundDigits = true;\n }\n pos++;\n valid = foundDigits;\n } else {\n break;\n }\n }\n\n if (valid) {\n resetPos = pos;\n }\n\n if (c === 'e' || c === 'E') {\n pos++;\n var acceptSign = true;\n var validExponent = false;\n while (pos < this.expression.length) {\n c = this.expression.charAt(pos);\n if (acceptSign && (c === '+' || c === '-')) {\n acceptSign = false;\n } else if (c >= '0' && c <= '9') {\n validExponent = true;\n acceptSign = false;\n } else {\n break;\n }\n pos++;\n }\n\n if (!validExponent) {\n pos = resetPos;\n }\n }\n\n if (valid) {\n this.current = this.newToken(TNUMBER, parseFloat(this.expression.substring(startPos, pos)));\n this.pos = pos;\n } else {\n this.pos = resetPos;\n }\n return valid;\n};\n\nTokenStream.prototype.isOperator = function () {\n var startPos = this.pos;\n var c = this.expression.charAt(this.pos);\n\n if (c === '+' || c === '-' || c === '*' || c === '/' || c === '%' || c === '^' || c === '?' || c === ':' || c === '.') {\n this.current = this.newToken(TOP, c);\n } else if (c === '∙' || c === '•') {\n this.current = this.newToken(TOP, '*');\n } else if (c === '>') {\n if (this.expression.charAt(this.pos + 1) === '=') {\n this.current = this.newToken(TOP, '>=');\n this.pos++;\n } else {\n this.current = this.newToken(TOP, '>');\n }\n } else if (c === '<') {\n if (this.expression.charAt(this.pos + 1) === '=') {\n this.current = this.newToken(TOP, '<=');\n this.pos++;\n } else {\n this.current = this.newToken(TOP, '<');\n }\n } else if (c === '|') {\n if (this.expression.charAt(this.pos + 1) === '|') {\n this.current = this.newToken(TOP, '||');\n this.pos++;\n } else {\n return false;\n }\n } else if (c === '=') {\n if (this.expression.charAt(this.pos + 1) === '=') {\n this.current = this.newToken(TOP, '==');\n this.pos++;\n } else {\n this.current = this.newToken(TOP, c);\n }\n } else if (c === '!') {\n if (this.expression.charAt(this.pos + 1) === '=') {\n this.current = this.newToken(TOP, '!=');\n this.pos++;\n } else {\n this.current = this.newToken(TOP, c);\n }\n } else {\n return false;\n }\n this.pos++;\n\n if (this.isOperatorEnabled(this.current.value)) {\n return true;\n } else {\n this.pos = startPos;\n return false;\n }\n};\n\nTokenStream.prototype.isOperatorEnabled = function (op) {\n return this.parser.isOperatorEnabled(op);\n};\n\nTokenStream.prototype.getCoordinates = function () {\n var line = 0;\n var column;\n var newline = -1;\n do {\n line++;\n column = this.pos - newline;\n newline = this.expression.indexOf('\\n', newline + 1);\n } while (newline >= 0 && newline < this.pos);\n\n return {\n line: line,\n column: column\n };\n};\n\nTokenStream.prototype.parseError = function (msg) {\n var coords = this.getCoordinates();\n throw new Error('parse error [' + coords.line + ':' + coords.column + ']: ' + msg);\n};\n\nfunction ParserState(parser, tokenStream, options) {\n this.parser = parser;\n this.tokens = tokenStream;\n this.current = null;\n this.nextToken = null;\n this.next();\n this.savedCurrent = null;\n this.savedNextToken = null;\n this.allowMemberAccess = options.allowMemberAccess !== false;\n}\n\nParserState.prototype.next = function () {\n this.current = this.nextToken;\n return (this.nextToken = this.tokens.next());\n};\n\nParserState.prototype.tokenMatches = function (token, value) {\n if (typeof value === 'undefined') {\n return true;\n } else if (Array.isArray(value)) {\n return contains(value, token.value);\n } else if (typeof value === 'function') {\n return value(token);\n } else {\n return token.value === value;\n }\n};\n\nParserState.prototype.save = function () {\n this.savedCurrent = this.current;\n this.savedNextToken = this.nextToken;\n this.tokens.save();\n};\n\nParserState.prototype.restore = function () {\n this.tokens.restore();\n this.current = this.savedCurrent;\n this.nextToken = this.savedNextToken;\n};\n\nParserState.prototype.accept = function (type, value) {\n if (this.nextToken.type === type && this.tokenMatches(this.nextToken, value)) {\n this.next();\n return true;\n }\n return false;\n};\n\nParserState.prototype.expect = function (type, value) {\n if (!this.accept(type, value)) {\n var coords = this.tokens.getCoordinates();\n throw new Error('parse error [' + coords.line + ':' + coords.column + ']: Expected ' + (value || type));\n }\n};\n\nParserState.prototype.parseAtom = function (instr) {\n var unaryOps = this.tokens.unaryOps;\n function isPrefixOperator(token) {\n return token.value in unaryOps;\n }\n\n if (this.accept(TNAME) || this.accept(TOP, isPrefixOperator)) {\n instr.push(new Instruction(IVAR, this.current.value));\n } else if (this.accept(TNUMBER)) {\n instr.push(new Instruction(INUMBER, this.current.value));\n } else if (this.accept(TSTRING)) {\n instr.push(new Instruction(INUMBER, this.current.value));\n } else if (this.accept(TPAREN, '(')) {\n this.parseExpression(instr);\n this.expect(TPAREN, ')');\n } else if (this.accept(TBRACKET, '[')) {\n if (this.accept(TBRACKET, ']')) {\n instr.push(new Instruction(IARRAY, 0));\n } else {\n var argCount = this.parseArrayList(instr);\n instr.push(new Instruction(IARRAY, argCount));\n }\n } else {\n throw new Error('unexpected ' + this.nextToken);\n }\n};\n\nParserState.prototype.parseExpression = function (instr) {\n var exprInstr = [];\n if (this.parseUntilEndStatement(instr, exprInstr)) {\n return;\n }\n this.parseVariableAssignmentExpression(exprInstr);\n if (this.parseUntilEndStatement(instr, exprInstr)) {\n return;\n }\n this.pushExpression(instr, exprInstr);\n};\n\nParserState.prototype.pushExpression = function (instr, exprInstr) {\n for (var i = 0, len = exprInstr.length; i < len; i++) {\n instr.push(exprInstr[i]);\n }\n};\n\nParserState.prototype.parseUntilEndStatement = function (instr, exprInstr) {\n if (!this.accept(TSEMICOLON)) return false;\n if (this.nextToken && this.nextToken.type !== TEOF && !(this.nextToken.type === TPAREN && this.nextToken.value === ')')) {\n exprInstr.push(new Instruction(IENDSTATEMENT));\n }\n if (this.nextToken.type !== TEOF) {\n this.parseExpression(exprInstr);\n }\n instr.push(new Instruction(IEXPR, exprInstr));\n return true;\n};\n\nParserState.prototype.parseArrayList = function (instr) {\n var argCount = 0;\n\n while (!this.accept(TBRACKET, ']')) {\n this.parseExpression(instr);\n ++argCount;\n while (this.accept(TCOMMA)) {\n this.parseExpression(instr);\n ++argCount;\n }\n }\n\n return argCount;\n};\n\nParserState.prototype.parseVariableAssignmentExpression = function (instr) {\n this.parseConditionalExpression(instr);\n while (this.accept(TOP, '=')) {\n var varName = instr.pop();\n var varValue = [];\n var lastInstrIndex = instr.length - 1;\n if (varName.type === IFUNCALL) {\n if (!this.tokens.isOperatorEnabled('()=')) {\n throw new Error('function definition is not permitted');\n }\n for (var i = 0, len = varName.value + 1; i < len; i++) {\n var index = lastInstrIndex - i;\n if (instr[index].type === IVAR) {\n instr[index] = new Instruction(IVARNAME, instr[index].value);\n }\n }\n this.parseVariableAssignmentExpression(varValue);\n instr.push(new Instruction(IEXPR, varValue));\n instr.push(new Instruction(IFUNDEF, varName.value));\n continue;\n }\n if (varName.type !== IVAR && varName.type !== IMEMBER) {\n throw new Error('expected variable for assignment');\n }\n this.parseVariableAssignmentExpression(varValue);\n instr.push(new Instruction(IVARNAME, varName.value));\n instr.push(new Instruction(IEXPR, varValue));\n instr.push(binaryInstruction('='));\n }\n};\n\nParserState.prototype.parseConditionalExpression = function (instr) {\n this.parseOrExpression(instr);\n while (this.accept(TOP, '?')) {\n var trueBranch = [];\n var falseBranch = [];\n this.parseConditionalExpression(trueBranch);\n this.expect(TOP, ':');\n this.parseConditionalExpression(falseBranch);\n instr.push(new Instruction(IEXPR, trueBranch));\n instr.push(new Instruction(IEXPR, falseBranch));\n instr.push(ternaryInstruction('?'));\n }\n};\n\nParserState.prototype.parseOrExpression = function (instr) {\n this.parseAndExpression(instr);\n while (this.accept(TOP, 'or')) {\n var falseBranch = [];\n this.parseAndExpression(falseBranch);\n instr.push(new Instruction(IEXPR, falseBranch));\n instr.push(binaryInstruction('or'));\n }\n};\n\nParserState.prototype.parseAndExpression = function (instr) {\n this.parseComparison(instr);\n while (this.accept(TOP, 'and')) {\n var trueBranch = [];\n this.parseComparison(trueBranch);\n instr.push(new Instruction(IEXPR, trueBranch));\n instr.push(binaryInstruction('and'));\n }\n};\n\nvar COMPARISON_OPERATORS = ['==', '!=', '<', '<=', '>=', '>', 'in'];\n\nParserState.prototype.parseComparison = function (instr) {\n this.parseAddSub(instr);\n while (this.accept(TOP, COMPARISON_OPERATORS)) {\n var op = this.current;\n this.parseAddSub(instr);\n instr.push(binaryInstruction(op.value));\n }\n};\n\nvar ADD_SUB_OPERATORS = ['+', '-', '||'];\n\nParserState.prototype.parseAddSub = function (instr) {\n this.parseTerm(instr);\n while (this.accept(TOP, ADD_SUB_OPERATORS)) {\n var op = this.current;\n this.parseTerm(instr);\n instr.push(binaryInstruction(op.value));\n }\n};\n\nvar TERM_OPERATORS = ['*', '/', '%'];\n\nParserState.prototype.parseTerm = function (instr) {\n this.parseFactor(instr);\n while (this.accept(TOP, TERM_OPERATORS)) {\n var op = this.current;\n this.parseFactor(instr);\n instr.push(binaryInstruction(op.value));\n }\n};\n\nParserState.prototype.parseFactor = function (instr) {\n var unaryOps = this.tokens.unaryOps;\n function isPrefixOperator(token) {\n return token.value in unaryOps;\n }\n\n this.save();\n if (this.accept(TOP, isPrefixOperator)) {\n if (this.current.value !== '-' && this.current.value !== '+') {\n if (this.nextToken.type === TPAREN && this.nextToken.value === '(') {\n this.restore();\n this.parseExponential(instr);\n return;\n } else if (this.nextToken.type === TSEMICOLON || this.nextToken.type === TCOMMA || this.nextToken.type === TEOF || (this.nextToken.type === TPAREN && this.nextToken.value === ')')) {\n this.restore();\n this.parseAtom(instr);\n return;\n }\n }\n\n var op = this.current;\n this.parseFactor(instr);\n instr.push(unaryInstruction(op.value));\n } else {\n this.parseExponential(instr);\n }\n};\n\nParserState.prototype.parseExponential = function (instr) {\n this.parsePostfixExpression(instr);\n while (this.accept(TOP, '^')) {\n this.parseFactor(instr);\n instr.push(binaryInstruction('^'));\n }\n};\n\nParserState.prototype.parsePostfixExpression = function (instr) {\n this.parseFunctionCall(instr);\n while (this.accept(TOP, '!')) {\n instr.push(unaryInstruction('!'));\n }\n};\n\nParserState.prototype.parseFunctionCall = function (instr) {\n var unaryOps = this.tokens.unaryOps;\n function isPrefixOperator(token) {\n return token.value in unaryOps;\n }\n\n if (this.accept(TOP, isPrefixOperator)) {\n var op = this.current;\n this.parseAtom(instr);\n instr.push(unaryInstruction(op.value));\n } else {\n this.parseMemberExpression(instr);\n while (this.accept(TPAREN, '(')) {\n if (this.accept(TPAREN, ')')) {\n instr.push(new Instruction(IFUNCALL, 0));\n } else {\n var argCount = this.parseArgumentList(instr);\n instr.push(new Instruction(IFUNCALL, argCount));\n }\n }\n }\n};\n\nParserState.prototype.parseArgumentList = function (instr) {\n var argCount = 0;\n\n while (!this.accept(TPAREN, ')')) {\n this.parseExpression(instr);\n ++argCount;\n while (this.accept(TCOMMA)) {\n this.parseExpression(instr);\n ++argCount;\n }\n }\n\n return argCount;\n};\n\nParserState.prototype.parseMemberExpression = function (instr) {\n this.parseAtom(instr);\n while (this.accept(TOP, '.') || this.accept(TBRACKET, '[')) {\n var op = this.current;\n\n if (op.value === '.') {\n if (!this.allowMemberAccess) {\n throw new Error('unexpected \".\", member access is not permitted');\n }\n\n this.expect(TNAME);\n instr.push(new Instruction(IMEMBER, this.current.value));\n } else if (op.value === '[') {\n if (!this.tokens.isOperatorEnabled('[')) {\n throw new Error('unexpected \"[]\", arrays are disabled');\n }\n\n this.parseExpression(instr);\n this.expect(TBRACKET, ']');\n instr.push(binaryInstruction('['));\n } else {\n throw new Error('unexpected symbol: ' + op.value);\n }\n }\n};\n\nfunction add(a, b) {\n return Number(a) + Number(b);\n}\n\nfunction sub(a, b) {\n return a - b;\n}\n\nfunction mul(a, b) {\n return a * b;\n}\n\nfunction div(a, b) {\n return a / b;\n}\n\nfunction mod(a, b) {\n return a % b;\n}\n\nfunction concat(a, b) {\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.concat(b);\n }\n return '' + a + b;\n}\n\nfunction equal(a, b) {\n return a === b;\n}\n\nfunction notEqual(a, b) {\n return a !== b;\n}\n\nfunction greaterThan(a, b) {\n return a > b;\n}\n\nfunction lessThan(a, b) {\n return a < b;\n}\n\nfunction greaterThanEqual(a, b) {\n return a >= b;\n}\n\nfunction lessThanEqual(a, b) {\n return a <= b;\n}\n\nfunction andOperator(a, b) {\n return Boolean(a && b);\n}\n\nfunction orOperator(a, b) {\n return Boolean(a || b);\n}\n\nfunction inOperator(a, b) {\n return contains(b, a);\n}\n\nfunction sinh(a) {\n return ((Math.exp(a) - Math.exp(-a)) / 2);\n}\n\nfunction cosh(a) {\n return ((Math.exp(a) + Math.exp(-a)) / 2);\n}\n\nfunction tanh(a) {\n if (a === Infinity) return 1;\n if (a === -Infinity) return -1;\n return (Math.exp(a) - Math.exp(-a)) / (Math.exp(a) + Math.exp(-a));\n}\n\nfunction asinh(a) {\n if (a === -Infinity) return a;\n return Math.log(a + Math.sqrt((a * a) + 1));\n}\n\nfunction acosh(a) {\n return Math.log(a + Math.sqrt((a * a) - 1));\n}\n\nfunction atanh(a) {\n return (Math.log((1 + a) / (1 - a)) / 2);\n}\n\nfunction log10(a) {\n return Math.log(a) * Math.LOG10E;\n}\n\nfunction neg(a) {\n return -a;\n}\n\nfunction not(a) {\n return !a;\n}\n\nfunction trunc(a) {\n return a < 0 ? Math.ceil(a) : Math.floor(a);\n}\n\nfunction random(a) {\n return Math.random() * (a || 1);\n}\n\nfunction factorial(a) { // a!\n return gamma(a + 1);\n}\n\nfunction isInteger(value) {\n return isFinite(value) && (value === Math.round(value));\n}\n\nvar GAMMA_G = 4.7421875;\nvar GAMMA_P = [\n 0.99999999999999709182,\n 57.156235665862923517, -59.597960355475491248,\n 14.136097974741747174, -0.49191381609762019978,\n 0.33994649984811888699e-4,\n 0.46523628927048575665e-4, -0.98374475304879564677e-4,\n 0.15808870322491248884e-3, -0.21026444172410488319e-3,\n 0.21743961811521264320e-3, -0.16431810653676389022e-3,\n 0.84418223983852743293e-4, -0.26190838401581408670e-4,\n 0.36899182659531622704e-5\n];\n\n// Gamma function from math.js\nfunction gamma(n) {\n var t, x;\n\n if (isInteger(n)) {\n if (n <= 0) {\n return isFinite(n) ? Infinity : NaN;\n }\n\n if (n > 171) {\n return Infinity; // Will overflow\n }\n\n var value = n - 2;\n var res = n - 1;\n while (value > 1) {\n res *= value;\n value--;\n }\n\n if (res === 0) {\n res = 1; // 0! is per definition 1\n }\n\n return res;\n }\n\n if (n < 0.5) {\n return Math.PI / (Math.sin(Math.PI * n) * gamma(1 - n));\n }\n\n if (n >= 171.35) {\n return Infinity; // will overflow\n }\n\n if (n > 85.0) { // Extended Stirling Approx\n var twoN = n * n;\n var threeN = twoN * n;\n var fourN = threeN * n;\n var fiveN = fourN * n;\n return Math.sqrt(2 * Math.PI / n) * Math.pow((n / Math.E), n) *\n (1 + (1 / (12 * n)) + (1 / (288 * twoN)) - (139 / (51840 * threeN)) -\n (571 / (2488320 * fourN)) + (163879 / (209018880 * fiveN)) +\n (5246819 / (75246796800 * fiveN * n)));\n }\n\n --n;\n x = GAMMA_P[0];\n for (var i = 1; i < GAMMA_P.length; ++i) {\n x += GAMMA_P[i] / (n + i);\n }\n\n t = n + GAMMA_G + 0.5;\n return Math.sqrt(2 * Math.PI) * Math.pow(t, n + 0.5) * Math.exp(-t) * x;\n}\n\nfunction stringOrArrayLength(s) {\n if (Array.isArray(s)) {\n return s.length;\n }\n return String(s).length;\n}\n\nfunction hypot() {\n var sum = 0;\n var larg = 0;\n for (var i = 0; i < arguments.length; i++) {\n var arg = Math.abs(arguments[i]);\n var div;\n if (larg < arg) {\n div = larg / arg;\n sum = (sum * div * div) + 1;\n larg = arg;\n } else if (arg > 0) {\n div = arg / larg;\n sum += div * div;\n } else {\n sum += arg;\n }\n }\n return larg === Infinity ? Infinity : larg * Math.sqrt(sum);\n}\n\nfunction condition(cond, yep, nope) {\n return cond ? yep : nope;\n}\n\n/**\n* Decimal adjustment of a number.\n* From @escopecz.\n*\n* @param {Number} value The number.\n* @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).\n* @return {Number} The adjusted value.\n*/\nfunction roundTo(value, exp) {\n // If the exp is undefined or zero...\n if (typeof exp === 'undefined' || +exp === 0) {\n return Math.round(value);\n }\n value = +value;\n exp = -(+exp);\n // If the value is not a number or the exp is not an integer...\n if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {\n return NaN;\n }\n // Shift\n value = value.toString().split('e');\n value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));\n // Shift back\n value = value.toString().split('e');\n return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));\n}\n\nfunction setVar(name, value, variables) {\n if (variables) variables[name] = value;\n return value;\n}\n\nfunction arrayIndex(array, index) {\n return array[index | 0];\n}\n\nfunction max(array) {\n if (arguments.length === 1 && Array.isArray(array)) {\n return Math.max.apply(Math, array);\n } else {\n return Math.max.apply(Math, arguments);\n }\n}\n\nfunction min(array) {\n if (arguments.length === 1 && Array.isArray(array)) {\n return Math.min.apply(Math, array);\n } else {\n return Math.min.apply(Math, arguments);\n }\n}\n\nfunction arrayMap(f, a) {\n if (typeof f !== 'function') {\n throw new Error('First argument to map is not a function');\n }\n if (!Array.isArray(a)) {\n throw new Error('Second argument to map is not an array');\n }\n return a.map(function (x, i) {\n return f(x, i);\n });\n}\n\nfunction arrayFold(f, init, a) {\n if (typeof f !== 'function') {\n throw new Error('First argument to fold is not a function');\n }\n if (!Array.isArray(a)) {\n throw new Error('Second argument to fold is not an array');\n }\n return a.reduce(function (acc, x, i) {\n return f(acc, x, i);\n }, init);\n}\n\nfunction arrayFilter(f, a) {\n if (typeof f !== 'function') {\n throw new Error('First argument to filter is not a function');\n }\n if (!Array.isArray(a)) {\n throw new Error('Second argument to filter is not an array');\n }\n return a.filter(function (x, i) {\n return f(x, i);\n });\n}\n\nfunction stringOrArrayIndexOf(target, s) {\n if (!(Array.isArray(s) || typeof s === 'string')) {\n throw new Error('Second argument to indexOf is not a string or array');\n }\n\n return s.indexOf(target);\n}\n\nfunction arrayJoin(sep, a) {\n if (!Array.isArray(a)) {\n throw new Error('Second argument to join is not an array');\n }\n\n return a.join(sep);\n}\n\nfunction sign(x) {\n return ((x > 0) - (x < 0)) || +x;\n}\n\nvar ONE_THIRD = 1/3;\nfunction cbrt(x) {\n return x < 0 ? -Math.pow(-x, ONE_THIRD) : Math.pow(x, ONE_THIRD);\n}\n\nfunction expm1(x) {\n return Math.exp(x) - 1;\n}\n\nfunction log1p(x) {\n return Math.log(1 + x);\n}\n\nfunction log2(x) {\n return Math.log(x) / Math.LN2;\n}\n\nfunction Parser(options) {\n this.options = options || {};\n this.unaryOps = {\n sin: Math.sin,\n cos: Math.cos,\n tan: Math.tan,\n asin: Math.asin,\n acos: Math.acos,\n atan: Math.atan,\n sinh: Math.sinh || sinh,\n cosh: Math.cosh || cosh,\n tanh: Math.tanh || tanh,\n asinh: Math.asinh || asinh,\n acosh: Math.acosh || acosh,\n atanh: Math.atanh || atanh,\n sqrt: Math.sqrt,\n cbrt: Math.cbrt || cbrt,\n log: Math.log,\n log2: Math.log2 || log2,\n ln: Math.log,\n lg: Math.log10 || log10,\n log10: Math.log10 || log10,\n expm1: Math.expm1 || expm1,\n log1p: Math.log1p || log1p,\n abs: Math.abs,\n ceil: Math.ceil,\n floor: Math.floor,\n round: Math.round,\n trunc: Math.trunc || trunc,\n '-': neg,\n '+': Number,\n exp: Math.exp,\n not: not,\n length: stringOrArrayLength,\n '!': factorial,\n sign: Math.sign || sign\n };\n\n this.binaryOps = {\n '+': add,\n '-': sub,\n '*': mul,\n '/': div,\n '%': mod,\n '^': Math.pow,\n '||': concat,\n '==': equal,\n '!=': notEqual,\n '>': greaterThan,\n '<': lessThan,\n '>=': greaterThanEqual,\n '<=': lessThanEqual,\n and: andOperator,\n or: orOperator,\n 'in': inOperator,\n '=': setVar,\n '[': arrayIndex\n };\n\n this.ternaryOps = {\n '?': condition\n };\n\n this.functions = {\n random: random,\n fac: factorial,\n min: min,\n max: max,\n hypot: Math.hypot || hypot,\n pyt: Math.hypot || hypot, // backward compat\n pow: Math.pow,\n atan2: Math.atan2,\n 'if': condition,\n gamma: gamma,\n roundTo: roundTo,\n map: arrayMap,\n fold: arrayFold,\n filter: arrayFilter,\n indexOf: stringOrArrayIndexOf,\n join: arrayJoin\n };\n\n this.consts = {\n E: Math.E,\n PI: Math.PI,\n 'true': true,\n 'false': false\n };\n}\n\nParser.prototype.parse = function (expr) {\n var instr = [];\n var parserState = new ParserState(\n this,\n new TokenStream(this, expr),\n { allowMemberAccess: this.options.allowMemberAccess }\n );\n\n parserState.parseExpression(instr);\n parserState.expect(TEOF, 'EOF');\n\n return new Expression(instr, this);\n};\n\nParser.prototype.evaluate = function (expr, variables) {\n return this.parse(expr).evaluate(variables);\n};\n\nvar sharedParser = new Parser();\n\nParser.parse = function (expr) {\n return sharedParser.parse(expr);\n};\n\nParser.evaluate = function (expr, variables) {\n return sharedParser.parse(expr).evaluate(variables);\n};\n\nvar optionNameMap = {\n '+': 'add',\n '-': 'subtract',\n '*': 'multiply',\n '/': 'divide',\n '%': 'remainder',\n '^': 'power',\n '!': 'factorial',\n '<': 'comparison',\n '>': 'comparison',\n '<=': 'comparison',\n '>=': 'comparison',\n '==': 'comparison',\n '!=': 'comparison',\n '||': 'concatenate',\n 'and': 'logical',\n 'or': 'logical',\n 'not': 'logical',\n '?': 'conditional',\n ':': 'conditional',\n '=': 'assignment',\n '[': 'array',\n '()=': 'fndef'\n};\n\nfunction getOptionName(op) {\n return optionNameMap.hasOwnProperty(op) ? optionNameMap[op] : op;\n}\n\nParser.prototype.isOperatorEnabled = function (op) {\n var optionName = getOptionName(op);\n var operators = this.options.operators || {};\n\n return !(optionName in operators) || !!operators[optionName];\n};\n\n/*!\n Based on ndef.parser, by Raphael Graf(r@undefined.ch)\n http://www.undefined.ch/mparser/index.html\n\n Ported to JavaScript and modified by Matthew Crumley (email@matthewcrumley.com, http://silentmatt.com/)\n\n You are free to use and modify this code in anyway you find useful. Please leave this comment in the code\n to acknowledge its original source. If you feel like it, I enjoy hearing about projects that use my code,\n but don't feel like you have to let me know or ask permission.\n*/\n\n// Backwards compatibility\nvar index = {\n Parser: Parser,\n Expression: Expression\n};\n\nexport default index;\nexport { Expression, Parser };\n","import {\n kosAction,\n ObservableData,\n uuid,\n type KosData,\n type KosModelRegistrationType,\n} from \"../../../core\";\nimport { 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\";\n\nimport { Parser } from \"expr-eval\";\nimport type { KosExpressionEvaluatorOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"kos-expression-evaluator-model\";\n\n/**\n * Result of evaluating an expression, containing either a successful value or error details.\n *\n * @example\n * ```typescript\n * const result = evaluator.getExpressionValue('myExpression');\n * if (result?.error) {\n * console.error(`Expression error: ${result.error}`);\n * } else {\n * console.log(`Result: ${result?.value}`);\n * }\n * ```\n */\nexport interface ExpressionResult {\n /** The computed value of the expression, or undefined if evaluation failed */\n value: unknown;\n /** Error message if expression evaluation failed, undefined if successful */\n error?: string;\n}\n\n/**\n * A named expression that can be dynamically evaluated against context data.\n * Expressions automatically re-evaluate when their dependencies change.\n */\n/**\n * A reactive expression that automatically re-evaluates when its dependencies change.\n * This class is made reactive by the parent model's makeAutoObservable.\n */\nclass ReactiveExpression implements NamedExpression {\n name: string;\n expression: string;\n private expr: unknown;\n private getContextData: (() => Record<string, unknown>) | null = null;\n // Cache the last result to allow comparison without re-evaluation\n private _lastResult: ExpressionResult = { value: undefined };\n\n constructor(\n name: string,\n expression: string,\n expr: unknown,\n getContextData: () => Record<string, unknown>\n ) {\n this.name = name;\n this.expression = expression;\n this.expr = expr;\n this.getContextData = getContextData;\n // Initialize with undefined result - will be set by initial evaluation\n this._lastResult = { value: undefined, error: undefined };\n }\n\n /**\n * Pure getter that returns the cached result without side effects.\n */\n get result(): ExpressionResult {\n return this._lastResult;\n }\n\n /**\n * Update the cached result. Called by the parent model after evaluation.\n */\n updateResult(result: ExpressionResult): void {\n this._lastResult = result;\n }\n\n /**\n * Evaluate the expression with the given context data.\n * This method allows the parent model to trigger evaluation without side effects in getters.\n */\n evaluate(contextData: Record<string, unknown>): ExpressionResult {\n try {\n const value = (this.expr as any).evaluate(contextData as never);\n return { value, error: undefined };\n } catch (error) {\n return {\n value: undefined,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n}\n\nexport interface NamedExpression {\n /** Unique name identifier for this expression */\n name: string;\n /** The expression string (JavaScript-like syntax) */\n expression: string;\n /** Getter that returns the cached result */\n get result(): ExpressionResult;\n /** Method to evaluate the expression with given context data */\n evaluate(contextData: Record<string, unknown>): ExpressionResult;\n /** Method to update the cached result */\n updateResult(result: ExpressionResult): void;\n}\n\n/**\n * KOS Expression Evaluator Model - Reactive expression evaluation with dynamic context and type-safe named expressions.\n *\n * This model provides a reactive expression evaluation system that automatically re-evaluates\n * expressions when their context data changes. Perfect for business rules, computed values,\n * and conditional logic that needs to stay synchronized with changing data.\n *\n * ## Key Features\n * - **Automatic reactivity** - Expressions re-evaluate when dependencies change thanks to KOS reactive patterns\n * - **Type safety** - Generic type parameter provides compile-time checking for expression names\n * - **Efficient updates** - Only affected expressions recalculate when their data dependencies change\n * - **Synchronous access** - Results available immediately via getters\n * - **Error handling** - Expressions with runtime errors are handled gracefully\n * - **KOS model integration** - Add any KOS model to context for fully reactive expressions\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const evaluator = KosExpressionEvaluatorModel.instance('my-evaluator').build();\n *\n * evaluator.setContextData({ temperature: 72, humidity: 45 });\n * evaluator.addExpression('isComfortable', 'temperature >= 68 && temperature <= 78');\n *\n * console.log(evaluator.results.isComfortable?.value); // true\n * ```\n *\n * @group KOS Model\n * @category Expression Processing\n * @useDeclaredType\n */\nexport type KosExpressionEvaluatorModel<T extends string = string> =\n PublicModelInterface<KosExpressionEvaluatorModelImpl<T>>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\nexport class KosExpressionEvaluatorModelImpl<T extends string = string>\n implements IKosDataModel, IKosIdentifiable\n{\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<\n KosExpressionEvaluatorModel,\n KosExpressionEvaluatorOptions\n >;\n id: string;\n private logger: KosContextLogger;\n\n private parser: Parser;\n private _data: KosData<Record<string, unknown>>;\n private _expressions = new Map<string, NamedExpression>();\n // Use ObservableData for results to handle dynamic properties properly\n private _results: KosData<Record<string, ExpressionResult>>;\n private _contextRevision = 0;\n\n constructor(\n modelId: string,\n options: KosExpressionEvaluatorOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._data = ObservableData();\n this._results = ObservableData(); // Initialize with ObservableData for dynamic properties\n this.parser = new Parser();\n\n // Add custom functions to the parser for common visibility patterns\n\n // exists(value) - Check if value is not undefined or null\n this.parser.functions.exists = (value: unknown) =>\n value !== undefined && value !== null;\n\n // isEmpty(value) - Check if value is empty (null, undefined, \"\", [], or {})\n this.parser.functions.isEmpty = (value: unknown) => {\n if (value === undefined || value === null) return true;\n if (typeof value === \"string\") return value.length === 0;\n if (Array.isArray(value)) return value.length === 0;\n if (typeof value === \"object\") return Object.keys(value).length === 0;\n return false;\n };\n\n // Caller-supplied functions (may not shadow the built-ins above)\n for (const [name, fn] of Object.entries(options?.customFunctions ?? {})) {\n if (name in this.parser.functions) {\n this.logger.warn(\n `customFunctions.${name} ignored: a built-in with that name exists`\n );\n continue;\n }\n this.parser.functions[name] = fn;\n }\n }\n\n /**\n * Get the current context data that expressions are evaluated against.\n *\n * @returns The current context data as a record of key-value pairs\n */\n get data(): Record<string, unknown> {\n return this._data;\n }\n\n get contextRevision(): number {\n return this._contextRevision;\n }\n\n /**\n * Replace the entire context data with new values. All expressions will\n * automatically re-evaluate against the new context.\n *\n * @param newData - Complete new context data to replace existing data\n *\n * @example\n * ```typescript\n * evaluator.setContextData({ temperature: 75, humidity: 40 });\n * ```\n */\n setContextData(newData: Record<string, unknown>): void {\n this._data.setValues(newData);\n // Increment revision to trigger effect\n kosAction(() => {\n this._contextRevision++;\n this.logger.debug(\n \"Context revision incremented to:\",\n this._contextRevision\n );\n });\n }\n\n /**\n * Update a single value in the context data. All expressions using this\n * value will automatically re-evaluate.\n *\n * @param key - The context data key to update\n * @param value - The new value to set\n *\n * @example\n * ```typescript\n * evaluator.updateContextValue('temperature', 85);\n * ```\n */\n updateContextValue(key: string, value: unknown): void {\n this._data[key] = value;\n }\n\n /**\n * Update a nested property in the context data using dot notation.\n * This method safely updates nested properties without replacing the entire object structure.\n *\n * @param path - Dot-separated path to the nested property (e.g., 'sensors.humidity', 'config.thresholds.temp')\n * @param value - The new value to set at the nested path\n *\n * @example\n * ```typescript\n * evaluator.updateNestedValue('sensors.humidity', 60);\n * ```\n */\n updateNestedValue(path: string, value: unknown): void {\n const pathSegments = path.split(\".\");\n const lastSegment = pathSegments.pop();\n\n if (!lastSegment) {\n this.logger.error(`Invalid path \"${path}\" - cannot be empty`);\n return;\n }\n\n // Navigate to the parent object\n let current: Record<string, unknown> = this._data;\n for (const segment of pathSegments) {\n if (current[segment] === undefined || current[segment] === null) {\n // Create nested object if it doesn't exist\n current[segment] = {};\n }\n current = current[segment] as Record<string, unknown>;\n }\n\n // Set the final value\n current[lastSegment] = value;\n\n this.logger.debug(`Updated nested context value \"${path}\" to:`, value);\n }\n\n /**\n * Add a KOS model to the evaluation context. The model's observable properties\n * will be accessible via dotted notation and expressions will automatically\n * re-evaluate when the model's data changes.\n *\n * @param key - The context key to store the model under\n * @param model - Any KOS model instance (must be observable)\n *\n * @example\n * ```typescript\n * const sensorModel = SensorModel.instance('main-sensor').build();\n * evaluator.addModelToContext('sensor', sensorModel);\n * evaluator.addExpression('isCritical', 'sensor.temperature > 80');\n * ```\n */\n addModelToContext(key: string, model: unknown): void {\n this._data[key] = model;\n }\n\n /**\n * Add a named expression that will be automatically evaluated against context data.\n * The expression will re-evaluate whenever its dependencies in the context change.\n *\n * @param name - Unique identifier for this expression (type-safe when using generic)\n * @param expressionString - JavaScript-like expression string\n * @throws {Error} If the expression has invalid syntax\n *\n * @example\n * ```typescript\n * evaluator.addExpression('isHot', 'temperature > 80');\n * ```\n */\n addExpression(name: T, expressionString: string): void {\n try {\n const expr = this.parser.parse(expressionString);\n\n // Create reactive expression instance - evaluation is now handled by the main model\n const reactiveExpression = new ReactiveExpression(\n name,\n expressionString,\n expr,\n () => this.data\n );\n\n this._expressions.set(name, reactiveExpression);\n\n // Perform initial evaluation and cache the result\n this.evaluateExpression(name);\n\n this.logger.debug(`Added expression \"${name}\": ${expressionString}`);\n } catch (error) {\n this.logger.error(`Failed to parse expression \"${name}\"`, error);\n throw error;\n }\n }\n\n removeExpression(name: T): boolean {\n const removed = this._expressions.delete(name);\n if (removed) {\n delete this._results[name as string];\n this.logger.debug(`Removed expression \"${name}\"`);\n } else {\n this.logger.warn(\n `Attempted to remove non-existent expression \"${name}\". Available expressions: [${this.expressionNames.join(\n \", \"\n )}]`\n );\n }\n return removed;\n }\n\n getExpression(name: T): NamedExpression | undefined {\n const expression = this._expressions.get(name);\n if (!expression) {\n this.logger.warn(\n `Expression \"${name}\" not found. Available expressions: [${this.expressionNames.join(\n \", \"\n )}]`\n );\n }\n return expression;\n }\n\n getExpressionValue(name: T): ExpressionResult | undefined {\n const expression = this._expressions.get(name);\n if (!expression) {\n this.logger.warn(\n `Expression \"${name}\" not found. Available expressions: [${this.expressionNames.join(\n \", \"\n )}]`\n );\n return undefined;\n }\n return expression.result;\n }\n\n /**\n * Get the cached result of an expression without triggering re-evaluation.\n * This is useful for dependency tracking in effects where you want to avoid\n * creating reactive chains through the expression evaluation.\n *\n * @param name - The expression name to get the cached result for\n * @returns The last cached result, or undefined if expression doesn't exist\n *\n * @example\n * ```typescript\n * const cached = evaluator.getCachedExpressionValue('myExpression');\n * ```\n */\n getCachedExpressionValue(name: T): ExpressionResult | undefined {\n const expression = this._expressions.get(name) as\n | ReactiveExpression\n | undefined;\n if (!expression) {\n return undefined;\n }\n return expression.result;\n }\n\n get expressions(): NamedExpression[] {\n return Array.from(this._expressions.values());\n }\n\n get expressionNames(): T[] {\n return Array.from(this._expressions.keys()) as T[];\n }\n\n // Reactive getter that evaluates expressions when accessed\n get results(): Record<T, ExpressionResult> {\n // Force evaluation of all expressions to ensure they're current\n // This creates MobX dependencies on the actual context data being used\n this.evaluateAllExpressions();\n\n return this._results as Record<T, ExpressionResult>;\n }\n\n /**\n * Force re-evaluation of all expressions and update cached results.\n * This is called by the effect when context data changes.\n */\n private evaluateAllExpressions(): void {\n const keys = Array.from(this._expressions.keys());\n keys.forEach((key) => {\n const expression = this._expressions.get(key);\n if (expression) {\n // Call evaluate method instead of getter to avoid side effects in getter\n this.evaluateExpression(key as T);\n }\n });\n }\n\n /**\n * Evaluate a specific expression and update the cached result if it changed.\n */\n private evaluateExpression(name: T): void {\n this.logger.debug(`Evaluating expression: ${String(name)}`);\n const expression = this._expressions.get(name);\n if (!expression) {\n this.logger.warn(`Expression \"${String(name)}\" not found`);\n return;\n }\n\n // Use the expression's evaluate method to get the new result\n const newResult = expression.evaluate(this.data);\n this.logger.debug(`Expression \"${String(name)}\" evaluated to:`, newResult);\n\n // Only update if the result actually changed - direct comparison is much more efficient\n const currentResult = expression.result;\n if (\n newResult.value !== currentResult.value ||\n newResult.error !== currentResult.error\n ) {\n this.logger.debug(\n `Expression \"${String(name)}\" result changed from`,\n currentResult,\n \"to\",\n newResult\n );\n expression.updateResult(newResult);\n this.updateResult(name as string, newResult);\n }\n }\n\n /**\n * Internal method to update the results object when expression values change.\n * This is called by ReactiveExpression when its value changes.\n * ObservableData handles dynamic properties automatically with MobX atoms.\n */\n private updateResult(name: string, result: ExpressionResult): void {\n this.logger.debug(\n `ExpressionEvaluator.updateResult called for \"${name}\":`,\n result\n );\n // ObservableData handles dynamic properties perfectly!\n // Wrap in kosAction to prevent MobX strict mode violations\n kosAction(() => {\n this._results[name] = result;\n });\n }\n\n /**\n * Create an anonymous reactive expression and return its generated ID.\n * The expression becomes fully reactive and can be accessed via the returned ID.\n *\n * @param expressionString - JavaScript-like expression string\n * @returns Generated UUID that can be used to access the expression via `getExpressionValue(id)` or `results[id]`\n *\n * @example\n * ```typescript\n * const tempCheckId = evaluator.createExpression('temperature > 75');\n * const result = evaluator.getExpressionValue(tempCheckId);\n * ```\n */\n createExpression(expressionString: string): string {\n // Generate a UUID for the anonymous expression\n const anonymousId = uuid();\n\n // Add it as a named expression (making it fully reactive)\n // Cast to T since uuid() generates a string that will be used as expression name\n this.addExpression(anonymousId as T, expressionString);\n\n return anonymousId;\n }\n}\n","import { KosExpressionEvaluatorModelImpl } from \"./kos-expression-evaluator-model\";\n\nexport type {\n KosExpressionEvaluatorModel,\n KosExpressionEvaluatorModelImpl,\n ExpressionResult,\n NamedExpression,\n} from \"./kos-expression-evaluator-model\";\nexport type * from \"./types\";\n\nexport const KosExpressionEvaluator =\n KosExpressionEvaluatorModelImpl.Registration;\n","import { type ServiceResponse } from \"../../../../core\";\nimport { KosLog } from \"../../../../core/core/log\";\nimport API, { type ApiPath, type ApiResponse } from \"../../../utils/service\";\n\nconst log = KosLog.createLogger({\n name: \"kos-log-manager-service\",\n group: \"Services\",\n});\n\nconst SERVICE_PATH: ApiPath = \"/api/kos/logs/overrides\";\n\nexport type KosLogManagerResponse = ApiResponse<typeof SERVICE_PATH, \"get\">;\n\n/**\n * @category Service\n * Retrieves the initial kos-log-manager data.\n */\nexport const getLogOverrides = async (): Promise<\n ServiceResponse<KosLogManagerResponse>\n> => {\n log.debug(\"sending GET for kos-log-manager\");\n return await API.get(SERVICE_PATH);\n};\n","import type { LogLevelDesc } from \"loglevel\";\nimport {\n KosDataContainer,\n KosLog,\n type IKosDataContainer,\n type KosRequest,\n type KosResponse,\n} from \"../../../core\";\nimport {\n get,\n kosModel,\n kosTopicHandler,\n type ApiCallbackWithWildcard,\n} 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 { getLogOverrides } from \"./services\";\n\nimport type {\n KosLogManagerOptions,\n LogLevelDescriptor,\n LogLevelNames,\n LogOverride,\n} from \"./types\";\n\n/**\n * Model type identifier for the KOS Log Manager\n */\nexport const MODEL_TYPE = \"kos-log-manager-model\";\n\n/**\n * KOS Log Manager Model - Centralized runtime log level management for the entire KOS system.\n *\n * This singleton model provides comprehensive control over logging behavior across the KOS UI SDK\n * and connected applications. It manages dynamic log level overrides, responds to real-time\n * configuration changes, and provides both REST API and WebSocket interfaces for log management.\n * Essential for debugging, performance monitoring, and production troubleshooting.\n *\n * ## Key Features\n * - **Runtime Log Level Control** - Dynamically adjust log levels without application restart\n * - **Hierarchical Logger Management** - Apply overrides to parent loggers and all children\n * - **Real-time Configuration** - WebSocket-based updates propagate instantly across clients\n * - **REST API Integration** - Query and manage logger configurations via HTTP endpoints\n * - **Override Persistence** - Log overrides are maintained across sessions and page refreshes\n * - **Multi-Node Support** - Coordinate logging across different KOS device nodes\n *\n * ## Topic-Based Reactivity\n * The model listens to these KOS topics for real-time log management:\n * - **`/kos/logs/override/add/*`** - Fired when new log level overrides are created\n * - **`/kos/logs/override/remove/*`** - Fired when log level overrides are removed\n *\n * Both topics support wildcard capture for node type targeting, enabling precise\n * control over which device nodes receive logging configuration changes.\n *\n * ## Architecture Integration\n * The log manager integrates with the broader KOS logging ecosystem:\n * - **KosLog System** - Manages underlying logger instances and level settings\n * - **LogStreamModel** - Streams managed by this model's log level policies\n * - **LogBlockModel** - Individual log entries governed by level settings\n * - **REST Endpoints** - Provides `/api/kos/ui/loggers` for external access\n *\n * ## Common Use Cases\n * - **Development Debugging** - Increase log verbosity for specific components during development\n * - **Production Troubleshooting** - Temporarily enable debug logging to diagnose issues\n * - **Performance Monitoring** - Adjust log levels to reduce overhead in production\n * - **System Administration** - Centrally manage logging across distributed KOS deployments\n * - **Dynamic Configuration** - Change logging behavior without service interruption\n * - **Selective Logging** - Enable detailed logging for specific modules while keeping others quiet\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const logManager = KosLogManager.instance('log-control').build();\n *\n * // Get all current logger configurations via REST API\n * const loggers = await logManager.getAllLoggers();\n * console.log(`Managing ${loggers.length} loggers`);\n * ```\n *\n * @group KOS Model\n * @category Device Logging\n * @useDeclaredType\n *\n * @see {@link LogStreamModel} - Streams whose content is governed by log levels managed here\n * @see {@link LogBlockModel} - Individual log entries affected by level settings\n * @see {@link KosLogManagerOptions} - Configuration options for the log manager\n * @see {@link LogOverride} - Log level override structure for runtime control\n * @see {@link LogLevelDescriptor} - Logger information structure returned by REST API\n */\nexport type KosLogManagerModel = PublicModelInterface<KosLogManagerModelImpl>;\n\nconst TOPIC_OVERRIDE_ADD = \"/kos/logs/override/add/*\";\nconst TOPIC_OVERRIDE_REMOVE = \"/kos/logs/override/remove/*\";\n\nconst getLogLevelName = (level: LogLevelDesc): LogLevelNames => {\n if (typeof level === \"string\") {\n return level as LogLevelNames;\n }\n if (typeof level === \"number\") {\n switch (level) {\n case 0:\n return \"trace\";\n case 1:\n return \"debug\";\n case 2:\n return \"info\";\n case 3:\n return \"warn\";\n case 4:\n return \"error\";\n default:\n return \"info\"; // Default to info if level is not recognized\n }\n }\n return \"info\"; // Default to info if level is not recognized\n};\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class KosLogManagerModelImpl implements IKosDataModel, IKosIdentifiable {\n id: string;\n private logger: KosContextLogger;\n\n private _overrides: IKosDataContainer<LogOverride>;\n constructor(\n modelId: string,\n options: KosLogManagerOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._overrides = new KosDataContainer();\n if (options) {\n // Assign options properties here.\n }\n }\n\n updateModel(_options: KosLogManagerOptions): void {\n // Update model properties here.\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * Resolves all registered loggers and their current log levels.\n * @returns A map of logger names to their log level descriptors\n * @private\n */\n private resolveLoggers(): Record<string, LogLevelDescriptor> {\n const loggers = KosLog.getLoggers();\n const result = Object.entries(loggers).map<LogLevelDescriptor>(\n ([name, logger]) => {\n return {\n name,\n level: getLogLevelName(logger.getLevel()) as LogLevelNames,\n };\n }\n );\n const resultMap = result.reduce<Record<string, LogLevelDescriptor>>(\n (acc, { name, level }) => {\n acc[name] = { name, level };\n return acc;\n },\n {} as Record<string, LogLevelDescriptor>\n );\n this.logger.debug(\"Resolved loggers\", resultMap);\n\n return resultMap;\n }\n /**\n * REST API endpoint to retrieve all logger configurations.\n * @get /api/kos/ui/loggers\n * @param _req - The incoming request (unused)\n * @param res - The response object to send logger data\n * @returns Array of log level descriptors for all loggers\n */\n @get(\"/api/kos/ui/loggers\")\n async getAllLoggers(\n _req?: KosRequest,\n res?: KosResponse\n ): Promise<LogLevelDescriptor[]> {\n const loggers = Object.values(this.resolveLoggers());\n\n res?.send(loggers);\n return loggers;\n }\n\n /**\n * Applies a log level override to matching loggers.\n * Sets the specified log level for the logger and all child loggers\n * whose names start with the override name.\n * @param override - The log override configuration to apply\n * @private\n */\n private setLogLevels(override: LogOverride): void {\n const loggers = Object.values(this.resolveLoggers()).filter((logger) =>\n logger.name.startsWith(override.name)\n );\n\n // Set the level of the child logger to the override level\n loggers.forEach((logger) => {\n const _logger = KosLog.getLoggers()[logger.name];\n if (!_logger) {\n this.logger.debug(`Logger ${logger.name} not found`);\n return;\n }\n _logger.setLevel(override.level);\n });\n // Set the level of the logger\n const _logger = KosLog.getLoggers()[override.name];\n if (!_logger) {\n this.logger.debug(`Logger ${override.name} not found`);\n return;\n }\n _logger.setLevel(override.level);\n globalThis.kos.logOverrides = this._overrides.data;\n }\n\n /**\n * Resets log levels to their defaults for matching loggers.\n * Removes the override for the logger and all child loggers\n * whose names start with the override name.\n * @param override - The log override configuration to reset\n * @private\n */\n private resetLogLevels(override: LogOverride): void {\n const loggers = Object.values(this.resolveLoggers()).filter((logger) =>\n logger.name.startsWith(override.name)\n );\n\n // Set the level of the child logger to the override level\n loggers.forEach((logger) => {\n const _logger = KosLog.getLoggers()[logger.name];\n if (!_logger) {\n this.logger.debug(`Logger ${logger.name} not found`);\n }\n _logger?.resetLevel();\n });\n // Set the level of the logger\n const _logger = KosLog.getLoggers()[override.name];\n if (!_logger) {\n this.logger.debug(`Logger ${override.name} not found`);\n }\n _logger?.resetLevel();\n globalThis.kos.logOverrides = this._overrides.data;\n }\n\n /**\n * WebSocket handler for log override addition events.\n * Listens to: /kos/logs/override/add/*\n * @param override - The log override to add\n * @param payload - Contains wildcard capture data including nodeType\n */\n @kosTopicHandler({\n topic: TOPIC_OVERRIDE_ADD,\n websocket: true,\n wildcardName: \"nodeType\",\n })\n handleOverrideAdded(\n override: LogOverride,\n payload: ApiCallbackWithWildcard<any>\n ) {\n this.logger.debug(\n `Override received for node type ${\n payload.wildcardCapture?.nodeType ?? \"unknown\"\n }`\n );\n this._overrides.addModel({ ...override, id: override.name });\n this.setLogLevels(override);\n }\n\n /**\n * WebSocket handler for log override removal events.\n * Listens to: /kos/logs/override/remove/*\n * @param override - The log override to remove\n */\n @kosTopicHandler({\n topic: TOPIC_OVERRIDE_REMOVE,\n websocket: true,\n wildcardName: \"nodeType\",\n })\n handleOverrideRemoved(override: LogOverride) {\n this._overrides.removeModel(override.name);\n this.resetLogLevels(override);\n }\n\n /**\n * Initializes the log manager model.\n * Called during model creation lifecycle.\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing kos-log-manager ${this.id}`);\n }\n\n /**\n * Loads existing log overrides from the server.\n * Fetches UI-specific overrides and applies them to the current loggers.\n * Called after model initialization.\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading kos-log-manager ${this.id}`);\n\n const [error, overrides] = await getLogOverrides();\n if (error) {\n this.logger.error(\"Failed to load log overrides\", error);\n return;\n }\n const uiOverrides =\n overrides\n ?.filter((override) => override.type?.toUpperCase() === \"UI\")\n .map<LogOverride>((override) => {\n return {\n name: override.name ?? \"\",\n type: override.type ?? \"\",\n level: (override.level ?? \"info\") as LogLevelNames,\n id: override.name || \"\",\n };\n }) ?? [];\n this._overrides.addAll(uiOverrides);\n uiOverrides.forEach((override) => {\n this.setLogLevels(override);\n });\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { KosLogManagerOptions } from \"./types\";\nimport {\n KosLogManagerModelImpl,\n MODEL_TYPE,\n KosLogManagerModel,\n} from \"./kos-log-manager-model\";\n\n/**\n * # KosLogManager\n *\n * The registration bean includes convenience methods for creating and working with KosLogManagerModel instances.\n\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: KosLogManager.type, id: \"kosLogManagerId\"})\n * private kosLogManagerModel: KosLogManagerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new KosLogManagerModel 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 = KosLogManager.factory({\n * // Add option data\n * });\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 KosLogManagerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (KosLogManager.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to KosLogManagerModel\n * // and the compiler will know that the model has the KosLogManagerModel interface\n * model.updateAvailability(false);\n\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 { KosLogManager } 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(KosLogManager);\n * ```\n *\n * ## registration.singleton\n \n * The kosLogManager 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 KosLogManager = new SingletonKosModelRegistrationFactory<\n KosLogManagerModel,\n KosLogManagerOptions\n>({\n class: KosLogManagerModelImpl,\n type: MODEL_TYPE,\n});\n","import {\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\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\n/**\n * KOS Time Model - System time management with real-time synchronization and timezone control.\n *\n * This singleton model provides centralized control over system time, date, and timezone settings\n * with automatic event propagation when changes occur. Essential for applications that need to\n * synchronize time-based operations, schedule events, or maintain consistent timestamps across\n * the system.\n *\n * ## Key Features\n * - **System Time Control** - Update system hours, minutes, and seconds programmatically\n * - **Date Management** - Set system date including month, day, and year\n * - **Timezone Handling** - Change and track timezone with automatic updates\n * - **Real-time Events** - Automatic notifications when time, date, or timezone changes\n * - **EventBus Integration** - Publishes changes to internal EventBus for UI updates\n * - **WebSocket Sync** - Changes propagate across all connected clients\n *\n * ## Topic-Based Reactivity\n * The model listens to three KOS topics for time synchronization:\n * - **`/kos/time/time`** - Fired when system time changes (hour/minute/second)\n * - **`/kos/time/day`** - Fired when the date changes (day rollover or manual change)\n * - **`/kos/time/timezone`** - Fired when timezone is updated\n *\n * Additionally, the model publishes to internal EventBus topics:\n * - `TIME_CHANGE` - For UI components to react to time updates\n * - `DAY_CHANGE` - For date-dependent UI updates\n * - `TIMEZONE_CHANGE` - For timezone-aware components\n *\n * ## Common Use Cases\n * - **System Clock Management** - Synchronize device time with server time\n * - **Scheduled Operations** - Trigger events based on time changes\n * - **Multi-timezone Support** - Handle devices in different time zones\n * - **Time-based UI Updates** - Keep clocks and calendars synchronized\n * - **Audit Logging** - Ensure consistent timestamps across the system\n * - **Day Rollover Handling** - Reset daily counters or refresh data\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const timeModel = KosTime.instance().build();\n *\n * // Update system time and date\n * await timeModel.updateSystemTime({ hour: 15, min: 45, sec: 30 });\n * await timeModel.updateSystemDate({ month: 3, day: 15, year: 2024 });\n * await timeModel.updateSystemTimezone('America/New_York');\n * ```\n *\n * @group KOS Model\n * @category System Integration\n * @useDeclaredType\n *\n * @see {@link TimeBean} - Time value structure (hour, minute, second)\n * @see {@link DateBean} - Date value structure (month, day, year)\n * @see {@link KosTimeOptions} - Configuration options for time model\n */\nexport type KosTimeModel = PublicModelInterface<KosTimeModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\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 /**\n * @internal\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\n if (!tz) {\n this.logger.warn(\n `Failed to retrieve timezone from system. Timezone is undefined.`\n );\n return;\n }\n\n this.setTimezone(tz);\n }\n setTimezone(tz: string) {\n this.timezone = tz ?? \"\";\n }\n\n /**\n * @internal\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\n/**\n * Log Block Container Model - Manages multiple log blocks with automatic sorting and organization.\n *\n * This container model manages collections of LogBlockModel instances, providing organized access\n * to log blocks with automatic sorting by block number. It serves as the storage layer within\n * LogStreamModel instances, handling the efficient organization and retrieval of log blocks\n * that make up a complete log stream.\n *\n * ## Key Features\n * - **Automatic Sorting** - Maintains blocks sorted by block number for sequential access\n * - **Block Management** - Add, remove, and retrieve log blocks efficiently\n * - **Memory Organization** - Organized storage of log blocks within streams\n * - **Stream Integration** - Essential component of LogStreamModel architecture\n * - **Sequential Access** - Optimized for accessing blocks in chronological order\n *\n * ## Architecture Role\n * The container fits into the log streaming architecture as:\n * - **LogStreamModel** uses LogBlockContainerModel to organize its blocks\n * - **LogBlockContainerModel** manages multiple LogBlockModel instances\n * - **LogBlockModel** contains the actual log lines and metadata\n * - Automatic sorting by blockNum ensures proper sequential log ordering\n *\n * ## Common Use Cases\n * - **Stream Block Storage** - Central storage for all blocks within a log stream\n * - **Sequential Block Access** - Navigate through log blocks in chronological order\n * - **Block Organization** - Maintain sorted collections of log segments\n * - **Memory Management** - Efficiently organize log data for stream processing\n * - **Block Lifecycle** - Handle adding and removing blocks as streams evolve\n *\n * @example Container Usage Within Stream\n * ```typescript\n * // Typically used internally by LogStreamModel\n * const logStream = LogStream.instance('system-logs').build();\n * await logStream.load();\n *\n * // Access the container through the stream\n * const blockContainer = logStream._blocks; // Internal container\n * const blocks = logStream.blocks; // Public access to blocks\n *\n * // Container automatically sorts blocks by blockNum\n * console.log(`Stream has ${blocks.length} blocks`);\n * blocks.forEach(block => {\n * console.log(`Block ${block.blockNum}: ${block.lineCount} lines`);\n * });\n * ```\n *\n * @example Direct Container Operations\n * ```typescript\n * // Create container (typically done internally)\n * const container = LogBlockContainer.instance('log-blocks')\n * .options({})\n * .build();\n *\n * // Add blocks to container\n * const block1 = LogBlock.instance('block-1')\n * .options({\n * nodeId: 'primary',\n * stream: 'app-logs',\n * blockNum: 1,\n * startLineNum: 1,\n * endLineNum: 100,\n * startTime: new Date('2024-01-01T10:00:00Z'),\n * endTime: new Date('2024-01-01T10:05:00Z'),\n * lineCount: 100\n * })\n * .build();\n *\n * const block2 = LogBlock.instance('block-2')\n * .options({\n * nodeId: 'primary',\n * stream: 'app-logs',\n * blockNum: 2,\n * startLineNum: 101,\n * endLineNum: 200,\n * startTime: new Date('2024-01-01T10:05:00Z'),\n * endTime: new Date('2024-01-01T10:10:00Z'),\n * lineCount: 100\n * })\n * .build();\n *\n * container.addModel(block1);\n * container.addModel(block2);\n *\n * // Blocks are automatically sorted by blockNum\n * const sortedBlocks = container.data;\n * console.log(`First block: ${sortedBlocks[0].blockNum}`); // 1\n * console.log(`Second block: ${sortedBlocks[1].blockNum}`); // 2\n * ```\n *\n * @example React Block List Component\n * ```typescript\n * const BlockList: React.FC<{ container: LogBlockContainerModel }> = kosComponent(({ container }) => {\n * return (\n * <div className=\"block-list\">\n * <h3>Log Blocks ({container.data.length})</h3>\n * <div className=\"blocks\">\n * {container.data.map(block => (\n * <div key={block.id} className=\"block-item\">\n * <div className=\"block-header\">\n * <span className=\"block-num\">Block {block.blockNum}</span>\n * <span className=\"line-range\">\n * Lines {block.startLineNum}-{block.endLineNum}\n * </span>\n * </div>\n * <div className=\"block-details\">\n * <span>Stream: {block.stream}</span>\n * <span>Lines: {block.lineCount}</span>\n * <span>Loaded: {block.lines.length}</span>\n * </div>\n * <div className=\"block-time\">\n * {block.startTime.toLocaleString()} - {block.endTime.toLocaleString()}\n * </div>\n * </div>\n * ))}\n * </div>\n * </div>\n * );\n * });\n * ```\n *\n * @group KOS Model\n * @category Device Logging\n * @interface\n *\n * @see {@link LogStreamModel} - Parent stream model that uses this container\n * @see {@link LogBlockModel} - Individual log blocks managed by this container\n * @see {@link LogBlockContainerOptions} - Configuration options for the container\n */\nexport type LogBlockContainerModel =\n PublicModelInterface<LogBlockContainerModelImpl>;\n\n/**\n * @ignore\n * @internal\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 { getQueryParams, KosLog } from \"../../core\";\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.debug(`getKosConnectionId: ${result}`);\n\n return result;\n};\n","import {\n KosLog,\n type ClientResponse,\n type DeepRequired,\n type ElementType,\n type ServiceResponse,\n} from \"../../../../core\";\nimport { getKosConnectionId } from \"../../../utils/get-kos-connection-id\";\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\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 * @group KOS Model\n * @category Device Logging\n * Retrieves the initial list of log-stream-container data.\n */\nexport const getLogStreams = async (): Promise<\n ServiceResponse<LogStreamContainerClientResponse>\n> => {\n const destinationAddress = getKosConnectionId();\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 destinationAddress = getKosConnectionId();\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 destinationAddress = getKosConnectionId();\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 destinationAddress = getKosConnectionId();\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 destinationAddress = getKosConnectionId();\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 destinationAddress = getKosConnectionId();\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\n/**\n * Log Block Model - Individual log data block management within streaming log systems.\n *\n * This model represents a single block of log data within a LogStreamModel, providing efficient\n * memory management and organized access to log lines. Log blocks are the fundamental storage\n * units that enable high-performance log streaming by breaking large log streams into\n * manageable, sequential segments with precise line numbering and timing information.\n *\n * ## Key Features\n * - **Block-based Storage** - Efficient memory usage through segmented log storage\n * - **Line Management** - Precise line numbering with start/end tracking\n * - **Time-based Organization** - Temporal ordering with start and end timestamps\n * - **Dynamic Loading** - On-demand synchronization of log lines from source\n * - **Incremental Updates** - Add new lines without full reload\n * - **Stream Integration** - Seamless integration with LogStreamModel containers\n *\n * ## Architecture Relationship\n * LogBlock works as a component within the broader log streaming architecture:\n * - **LogStreamModel** contains multiple LogBlockModels via LogBlockContainerModel\n * - **LogBlockContainerModel** manages and sorts blocks by block number\n * - **LogBlockModel** stores the actual log lines and metadata for a specific segment\n * - This design enables efficient memory usage and fast access to recent log data\n *\n * ## Common Use Cases\n * - **Memory-efficient Log Storage** - Break large log streams into manageable blocks\n * - **Sequential Log Access** - Navigate through log history by block\n * - **Selective Loading** - Load only needed blocks for performance\n * - **Log Line Management** - Add, retrieve, and manage individual log entries\n * - **Time-based Log Analysis** - Filter and analyze logs by time ranges\n * - **Stream Synchronization** - Keep log blocks synchronized with source streams\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * // Typically accessed through LogStreamModel, not created directly\n * const logStream = LogStream.instance('app-logs')\n * .options({ name: 'application-logs', nodeId: 'primary' })\n * .build();\n *\n * await logStream.load();\n *\n * // Access blocks within the stream\n * const blocks = logStream.blocks;\n * const currentBlock = logStream.currentBlock;\n *\n * if (currentBlock) {\n * console.log(`Block ${currentBlock.blockNum}`);\n * console.log(`Lines: ${currentBlock.startLineNum}-${currentBlock.endLineNum}`);\n * console.log(`Time range: ${currentBlock.startTime} to ${currentBlock.endTime}`);\n * console.log(`Line count: ${currentBlock.lineCount}`);\n * }\n * ```\n *\n * @example Block Line Management\n * ```typescript\n * // Access through log stream\n * const logStream = LogStream.instance('system-logs').build();\n * const block = logStream.currentBlock;\n *\n * if (block) {\n * // Get current lines\n * console.log(`Block has ${block.lines.length} loaded lines`);\n *\n * // Add new lines (typically done automatically by stream)\n * block.addLines(['New log entry 1', 'New log entry 2']);\n *\n * // Sync with remote source\n * await block.syncLines();\n *\n * // Process lines\n * block.lines.forEach((line, index) => {\n * const globalLineNum = block.startLineNum + index;\n * console.log(`Line ${globalLineNum}: ${line}`);\n * });\n * }\n * ```\n *\n * @example Block Analysis and Filtering\n * ```typescript\n * // Analyze blocks within a stream\n * const logStream = LogStream.instance('error-logs').build();\n * await logStream.load();\n *\n * // Find blocks within a time range\n * const startTime = new Date('2024-01-01T00:00:00Z');\n * const endTime = new Date('2024-01-01T23:59:59Z');\n *\n * const blocksInRange = logStream.blocks.filter(block =>\n * block.startTime >= startTime && block.endTime <= endTime\n * );\n *\n * console.log(`Found ${blocksInRange.length} blocks in date range`);\n *\n * // Process error logs from specific blocks\n * for (const block of blocksInRange) {\n * await block.syncLines(); // Ensure lines are loaded\n *\n * const errorLines = block.lines\n * .map((line, index) => ({ line, lineNum: block.startLineNum + index }))\n * .filter(({ line }) => line.includes('ERROR'));\n *\n * if (errorLines.length > 0) {\n * console.log(`Block ${block.blockNum} has ${errorLines.length} errors`);\n * errorLines.forEach(({ line, lineNum }) => {\n * console.log(`Line ${lineNum}: ${line}`);\n * });\n * }\n * }\n * ```\n *\n * @example Block Container Integration\n * ```typescript\n * // Access blocks through their container\n * const logStream = LogStream.instance('debug-logs').build();\n * const blockContainer = logStream.blocks; // This is a LogBlockContainerModel\n *\n * // Blocks are automatically sorted by block number\n * const sortedBlocks = blockContainer.data;\n * console.log(`Stream has ${sortedBlocks.length} blocks`);\n *\n * // Get specific block by ID\n * const blockId = 'debug-logs-block-5';\n * const specificBlock = blockContainer.getModel(blockId);\n *\n * if (specificBlock) {\n * console.log(`Block ${specificBlock.blockNum} loaded`);\n * await specificBlock.syncLines();\n * }\n *\n * // Add new block to container (typically done automatically)\n * const newBlockOptions: LogBlockOptions = {\n * nodeId: 'primary',\n * stream: 'debug-logs',\n * blockNum: 10,\n * startLineNum: 1000,\n * endLineNum: 1099,\n * startTime: new Date(),\n * endTime: new Date(Date.now() + 60000),\n * lineCount: 100\n * };\n *\n * const newBlock = LogBlock.instance('debug-logs-block-10')\n * .options(newBlockOptions)\n * .build();\n *\n * blockContainer.addModel(newBlock);\n * ```\n *\n * @example Block Update and Synchronization\n * ```typescript\n * const block = logStream.currentBlock;\n *\n * if (block) {\n * // Update block metadata (typically done by stream management)\n * const updatedOptions: LogBlockOptions = {\n * ...block,\n * endLineNum: block.endLineNum + 50,\n * endTime: new Date(),\n * lineCount: block.lineCount + 50\n * };\n *\n * block.updateModel(updatedOptions);\n *\n * // Sync to get new lines\n * await block.syncLines();\n *\n * console.log(`Block now has ${block.lines.length} lines loaded`);\n * console.log(`Updated end time: ${block.endTime}`);\n * }\n * ```\n *\n * @group KOS Model\n * @category Device Logging\n * @useDeclaredType\n *\n * @see {@link LogStreamModel} - Parent stream model that contains log blocks\n * @see {@link LogBlockContainerModel} - Container that manages multiple log blocks\n * @see {@link LogBlockOptions} - Configuration options for log block instances\n * @see {@link LogBlockType} - Type definition for block data exchange\n * @see {@link LogLinesType} - Type definition for line data with block metadata\n */\nexport type LogBlockModel = PublicModelInterface<LogBlockModelImpl>;\n\n/**\n * @ignore\n * @internal\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\n/**\n * Log Stream Model - Real-time streaming log viewer with efficient block-based management and async iteration.\n *\n * This model provides high-performance log streaming capabilities for monitoring KOS device logs in real-time.\n * It organizes log data into efficient blocks for memory management and provides async iterator support\n * for continuous log consumption. Essential for debugging, monitoring, and troubleshooting KOS applications.\n *\n * ## Key Features\n * - **Real-time Log Streaming** - Live log updates as they are generated on the device\n * - **Block-based Management** - Efficient memory usage through log block organization\n * - **Async Iterator Support** - Stream logs using modern async/await patterns\n * - **Subscription Control** - Subscribe/unsubscribe to specific log streams\n * - **Line Number Tracking** - Maintains accurate line numbering across blocks\n * - **Multi-stream Support** - Handle multiple log streams simultaneously through container model\n *\n * ## Common Use Cases\n * - **Development Debugging** - Monitor application logs during development\n * - **Production Monitoring** - Track system health and errors in deployed applications\n * - **Troubleshooting** - Analyze log patterns to diagnose issues\n * - **Log Analysis** - Process log streams for metrics and insights\n * - **Real-time Dashboards** - Display live log feeds in monitoring interfaces\n * - **Automated Log Processing** - Stream logs to external analysis tools\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const logStream = LogStream.instance('application-logs')\n * .options({ name: 'application-logs', nodeId: 'primary' })\n * .build();\n *\n * await logStream.subscribe();\n * const iterator = logStream.start();\n * for await (const logLine of iterator) {\n * console.log(`[LOG] ${logLine}`);\n * }\n * ```\n *\n * @group KOS Model\n * @category Device Logging\n * @useDeclaredType\n *\n * @see {@link LogStreamOptions} - Configuration options for log stream instances\n * @see {@link LogStreamContainerModel} - Container model for managing multiple streams\n * @see {@link LogBlockModel} - Individual log block management within streams\n */\nexport type LogStreamModel = PublicModelInterface<LogStreamModelImpl>;\n/**\n * @ignore\n * @internal\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 /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing log-stream ${this.id}`);\n }\n\n /**\n * @internal\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();\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 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\n/**\n * Log Stream Container Model - Manages multiple log streams with real-time topic-based synchronization.\n *\n * This container model manages multiple LogStreamModel instances and handles real-time log events\n * from the KOS system. It provides centralized management of log streams, automatic stream discovery,\n * and coordinated event handling for efficient log processing across multiple sources.\n *\n * ## Topic-Based Reactivity\n * The container listens to these KOS topics for real-time log management:\n * - **`/kos/logs/subscription/addBlock/*`** - Fired when new log blocks are created\n * - **`/kos/logs/subscription/updateBlock/*`** - Fired when existing log blocks are updated\n * - **`/kos/logs/subscription/removeBlock/*`** - Fired when log blocks are removed\n * - **`/kos/logs/subscription/lines/*`** - Fired when new log lines are added to blocks\n * - **`/kos/logs/streams/add/*`** - Fired when new log streams are discovered\n *\n * ## Key Features\n * - **Multi-stream Management** - Handle multiple log streams simultaneously\n * - **Automatic Stream Discovery** - Automatically add new streams as they become available\n * - **Topic-based Synchronization** - Real-time updates via KOS event system\n * - **Stream Selection** - Track currently selected stream for UI purposes\n * - **Block Management** - Coordinate block updates across all managed streams\n *\n * ## Common Use Cases\n * - **Log Dashboard** - Central management of multiple log sources\n * - **System Monitoring** - Monitor logs from all system components\n * - **Debugging Interface** - Switch between different log streams during troubleshooting\n * - **Log Aggregation** - Collect and manage logs from distributed sources\n *\n * @example Basic Usage\n * ```typescript\n * const logContainer = LogStreamContainer.instance('main-logger')\n * .options({})\n * .build();\n *\n * // Subscribe to and manage multiple streams\n * await logContainer.subscribeToLogStream('application-logs');\n * const appStream = logContainer.getModel('application-logs');\n * logContainer.updateSelectedStream(appStream);\n * ```\n *\n * @group KOS Model\n * @category Device Logging\n * @interface\n * @useDeclaredType\n *\n * @see {@link LogStreamModel} - Individual log stream management\n * @see {@link LogStreamContainerOptions} - Configuration options for the container\n */\nexport type LogStreamContainerModel =\n PublicModelInterface<LogStreamContainerModelImpl>;\n\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/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class LogStreamContainerModelImpl\n implements IKosIdentifiable, IKosModelHolder<LogStreamModel>, IKosDataModel\n{\n /** Unique identifier for the container model instance */\n id: string;\n /** Context logger for debugging log stream operations */\n private logger: KosContextLogger;\n /** Currently selected log stream for UI display purposes */\n selectedStream?: LogStreamModel;\n /** Container for managing LogStream model instances */\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 /**\n * @internal\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 /**\n * @internal\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 KosLog,\n KosServiceResponse,\n ServiceFactory,\n resolveServiceUrl,\n} from \"../../../../core\";\nimport { FutureEndState, FutureResponse } from \"../../../services/future\";\nimport { FutureManager } from \"../../../utils/future-manager\";\nimport { getKosConnectionId } from \"../../../utils/get-kos-connection-id\";\nconst { URL } = resolveServiceUrl(\"TROUBLE_SERVICE\");\nconst { getAll, postModel } = ServiceFactory.build({\n basePath: `${URL}/api/kos/troubles`,\n});\n\nexport interface TroubleResponse<ClientAttributes = any> {\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 attrs: ClientAttributes;\n}\n\nconst log = KosLog.createLogger({ name: \"trouble-services\" });\n\n/**\n * @category Service\n * @internal\n * Retrieves the initial Trouble data.\n */\nexport const getTroubles = async (servicePath: string) => {\n const isKosTroubles = servicePath.includes(\"/kos/troubles\");\n const destinationAddress = getKosConnectionId();\n log.info(\n `Fetching troubles from ${servicePath} with destination address: ${\n isKosTroubles ? destinationAddress : \"N/A (not a kos troubles path)\"\n }`\n );\n\n const response = await getAll<TroubleResponse>({\n urlOverride: `${URL}${servicePath}`,\n destinationAddress: isKosTroubles ? destinationAddress : undefined,\n });\n return response;\n};\n\nexport const resolveTrouble = async (\n troubleId: string,\n servicePath = \"/api/kos/troubles\",\n tracker?: string\n) => {\n try {\n const isKosTroubles = servicePath.includes(\"/kos/troubles\");\n const destinationAddress = getKosConnectionId();\n const response: KosServiceResponse<FutureResponse> = (await postModel({\n model: {},\n urlOverride: `${URL}${servicePath}/resolve/${troubleId}`,\n destinationAddress: isKosTroubles ? destinationAddress : undefined,\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 servicePath = \"/api/kos/troubles\",\n tracker?: string\n) => {\n try {\n const destinationAddress = getKosConnectionId();\n const response: KosServiceResponse<FutureResponse> = (await postModel({\n model: troubleIds,\n urlOverride: `${URL}${servicePath}/resolve/`,\n destinationAddress,\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, type TroubleResponse } 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\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 servicePath: string;\n group?: string;\n createTime?: string;\n rawJson?: TroubleResponse<any>;\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 servicePath,\n rawJson,\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 this.rawJson = rawJson;\n this.servicePath = servicePath ?? \"/api/kos/troubles\";\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, this.servicePath, 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","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport {\n DependencyLifecycle,\n ExtensionManager,\n destroyKosModel,\n kosContainerAware,\n kosFutureAware,\n kosLoggerAware,\n kosModel,\n kosTopicHandler,\n type IKosDataModel,\n type IKosIdentifiable,\n type KosContainerAwareWithProp,\n type KosFutureAwareFull,\n type KosLoggerAware,\n type KosModelRegistrationType,\n type PublicModelInterface,\n} from \"../../../core\";\n\nimport { KosCoreModelPropertyMapper } from \"../../constants\";\nimport { kosFuture } from \"../../decorators\";\nimport {\n defaultTroubleColorMapper,\n defaultTroubleRankMapper,\n defaultTroubleRoleMapper,\n} from \"../../utils/trouble-utils\";\nimport {\n bulkResolveTroubles,\n getTroubles,\n type TroubleResponse,\n} from \"../trouble/services\";\nimport { Trouble } from \"../trouble/trouble-registration\";\nimport type { TroubleModel } from \"../trouble/types\";\nimport { troublePathFactory } from \"./trouble-utils\";\nimport type { TroubleContainerOptions } from \"./types\";\n\nconst addTrouble = (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\n const newTrouble = Trouble.factory(`trouble-${trouble.id}`)(options);\n return newTrouble;\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 type TroubleContainerModel =\n PublicModelInterface<TroubleContainerModelImpl>;\nexport interface TroubleContainerModelImpl\n extends KosContainerAwareWithProp<TroubleModel, \"troubles\">,\n KosFutureAwareFull,\n KosLoggerAware {}\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({ modelTypeId: MODEL_TYPE, singleton: true })\n@kosLoggerAware()\n@kosFutureAware()\n@kosContainerAware<TroubleModel>({\n containerProperty: \"troubles\",\n containerOptions: {\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 },\n})\nexport class TroubleContainerModelImpl\n implements IKosIdentifiable, IKosDataModel\n{\n static Registration: KosModelRegistrationType<\n TroubleContainerModelImpl,\n TroubleContainerOptions\n >;\n id: string;\n servicePath = \"/api/kos/troubles\";\n constructor(modelId: string, options: TroubleContainerOptions) {\n this.id = modelId;\n this.servicePath = options.servicePath ?? this.servicePath;\n }\n\n // -------------------LIFECYCLE----------------------------\n async reload(): Promise<void> {\n this.logger.info(\"reloading trouble container\");\n const _troubles = await getTroubles(this.servicePath);\n const incoming = _troubles?.data ?? [];\n\n const incomingKeys = new Set(incoming.map((t) => `trouble-${t.id}`));\n\n const toRemove = this.troubles.data\n .map((m) => m.id)\n .filter((id) => !incomingKeys.has(id));\n\n const toAdd = incoming\n .filter((t) => !this.troubles.getModel(`trouble-${t.id}`))\n .map(addTrouble);\n\n this.troubles.removeAll(toRemove);\n this.troubles.addAll(toAdd);\n }\n async load(): Promise<void> {\n this.logger.debug(\"loading trouble container\");\n try {\n const _troubles = await getTroubles(this.servicePath);\n _troubles?.data.forEach((trouble) => {\n const options = {\n ...trouble,\n servicePath: this.servicePath,\n rank: troubleRankMapper(trouble),\n color: troubleColorMapper(trouble),\n role: troubleRoleMapper(trouble),\n id: String(trouble.id),\n rawJson: trouble,\n };\n\n const newTrouble = Trouble.factory(`trouble-${trouble.id}`)(options);\n this.troubles.addModel(newTrouble);\n });\n } catch (e) {\n this.logger.error(e);\n throw e;\n }\n }\n\n @kosFuture()\n async resolveAll(tracker?: string) {\n const troubleIds = this.troubles.data\n .filter((trouble) => trouble.resolvable)\n .map((trouble) => trouble.rawId);\n return await bulkResolveTroubles(troubleIds, this.servicePath, tracker);\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 servicePath: this.servicePath,\n rank: troubleRankMapper(trouble),\n color: troubleColorMapper(trouble),\n role: troubleRoleMapper(trouble),\n id: String(trouble.id),\n rawJson: trouble,\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","export {\n Troubles,\n type TroubleContainerModel,\n} from \"./trouble-container-model\";\n\nexport type { TroubleContainerOptions } from \"./types\";\n\nimport { TroubleContainerModelImpl } from \"./trouble-container-model\";\n\nexport const TroubleContainer = TroubleContainerModelImpl.Registration;\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 type { TroubleContainerModel } from \"../trouble-container\";\nimport { TroubleContainer } from \"../trouble-container\";\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\n/**\n * OTA - Over-the-Air update management system for KOS devices.\n *\n * The OTA model provides comprehensive management of software updates and artifacts on KOS devices,\n * including real-time download progress tracking, installation management, and error handling.\n * This model is essential for applications that need to manage software updates, display update\n * status, and handle system maintenance operations.\n *\n * ## Key Features\n * - **Real-Time Update Tracking** - Live monitoring of download progress and installation status\n * - **Artifact Management** - Complete visibility into available and installed software artifacts\n * - **Trouble Integration** - Integration with KOS trouble system for error tracking and resolution\n * - **Status Monitoring** - Comprehensive status tracking (downloading, pending, ready, error, idle)\n * - **Installation Control** - Safe installation and reboot management for pending updates\n * - **Progress Reporting** - Detailed download progress with size and percentage completion\n *\n * ## Topic-Based Reactivity\n * The model listens to these KOS topics for real-time synchronization:\n * - **`/kos/ota/artifacts/all`** - Complete artifact list updates from OTA service\n * - **`/kos/ota/artifacts/changed`** - Incremental artifact status changes during downloads\n *\n * ## Update States\n * - **idle** - No updates in progress, system ready\n * - **downloading** - Updates actively downloading from remote sources\n * - **pending** - Updates downloaded and staged, ready for installation\n * - **ready** - Updates installed and ready for use\n * - **error** - Update process encountered errors, intervention needed\n *\n * ## Common Use Cases\n * - **Update Status Dashboard** - Display current update status and progress to users\n * - **System Maintenance** - Manage scheduled updates and installations\n * - **Error Handling** - Monitor and resolve update-related issues\n * - **Progress Monitoring** - Track download progress for large artifacts\n * - **Installation Management** - Control when updates are applied to minimize downtime\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const otaModel = Ota.instance('system-updater').build();\n *\n * // Access current update status and manage installations\n * console.log(otaModel.status); // 'idle' | 'downloading' | 'pending' | 'ready' | 'error'\n * if (otaModel.status === 'pending') {\n * otaModel.installAndReboot();\n * }\n * ```\n *\n * @group KOS Model\n * @category System Integration\n * @useDeclaredType\n *\n * @see {@link UpdaterOptions} - Configuration options for OTA model\n * @see {@link UpdaterItem} - Individual update artifact interface\n * @see {@link UpdaterStatus} - Available update status types\n * @see {@link OTAArtifactResponse} - Raw artifact data from OTA service\n * @see {@link TroubleContainer} - Integrated trouble management system\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/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class OtaModelImpl implements IKosDataModel, IKosIdentifiable {\n /** Unique identifier for the model instance */\n id: string;\n private logger: KosContextLogger;\n\n /** Internal data container holding all available update artifacts */\n private data: IKosDataContainer<UpdaterItem> = new KosDataContainer();\n\n /** Trouble container dependency for tracking OTA-related troubles */\n @kosDependency({ modelType: TroubleContainer.type })\n private troubleContainer!: TroubleContainerModel;\n\n /** Trouble condition indicating downloads are currently in progress */\n get downloadInProgressTrouble() {\n const downloadInProgressTrouble =\n this.troubleContainer.troubles.getIndexByKey(\n \"byType\",\n \"OTADownloadInProgressTrouble\"\n )?.[0];\n\n return downloadInProgressTrouble;\n }\n\n /** Trouble condition indicating updates are downloaded and pending installation */\n get updatePendingTrouble() {\n const updatePendingTrouble = this.troubleContainer.troubles.getIndexByKey(\n \"byType\",\n \"OTAUpdatePendingTrouble\"\n )?.[0];\n\n return updatePendingTrouble;\n }\n\n /** Trouble condition indicating OTA process is paused due to errors */\n get pausedDueToErrorsTrouble() {\n const pendingTrouble = this.troubleContainer.troubles.getIndexByKey(\n \"byType\",\n \"OTAPausedDueToErrorsTrouble\"\n )?.[0];\n\n return pendingTrouble;\n }\n\n /** Collection of all available update artifacts with their current status */\n get updates() {\n return this.data;\n }\n\n /** Current overall update status based on active trouble conditions */\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 /**\n * Installs pending updates and initiates system reboot.\n * This method resolves the OTAUpdatePendingTrouble to trigger installation.\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 /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing ota ${this.id}`);\n }\n\n /**\n * @internal\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 * Bridge a @kosFuture method call to a Promise that settles on the FUTURE's\n * terminal state — not on the HTTP acknowledgment.\n *\n * A @kosFuture method resolves as soon as the backend accepts the operation;\n * the real outcome (SUCCESS / FAIL / ABORT / CANCEL) arrives later on the\n * future model via topic updates. Inside React that state is observable\n * through the model's future-aware getters, but imperative callers (commands,\n * services, tests) have no way to await the outcome. This util observes the\n * future created by the call and resolves/rejects the returned promise from\n * its end state, with cancellation and progress subscription support.\n */\n\nimport { reaction } from \"mobx\";\nimport { KosLog } from \"../../core\";\nimport type {\n FutureContainer,\n IFutureModel,\n} from \"../models/future/future-types\";\nimport { FutureEndState } from \"../services/future\";\nimport type { CancellablePromise } from \"../types/cancellable-promise\";\n\nconst log = KosLog.createLogger({ name: \"await-future-call\", group: \"Models\" });\n\n/**\n * Rejection raised when the awaited future ends in FAIL / ABORT / CANCEL.\n * `reason` carries the backend's reason code (e.g. a ReasonException id),\n * so callers can map it to user-facing messages.\n */\nexport class FutureCallError extends Error {\n readonly endState: FutureEndState;\n readonly reason?: string;\n readonly futureId?: string;\n\n constructor(endState: FutureEndState, reason?: string, futureId?: string) {\n super(reason ?? `Future ended with ${endState}`);\n this.name = \"FutureCallError\";\n this.endState = endState;\n this.reason = reason;\n this.futureId = futureId;\n }\n\n get isCancelled() {\n return (\n this.endState === FutureEndState.Canceled ||\n this.endState === FutureEndState.Aborted\n );\n }\n}\n\nexport interface AwaitFutureCallOptions {\n /** Alias the wrapped method registers its future under (@kosFuture alias). */\n alias?: string;\n /**\n * Reject with a timeout error if the future has not reached an end state\n * within this window. Unset = wait indefinitely.\n */\n timeoutMs?: number;\n}\n\n/**\n * Invoke a @kosFuture method on a future-aware model and return a\n * CancellablePromise that settles from the future's end state:\n *\n * - resolves with the method's response once the future ends in SUCCESS\n * - rejects with {@link FutureCallError} on FAIL / ABORT / CANCEL\n * - rejects with the service error if the call itself throws\n * - resolves with the response when the call turns out not to be\n * future-tracked (no future was produced)\n *\n * The future created by the call is captured reactively (the @kosFuture\n * wrapper registers it on the model's futureHandler before the request is\n * sent), so no timing hacks are needed and concurrent operations on other\n * aliases are unaffected.\n *\n * @example Awaiting real completion from a command\n * ```typescript\n * try {\n * await awaitFutureCall(artifact, (a) =>\n * a.publishImportedKab(path, version, qualifier)\n * );\n * studio.notifications.success(\"Published\");\n * } catch (e) {\n * if (e instanceof FutureCallError && !e.isCancelled) {\n * studio.notifications.error(mapReason(e.reason));\n * }\n * }\n * ```\n *\n * @example Cancellation and progress\n * ```typescript\n * const call = awaitFutureCall(model, (m) => m.performOperation());\n * const stop = call.onProgressUpdate((p, status) => render(p, status));\n * // later: await call.cancel();\n * ```\n */\nexport function awaitFutureCall<T extends FutureContainer, R>(\n model: T,\n methodCall: (model: T) => Promise<R>,\n options: AwaitFutureCallOptions = {}\n): CancellablePromise<R> {\n const { alias, timeoutMs } = options;\n\n const initial = model.futureHandler.getFuture(alias);\n\n let tracked: IFutureModel | undefined;\n let settled = false;\n let acked = false;\n let ackResponse: R | undefined;\n let cancelRequested = false;\n const disposers: Array<() => void> = [];\n const progressCallbacks = new Set<\n (progress: number, status: string) => void\n >();\n\n const dispose = () => {\n disposers.forEach((d) => d());\n disposers.length = 0;\n progressCallbacks.clear();\n };\n\n const promise = new Promise<R>((resolve, reject) => {\n const settle = (fn: () => void) => {\n if (settled) return;\n settled = true;\n dispose();\n fn();\n };\n\n const finishFromEndState = (endState: FutureEndState | undefined) => {\n if (!endState) return;\n if (endState === FutureEndState.Success) {\n settle(() => resolve(ackResponse as R));\n } else {\n settle(() =>\n reject(new FutureCallError(endState, tracked?.reason, tracked?.id))\n );\n }\n };\n\n const watchTracked = (future: IFutureModel) => {\n tracked = future;\n\n if (cancelRequested) {\n future.cancelFuture().catch((e) => log.error(e));\n }\n\n // Settle from the terminal state. fireImmediately covers futures that\n // completed before we attached (fast operations, ack-time end states).\n disposers.push(\n reaction(\n () => future.endState,\n (endState) => finishFromEndState(endState),\n { fireImmediately: true }\n )\n );\n\n // Progress fan-out for subscribers.\n disposers.push(\n reaction(\n () => [future.progress, future.status] as const,\n ([progress, status]) => {\n progressCallbacks.forEach((cb) => {\n try {\n cb(progress, status);\n } catch (e) {\n log.warn(\"progress callback error\", e);\n }\n });\n },\n { fireImmediately: true }\n )\n );\n };\n\n // Capture the future this call registers on the handler. The @kosFuture\n // wrapper adds it before the request is issued, so it always appears\n // before the acknowledgment resolves.\n disposers.push(\n reaction(\n () => model.futureHandler.getFuture(alias),\n (future) => {\n if (!tracked && future && future !== initial) {\n watchTracked(future);\n return;\n }\n // The handler dropped the future without a terminal state — the\n // call produced nothing to track (e.g. empty future response).\n if (tracked && !future && !tracked.endState && acked) {\n settle(() => resolve(ackResponse as R));\n }\n },\n { fireImmediately: true }\n )\n );\n\n if (timeoutMs !== undefined) {\n const timer = setTimeout(() => {\n settle(() =>\n reject(\n new Error(`Future for call did not complete within ${timeoutMs}ms`)\n )\n );\n }, timeoutMs);\n disposers.push(() => clearTimeout(timer));\n }\n\n methodCall(model)\n .then((response) => {\n acked = true;\n ackResponse = response;\n\n if (!tracked) {\n // Not a future-tracked call — the acknowledgment is the outcome.\n settle(() => resolve(response));\n return;\n }\n finishFromEndState(tracked.endState);\n })\n .catch((error) => {\n settle(() => reject(error));\n });\n }) as CancellablePromise<R>;\n\n promise.cancel = async () => {\n cancelRequested = true;\n if (tracked && !tracked.endState) {\n await tracked.cancelFuture();\n }\n };\n\n promise.getController = () => undefined;\n\n promise.isCancelled = () =>\n cancelRequested ||\n tracked?.endState === FutureEndState.Canceled ||\n tracked?.endState === FutureEndState.Aborted;\n\n Object.defineProperty(promise, \"progress\", {\n get: () => tracked?.progress ?? 0,\n enumerable: true,\n });\n\n Object.defineProperty(promise, \"status\", {\n get: () => tracked?.status ?? \"PENDING\",\n enumerable: true,\n });\n\n Object.defineProperty(promise, \"isRunning\", {\n get: () => !settled && (!tracked || !tracked.endState),\n enumerable: true,\n });\n\n Object.defineProperty(promise, \"timeRemaining\", {\n get: () => tracked?.timeRemaining ?? \"\",\n enumerable: true,\n });\n\n promise.onProgressUpdate = (\n callback: (progress: number, status: string) => void\n ) => {\n progressCallbacks.add(callback);\n callback(promise.progress, promise.status);\n return () => progressCallbacks.delete(callback);\n };\n\n return promise;\n}\n","import { autorun as kosAutoEffect } from \"mobx\";\n\n/**\n * A long-running operation whose progress can be observed imperatively.\n *\n * This is the consumer-facing contract for progress surfaces (progress\n * notifications, status indicators, modals): they depend on this interface,\n * never on the producer. Producers adapt their source to it — e.g.\n * `awaitFutureCall` adapts a KOS Future, but an XHR upload or an aggregate\n * over several operations can implement it just as well.\n */\nexport interface ProgressOperation<T = unknown> extends Promise<T> {\n /**\n * Percent complete, 0-100. Values <= 0 mean the operation has not reported\n * real progress yet — consumers should render an indeterminate state.\n */\n readonly progress: number;\n\n /**\n * Current status of the operation.\n * Common values: \"NOT_ACTIVE\", \"IN_PROGRESS\", a terminal end state\n * (\"SUCCESS\" | \"FAIL\" | \"ABORT\" | \"CANCEL\"), or consumer-defined.\n */\n readonly status: string;\n\n /**\n * Whether the operation is currently running\n */\n readonly isRunning: boolean;\n\n /**\n * Human-readable time remaining (e.g. \"2 minutes\"), when the source can\n * estimate it. Empty/undefined when unknown.\n */\n readonly timeRemaining?: string;\n\n /**\n * Cancel this specific operation\n */\n cancel(): Promise<void>;\n\n /**\n * Check if this operation was cancelled. Optional — consumers must treat\n * a missing implementation as \"unknown\".\n */\n isCancelled?(): boolean;\n\n /**\n * Subscribe to progress updates\n * Returns a dispose function to clean up the subscription\n */\n onProgressUpdate(\n callback: (progress: number, status: string) => void\n ): () => void;\n}\n\n/**\n * A Promise that can be cancelled and provides progress/state tracking\n */\nexport interface CancellablePromise<T> extends ProgressOperation<T> {\n /**\n * Get the underlying AbortController for this operation\n */\n getController(): AbortController | undefined;\n\n /**\n * Check if this operation is cancelled\n */\n isCancelled(): boolean;\n}\n\n/**\n * Options for creating a cancellable promise with progress tracking\n */\nexport interface CancellablePromiseOptions<T> {\n promise: Promise<T>;\n abortController?: AbortController;\n cancelFuture?: () => Promise<void>;\n future?: any; // The KOS Future object for progress tracking\n}\n\n/**\n * Create a cancellable promise wrapper with reactive progress tracking\n */\nexport function createCancellablePromise<T>(\n promise: Promise<T>,\n abortController?: AbortController,\n cancelFuture?: () => Promise<void>,\n future?: any\n): CancellablePromise<T>;\nexport function createCancellablePromise<T>(\n options: CancellablePromiseOptions<T>\n): CancellablePromise<T>;\nexport function createCancellablePromise<T>(\n promiseOrOptions: Promise<T> | CancellablePromiseOptions<T>,\n abortController?: AbortController,\n cancelFuture?: () => Promise<void>,\n future?: any\n): CancellablePromise<T> {\n // Handle both call signatures\n const options =\n promiseOrOptions instanceof Promise\n ? { promise: promiseOrOptions, abortController, cancelFuture, future }\n : promiseOrOptions;\n\n const {\n promise,\n abortController: controller,\n cancelFuture: cancelFn,\n future: futureRef,\n } = options;\n\n // Create the base promise\n const cancellablePromise = promise as CancellablePromise<T>;\n\n // Progress tracking state\n let currentProgress = 0;\n let currentStatus = \"PENDING\";\n let isRunning = true;\n const progressCallbacks = new Set<\n (progress: number, status: string) => void\n >();\n\n // Update progress from Future if available\n let effectDisposer: (() => void) | undefined;\n if (futureRef && typeof futureRef === \"object\") {\n // Use kosAutoEffect to track Future changes\n effectDisposer = kosAutoEffect(() => {\n const newProgress = futureRef.progress || 0;\n const newStatus = futureRef.status || \"PENDING\";\n const newIsRunning = !futureRef.endState;\n\n if (\n newProgress !== currentProgress ||\n newStatus !== currentStatus ||\n newIsRunning !== isRunning\n ) {\n currentProgress = newProgress;\n currentStatus = newStatus;\n isRunning = newIsRunning;\n\n // Notify all subscribers\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n }\n });\n }\n\n // Clean up effect when promise completes\n promise.finally(() => {\n isRunning = false;\n if (!controller?.signal.aborted) {\n currentStatus = \"COMPLETED\";\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n }\n if (effectDisposer) {\n effectDisposer();\n }\n progressCallbacks.clear();\n });\n\n // Add cancellation methods\n cancellablePromise.cancel = async () => {\n if (controller && !controller.signal.aborted) {\n controller.abort();\n }\n if (cancelFn) {\n await cancelFn();\n }\n isRunning = false;\n currentStatus = \"CANCELLED\";\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n if (effectDisposer) {\n effectDisposer();\n }\n };\n\n cancellablePromise.getController = () => controller;\n\n cancellablePromise.isCancelled = () => controller?.signal.aborted ?? false;\n\n // Add progress tracking properties\n Object.defineProperty(cancellablePromise, \"progress\", {\n get: () => currentProgress,\n enumerable: true,\n });\n\n Object.defineProperty(cancellablePromise, \"status\", {\n get: () => currentStatus,\n enumerable: true,\n });\n\n Object.defineProperty(cancellablePromise, \"isRunning\", {\n get: () => isRunning,\n enumerable: true,\n });\n\n cancellablePromise.onProgressUpdate = (\n callback: (progress: number, status: string) => void\n ) => {\n progressCallbacks.add(callback);\n\n // Call immediately with current state\n callback(currentProgress, currentStatus);\n\n // Return dispose function\n return () => progressCallbacks.delete(callback);\n };\n\n return cancellablePromise;\n}\n","/**\n * Utility to make any @kosFuture method call cancellable without accessing the future directly\n */\n\nimport { KosLog } from \"../../core\";\nimport type { FutureContainer } from \"../models/future/future-types\";\nimport type { CancellablePromise } from \"../types/cancellable-promise\";\nimport { createCancellablePromise } from \"../types/cancellable-promise\";\n\n/**\n * Wraps a @kosFuture method call to return a CancellablePromise\n * This gives you direct cancellation control without needing to access model.future\n *\n * @example\n * ```typescript\n * // Instead of:\n * const promise = model.performOperation('data');\n * // Later: await model.future?.cancelFuture();\n *\n * // Use:\n * const cancellable = makeCancellable(model, m => m.performOperation('data'));\n * // Later: await cancellable.cancel();\n * ```\n */\nexport function makeCancellable<T extends FutureContainer, R>(\n model: T,\n methodCall: (model: T) => Promise<R>\n): CancellablePromise<R> {\n // Store the current future before the call\n const initialFuture = model.futureHandler.future;\n\n // Execute the method call\n const promise = methodCall(model);\n\n // Wait a tick to get the new future created by the method\n let newFuture: any = null;\n setTimeout(() => {\n newFuture = model.futureHandler.future;\n // Only use the new future if it's different from the initial one\n if (newFuture === initialFuture) {\n newFuture = null;\n }\n }, 0);\n\n return createCancellablePromise({\n promise,\n abortController: undefined, // No direct AbortController access\n cancelFuture: async () => {\n // Cancel through the Future system\n if (newFuture) {\n await newFuture.cancelFuture();\n } else {\n // Fallback to current future\n const currentFuture = model.futureHandler.future;\n if (currentFuture) {\n await currentFuture.cancelFuture();\n }\n }\n },\n future: newFuture, // Pass the future for progress tracking\n });\n}\n\n/**\n * Alternative approach using method decoration at call time\n * This is more explicit but requires wrapping individual calls\n *\n * @example\n * ```typescript\n * const cancellable = withCancellation(model, 'performOperation', 'data');\n * await cancellable.cancel();\n * ```\n */\nexport function withCancellation<T extends FutureContainer, K extends keyof T>(\n model: T,\n methodName: K,\n ...args: T[K] extends (...args: infer A) => any ? A : never\n): CancellablePromise<\n T[K] extends (...args: any[]) => Promise<infer R> ? R : never\n> {\n const method = model[methodName];\n if (typeof method !== \"function\") {\n throw new Error(`${String(methodName)} is not a method`);\n }\n\n // Store the current future state\n const initialFuture = model.futureHandler.future;\n\n // Call the method\n const promise = (method as any).apply(model, args);\n\n // Get the new future after method execution\n let targetFuture: any = null;\n setTimeout(() => {\n const currentFuture = model.futureHandler.future;\n if (currentFuture && currentFuture !== initialFuture) {\n targetFuture = currentFuture;\n }\n }, 0);\n\n return createCancellablePromise({\n promise,\n abortController: undefined,\n cancelFuture: async () => {\n if (targetFuture) {\n await targetFuture.cancelFuture();\n } else {\n const fallbackFuture = model.futureHandler.future;\n if (fallbackFuture) {\n await fallbackFuture.cancelFuture();\n }\n }\n },\n future: targetFuture, // Pass the future for progress tracking\n });\n}\n\n/**\n * Batch cancellation utility for multiple operations\n *\n * @example\n * ```typescript\n * const batch = createCancellationBatch();\n *\n * const op1 = batch.add(model, m => m.performOperation1());\n * const op2 = batch.add(model, m => m.performOperation2());\n *\n * // Cancel all operations at once\n * await batch.cancelAll();\n * ```\n */\nexport class CancellationBatch {\n private operations: Array<CancellablePromise<any>> = [];\n\n add<T extends FutureContainer, R>(\n model: T,\n methodCall: (model: T) => Promise<R>\n ): CancellablePromise<R> {\n const cancellable = makeCancellable(model, methodCall);\n this.operations.push(cancellable);\n return cancellable;\n }\n\n async cancelAll(): Promise<void> {\n await Promise.all(\n this.operations.map((op) =>\n op.cancel().catch(() => {\n // Ignore cancellation errors, just log them if needed\n KosLog.warn(\"Cancellation failed for operation:\", op);\n })\n )\n );\n }\n\n getAllControllers(): Array<AbortController | undefined> {\n return this.operations.map((op) => op.getController());\n }\n\n getActiveCount(): number {\n return this.operations.filter((op) => !op.isCancelled()).length;\n }\n\n clear(): void {\n this.operations = [];\n }\n}\n\nexport function createCancellationBatch(): CancellationBatch {\n return new CancellationBatch();\n}\n","/**\n * Utility for creating cancellable service functions\n */\n\nexport type CancellableFunction<T extends (...args: any[]) => any> = T & {\n /**\n * Cancel any in-flight request\n */\n cancel: () => void;\n /**\n * Get the current AbortController\n */\n getController: () => AbortController | undefined;\n /**\n * Check if there's an active request\n */\n isActive: () => boolean;\n};\n\n/**\n * Creates a cancellable version of a service function.\n * The service function must accept an AbortSignal as its last parameter.\n *\n * @example\n * ```typescript\n * // Original service\n * const getUsers = async (params?: UserParams, signal?: AbortSignal) => {\n * return api.get('/users', params, { signal });\n * };\n *\n * // Make it cancellable\n * const cancellableGetUsers = createCancellableService(getUsers);\n *\n * // Use it\n * const users = await cancellableGetUsers({ page: 1 });\n *\n * // Cancel if needed\n * cancellableGetUsers.cancel();\n * ```\n */\nexport function createCancellableService<TArgs extends any[], TReturn>(\n serviceFunction: (...args: [...TArgs, AbortSignal?]) => Promise<TReturn>\n): CancellableFunction<(...args: TArgs) => Promise<TReturn>> {\n let controller: AbortController | undefined;\n\n const wrappedFunction = async (...args: TArgs): Promise<TReturn> => {\n // Cancel previous request\n if (controller) {\n controller.abort();\n }\n\n // Create new controller\n controller = new AbortController();\n const currentController = controller;\n\n try {\n // Call the service with the abort signal\n return await serviceFunction(...args, currentController.signal);\n } finally {\n // Clear controller if this is still the active request\n if (controller === currentController) {\n controller = undefined;\n }\n }\n };\n\n // Add utility methods\n wrappedFunction.cancel = () => {\n if (controller) {\n controller.abort();\n controller = undefined;\n }\n };\n\n wrappedFunction.getController = () => controller;\n\n wrappedFunction.isActive = () => !!controller;\n\n return wrappedFunction as CancellableFunction<\n (...args: TArgs) => Promise<TReturn>\n >;\n}\n\n/**\n * Creates a cancellable service class that manages multiple service functions\n *\n * @example\n * ```typescript\n * class UserService extends CancellableServiceManager {\n * getUsers = this.createMethod(async (params?: UserParams, signal?: AbortSignal) => {\n * return api.get('/users', params, { signal });\n * });\n *\n * getUser = this.createMethod(async (id: string, signal?: AbortSignal) => {\n * return api.get(`/users/${id}`, undefined, { signal });\n * });\n * }\n * ```\n */\nexport class CancellableServiceManager {\n private controllers = new Map<string, AbortController>();\n\n /**\n * Create a cancellable method\n */\n protected createMethod<TArgs extends any[], TReturn>(\n name: string,\n serviceFunction: (...args: [...TArgs, AbortSignal?]) => Promise<TReturn>\n ): CancellableFunction<(...args: TArgs) => Promise<TReturn>> {\n const wrappedFunction = async (...args: TArgs): Promise<TReturn> => {\n // Cancel previous request for this method\n this.cancelMethod(name);\n\n // Create new controller\n const controller = new AbortController();\n this.controllers.set(name, controller);\n\n try {\n return await serviceFunction(...args, controller.signal);\n } finally {\n // Clear controller if it's still the active one\n if (this.controllers.get(name) === controller) {\n this.controllers.delete(name);\n }\n }\n };\n\n wrappedFunction.cancel = () => this.cancelMethod(name);\n wrappedFunction.getController = () => this.controllers.get(name);\n wrappedFunction.isActive = () => this.controllers.has(name);\n\n return wrappedFunction as CancellableFunction<\n (...args: TArgs) => Promise<TReturn>\n >;\n }\n\n /**\n * Cancel a specific method's request\n */\n cancelMethod(name: string): void {\n const controller = this.controllers.get(name);\n if (controller) {\n controller.abort();\n this.controllers.delete(name);\n }\n }\n\n /**\n * Cancel all active requests\n */\n cancelAll(): void {\n for (const controller of this.controllers.values()) {\n controller.abort();\n }\n this.controllers.clear();\n }\n\n /**\n * Get all active method names\n */\n getActiveMethods(): string[] {\n return Array.from(this.controllers.keys());\n }\n\n /**\n * Check if any requests are active\n */\n hasActiveRequests(): boolean {\n return this.controllers.size > 0;\n }\n}\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 { BASE_URL, getQueryParams, kosFetch } from \"../../../../core\";\n\nconst params = getQueryParams();\nconst DEBUG =\n (params as any).debug === \"true\" || (params as any).debug === true;\n// const MSG_TYPE_CANVAS_DATA = 'canvas-data';\nconst PATH_CANVAS_DATA = \"/api/system/canvas\";\n\n/**\n * Sends canvas data to a specified endpoint using a POST request.\n *\n * @param data - The data to be sent to the canvas endpoint.\n * @returns A promise that resolves when the data has been successfully sent.\n */\nexport const sendCanvasData = async (data: any, apiPathOverride?: string) => {\n const path = apiPathOverride || PATH_CANVAS_DATA;\n const FULL_PATH = `${BASE_URL}${path}`;\n await kosFetch(FULL_PATH, {\n method: \"POST\",\n headers: {\n hide: DEBUG ? \"false\" : \"true\",\n },\n body: data,\n });\n // sendKosMessage(data, {\n // requestType: MSG_TYPE_CANVAS_DATA,\n // headers: {\n // hide: 'true',\n // },\n // });\n};\n","/**\n * Converts an RGB color value to the RGB332 color format.\n *\n * RGB332 is a compact 8-bit color format where:\n * - The red component is represented by the 3 most significant bits.\n * - The green component is represented by the next 3 bits.\n * - The blue component is represented by the 2 least significant bits.\n *\n * @param r - The red component of the color (0-255).\n * @param g - The green component of the color (0-255).\n * @param b - The blue component of the color (0-255).\n * @returns The RGB332 representation of the color as an 8-bit number.\n */\nconst rgbToRgb332 = (r: number, g: number, b: number): number =>\n ((r >> 5) << 5) | ((g >> 5) << 2) | (b >> 6);\n\n/**\n * Encodes an RGBA frame into a specified format.\n *\n * @param rgba - A `Uint8ClampedArray` containing the RGBA pixel data of the frame.\n * @param format - The desired output format. Can be either `'base64'` or `'rgb332'`.\n * - `'base64'`: Encodes the frame as a Base64 string.\n * - `'rgb332'`: Encodes the frame using the RGB332 color format.\n * @param stripAlpha - A boolean indicating whether to exclude the alpha channel\n * from the encoding. If `true`, the alpha channel is removed.\n\n * @returns A string representing the encoded frame in the specified format.\n */\nexport function encodeFrame(\n rgba: Uint8ClampedArray,\n format: \"base64\" | \"rgb332\",\n stripAlpha: boolean\n): string {\n if (format === \"base64\") {\n const rgb = stripAlpha\n ? rgba.filter((_, i) => i % 4 !== 3)\n : Array.from(rgba);\n return btoa(String.fromCharCode(...rgb));\n } else {\n const rgb332: number[] = [];\n for (let i = 0; i < rgba.length; i += 4) {\n rgb332.push(rgbToRgb332(rgba[i], rgba[i + 1], rgba[i + 2]));\n }\n return String.fromCharCode(...rgb332);\n }\n}\n","import { EventBus } from \"../../../common\";\nimport { kosDependency, 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 { BrowserRouter, type KosBrowserRouter } from \"../browser-router\";\nimport type { DoneAware, Renderer } from \"../canvas-dispatcher\";\nimport { sendCanvasData } from \"../canvas-dispatcher/services\";\nimport { encodeFrame } from \"../canvas-dispatcher/utils/encode-frame\";\n\nimport type { CanvasRendererOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"canvas-renderer-model\";\n\nexport type CanvasRendererModel = PublicModelInterface<CanvasRendererModelImpl>;\n\nfunction isDoneAware(obj: any): obj is DoneAware {\n return typeof obj.onDone === \"function\";\n}\n@kosModel(MODEL_TYPE)\nexport class CanvasRendererModelImpl\n implements IKosDataModel, IKosIdentifiable\n{\n id: string;\n\n @kosDependency({\n modelType: BrowserRouter.type,\n })\n private router!: KosBrowserRouter;\n private logger: KosContextLogger;\n private _renderer: Renderer | null = null;\n private _clearOnComplete: boolean | undefined = undefined;\n private isStreaming = false;\n private renderLoopId: number | null = null;\n private sendIntervalId: ReturnType<typeof setInterval> | null = null;\n private timeoutId: ReturnType<typeof setTimeout> | null = null;\n private apiPath: string;\n private endpointName: string;\n width = 50;\n height = 30;\n fps = 10;\n durationMs: number | null = null;\n private _onFrame: ((dataString: string) => void) | null = null;\n\n constructor(\n modelId: string,\n options: CanvasRendererOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n this.width = options.width ?? 50;\n this.height = options.height ?? 30;\n this.fps = options.fps ?? 10;\n this.durationMs = options.durationMs ?? null;\n this.apiPath = options.apiPath ?? \"/api/system/canvas\";\n this.endpointName = options.endpoint;\n }\n\n set onFrame(callback: (dataString: string) => void) {\n this._onFrame = callback;\n }\n\n set renderer(renderer: Renderer | null) {\n if (this._renderer) {\n // If we already have a renderer, stop it first\n this.stopStreaming();\n this._renderer.dispose?.();\n }\n this._renderer = renderer;\n\n if (this.isStreaming) {\n // If we are currently streaming, restart the stream with the new renderer\n this.startStreaming();\n }\n }\n\n setClearOnComplete(clear: boolean | undefined) {\n this._clearOnComplete = clear;\n }\n\n /**\n * Sends a data frame to the canvas dispatcher.\n *\n * @param data - The data frame to be sent as a string.\n *\n * @remarks\n * This method is responsible for dispatching the provided data frame\n * to the canvas system using the `sendCanvasData` function.\n */\n sendDataFrame(data: string, apiPath?: string): void {\n sendCanvasData(data, apiPath);\n }\n\n checkStreaming() {\n // If one-shot renderer, stop after 1 frame\n if (this.isOneShotDone() || !this.isStreaming) {\n requestAnimationFrame(() => {\n // Don't clear canvas for one-shot renderers\n const isOneShot = this.isOneShotDone();\n this.stopStreaming(!isOneShot);\n });\n return;\n }\n }\n private handleFrame(rgba: Uint8ClampedArray) {\n const dataString = encodeFrame(rgba, \"base64\", true);\n this.sendDataFrame(dataString, this.apiPath);\n this._onFrame?.(dataString);\n }\n\n stopStreaming(clearCanvas = true) {\n this.logger.debug(`stopStreaming called with clearCanvas=${clearCanvas}`);\n this.isStreaming = false;\n if (this.renderLoopId) cancelAnimationFrame(this.renderLoopId);\n if (this.sendIntervalId) clearInterval(this.sendIntervalId);\n if (this.timeoutId) clearTimeout(this.timeoutId);\n this._renderer?.pause?.();\n\n // Clear the canvas by sending a blank frame (unless explicitly disabled)\n if (clearCanvas) {\n this.logger.debug(`Clearing canvas...`);\n this.clearCanvas();\n }\n }\n\n private clearCanvas(): void {\n // Use current dimensions if available, otherwise fall back to constructor defaults\n const canvasWidth = this.width > 0 ? this.width : 50; // Default from constructor\n const canvasHeight = this.height > 0 ? this.height : 30; // Default from constructor\n\n if (canvasWidth > 0 && canvasHeight > 0) {\n // Create a blank (black) frame\n const pixelCount = canvasWidth * canvasHeight * 4; // RGBA\n const blankPixels = new Uint8ClampedArray(pixelCount);\n // Array is initialized to 0s (black with 0 alpha), set alpha to 255 for solid black\n for (let i = 3; i < pixelCount; i += 4) {\n blankPixels[i] = 255; // Set alpha channel to fully opaque\n }\n\n // Send the blank frame\n const dataString = encodeFrame(blankPixels, \"base64\", true);\n this.logger.debug(\n `Sending clear frame: ${canvasWidth}x${canvasHeight}, apiPath: ${this.apiPath}`\n );\n this.sendDataFrame(dataString, this.apiPath);\n this._onFrame?.(dataString);\n }\n }\n\n isOneShotDone() {\n return (\n isDoneAware(this._renderer) &&\n this._renderer.isOneShot?.() === true &&\n (this._renderer as any).isOneShotDone\n );\n }\n\n startStreaming() {\n {\n if (!this._renderer) return;\n\n if (!this.apiPath) {\n this.logger.error(\n `No endpoint configured for canvas renderer ${this.id}`\n );\n return;\n }\n this.isStreaming = true;\n this._renderer.reset();\n this._renderer.play?.();\n\n const doneAware = isDoneAware(this._renderer);\n\n // Register completion callback for DoneAware renderers\n if (isDoneAware(this._renderer)) {\n this._renderer.onDone(() => {\n this.logger.debug(`Renderer completed for ${this.id}`);\n\n // Publish completion event to EventBus\n EventBus.publish(\"/canvas/renderer/completed\", {\n endpoint: this.endpointName,\n rendererId: this.id,\n rendererType: this._renderer?.constructor.name,\n timestamp: Date.now(),\n });\n\n // Determine whether to clear canvas on completion\n // Priority: explicit clearOnComplete > renderer type default\n let shouldClear = true;\n\n if (this._clearOnComplete !== undefined) {\n // Explicit setting takes precedence\n shouldClear = this._clearOnComplete;\n } else {\n // Default: clear for continuous renderers, keep for one-shot\n const isOneShot = (this._renderer as any)?.isOneShot?.() ?? false;\n shouldClear = !isOneShot;\n }\n\n this.stopStreaming(shouldClear);\n });\n }\n\n // Always render once immediately\n this._renderer.renderFrame(this.width, this.height);\n const initialPixels = this._renderer.readPixels?.(\n this.width,\n this.height\n );\n if (initialPixels && this._onFrame) {\n this.handleFrame(initialPixels);\n }\n\n // If one-shot renderer, stop after 1 frame\n if (this.isOneShotDone()) {\n requestAnimationFrame(() => {\n // Don't clear canvas for one-shot renderers\n this.stopStreaming(false);\n });\n return;\n }\n\n // Start rendering loop\n const renderLoop = () => {\n this._renderer?.renderFrame(this.width, this.height);\n this.renderLoopId = requestAnimationFrame(renderLoop);\n };\n this.renderLoopId = requestAnimationFrame(renderLoop);\n\n // Stream pixel data\n this.sendIntervalId = setInterval(() => {\n const pixels = this._renderer?.readPixels?.(this.width, this.height);\n if (pixels && this._onFrame) {\n this.handleFrame(pixels);\n this.checkStreaming();\n }\n }, 1000 / this.fps);\n\n // Stop non-DoneAware renderers after a fixed duration\n if (!doneAware && this.durationMs != null) {\n this.timeoutId = setTimeout(() => {\n this.stopStreaming();\n }, this.durationMs);\n }\n }\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing canvas-renderer ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading canvas-renderer ${this.id}`);\n\n this.router.use(\n \"POST\",\n `/api/ui/canvas/${this.endpointName}/stop`,\n async (_req, res) => {\n this.logger.debug(`HTTP stop endpoint called for ${this.endpointName}`);\n this.stopStreaming();\n res.send({ status: \"OK\" });\n }\n );\n\n this.router.use(\n \"POST\",\n `/api/ui/canvas/${this.endpointName}/start`,\n async (_req, res) => {\n this.startStreaming();\n\n res.send({ status: \"OK\" });\n }\n );\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { CanvasRendererModel } from \"./canvas-renderer-model\";\nimport { CanvasRendererModelImpl, MODEL_TYPE } from \"./canvas-renderer-model\";\nimport type { CanvasRendererOptions } from \"./types\";\n\n/**\n * # CanvasRenderer\n *\n * The registration bean includes convenience methods for creating and working with CanvasRendererModel 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: CanvasRenderer.type, id: \"canvasRendererId\"})\n * private canvasRendererModel: CanvasRendererModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new CanvasRendererModel 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 = CanvasRenderer.factory(\"canvasRendererId\")({\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 CanvasRendererModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (CanvasRenderer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to CanvasRendererModel\n * // and the compiler will know that the model has the CanvasRendererModel 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 { CanvasRenderer } 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(CanvasRenderer);\n * ```\n *\n * ## registration.singleton\n \n * The canvasRenderer 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 CanvasRenderer = new KosModelRegistrationFactory<\n CanvasRendererModel,\n CanvasRendererOptions\n>({\n class: CanvasRendererModelImpl,\n type: MODEL_TYPE,\n});\n","import type { DoneAware, Renderer } from \"../../../types\";\n\n/**\n * A base class for rendering video frames using a 2D canvas.\n *\n * Provides utilities for frame capture, playback control, and detecting when a video has finished playing.\n * Implements the `Renderer` and `DoneAware` interfaces to integrate with a unified animation/rendering system.\n */\nexport class VideoRendererBase implements Renderer, DoneAware {\n /** The underlying HTML video element used as the media source */\n protected video: HTMLVideoElement;\n\n /** Internal offscreen canvas used to draw current video frame */\n protected canvas: HTMLCanvasElement;\n\n /** 2D rendering context for the offscreen canvas */\n protected ctx: CanvasRenderingContext2D;\n\n /** Timestamp of the last update (used for throttling if needed) */\n protected lastUpdate = 0;\n\n /** Callback to invoke when video playback completes */\n private doneCallback: (() => void) | null = null;\n\n /**\n * Constructs a video renderer that will play and extract pixels from the provided source.\n *\n * @param src - The URL or path of the video to play\n */\n constructor({ src }: { src: string }) {\n this.video = document.createElement(\"video\");\n this.video.src = src;\n this.video.crossOrigin = \"anonymous\"; // Allow CORS-safe use in canvas\n this.video.muted = true; // Prevent autoplay restrictions\n this.video.loop = false; // We trigger done manually when finished\n\n this.canvas = document.createElement(\"canvas\");\n const ctx = this.canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"2D canvas not supported\");\n this.ctx = ctx;\n\n this.handleEnded = this.handleEnded.bind(this);\n this.video.addEventListener(\"ended\", this.handleEnded);\n }\n\n private handleEnded(): void {\n if (this.doneCallback) this.doneCallback();\n }\n /**\n * Resets the video to the beginning and pauses playback.\n */\n reset(): void {\n this.video.pause();\n this.video.currentTime = 0;\n this.lastUpdate = performance.now();\n }\n\n /**\n * Starts or resumes playback of the video.\n */\n play(): void {\n this.video.play().catch(console.warn); // Prevent unhandled promise if autoplay fails\n }\n\n /**\n * Pauses video playback.\n */\n pause(): void {\n this.video.pause();\n }\n\n /**\n * Draws the current video frame onto the offscreen canvas at the given resolution.\n *\n * @param width - Desired canvas width\n * @param height - Desired canvas height\n */\n renderFrame(width: number, height: number): void {\n this.canvas.width = width;\n this.canvas.height = height;\n\n if (this.video.readyState >= 2) {\n this.ctx.drawImage(this.video, 0, 0, width, height);\n }\n }\n\n /**\n * Extracts the most recently rendered frame's pixel data as a flat RGBA array.\n *\n * @param width - Width of the canvas area to extract\n * @param height - Height of the canvas area to extract\n * @returns A Uint8ClampedArray containing RGBA values\n */\n readPixels(width: number, height: number): Uint8ClampedArray {\n return this.ctx.getImageData(0, 0, width, height).data;\n }\n\n /**\n * Registers a callback to be invoked once the video finishes playing.\n *\n * @param callback - Function to call on video end\n */\n onDone(callback: () => void): void {\n this.doneCallback = callback;\n }\n\n dispose(): void {\n this.video.pause();\n this.video.removeAttribute(\"src\");\n this.video.load(); // Unload the video data\n this.video.remove(); // Remove from DOM if ever added\n\n this.video.removeEventListener(\"ended\", this.handleEnded);\n this.doneCallback = null;\n }\n\n /**\n * Utility method for timing-based frame updates (optional use).\n *\n * @param intervalMs - Minimum time between steps in milliseconds\n * @returns `true` if enough time has passed to trigger a new update\n */\n protected shouldStep(intervalMs: number): boolean {\n const now = performance.now();\n if (now - this.lastUpdate >= intervalMs) {\n this.lastUpdate = now;\n return true;\n }\n return false;\n }\n}\n","import type { Renderer } from \"../../../types\";\n\n/**\n * Abstract base class for WebGL-based renderers.\n *\n * Provides a shared WebGL canvas, rendering context, and utility methods for\n * consistent pixel reading and throttled animation timing.\n */\nexport abstract class WebGLRendererBase implements Renderer {\n /** The internal offscreen canvas used for rendering */\n protected canvas: HTMLCanvasElement;\n\n /** The WebGL rendering context used to draw and sample frames */\n protected gl: WebGLRenderingContext;\n\n /** The last known canvas width used for reading pixels */\n protected lastWidth = 0;\n\n /** The last known canvas height used for reading pixels */\n protected lastHeight = 0;\n\n /** Timestamp of the last frame update used for throttling */\n protected lastUpdate = 0;\n\n constructor() {\n this.canvas = document.createElement(\"canvas\");\n const gl = this.canvas.getContext(\"webgl\");\n if (!gl) throw new Error(\"WebGL not supported\");\n this.gl = gl;\n }\n\n /**\n * Reset the internal renderer state.\n * Must be implemented by subclasses to reset animation state.\n */\n abstract reset(): void;\n\n /**\n * Render a frame at the given resolution into the internal WebGL canvas.\n * This method should perform the draw but not return the pixels.\n *\n * @param width - The width of the canvas to render to\n * @param height - The height of the canvas to render to\n */\n abstract renderFrame(width: number, height: number): void;\n\n /**\n * Throttle rendering logic based on a minimum time interval.\n *\n * @param intervalMs - The minimum time in milliseconds between steps\n * @returns `true` if enough time has passed to perform a new step\n */\n protected shouldStep(intervalMs: number): boolean {\n const now = performance.now();\n if (now - this.lastUpdate >= intervalMs) {\n this.lastUpdate = now;\n return true;\n }\n return false;\n }\n\n /**\n * Read and return the current pixel buffer from the WebGL canvas.\n * The result is vertically flipped to match 2D canvas expectations.\n *\n * @param width - Optional override for width (defaults to `lastWidth`)\n * @param height - Optional override for height (defaults to `lastHeight`)\n * @returns A `Uint8ClampedArray` of RGBA pixel data\n */\n readPixels(\n width = this.lastWidth,\n height = this.lastHeight\n ): Uint8ClampedArray {\n const pixels = new Uint8Array(width * height * 4);\n this.gl.readPixels(\n 0,\n 0,\n width,\n height,\n this.gl.RGBA,\n this.gl.UNSIGNED_BYTE,\n pixels\n );\n\n // WebGL stores pixels from bottom-to-top; flip to match top-to-bottom\n const flipped = new Uint8ClampedArray(pixels.length);\n for (let y = 0; y < height; y++) {\n const src = y * width * 4;\n const dst = (height - 1 - y) * width * 4;\n flipped.set(pixels.subarray(src, src + width * 4), dst);\n }\n\n return flipped;\n }\n}\n","import type { Renderer } from \"../../types\";\nimport { WebGLRendererBase } from \"./base/webgl-base-renderer\";\n\n/**\n * A WebGL-based renderer that creates a vertical color-drop animation.\n *\n * This renderer simulates falling color bands (like a waterfall or rain)\n * by animating a vertical gradient of hues within a specified hue range.\n *\n * The animation is driven by a shader program and controlled through\n * uniform parameters including `hueOffset`, `minHue`, and `maxHue`.\n */\nexport class DropRenderer extends WebGLRendererBase implements Renderer {\n // Shader program and related attribute/uniform handles\n private program: WebGLProgram;\n private posBuffer: WebGLBuffer;\n private aPosition: number;\n private uMinHue: WebGLUniformLocation;\n private uMaxHue: WebGLUniformLocation;\n private uHueOffset: WebGLUniformLocation;\n private uGridHeight: WebGLUniformLocation;\n\n // Animation state\n private minHue = 0;\n private maxHue = 80;\n private hueOffset = 0;\n private speedPx = 1; // vertical scroll speed in pixels per update\n\n /**\n * Creates a new DropRenderer with the specified scroll speed.\n * @param speedPx - The vertical speed in pixels per update cycle.\n */\n constructor({ speedPx = 1 }: { speedPx?: number } = {}) {\n super();\n this.speedPx = speedPx;\n\n const gl = this.gl;\n\n const vertexShaderSource = `\n attribute vec2 a_position;\n void main() {\n gl_Position = vec4(a_position, 0, 1);\n }\n `;\n\n const fragmentShaderSource = `\n precision mediump float;\n uniform float minHue;\n uniform float maxHue;\n uniform float hueOffset;\n uniform float gridHeight;\n\n vec3 hslToRgb(float h, float s, float l) {\n float c = (1.0 - abs(2.0 * l - 1.0)) * s;\n float x = c * (1.0 - abs(mod(h * 6.0, 2.0) - 1.0));\n float m = l - c / 2.0;\n vec3 rgb;\n\n if (h < 1.0/6.0) rgb = vec3(c, x, 0.0);\n else if (h < 2.0/6.0) rgb = vec3(x, c, 0.0);\n else if (h < 3.0/6.0) rgb = vec3(0.0, c, x);\n else if (h < 4.0/6.0) rgb = vec3(0.0, x, c);\n else if (h < 5.0/6.0) rgb = vec3(x, 0.0, c);\n else rgb = vec3(c, 0.0, x);\n\n return rgb + vec3(m);\n }\n\n void main() {\n float relY = mod((1.0 - gl_FragCoord.y / gridHeight) - hueOffset, 1.0);\n float hue = minHue + relY * (maxHue - minHue);\n vec3 rgb = hslToRgb(hue, 1.0, 0.5);\n gl_FragColor = vec4(rgb, 1.0);\n }\n `;\n\n // Compile and link shaders\n const vertexShader = this.compileShader(\n gl.VERTEX_SHADER,\n vertexShaderSource\n );\n const fragmentShader = this.compileShader(\n gl.FRAGMENT_SHADER,\n fragmentShaderSource\n );\n this.program = this.createProgram(vertexShader, fragmentShader);\n\n // Set up vertex buffer for a full-screen quad\n this.posBuffer = gl.createBuffer()!;\n gl.bindBuffer(gl.ARRAY_BUFFER, this.posBuffer);\n gl.bufferData(\n gl.ARRAY_BUFFER,\n new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),\n gl.STATIC_DRAW\n );\n\n // Locate attribute and uniform bindings\n this.aPosition = gl.getAttribLocation(this.program, \"a_position\");\n this.uMinHue = gl.getUniformLocation(this.program, \"minHue\")!;\n this.uMaxHue = gl.getUniformLocation(this.program, \"maxHue\")!;\n this.uHueOffset = gl.getUniformLocation(this.program, \"hueOffset\")!;\n this.uGridHeight = gl.getUniformLocation(this.program, \"gridHeight\")!;\n }\n\n /**\n * Resets the renderer's animation state to its initial values.\n */\n reset(): void {\n this.hueOffset = 0;\n this.lastUpdate = performance.now();\n }\n\n /**\n * Renders a new frame by updating hueOffset and redrawing the gradient.\n *\n * @param width - Width of the output frame\n * @param height - Height of the output frame\n */\n renderFrame(width: number, height: number): void {\n const gl = this.gl;\n this.canvas.width = width;\n this.canvas.height = height;\n\n if (this.shouldStep(50)) {\n // Convert pixel-based speed to relative offset (0 to 1)\n const normalizedSpeed = this.speedPx / height;\n this.hueOffset = (this.hueOffset + normalizedSpeed) % 1.0;\n }\n\n gl.viewport(0, 0, width, height);\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.useProgram(this.program);\n\n gl.enableVertexAttribArray(this.aPosition);\n gl.bindBuffer(gl.ARRAY_BUFFER, this.posBuffer);\n gl.vertexAttribPointer(this.aPosition, 2, gl.FLOAT, false, 0, 0);\n\n // Pass uniforms to shader\n gl.uniform1f(this.uMinHue, this.minHue / 360.0);\n gl.uniform1f(this.uMaxHue, this.maxHue / 360.0);\n gl.uniform1f(this.uHueOffset, this.hueOffset);\n gl.uniform1f(this.uGridHeight, height);\n\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n }\n\n /**\n * Compiles a GLSL shader of the given type.\n *\n * @param type - gl.VERTEX_SHADER or gl.FRAGMENT_SHADER\n * @param source - GLSL source code\n * @returns The compiled shader object\n */\n private compileShader(type: number, source: string): WebGLShader {\n const shader = this.gl.createShader(type)!;\n this.gl.shaderSource(shader, source);\n this.gl.compileShader(shader);\n if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {\n throw new Error(\n this.gl.getShaderInfoLog(shader) || \"Shader compile failed\"\n );\n }\n return shader;\n }\n\n /**\n * Links a vertex and fragment shader into a complete WebGL program.\n *\n * @param vertexShader - Compiled vertex shader\n * @param fragmentShader - Compiled fragment shader\n * @returns The linked WebGL program\n */\n private createProgram(\n vertexShader: WebGLShader,\n fragmentShader: WebGLShader\n ): WebGLProgram {\n const program = this.gl.createProgram()!;\n this.gl.attachShader(program, vertexShader);\n this.gl.attachShader(program, fragmentShader);\n this.gl.linkProgram(program);\n if (!this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) {\n throw new Error(\"Program linking failed\");\n }\n return program;\n }\n}\n","import type { Renderer } from \"../../../types\";\n\n/**\n * An abstract base class for 2D canvas rendering. This class provides a foundational\n * implementation for managing a canvas element and its 2D rendering context, as well\n * as utility methods for rendering and pixel data extraction.\n *\n * Subclasses must implement the `reset` and `renderFrame` methods to define specific\n * rendering behavior.\n *\n * @implements Renderer\n */\nexport abstract class Canvas2DRendererBase implements Renderer {\n protected canvas: HTMLCanvasElement;\n protected ctx: CanvasRenderingContext2D;\n protected lastUpdate = 0;\n\n constructor() {\n this.canvas = document.createElement(\"canvas\");\n const ctx = this.canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"2D canvas not supported\");\n this.ctx = ctx;\n }\n\n dispose(): void {\n this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);\n this.canvas.remove();\n }\n /**\n * Determines whether a specified time interval has elapsed since the last update.\n *\n * @param intervalMs - The time interval in milliseconds to check against.\n * @returns `true` if the elapsed time since the last update is greater than or equal to the specified interval; otherwise, `false`.\n */\n protected shouldStep(intervalMs: number): boolean {\n const now = performance.now();\n if (now - this.lastUpdate >= intervalMs) {\n this.lastUpdate = now;\n return true;\n }\n return false;\n }\n abstract reset(): void;\n abstract renderFrame(width: number, height: number): void;\n\n /**\n * Reads pixel data from the canvas context within the specified width and height.\n *\n * @param width - The width of the area to read pixels from, starting at the top-left corner (0, 0).\n * @param height - The height of the area to read pixels from, starting at the top-left corner (0, 0).\n * @returns A `Uint8ClampedArray` containing the RGBA pixel data for the specified area.\n */\n readPixels(width: number, height: number): Uint8ClampedArray {\n return this.ctx.getImageData(0, 0, width, height).data;\n }\n}\n","import type { OneShotCapable } from \"../../../types\";\n\nexport type AbstractConstructor<T = any> = abstract new (...args: any[]) => T;\n\nexport function OneShotRendererMixin<TBase extends AbstractConstructor>(\n Base: TBase\n): AbstractConstructor<InstanceType<TBase> & OneShotCapable> {\n abstract class Mixin extends Base implements OneShotCapable {\n private doneCallback: (() => void) | null = null;\n private oneShotDone = false;\n\n isOneShot(): boolean {\n return true;\n }\n\n onDone(cb: () => void): void {\n this.doneCallback = cb;\n }\n\n public signalDoneIfNeeded(): void {\n if (!this.oneShotDone) {\n this.doneCallback?.();\n this.oneShotDone = true;\n }\n }\n\n public resetOneShot(): void {\n this.doneCallback = null;\n this.oneShotDone = false;\n }\n\n public get isOneShotDone(): boolean {\n return this.oneShotDone;\n }\n }\n\n return Mixin as unknown as AbstractConstructor<\n InstanceType<TBase> & OneShotCapable\n >;\n}\n","import type { OneShotCapable, Renderer } from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { OneShotRendererMixin } from \"./mixins/one-shot-renderer-mixin\";\n\nconst GradientBase = OneShotRendererMixin(Canvas2DRendererBase);\n\nexport type GradientDirection = \"horizontal\" | \"vertical\" | \"radial\";\n\nexport class GradientRenderer\n extends GradientBase\n implements Renderer, OneShotCapable\n{\n private offset = 0;\n private speed: number;\n private colors: string[];\n private direction: GradientDirection;\n private loop: boolean;\n\n constructor({\n colors = [\"red\", \"yellow\", \"green\"],\n direction = \"horizontal\",\n speed = 2,\n loop = true,\n }: {\n colors?: string[];\n direction?: GradientDirection;\n speed?: number;\n loop?: boolean;\n } = {}) {\n super();\n this.colors = colors;\n this.direction = direction;\n this.speed = speed;\n this.loop = loop;\n }\n\n override reset(): void {\n this.offset = 0;\n this.lastUpdate = performance.now();\n if (!this.loop) this.resetOneShot();\n }\n\n override renderFrame(width: number, height: number): void {\n if (!this.loop && this.isOneShotDone) return;\n\n // Only update offset if looping\n if (this.loop && this.shouldStep(50)) {\n this.offset += this.speed;\n }\n\n const startX = this.loop ? -this.offset : 0;\n const endX = this.loop ? width * 2 - this.offset : width;\n\n const gradient = this.ctx.createLinearGradient(startX, 0, endX, 0);\n const step = 1 / (this.colors.length - 1);\n this.colors.forEach((color, i) => {\n gradient.addColorStop(i * step, color);\n });\n\n this.ctx.fillStyle = gradient;\n this.ctx.fillRect(0, 0, width, height);\n\n // If one-shot, signal done right after rendering once\n if (!this.loop && !this.isOneShotDone) {\n this.signalDoneIfNeeded();\n }\n }\n}\n","import type { OneShotCapable, Renderer } from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { OneShotRendererMixin } from \"./mixins/one-shot-renderer-mixin\";\n\nconst Base = OneShotRendererMixin(Canvas2DRendererBase);\n\nexport class ImageRenderer extends Base implements Renderer, OneShotCapable {\n private img: HTMLImageElement;\n private loaded = false;\n\n constructor({ src }: { src: string }) {\n super();\n this.img = new Image();\n this.img.src = src;\n this.img.crossOrigin = \"anonymous\";\n\n this.img.onload = () => {\n this.loaded = true;\n // this.signalDoneIfNeeded();\n };\n }\n\n override reset(): void {\n this.resetOneShot();\n // Optionally reset loaded state if reusing src dynamically\n }\n\n override renderFrame(width: number, height: number): void {\n if (!this.loaded || this.isOneShotDone) return;\n\n this.canvas.width = width;\n this.canvas.height = height;\n this.ctx.drawImage(this.img, 0, 0, width, height);\n\n this.signalDoneIfNeeded();\n }\n}\n","import type { VideoRenderDataSpecification } from \"../../types\";\nimport { VideoRendererBase } from \"./base/video-base-renderer\";\n\n/**\n * Enhanced video renderer with configurable looping support.\n *\n * Supports:\n * - Infinite looping (loop: true)\n * - Fixed number of loops (loop: number)\n * - Single play (loop: false or undefined)\n * - Start/end time trimming\n */\nexport class LoopingVideoRenderer extends VideoRendererBase {\n private loopConfig: boolean | number;\n private currentLoopCount = 0;\n private startTime: number;\n private endTime: number | null;\n private completionCallback: (() => void) | null = null;\n\n constructor(data: VideoRenderDataSpecification) {\n super(data);\n\n this.loopConfig = data.loop ?? false;\n this.startTime = data.startTime ?? 0;\n this.endTime = data.endTime ?? null;\n\n // Remove the base class ended handler and use our own\n this.video.removeEventListener(\"ended\", (this as any).handleEnded);\n this.video.addEventListener(\"ended\", this.handleVideoEnd.bind(this));\n\n // Set initial start time if specified\n if (this.startTime > 0) {\n this.video.currentTime = this.startTime;\n }\n\n // Handle end time if specified\n if (this.endTime !== null) {\n this.video.addEventListener(\n \"timeupdate\",\n this.handleTimeUpdate.bind(this)\n );\n }\n }\n\n private handleTimeUpdate(): void {\n if (this.endTime !== null && this.video.currentTime >= this.endTime) {\n this.handleVideoEnd();\n }\n }\n\n private handleVideoEnd(): void {\n if (this.loopConfig === true) {\n // Infinite loop\n this.video.currentTime = this.startTime;\n this.video.play().catch(console.warn);\n } else if (\n typeof this.loopConfig === \"number\" &&\n this.currentLoopCount < this.loopConfig - 1\n ) {\n // Still have loops remaining\n this.currentLoopCount++;\n this.video.currentTime = this.startTime;\n this.video.play().catch(console.warn);\n } else {\n // All loops complete or single play done\n this.video.pause();\n if (this.completionCallback) {\n this.completionCallback();\n }\n }\n }\n\n override reset(): void {\n super.reset();\n this.currentLoopCount = 0;\n this.video.currentTime = this.startTime;\n }\n\n override onDone(callback: () => void): void {\n this.completionCallback = callback;\n }\n\n /**\n * Returns true if this renderer should only play once (no looping)\n */\n isOneShot(): boolean {\n return this.loopConfig === false || this.loopConfig === 1;\n }\n\n override dispose(): void {\n this.video.removeEventListener(\"ended\", this.handleVideoEnd);\n this.video.removeEventListener(\"timeupdate\", this.handleTimeUpdate);\n this.completionCallback = null;\n super.dispose();\n }\n}\n","/**\n * Color utility functions for canvas renderers\n */\n\nexport interface RgbColor {\n r: number;\n g: number;\n b: number;\n}\n\n/**\n * Converts a hex color string to RGB values\n * @param hex - Hex color string (with or without #, e.g., \"#ff0000\", \"ff0000\", \"#f00\", \"f00\")\n * @returns RGB color object with r, g, b values (0-255)\n * @throws Error if hex string is invalid\n */\nexport function hexToRgb(hex: string): RgbColor {\n // Remove # if present\n const cleanHex = hex.replace(\"#\", \"\");\n\n // Validate hex string\n if (!/^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(cleanHex)) {\n throw new Error(`Invalid hex color: ${hex}`);\n }\n\n let r: number, g: number, b: number;\n\n if (cleanHex.length === 3) {\n // Short form: \"f0a\" -> \"ff00aa\"\n r = parseInt(cleanHex[0] + cleanHex[0], 16);\n g = parseInt(cleanHex[1] + cleanHex[1], 16);\n b = parseInt(cleanHex[2] + cleanHex[2], 16);\n } else {\n // Long form: \"ff00aa\"\n r = parseInt(cleanHex.substring(0, 2), 16);\n g = parseInt(cleanHex.substring(2, 4), 16);\n b = parseInt(cleanHex.substring(4, 6), 16);\n }\n\n return { r, g, b };\n}\n\n/**\n * Normalizes a color value to RGB format\n * @param color - Either an RGB object or hex string\n * @returns RGB color object with r, g, b values (0-255)\n */\nexport function normalizeColor(color: RgbColor | string): RgbColor {\n if (typeof color === \"string\") {\n return hexToRgb(color);\n }\n return color;\n}\n\n/**\n * Converts RGB values to a CSS-compatible rgb() string\n * @param color - RGB color object or hex string\n * @returns CSS rgb() string, e.g., \"rgb(255,0,0)\"\n */\nexport function toRgbString(color: RgbColor | string): string {\n const rgb = normalizeColor(color);\n return `rgb(${rgb.r},${rgb.g},${rgb.b})`;\n}\n\n/**\n * Converts RGB values to hex string\n * @param color - RGB color object\n * @returns Hex color string with # prefix, e.g., \"#ff0000\"\n */\nexport function rgbToHex(color: RgbColor): string {\n const toHex = (n: number) =>\n Math.max(0, Math.min(255, Math.round(n)))\n .toString(16)\n .padStart(2, \"0\");\n return `#${toHex(color.r)}${toHex(color.g)}${toHex(color.b)}`;\n}\n","import type { Renderer, MatrixRenderDataSpecification } from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { normalizeColor } from \"../color-utils\";\n\n/**\n * A falling-character visual effect inspired by the Matrix.\n *\n * This renderer creates animated vertical columns of glowing characters that fall\n * at different speeds and randomness, using a 2D canvas buffer.\n */\nexport class MatrixRenderer extends Canvas2DRendererBase implements Renderer {\n /** Tracks the Y position of the falling highlight in each column */\n private columns: number[] = [];\n\n /** Probability that a column will advance during an update */\n private fallChance: number;\n\n /** Vertical step size (in pixels) for falling columns */\n private speed: number;\n\n /** Base color for the matrix rain effect */\n private baseColor: { r: number; g: number; b: number };\n\n /** Calculated colors for different trail positions */\n private trailColors: Array<{ r: number; g: number; b: number }>;\n\n /**\n * Constructs a Matrix-style renderer.\n *\n * @param data - Matrix renderer configuration\n */\n constructor(data: MatrixRenderDataSpecification = {}) {\n super();\n this.speed = data.speed ?? 1;\n this.fallChance = data.fallChance ?? 0.7;\n\n // Default to cyan if no color provided, normalize color if provided\n if (data.baseColor) {\n this.baseColor = normalizeColor(data.baseColor);\n } else {\n this.baseColor = { r: 0, g: 255, b: 255 }; // Default cyan\n }\n\n // Pre-calculate trail colors based on the base color\n this.trailColors = this.calculateTrailColors();\n }\n\n /**\n * Calculates the trail colors based on the base color.\n * Creates a gradient from bright to dim for the trailing effect.\n */\n private calculateTrailColors(): Array<{ r: number; g: number; b: number }> {\n const trailLength = 5;\n const colors: Array<{ r: number; g: number; b: number }> = [];\n\n for (let i = 0; i <= trailLength; i++) {\n // Calculate fade factor (1.0 at head, decreasing towards tail)\n const fadeFactor = 1.0 - (i / trailLength) * 0.6; // Fade to 40% brightness\n\n colors.push({\n r: Math.floor(this.baseColor.r * fadeFactor),\n g: Math.floor(this.baseColor.g * fadeFactor),\n b: Math.floor(this.baseColor.b * fadeFactor),\n });\n }\n\n return colors;\n }\n\n /**\n * Resets all column positions and timing state.\n */\n reset(): void {\n this.columns = [];\n this.lastUpdate = performance.now();\n }\n\n /**\n * Renders the next frame of the animation into the internal canvas buffer.\n *\n * @param width - Width of the canvas in pixels\n * @param height - Height of the canvas in pixels\n */\n renderFrame(width: number, height: number): void {\n // Initialize columns randomly if width changed or first render\n if (this.columns.length !== width) {\n this.columns = Array(width)\n .fill(0)\n .map(() => Math.floor(Math.random() * height));\n }\n\n // Advance column positions based on fallChance and speed\n if (this.shouldStep(50)) {\n this.columns = this.columns.map((y) =>\n y > height + 5\n ? 0\n : y + (Math.random() < this.fallChance ? this.speed : 0)\n );\n }\n\n // Create a new pixel buffer\n const imageData = this.ctx.createImageData(width, height);\n const data = imageData.data;\n data.fill(0); // Fully transparent black base\n\n // Draw glow trails and leading dots for each column\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const colY = this.columns[x];\n let r = 0,\n g = 0,\n b = 0;\n\n if (y === colY) {\n // Brightest point - use the base color at full intensity\n r = this.baseColor.r;\n g = this.baseColor.g;\n b = this.baseColor.b;\n } else if (y < colY && y > colY - this.trailColors.length) {\n // Trailing glow - use pre-calculated trail colors\n const trailIndex = colY - y;\n if (trailIndex < this.trailColors.length) {\n const color = this.trailColors[trailIndex];\n r = color.r;\n g = color.g;\n b = color.b;\n }\n }\n\n const i = (y * width + x) * 4;\n data[i] = r;\n data[i + 1] = g;\n data[i + 2] = b;\n data[i + 3] = 255; // fully opaque\n }\n }\n\n // Write pixel buffer to canvas\n this.ctx.putImageData(imageData, 0, 0);\n }\n}\n","import type { DoneAware, Renderer } from \"../../types\";\n\n/**\n * Predefined overlay positions for easy positioning\n */\nexport type OverlayPosition =\n | \"top-left\"\n | \"top-center\"\n | \"top-right\"\n | \"center-left\"\n | \"center\"\n | \"center-right\"\n | \"bottom-left\"\n | \"bottom-center\"\n | \"bottom-right\";\n\n/**\n * Custom positioning with explicit coordinates\n */\nexport interface OverlayCustomPosition {\n x: number;\n y: number;\n}\n\n/**\n * Configuration for a single overlay icon\n */\nexport interface OverlayIconConfig {\n /** Image source for the overlay icon */\n src: string;\n /** Size of the overlay icon (width and height) */\n size: number;\n /** Position of the overlay - either predefined name or custom coordinates */\n position: OverlayPosition | OverlayCustomPosition;\n /** Optional offset from the position in pixels */\n offset?: { x?: number; y?: number };\n /** Optional opacity (0-1) */\n opacity?: number;\n /** Whether the overlay should always be visible (default: true) */\n persistent?: boolean;\n}\n\n/**\n * Configuration for overlay renderer\n */\nexport interface OverlayRenderDataSpecification {\n /** The base renderer configuration */\n baseRenderer: {\n type: string;\n data: any;\n };\n /** Array of overlay icons to display */\n overlays: OverlayIconConfig[];\n /** Whether overlays should remain visible after base renderer completes (default: true) */\n persistOverlaysOnComplete?: boolean;\n}\n\n/**\n * A renderer that wraps another renderer and adds static overlay icons\n * that are not affected by scrolling, scaling, or other transformations.\n */\nexport class OverlayRenderer implements Renderer, DoneAware {\n private baseRenderer: Renderer;\n private overlayIcons: Map<string, HTMLImageElement> = new Map();\n private overlayConfigs: OverlayIconConfig[];\n private loadedIcons = new Set<string>();\n private canvas: HTMLCanvasElement;\n private ctx: CanvasRenderingContext2D;\n private persistOverlaysOnComplete: boolean;\n private baseRendererCompleted = false;\n private completionCallback: (() => void) | null = null;\n private hasSignaledCompletion = false;\n\n constructor(\n data: OverlayRenderDataSpecification,\n rendererFactory: (type: string, data: any) => Renderer\n ) {\n // Create the base renderer\n this.baseRenderer = rendererFactory(\n data.baseRenderer.type,\n data.baseRenderer.data\n );\n this.overlayConfigs = data.overlays;\n this.persistOverlaysOnComplete = data.persistOverlaysOnComplete !== false; // Default to true\n\n // Create our own canvas for compositing\n this.canvas = document.createElement(\"canvas\");\n const ctx = this.canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"2D canvas not supported\");\n this.ctx = ctx;\n\n // Load overlay images\n this.loadOverlayImages();\n\n // Listen for base renderer completion if it supports DoneAware\n if (\n \"onDone\" in this.baseRenderer &&\n typeof this.baseRenderer.onDone === \"function\"\n ) {\n (this.baseRenderer as any).onDone(() => {\n this.baseRendererCompleted = true;\n // When base completes and we should NOT persist, signal our completion\n if (!this.persistOverlaysOnComplete && this.completionCallback) {\n this.completionCallback();\n }\n });\n }\n }\n\n private async loadOverlayImages(): Promise<void> {\n for (const overlay of this.overlayConfigs) {\n const img = new Image();\n img.crossOrigin = \"anonymous\";\n\n img.onload = () => {\n this.loadedIcons.add(overlay.src);\n };\n\n img.onerror = (error) => {\n console.error(`Failed to load overlay image: ${overlay.src}`, error);\n };\n\n img.src = overlay.src;\n this.overlayIcons.set(overlay.src, img);\n }\n }\n\n private calculateOverlayPosition(\n overlay: OverlayIconConfig,\n canvasWidth: number,\n canvasHeight: number\n ): { x: number; y: number } {\n let x: number;\n let y: number;\n\n if (typeof overlay.position === \"string\") {\n // Predefined position\n switch (overlay.position) {\n case \"top-left\":\n x = 0;\n y = 0;\n break;\n case \"top-center\":\n x = (canvasWidth - overlay.size) / 2;\n y = 0;\n break;\n case \"top-right\":\n x = canvasWidth - overlay.size;\n y = 0;\n break;\n case \"center-left\":\n x = 0;\n y = (canvasHeight - overlay.size) / 2;\n break;\n case \"center\":\n x = (canvasWidth - overlay.size) / 2;\n y = (canvasHeight - overlay.size) / 2;\n break;\n case \"center-right\":\n x = canvasWidth - overlay.size;\n y = (canvasHeight - overlay.size) / 2;\n break;\n case \"bottom-left\":\n x = 0;\n y = canvasHeight - overlay.size;\n break;\n case \"bottom-center\":\n x = (canvasWidth - overlay.size) / 2;\n y = canvasHeight - overlay.size;\n break;\n case \"bottom-right\":\n x = canvasWidth - overlay.size;\n y = canvasHeight - overlay.size;\n break;\n default:\n x = 0;\n y = 0;\n }\n } else {\n // Custom position\n x = overlay.position.x;\n y = overlay.position.y;\n }\n\n // Apply offset if provided\n if (overlay.offset) {\n x += overlay.offset.x || 0;\n y += overlay.offset.y || 0;\n }\n\n return { x, y };\n }\n\n reset(): void {\n this.baseRenderer.reset();\n this.baseRendererCompleted = false;\n this.hasSignaledCompletion = false;\n }\n\n renderFrame(width: number, height: number): void {\n // Set canvas size - this clears the canvas\n this.canvas.width = width;\n this.canvas.height = height;\n\n // Clear the canvas explicitly\n this.ctx.clearRect(0, 0, width, height);\n\n // If base renderer has completed and we persist overlays\n if (this.baseRendererCompleted && this.persistOverlaysOnComplete) {\n // Just render overlays on clear canvas\n this.renderOverlays(width, height);\n } else {\n // Normal operation: render base content + overlays\n\n // Call base renderer's renderFrame\n this.baseRenderer.renderFrame(width, height);\n\n // Get the base renderer's pixel data\n const basePixels = this.baseRenderer.readPixels(width, height);\n\n // Put base content on our canvas if it exists\n if (basePixels && basePixels.length > 0) {\n const imageData = new ImageData(\n basePixels as unknown as Uint8ClampedArray<ArrayBuffer>,\n width,\n height\n );\n this.ctx.putImageData(imageData, 0, 0);\n }\n\n // Render overlays on top\n this.renderOverlays(width, height);\n }\n }\n\n private renderOverlays(canvasWidth: number, canvasHeight: number): void {\n for (const overlay of this.overlayConfigs) {\n if (!overlay.persistent && overlay.persistent !== undefined) {\n continue; // Skip non-persistent overlays when not needed\n }\n\n const img = this.overlayIcons.get(overlay.src);\n if (!img || !this.loadedIcons.has(overlay.src)) {\n continue; // Skip if image not loaded\n }\n\n const position = this.calculateOverlayPosition(\n overlay,\n canvasWidth,\n canvasHeight\n );\n\n // Save context state\n this.ctx.save();\n\n // Apply opacity if specified\n if (overlay.opacity !== undefined) {\n this.ctx.globalAlpha = Math.max(0, Math.min(1, overlay.opacity));\n }\n\n // Draw the overlay icon\n this.ctx.drawImage(\n img,\n position.x,\n position.y,\n overlay.size,\n overlay.size\n );\n\n // Restore context state\n this.ctx.restore();\n }\n }\n\n readPixels(width: number, height: number): Uint8ClampedArray {\n // Return current canvas pixels\n return this.ctx.getImageData(0, 0, width, height).data;\n }\n\n play?(): void {\n if (this.baseRenderer.play) {\n this.baseRenderer.play();\n }\n }\n\n pause?(): void {\n if (this.baseRenderer.pause) {\n this.baseRenderer.pause();\n }\n }\n\n dispose?(): void {\n // Clean up overlay images\n this.overlayIcons.clear();\n this.loadedIcons.clear();\n\n // Clean up canvas\n this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);\n this.canvas.remove();\n\n // Dispose base renderer\n if (this.baseRenderer.dispose) {\n this.baseRenderer.dispose();\n }\n }\n\n // DoneAware implementation\n onDone(callback: () => void): void {\n this.completionCallback = callback;\n\n // If base renderer is already completed, we might need to call the callback\n if (this.hasSignaledCompletion) {\n callback();\n }\n }\n\n isOneShot?(): boolean {\n // Never act as one-shot if we persist overlays (we need to keep rendering them)\n if (this.persistOverlaysOnComplete) {\n return false;\n }\n\n // Otherwise, delegate to base renderer\n if (\n \"isOneShot\" in this.baseRenderer &&\n typeof this.baseRenderer.isOneShot === \"function\"\n ) {\n return (this.baseRenderer as any).isOneShot();\n }\n return false;\n }\n}\n","import type {\n DoneAware,\n ImageRenderDataSpecification,\n Renderer,\n} from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { toRgbString } from \"../color-utils\";\n\n/**\n * Enhanced image renderer with scrolling capabilities.\n *\n * Features:\n * - Smooth scrolling in any direction\n * - Configurable speed and gap\n * - Looping support\n * - Completion events when scroll finishes (if not looping)\n */\nexport class ScrollingImageRenderer\n extends Canvas2DRendererBase\n implements Renderer, DoneAware\n{\n private img: HTMLImageElement;\n private loaded = false;\n private scrollConfig: ImageRenderDataSpecification[\"scroll\"];\n private loopConfig: boolean | number;\n private duration: number | undefined;\n private pauseDuration: number;\n private colorOverride: ImageRenderDataSpecification[\"colorOverride\"];\n private originalSvgData: string | null = null;\n private position = 0;\n private startTime = 0;\n private lastFrameTime = 0;\n private currentLoopCount = 0;\n private completionCallback: (() => void) | null = null;\n private isPlaying = false;\n private completed = false;\n private isPaused = false;\n private pauseStartTime = 0;\n\n constructor(data: ImageRenderDataSpecification) {\n super();\n\n this.img = new Image();\n this.img.crossOrigin = \"anonymous\";\n\n this.scrollConfig = data.scroll;\n this.loopConfig = data.loop ?? false;\n this.duration = data.duration;\n this.pauseDuration = data.pauseBetweenLoops ?? 0;\n this.colorOverride = data.colorOverride;\n\n // Check if this is an SVG and we have color override\n if (this.colorOverride && data.src.toLowerCase().includes(\".svg\")) {\n this.loadAndProcessSvg(data.src);\n } else {\n this.img.src = data.src;\n }\n\n this.img.onload = () => {\n this.loaded = true;\n };\n\n this.img.onerror = (error) => {\n console.error(\"Failed to load image:\", error);\n };\n }\n\n override reset(): void {\n this.position = 0;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n this.currentLoopCount = 0;\n this.completed = false;\n this.isPlaying = false;\n this.isPaused = false;\n this.pauseStartTime = 0;\n }\n\n play(): void {\n if (!this.isPlaying) {\n this.isPlaying = true;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n }\n }\n\n pause(): void {\n this.isPlaying = false;\n }\n\n override renderFrame(width: number, height: number): void {\n if (!this.loaded) {\n // Image not loaded yet\n return;\n }\n\n if (this.completed) {\n // Animation completed - keep showing last frame\n return;\n }\n\n if (this.isPaused) {\n // During pause, show blank screen\n this.canvas.width = width;\n this.canvas.height = height;\n this.ctx.clearRect(0, 0, width, height);\n\n // Check if pause duration has elapsed\n if (this.pauseDuration > 0) {\n const pauseElapsed = performance.now() - this.pauseStartTime;\n if (pauseElapsed >= this.pauseDuration) {\n // End pause and start next loop\n this.isPaused = false;\n this.position = 0;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n }\n }\n return;\n }\n\n this.canvas.width = width;\n this.canvas.height = height;\n\n // Clear canvas\n this.ctx.clearRect(0, 0, width, height);\n\n if (!this.scrollConfig?.enabled) {\n // Static image display\n this.ctx.drawImage(this.img, 0, 0, width, height);\n\n // Check duration for static display\n if (this.duration && this.isPlaying) {\n const elapsed = performance.now() - this.startTime;\n if (elapsed >= this.duration) {\n this.handleCompletion();\n }\n }\n return;\n }\n\n // Scrolling logic\n const direction = this.scrollConfig.direction || \"left\";\n const speed = this.scrollConfig.speed || 50;\n const gap = this.scrollConfig.gap || 0;\n\n if (this.isPlaying) {\n const now = performance.now();\n const deltaTime = (now - this.lastFrameTime) / 1000; // Convert to seconds\n this.lastFrameTime = now;\n\n // Update position based on direction and speed\n const moveDistance = speed * deltaTime;\n\n switch (direction) {\n case \"left\":\n this.position += moveDistance; // Position increases as image moves left\n break;\n case \"right\":\n this.position += moveDistance;\n break;\n case \"up\":\n this.position += moveDistance; // Position increases as image moves up\n break;\n case \"down\":\n this.position += moveDistance;\n break;\n }\n }\n\n // Draw the scrolling image\n this.drawScrollingImage(width, height, direction, gap);\n\n // Check if scroll has completed one full cycle AFTER drawing\n // This ensures the last frame is drawn before stopping\n this.checkScrollCompletion(width, height, direction, gap);\n }\n\n private drawScrollingImage(\n width: number,\n height: number,\n direction: string,\n gap: number\n ): void {\n // Calculate image dimensions with aspect ratio\n const aspectRatio = this.img.width / this.img.height;\n let drawWidth: number;\n let drawHeight: number;\n\n if (this.scrollConfig?.maintainAspectRatio !== false) {\n // Maintain aspect ratio (default behavior)\n if (this.scrollConfig?.height) {\n // Height specified, calculate width\n drawHeight = this.scrollConfig.height;\n drawWidth = drawHeight * aspectRatio;\n } else if (this.scrollConfig?.width) {\n // Width specified, calculate height\n drawWidth = this.scrollConfig.width;\n drawHeight = drawWidth / aspectRatio;\n } else {\n // Default: fit to canvas height for horizontal scroll, width for vertical\n if (direction === \"left\" || direction === \"right\") {\n drawHeight = height;\n drawWidth = drawHeight * aspectRatio;\n } else {\n drawWidth = width;\n drawHeight = drawWidth / aspectRatio;\n }\n }\n } else {\n // Don't maintain aspect ratio - use specified dimensions or canvas size\n drawWidth = this.scrollConfig?.width || width;\n drawHeight = this.scrollConfig?.height || height;\n }\n\n // Calculate offsets for centering or explicit positioning\n let offsetX: number;\n let offsetY: number;\n\n // For horizontal scrolling, default Y to center, X to 0\n // For vertical scrolling, default X to center, Y to 0\n if (direction === \"left\" || direction === \"right\") {\n // Horizontal scrolling\n offsetX = 0; // X position is controlled by scrolling\n if (\n this.scrollConfig?.offsetY === \"center\" ||\n this.scrollConfig?.offsetY === undefined\n ) {\n offsetY = (height - drawHeight) / 2;\n } else {\n offsetY = this.scrollConfig.offsetY as number;\n }\n } else {\n // Vertical scrolling\n if (\n this.scrollConfig?.offsetX === \"center\" ||\n this.scrollConfig?.offsetX === undefined\n ) {\n offsetX = (width - drawWidth) / 2;\n } else {\n offsetX = this.scrollConfig.offsetX as number;\n }\n offsetY = 0; // Y position is controlled by scrolling\n }\n\n switch (direction) {\n case \"left\": {\n // Image moves from right to left\n // For images wider than canvas: we want the image to start fully off-screen right\n // and scroll left until it's fully off-screen left\n // Start position: left edge at right edge of canvas (x = width)\n // End position: right edge at left edge of canvas (x = -drawWidth)\n const xPos = width - this.position;\n\n // Draw main image if any part is visible\n if (xPos < width && xPos > -drawWidth) {\n this.ctx.drawImage(this.img, xPos, offsetY, drawWidth, drawHeight);\n }\n\n // If looping with gap (but not pause), draw the next image after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n this.position > gap\n ) {\n const nextXPos = xPos + drawWidth + gap;\n if (nextXPos < width) {\n this.ctx.drawImage(\n this.img,\n nextXPos,\n offsetY,\n drawWidth,\n drawHeight\n );\n }\n }\n break;\n }\n\n case \"right\": {\n // Image moves from left to right\n // Start position: off-screen left (-drawWidth)\n // End position: off-screen right (width)\n const xPos = -drawWidth + this.position;\n\n // Draw main image\n if (xPos > -drawWidth && xPos < width) {\n this.ctx.drawImage(this.img, xPos, offsetY, drawWidth, drawHeight);\n }\n\n // If looping with gap (but not pause), draw the next image after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n xPos - gap - drawWidth > -drawWidth\n ) {\n const nextXPos = xPos - drawWidth - gap;\n if (nextXPos < width) {\n this.ctx.drawImage(\n this.img,\n nextXPos,\n offsetY,\n drawWidth,\n drawHeight\n );\n }\n }\n break;\n }\n\n case \"up\": {\n // Image moves from bottom to top\n const yPos = height - this.position;\n\n // Draw main image\n if (yPos > -drawHeight && yPos < height) {\n this.ctx.drawImage(this.img, offsetX, yPos, drawWidth, drawHeight);\n }\n\n // If looping with gap (but not pause), draw the next image after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n yPos + drawHeight + gap < height\n ) {\n const nextYPos = yPos + drawHeight + gap;\n if (nextYPos > -drawHeight) {\n this.ctx.drawImage(\n this.img,\n offsetX,\n nextYPos,\n drawWidth,\n drawHeight\n );\n }\n }\n break;\n }\n\n case \"down\": {\n // Image moves from top to bottom\n const yPos = -drawHeight + this.position;\n\n // Draw main image\n if (yPos > -drawHeight && yPos < height) {\n this.ctx.drawImage(this.img, offsetX, yPos, drawWidth, drawHeight);\n }\n\n // If looping with gap (but not pause), draw the next image after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n yPos - gap - drawHeight > -drawHeight\n ) {\n const nextYPos = yPos - drawHeight - gap;\n if (nextYPos < height) {\n this.ctx.drawImage(\n this.img,\n offsetX,\n nextYPos,\n drawWidth,\n drawHeight\n );\n }\n }\n break;\n }\n }\n }\n\n private checkScrollCompletion(\n width: number,\n height: number,\n direction: string,\n gap: number\n ): void {\n if (!this.isPlaying) return;\n\n // Calculate the actual image dimensions - MUST match drawScrollingImage logic exactly\n const aspectRatio = this.img.width / this.img.height;\n let drawWidth: number;\n let drawHeight: number;\n\n if (this.scrollConfig?.maintainAspectRatio !== false) {\n if (this.scrollConfig?.height) {\n drawHeight = this.scrollConfig.height;\n drawWidth = drawHeight * aspectRatio;\n } else if (this.scrollConfig?.width) {\n drawWidth = this.scrollConfig.width;\n drawHeight = drawWidth / aspectRatio;\n } else {\n // Use passed canvas dimensions as default (not this.canvas)\n if (direction === \"left\" || direction === \"right\") {\n drawHeight = height;\n drawWidth = drawHeight * aspectRatio;\n } else {\n drawWidth = width;\n drawHeight = drawWidth / aspectRatio;\n }\n }\n } else {\n drawWidth = this.scrollConfig?.width || width;\n drawHeight = this.scrollConfig?.height || height;\n }\n\n let _cycleLength: number;\n\n switch (direction) {\n case \"left\":\n case \"right\":\n // Full cycle is when image travels completely across and off the screen\n // The image needs to travel: canvas width + image width\n _cycleLength = width + drawWidth;\n // Add gap only if we're looping for the next cycle\n if (this.loopConfig) {\n _cycleLength += gap;\n }\n break;\n case \"up\":\n case \"down\":\n // Full cycle is when image travels completely across and off the screen\n _cycleLength = height + drawHeight;\n // Add gap only if we're looping for the next cycle\n if (this.loopConfig) {\n _cycleLength += gap;\n }\n break;\n default:\n _cycleLength = 0;\n }\n\n // Check if we've completed a full cycle\n // For left/right scroll: image is off-screen when xPos <= -drawWidth (left) or xPos >= canvas.width (right)\n // For up/down scroll: image is off-screen when yPos <= -drawHeight (up) or yPos >= canvas.height (down)\n\n let isOffScreen = false;\n const buffer = 1; // Small buffer to ensure image is fully off-screen\n\n switch (direction) {\n case \"left\": {\n // Image has scrolled completely off the left edge\n const xPosLeft = width - this.position;\n isOffScreen = xPosLeft < -drawWidth - buffer;\n break;\n }\n case \"right\": {\n const xPosRight = -drawWidth + this.position;\n isOffScreen = xPosRight > width + buffer;\n break;\n }\n case \"up\": {\n const yPosUp = height - this.position;\n isOffScreen = yPosUp < -drawHeight - buffer;\n break;\n }\n case \"down\": {\n const yPosDown = -drawHeight + this.position;\n isOffScreen = yPosDown > height + buffer;\n break;\n }\n }\n\n if (isOffScreen) {\n if (\n this.loopConfig === false ||\n (typeof this.loopConfig === \"number\" && this.loopConfig === 1)\n ) {\n // Single play - stop\n this.handleCompletion();\n } else if (typeof this.loopConfig === \"number\" && this.loopConfig > 1) {\n // Limited loops\n this.currentLoopCount++;\n if (this.currentLoopCount >= this.loopConfig) {\n this.handleCompletion();\n } else {\n // Start pause before next loop\n this.startPauseOrNextLoop();\n }\n } else if (this.loopConfig === true) {\n // Infinite loop - start pause before next loop\n this.startPauseOrNextLoop();\n }\n }\n }\n\n private startPauseOrNextLoop(): void {\n if (this.pauseDuration > 0) {\n // Start pause with blank screen\n this.isPaused = true;\n this.pauseStartTime = performance.now();\n } else {\n // No pause configured, immediately start next loop\n this.position = 0;\n }\n }\n\n private handleCompletion(): void {\n this.completed = true;\n this.isPlaying = false;\n if (this.completionCallback) {\n this.completionCallback();\n }\n }\n\n onDone(callback: () => void): void {\n this.completionCallback = callback;\n }\n\n isOneShot(): boolean {\n return !this.scrollConfig?.enabled && !this.loopConfig;\n }\n\n private async loadAndProcessSvg(url: string): Promise<void> {\n try {\n const response = await fetch(url);\n const svgText = await response.text();\n this.originalSvgData = svgText;\n\n // Process the SVG with color override\n const processedSvg = this.applySvgColorOverride(svgText);\n\n // Convert to data URL\n const dataUrl = `data:image/svg+xml;base64,${btoa(processedSvg)}`;\n this.img.src = dataUrl;\n } catch (error) {\n console.error(\"Failed to load and process SVG:\", error);\n // Fallback to original URL\n this.img.src = url;\n }\n }\n\n private applySvgColorOverride(svgContent: string): string {\n if (!this.colorOverride) {\n return svgContent;\n }\n\n // Convert color to RGB string using utility function\n const newColor = toRgbString(this.colorOverride);\n\n // Replace common fill patterns in SVG\n const processedSvg = svgContent\n // Replace fill attributes\n .replace(/fill\\s*=\\s*[\"'][^\"']*[\"']/gi, `fill=\"${newColor}\"`)\n // Replace fill styles in style attributes\n .replace(/fill\\s*:\\s*[^;\"]*/gi, `fill:${newColor}`)\n // Replace stroke for outlined elements (optional - you might not want this)\n .replace(/stroke\\s*=\\s*[\"'][^\"']*[\"']/gi, `stroke=\"${newColor}\"`)\n .replace(/stroke\\s*:\\s*[^;\"]*/gi, `stroke:${newColor}`);\n\n return processedSvg;\n }\n\n override dispose(): void {\n this.img.removeAttribute(\"src\");\n this.completionCallback = null;\n this.originalSvgData = null;\n }\n}\n","import type {\n DoneAware,\n Renderer,\n TextRenderDataSpecification,\n} from \"../../types\";\nimport { toRgbString } from \"../color-utils\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\n\n/**\n * Enhanced text renderer with scrolling capabilities.\n *\n * Features:\n * - Smooth scrolling in any direction\n * - Configurable speed and gap\n * - Font size and family customization\n * - Color support with hex/RGB values\n * - Looping support\n * - Completion events when scroll finishes (if not looping)\n */\nexport class ScrollingTextRenderer\n extends Canvas2DRendererBase\n implements Renderer, DoneAware\n{\n private text: string;\n private lines: string[];\n private fontSize: number;\n private fontFamily: string;\n private lineHeight: number;\n private textColor: string;\n private scrollConfig: TextRenderDataSpecification[\"scroll\"];\n private loopConfig: boolean | number;\n private duration: number | undefined;\n private pauseDuration: number;\n private position = 0;\n private startTime = 0;\n private lastFrameTime = 0;\n private currentLoopCount = 0;\n private completionCallback: (() => void) | null = null;\n private isPlaying = false;\n private completed = false;\n private isPaused = false;\n private pauseStartTime = 0;\n\n // Text measurement cache\n private textWidth = 0;\n private textHeight = 0;\n private lineWidths: number[] = [];\n private textMeasured = false;\n\n constructor(data: TextRenderDataSpecification) {\n super();\n\n this.text = data.text;\n this.lines = data.text.split(\"\\n\");\n // Default to very small font size suitable for 30x50 LED panels (roughly 8-10 pixels high)\n this.fontSize = data.fontSize ?? 8;\n // Default line height with small spacing for LED panels\n this.lineHeight = data.lineHeight ?? this.fontSize + 2;\n // Use pixel-perfect monospace font stack - monospace ensures consistent character width\n this.fontFamily =\n data.fontFamily ?? \"monospace, 'Lucida Console', 'Courier New', Courier\";\n this.scrollConfig = data.scroll;\n this.loopConfig = data.loop ?? false;\n this.duration = data.duration;\n this.pauseDuration = data.pauseBetweenLoops ?? 0;\n\n // Set text color\n if (data.color) {\n this.textColor = toRgbString(data.color);\n } else {\n this.textColor = \"rgb(255,255,255)\"; // Default to white\n }\n }\n\n private measureText(): void {\n if (this.textMeasured) return;\n\n // Set up font for measurement\n this.ctx.font = `${this.fontSize}px ${this.fontFamily}`;\n\n // Measure each line individually\n this.lineWidths = [];\n let maxWidth = 0;\n\n for (const line of this.lines) {\n const metrics = this.ctx.measureText(line);\n const lineWidth = metrics.width;\n this.lineWidths.push(lineWidth);\n maxWidth = Math.max(maxWidth, lineWidth);\n }\n\n this.textWidth = maxWidth;\n // Total height is number of lines * line height\n this.textHeight = this.lines.length * this.lineHeight;\n this.textMeasured = true;\n }\n\n override reset(): void {\n this.position = 0;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n this.currentLoopCount = 0;\n this.completed = false;\n this.isPlaying = false;\n this.isPaused = false;\n this.pauseStartTime = 0;\n this.textMeasured = false; // Reset measurement cache\n this.lineWidths = []; // Reset line width cache\n }\n\n play(): void {\n if (!this.isPlaying) {\n this.isPlaying = true;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n }\n }\n\n pause(): void {\n this.isPlaying = false;\n }\n\n override renderFrame(width: number, height: number): void {\n this.canvas.width = width;\n this.canvas.height = height;\n\n // Measure text if not done yet\n this.measureText();\n\n if (this.completed) {\n // Animation completed - keep showing last frame\n return;\n }\n\n if (this.isPaused) {\n // During pause, show blank screen\n this.ctx.clearRect(0, 0, width, height);\n\n // Check if pause duration has elapsed\n if (this.pauseDuration > 0) {\n const pauseElapsed = performance.now() - this.pauseStartTime;\n if (pauseElapsed >= this.pauseDuration) {\n // End pause and start next loop\n this.isPaused = false;\n this.position = 0;\n this.startTime = performance.now();\n this.lastFrameTime = this.startTime;\n }\n }\n return;\n }\n\n // Clear canvas\n this.ctx.clearRect(0, 0, width, height);\n\n if (!this.scrollConfig?.enabled) {\n // Static text display\n this.drawStaticText(width, height);\n\n // Check duration for static display\n if (this.duration && this.isPlaying) {\n const elapsed = performance.now() - this.startTime;\n if (elapsed >= this.duration) {\n this.handleCompletion();\n }\n }\n return;\n }\n\n // Scrolling logic\n const direction = this.scrollConfig.direction || \"left\";\n const speed = this.scrollConfig.speed || 50;\n const gap = this.scrollConfig.gap || 0;\n\n if (this.isPlaying) {\n const now = performance.now();\n const deltaTime = (now - this.lastFrameTime) / 1000; // Convert to seconds\n this.lastFrameTime = now;\n\n // Update position based on direction and speed\n const moveDistance = speed * deltaTime;\n\n switch (direction) {\n case \"left\":\n case \"right\":\n case \"up\":\n case \"down\":\n this.position += moveDistance;\n break;\n }\n }\n\n // Draw the scrolling text\n this.drawScrollingText(width, height, direction, gap);\n\n // Check if scroll has completed one full cycle AFTER drawing\n this.checkScrollCompletion(width, height, direction);\n }\n\n private drawStaticText(width: number, height: number): void {\n // Set font and color\n this.ctx.font = `${this.fontSize}px ${this.fontFamily}`;\n this.ctx.fillStyle = this.textColor;\n this.ctx.textBaseline = \"top\";\n\n // Center the text block vertically\n const totalTextHeight = this.textHeight;\n const startY = (height - totalTextHeight) / 2;\n\n // Draw each line\n for (let i = 0; i < this.lines.length; i++) {\n const line = this.lines[i];\n const lineWidth = this.lineWidths[i];\n\n // Center each line horizontally\n const x = (width - lineWidth) / 2;\n const y = startY + i * this.lineHeight;\n\n this.ctx.fillText(line, x, y);\n }\n }\n\n private drawScrollingText(\n width: number,\n height: number,\n direction: string,\n gap: number\n ): void {\n // Set font and color\n this.ctx.font = `${this.fontSize}px ${this.fontFamily}`;\n this.ctx.fillStyle = this.textColor;\n this.ctx.textBaseline = \"top\";\n\n // Calculate base offsets for centering or explicit positioning\n let baseOffsetX: number;\n let baseOffsetY: number;\n\n // For horizontal scrolling, default Y to center, X to 0\n // For vertical scrolling, default X to center, Y to 0\n if (direction === \"left\" || direction === \"right\") {\n // Horizontal scrolling\n baseOffsetX = 0; // X position is controlled by scrolling\n if (\n this.scrollConfig?.offsetY === \"center\" ||\n this.scrollConfig?.offsetY === undefined\n ) {\n // Center the text block vertically\n baseOffsetY = (height - this.textHeight) / 2;\n } else {\n baseOffsetY = this.scrollConfig.offsetY as number;\n }\n } else {\n // Vertical scrolling\n if (\n this.scrollConfig?.offsetX === \"center\" ||\n this.scrollConfig?.offsetX === undefined\n ) {\n baseOffsetX = width / 2;\n this.ctx.textAlign = \"center\";\n } else {\n baseOffsetX = this.scrollConfig.offsetX as number;\n this.ctx.textAlign = \"left\";\n }\n baseOffsetY = 0; // Y position is controlled by scrolling\n }\n\n // Draw multi-line text for each direction\n this.drawMultiLineScrollText(\n direction,\n width,\n height,\n gap,\n baseOffsetX,\n baseOffsetY\n );\n }\n\n private drawMultiLineScrollText(\n direction: string,\n width: number,\n height: number,\n gap: number,\n baseOffsetX: number,\n baseOffsetY: number\n ): void {\n switch (direction) {\n case \"left\": {\n // Text moves from right to left\n const xPos = width - this.position;\n\n // Draw main text block if any part is visible\n if (xPos < width && xPos > -this.textWidth) {\n this.drawTextBlock(xPos, baseOffsetY, \"left\");\n }\n\n // If looping with gap (but not pause), draw the next text after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n this.position > gap\n ) {\n const nextXPos = xPos + this.textWidth + gap;\n if (nextXPos < width) {\n this.drawTextBlock(nextXPos, baseOffsetY, \"left\");\n }\n }\n break;\n }\n\n case \"right\": {\n // Text moves from left to right\n const xPos = -this.textWidth + this.position;\n\n // Draw main text block\n if (xPos > -this.textWidth && xPos < width) {\n this.drawTextBlock(xPos, baseOffsetY, \"left\");\n }\n\n // If looping with gap (but not pause), draw the next text after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n xPos - gap - this.textWidth > -this.textWidth\n ) {\n const nextXPos = xPos - this.textWidth - gap;\n if (nextXPos < width) {\n this.drawTextBlock(nextXPos, baseOffsetY, \"left\");\n }\n }\n break;\n }\n\n case \"up\": {\n // Text moves from bottom to top\n const yPos = height - this.position;\n\n // Draw main text block\n if (yPos > -this.textHeight && yPos < height) {\n this.drawTextBlock(baseOffsetX, yPos, \"center\");\n }\n\n // If looping with gap (but not pause), draw the next text after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n yPos + this.textHeight + gap < height\n ) {\n const nextYPos = yPos + this.textHeight + gap;\n if (nextYPos > -this.textHeight) {\n this.drawTextBlock(baseOffsetX, nextYPos, \"center\");\n }\n }\n break;\n }\n\n case \"down\": {\n // Text moves from top to bottom\n const yPos = -this.textHeight + this.position;\n\n // Draw main text block\n if (yPos > -this.textHeight && yPos < height) {\n this.drawTextBlock(baseOffsetX, yPos, \"center\");\n }\n\n // If looping with gap (but not pause), draw the next text after the gap\n if (\n this.loopConfig &&\n this.pauseDuration === 0 &&\n yPos - gap - this.textHeight > -this.textHeight\n ) {\n const nextYPos = yPos - this.textHeight - gap;\n if (nextYPos < height) {\n this.drawTextBlock(baseOffsetX, nextYPos, \"center\");\n }\n }\n break;\n }\n }\n }\n\n private drawTextBlock(\n x: number,\n y: number,\n alignment: \"left\" | \"center\"\n ): void {\n // Draw each line\n for (let i = 0; i < this.lines.length; i++) {\n const line = this.lines[i];\n const lineWidth = this.lineWidths[i];\n\n let lineX: number;\n if (alignment === \"center\") {\n // Center the line\n lineX = x - lineWidth / 2;\n } else {\n // Left align the line\n lineX = x;\n }\n\n const lineY = y + i * this.lineHeight;\n\n this.ctx.fillText(line, lineX, lineY);\n }\n }\n\n private checkScrollCompletion(\n width: number,\n height: number,\n direction: string\n ): void {\n if (!this.isPlaying) return;\n\n let isOffScreen = false;\n const buffer = 1; // Small buffer to ensure text is fully off-screen\n\n switch (direction) {\n case \"left\": {\n // Text has scrolled completely off the left edge\n const xPosLeft = width - this.position;\n isOffScreen = xPosLeft < -this.textWidth - buffer;\n break;\n }\n case \"right\": {\n const xPosRight = -this.textWidth + this.position;\n isOffScreen = xPosRight > width + buffer;\n break;\n }\n case \"up\": {\n const yPosUp = height - this.position;\n isOffScreen = yPosUp < -this.textHeight - buffer;\n break;\n }\n case \"down\": {\n const yPosDown = -this.textHeight + this.position;\n isOffScreen = yPosDown > height + buffer;\n break;\n }\n }\n\n if (isOffScreen) {\n if (\n this.loopConfig === false ||\n (typeof this.loopConfig === \"number\" && this.loopConfig === 1)\n ) {\n // Single play - stop\n this.handleCompletion();\n } else if (typeof this.loopConfig === \"number\" && this.loopConfig > 1) {\n // Limited loops\n this.currentLoopCount++;\n if (this.currentLoopCount >= this.loopConfig) {\n this.handleCompletion();\n } else {\n // Start pause before next loop\n this.startPauseOrNextLoop();\n }\n } else if (this.loopConfig === true) {\n // Infinite loop - start pause before next loop\n this.startPauseOrNextLoop();\n }\n }\n }\n\n private startPauseOrNextLoop(): void {\n if (this.pauseDuration > 0) {\n // Start pause with blank screen\n this.isPaused = true;\n this.pauseStartTime = performance.now();\n } else {\n // No pause configured, immediately start next loop\n this.position = 0;\n }\n }\n\n private handleCompletion(): void {\n this.completed = true;\n this.isPlaying = false;\n if (this.completionCallback) {\n this.completionCallback();\n }\n }\n\n onDone(callback: () => void): void {\n this.completionCallback = callback;\n }\n\n isOneShot(): boolean {\n return !this.scrollConfig?.enabled && !this.loopConfig;\n }\n\n override dispose(): void {\n this.completionCallback = null;\n }\n}\n","import type {\n DoneAware,\n Renderer,\n SequenceRenderDataSpecification,\n RenderSpecification,\n} from \"../../types\";\nimport { getRenderer } from \"./renderer-factory\";\n\n/**\n * A renderer that plays multiple patterns in sequence.\n *\n * Features:\n * - Plays patterns in order from a list of pattern IDs\n * - Supports looping the entire sequence\n * - Handles transitions between patterns\n * - Emits completion when all patterns have played\n */\nexport class SequenceRenderer implements Renderer, DoneAware {\n private patterns: string[];\n private currentPatternIndex = 0;\n private currentRenderer: Renderer | null = null;\n private loopConfig: boolean | number;\n private currentLoopCount = 0;\n private transitionDuration: number;\n private patternOverrides: Record<string, any>;\n private completionCallback: (() => void) | null = null;\n private patternStore: Map<string, RenderSpecification<any>>;\n private canvas: HTMLCanvasElement;\n private ctx: CanvasRenderingContext2D;\n private width = 0;\n private height = 0;\n\n constructor(\n data: SequenceRenderDataSpecification & {\n patternStore?: Map<string, RenderSpecification<any>>;\n }\n ) {\n this.patterns = data.patterns;\n this.loopConfig = data.loop ?? false;\n this.transitionDuration = data.transitionDuration ?? 0;\n this.patternOverrides = data.patternOverrides ?? {};\n this.patternStore = data.patternStore ?? new Map();\n\n this.canvas = document.createElement(\"canvas\");\n const ctx = this.canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"2D canvas not supported\");\n this.ctx = ctx;\n\n if (this.patterns.length === 0) {\n throw new Error(\"SequenceRenderer requires at least one pattern\");\n }\n\n this.loadCurrentPattern();\n }\n\n private loadCurrentPattern(): void {\n const patternId = this.patterns[this.currentPatternIndex];\n const patternSpec = this.patternStore.get(patternId);\n\n if (!patternSpec) {\n console.warn(`Pattern \"${patternId}\" not found in store, skipping`);\n this.moveToNextPattern();\n return;\n }\n\n // Clean up previous renderer\n if (this.currentRenderer) {\n this.currentRenderer.dispose?.();\n }\n\n // Apply any overrides for this specific pattern\n const overrides = this.patternOverrides[patternId] ?? {};\n const modifiedData = { ...patternSpec.data, ...overrides };\n\n // Create the renderer for this pattern\n try {\n this.currentRenderer = getRenderer({\n mode: patternSpec.type,\n data: modifiedData,\n });\n\n // If the pattern renderer is DoneAware, listen for its completion\n if (this.currentRenderer && this.isDoneAware(this.currentRenderer)) {\n this.currentRenderer.onDone(() => {\n this.handlePatternComplete();\n });\n }\n\n // Initialize the renderer\n if (this.currentRenderer) {\n this.currentRenderer.reset();\n this.currentRenderer.play?.();\n\n // Render initial frame if we have dimensions\n if (this.width > 0 && this.height > 0) {\n this.currentRenderer.renderFrame(this.width, this.height);\n }\n }\n } catch (error) {\n console.error(\n `Failed to create renderer for pattern \"${patternId}\":`,\n error\n );\n this.moveToNextPattern();\n }\n }\n\n private isDoneAware(obj: any): obj is DoneAware {\n return typeof obj?.onDone === \"function\";\n }\n\n private handlePatternComplete(): void {\n // Add transition delay if specified\n if (this.transitionDuration > 0) {\n setTimeout(() => {\n this.moveToNextPattern();\n }, this.transitionDuration);\n } else {\n this.moveToNextPattern();\n }\n }\n\n private moveToNextPattern(): void {\n this.currentPatternIndex++;\n\n if (this.currentPatternIndex >= this.patterns.length) {\n // We've completed all patterns in the sequence\n if (this.loopConfig === true) {\n // Infinite loop - restart from beginning\n this.currentPatternIndex = 0;\n this.loadCurrentPattern();\n } else if (\n typeof this.loopConfig === \"number\" &&\n this.currentLoopCount < this.loopConfig - 1\n ) {\n // Still have loops remaining\n this.currentLoopCount++;\n this.currentPatternIndex = 0;\n this.loadCurrentPattern();\n } else {\n // Sequence complete\n if (this.completionCallback) {\n this.completionCallback();\n }\n }\n } else {\n // Load next pattern in sequence\n this.loadCurrentPattern();\n }\n }\n\n reset(): void {\n this.currentPatternIndex = 0;\n this.currentLoopCount = 0;\n this.loadCurrentPattern();\n }\n\n play(): void {\n this.currentRenderer?.play?.();\n }\n\n pause(): void {\n this.currentRenderer?.pause?.();\n }\n\n renderFrame(width: number, height: number): void {\n this.width = width;\n this.height = height;\n this.canvas.width = width;\n this.canvas.height = height;\n\n if (this.currentRenderer) {\n this.currentRenderer.renderFrame(width, height);\n }\n }\n\n readPixels(width: number, height: number): Uint8ClampedArray {\n if (this.currentRenderer) {\n return this.currentRenderer.readPixels(width, height);\n }\n // Return empty canvas if no current renderer\n return this.ctx.getImageData(0, 0, width, height).data;\n }\n\n onDone(callback: () => void): void {\n this.completionCallback = callback;\n }\n\n isOneShot(): boolean {\n // Sequence is one-shot if no looping and only one pattern that is one-shot\n if (this.loopConfig === false || this.loopConfig === 1) {\n if (this.patterns.length === 1 && this.currentRenderer) {\n return (this.currentRenderer as any).isOneShot?.() ?? false;\n }\n return true;\n }\n return false;\n }\n\n dispose(): void {\n if (this.currentRenderer) {\n this.currentRenderer.dispose?.();\n }\n this.completionCallback = null;\n }\n\n /**\n * Set the pattern store for looking up patterns by ID\n */\n setPatternStore(store: Map<string, RenderSpecification<any>>): void {\n this.patternStore = store;\n // Reload current pattern with new store\n if (this.patterns.length > 0) {\n this.loadCurrentPattern();\n }\n }\n}\n","import type {\n OneShotCapable,\n Renderer,\n ColorRenderDataSpecification,\n} from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { OneShotRendererMixin } from \"./mixins/one-shot-renderer-mixin\";\nimport { toRgbString } from \"../color-utils\";\n\nconst Base = OneShotRendererMixin(Canvas2DRendererBase);\n\n/**\n * Renders a single solid color frame onto the canvas.\n * Implements OneShotCapable, signaling `onDone()` after the first render.\n */\nexport class SolidColorRenderer\n extends Base\n implements Renderer, OneShotCapable\n{\n private color: string;\n\n constructor(data: ColorRenderDataSpecification = { r: 0, g: 0, b: 0 }) {\n super();\n\n // Support both legacy r,g,b format and new color format\n let colorValue: { r: number; g: number; b: number } | string;\n\n if (data.color !== undefined) {\n colorValue = data.color;\n } else if (\n data.r !== undefined &&\n data.g !== undefined &&\n data.b !== undefined\n ) {\n colorValue = { r: data.r, g: data.g, b: data.b };\n } else {\n colorValue = { r: 0, g: 0, b: 0 }; // Default to black\n }\n\n this.color = toRgbString(colorValue);\n }\n\n setColor(color: { r: number; g: number; b: number } | string): void {\n this.color = toRgbString(color);\n this.resetOneShot();\n }\n\n override reset(): void {\n this.resetOneShot();\n }\n\n override renderFrame(width: number, height: number): void {\n if (this.isOneShotDone) return;\n\n this.canvas.width = width;\n this.canvas.height = height;\n\n this.ctx.fillStyle = this.color;\n this.ctx.fillRect(0, 0, width, height);\n\n this.signalDoneIfNeeded(); // tell the hook we're done\n }\n}\n","import type { Renderer } from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\n\n/**\n * A horizontal hue sweep renderer using 2D canvas.\n *\n * This renderer generates a horizontally scrolling gradient across a configurable hue range.\n * The hue scrolls left-to-right in HSL color space, creating a smooth and colorful sweep animation.\n */\nexport class SweepRenderer extends Canvas2DRendererBase implements Renderer {\n /** The horizontal pixel offset into the hue sweep */\n private offset = 0;\n\n /** Minimum hue (in degrees) to include in the sweep (e.g. 0 for red) */\n private minHue: number;\n\n /** Maximum hue (in degrees) to include in the sweep (e.g. 60 for yellow) */\n private maxHue: number;\n\n /** Horizontal sweep speed in pixels per update step */\n private speed: number;\n\n /**\n * Constructs a sweep renderer.\n *\n * @param minHue - Start of the hue range (in degrees, default 0)\n * @param maxHue - End of the hue range (in degrees, default 360)\n * @param speed - Horizontal speed of the sweep (pixels per update, default 1)\n */\n constructor({\n minHue = 0,\n maxHue = 360,\n speed = 1,\n }: {\n minHue?: number;\n maxHue?: number;\n speed?: number;\n } = {}) {\n super();\n this.minHue = minHue;\n this.maxHue = maxHue;\n this.speed = speed;\n }\n\n /**\n * Resets the animation state to the beginning of the sweep.\n */\n reset(): void {\n this.offset = 0;\n this.lastUpdate = performance.now();\n }\n\n /**\n * Converts an HSL color to RGB.\n *\n * @param h - Hue [0, 1]\n * @param s - Saturation [0, 1]\n * @param l - Lightness [0, 1]\n * @returns Tuple of [r, g, b] in range [0, 255]\n */\n private hslToRgb(h: number, s: number, l: number): [number, number, number] {\n let r: number, g: number, b: number;\n\n if (s === 0) {\n r = g = b = l; // Achromatic\n } else {\n const hue2rgb = (p: number, q: number, t: number): number => {\n if (t < 0) t += 1;\n if (t > 1) t -= 1;\n if (t < 1 / 6) return p + (q - p) * 6 * t;\n if (t < 1 / 2) return q;\n if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;\n return p;\n };\n const q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n const p = 2 * l - q;\n\n r = hue2rgb(p, q, h + 1 / 3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1 / 3);\n }\n\n return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];\n }\n\n /**\n * Renders the current frame by drawing a hue-mapped horizontal gradient across the canvas.\n *\n * @param width - Width of the canvas in pixels\n * @param height - Height of the canvas in pixels\n */\n renderFrame(width: number, height: number): void {\n // Only step the animation every ~50ms\n if (this.shouldStep(50)) {\n this.offset = (this.offset + this.speed) % width;\n }\n\n const imageData = this.ctx.createImageData(width, height);\n const data = imageData.data;\n\n let i = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n // Compute normalized hue position with offset\n const hue = ((x + this.offset) % width) / width;\n const mappedHue =\n this.minHue / 360 + hue * ((this.maxHue - this.minHue) / 360);\n\n const [r, g, b] = this.hslToRgb(mappedHue, 1, 0.5);\n\n data[i++] = r;\n data[i++] = g;\n data[i++] = b;\n data[i++] = 255; // alpha\n }\n }\n\n this.ctx.putImageData(imageData, 0, 0);\n }\n}\n","import {\n EXTENSION_CANVAS_RENDERER,\n ExtensionManager,\n registerExtensionPoint,\n} from \"../../../../../core\";\nimport type {\n RenderDataSpecification,\n Renderer,\n RendererConstructor,\n RendererMode,\n} from \"../../types\";\nimport { VideoRendererBase } from \"./base/video-base-renderer\";\nimport { DropRenderer } from \"./drop-renderer\";\nimport { GradientRenderer } from \"./gradient-renderer\";\nimport { ImageRenderer } from \"./image-renderer\";\nimport { LoopingVideoRenderer } from \"./looping-video-renderer\";\nimport { MatrixRenderer } from \"./matrix-renderer\";\nimport { OverlayRenderer } from \"./overlay-renderer\";\nimport { ScrollingImageRenderer } from \"./scrolling-image-renderer\";\nimport { ScrollingTextRenderer } from \"./scrolling-text-renderer\";\nimport { SequenceRenderer } from \"./sequence-renderer\";\nimport { SolidColorRenderer } from \"./solid-color-renderer\";\nimport { SweepRenderer } from \"./sweep-renderer\";\n\nconst canvasRenderers = new Map<string, RendererConstructor>();\nregisterExtensionPoint(EXTENSION_CANVAS_RENDERER, {\n register(id: string, renderer: RendererConstructor) {\n canvasRenderers.set(id, renderer);\n },\n execute(id: string, data: any): Renderer | null {\n const RendererClass = canvasRenderers.get(id);\n if (!RendererClass) {\n return null;\n }\n return new RendererClass(data);\n },\n});\n\n// Use the enhanced LoopingVideoRenderer for video mode\nExtensionManager.canvas.registerRenderer(\"video\", LoopingVideoRenderer);\n\n// Keep the base renderer available as \"video-basic\" if needed\nExtensionManager.canvas.registerRenderer(\"video-basic\", VideoRendererBase);\n\n// Register both image renderers - factory will choose based on data\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"image-static\",\n ImageRenderer\n);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"image-scrolling\",\n ScrollingImageRenderer\n);\n\n// Custom image renderer that chooses based on scroll config\nconst ImageRendererFactory = class {\n constructor(data: any) {\n if (data.scroll?.enabled) {\n return new ScrollingImageRenderer(data);\n }\n return new ImageRenderer(data);\n }\n} as any;\n\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"image\",\n ImageRendererFactory\n);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"color\",\n SolidColorRenderer\n);\n\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\"matrix\", MatrixRenderer);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\"sweep\", SweepRenderer);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"gradient\",\n GradientRenderer\n);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\"drop\", DropRenderer);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"sequence\",\n SequenceRenderer\n);\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"text\",\n ScrollingTextRenderer\n);\n\n// Create a factory for overlay renderer that provides access to the renderer factory\nconst OverlayRendererFactory = class {\n constructor(data: any) {\n // Create a factory function that the overlay renderer can use\n const rendererFactory = (type: string, rendererData: any) => {\n const renderer = getRenderer({ mode: type as any, data: rendererData });\n if (!renderer) {\n throw new Error(`Failed to create renderer of type: ${type}`);\n }\n return renderer;\n };\n return new OverlayRenderer(data, rendererFactory);\n }\n} as any;\n\nExtensionManager[EXTENSION_CANVAS_RENDERER].register(\n \"overlay\",\n OverlayRendererFactory\n);\n\n/**\n * Returns a renderer instance based on the specified mode and parameters.\n *\n * @param params - An object containing the parameters for the renderer.\n * @param params.mode - The mode of the renderer. Supported values are:\n * - `'matrix'`: Creates a matrix renderer with a specified fall chance.\n * - `'video'`: Creates a video renderer with a specified video source.\n * - `'image'`: Creates a image renderer with a specified inmage source.\n *\n * @param params.fallChance - The chance of falling, used only in `'matrix'` mode.\n * @param params.video - The video source identifier, used only in `'video'` mode.\n * - `'video1'`: Uses the `/assets/video.mp4` file.\n * - Any other value: Uses the `/assets/circle-spin.mp4` file.\n *\n * @returns A `Renderer` instance corresponding to the specified mode.\n *\n * @throws {Error} If an unknown mode is provided.\n */\nexport const getRenderer = <T extends RendererMode>({\n mode,\n data,\n}: {\n mode: T;\n data?: RenderDataSpecification<T> | null;\n}): Renderer | null => {\n const renderer: Renderer = ExtensionManager[\n EXTENSION_CANVAS_RENDERER\n ].execute(mode, data);\n if (renderer) {\n return renderer;\n }\n throw new Error(`Unknown mode: ${mode}`);\n};\n","import {\n KosModelContainer,\n type IKosModelContainer,\n type KosContext,\n} from \"../../../core\";\nimport { kosChild, kosModel, post } from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type {\n KosRequest,\n KosResponse,\n} from \"../../../core/core/services/browser-router\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { CanvasRenderer, type CanvasRendererModel } from \"../canvas-renderer\";\nimport { CanvasDispatcher } from \"./canvas-dispatcher-registration\";\nimport type {\n CanvasDispatcherOptions,\n EndpointData,\n RenderDataSpecification,\n RendererMode,\n RenderSpecification,\n} from \"./types\";\nimport { getRenderer } from \"./utils/renderers/renderer-factory\";\n\nexport const MODEL_TYPE = \"canvas-dispatcher-model\";\n\nexport type CanvasDispatcherModel =\n PublicModelInterface<CanvasDispatcherModelImpl>;\n\n/**\n * Converts a hex color string (e.g. \"#ff00aa\" or \"ff00aa\") to an RGB object.\n * @param hex - The hex color string.\n * @returns An object with r, g, b values (0-255), or null if invalid.\n */\nfunction hexToRgb(hex: string): { r: number; g: number; b: number } | null {\n // Remove leading '#' if present\n hex = hex.replace(/^#/, \"\");\n // Support short form (#f0a)\n if (hex.length === 3) {\n hex = hex\n .split(\"\")\n .map((c) => c + c)\n .join(\"\");\n }\n if (hex.length !== 6) return null;\n const num = parseInt(hex, 16);\n return {\n r: (num >> 16) & 255,\n g: (num >> 8) & 255,\n b: num & 255,\n };\n}\n\n@kosModel(MODEL_TYPE)\nexport class CanvasDispatcherModelImpl\n implements IKosDataModel, IKosIdentifiable\n{\n id: string;\n private logger: KosContextLogger;\n\n private _content: Map<string, string> = new Map();\n private _patterns: Map<string, RenderSpecification<any>> = new Map();\n\n @kosChild\n private _endpointRenderers: IKosModelContainer<CanvasRendererModel>;\n\n // Note: BrowserRouter is automatically injected when using HTTP decorators!\n\n pattern?: RendererMode;\n data?: RenderDataSpecification<any> | null;\n\n constructor(\n modelId: string,\n _options: CanvasDispatcherOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this._endpointRenderers = new KosModelContainer();\n }\n\n addNamedEndpoint(name: string, data: EndpointData) {\n if (this._endpointRenderers.getModel(name)) {\n this.logger.warn(`Endpoint \"${name}\" already exists. Overwriting.`);\n }\n const renderer = CanvasRenderer.instance(name)\n .options({\n apiPath: data.apiPath,\n width: data.width,\n height: data.height,\n fps: data.fps,\n durationMs: data.durationMs ?? null,\n endpoint: name,\n })\n .build();\n\n this._endpointRenderers.addModel(renderer);\n\n return renderer;\n }\n\n addContent(name: string, contentUrl: string) {\n if (this._content.has(name)) {\n this.logger.warn(`Content \"${name}\" already exists. Overwriting.`);\n }\n this._content.set(name, contentUrl);\n }\n\n addPattern(name: string, data: RenderSpecification<any>) {\n if (this._patterns.has(name)) {\n this.logger.warn(`Pattern \"${name}\" already exists. Overwriting.`);\n }\n this._patterns.set(name, data);\n }\n\n // -------------------HTTP ENDPOINTS----------------------------\n\n @post(\"/api/ui/canvas/patterns\")\n async handlePatternsPost(\n req: KosRequest<\"/api/ui/canvas/patterns\">,\n res: KosResponse\n ) {\n const pattern: RenderSpecification<any> | RenderSpecification<any>[] =\n req.body;\n const _data = Array.isArray(pattern) ? pattern : [pattern];\n if (_data.some((p) => !p.id || !p.type || !p.data)) {\n res.status?.(400).send({ error: `Invalid pattern data` });\n return;\n }\n\n for (const pattern of _data) {\n if (this._patterns.has(pattern.id)) {\n this.logger.warn(\n `Pattern \"${pattern.id}\" already exists. Overwriting.`\n );\n }\n this.addPattern(pattern.id, pattern);\n }\n\n res.status?.(200).send({ status: \"OK\" });\n }\n\n @post(\"/api/ui/canvas/pattern/:endpoint/:pattern\")\n async handlePatternApplication(\n req: KosRequest<\"/api/ui/canvas/pattern/:endpoint/:pattern\">,\n res: KosResponse\n ) {\n const pattern = req.params.pattern;\n const endpoint = req.params.endpoint;\n\n const rendererModel = this._endpointRenderers.getModel(endpoint);\n if (!rendererModel) {\n res.status?.(404).send({ error: `Endpoint \"${endpoint}\" not found` });\n return;\n }\n if (!this._patterns.has(pattern)) {\n res.status?.(404).send({ error: `Pattern \"${pattern}\" not found` });\n return;\n }\n\n const patternData = this._patterns.get(pattern)!;\n\n const mode = patternData.type as RendererMode;\n // Merge request body data with pattern data to allow runtime overrides\n const requestData = req.body || {};\n this.data = {\n ...patternData.data,\n ...requestData,\n } as RenderDataSpecification<any>;\n\n // If it's a sequence renderer, pass the pattern store\n const rendererData =\n mode === \"sequence\"\n ? { ...this.data, patternStore: this._patterns }\n : this.data;\n\n rendererModel.renderer = getRenderer({\n mode: mode,\n data: rendererData,\n });\n\n // Set the clearOnComplete option if specified\n rendererModel.setClearOnComplete(patternData.clearOnComplete);\n\n rendererModel.startStreaming();\n res.status?.(200).send({ status: \"OK\" });\n }\n\n @post(\"/api/ui/canvas/color/:endpoint/:color\")\n async handleColorApplication(\n req: KosRequest<\"/api/ui/canvas/color/:endpoint/:color\">,\n res: KosResponse\n ) {\n const color = req.params.color;\n const rgb = hexToRgb(color);\n\n if (!rgb) {\n res.status?.(400).send({ error: \"Invalid color format\" });\n return;\n }\n\n const endpoint = req.params.endpoint;\n const rendererModel = this._endpointRenderers.getModel(endpoint);\n if (!rendererModel) {\n res.status?.(404).send({ error: `Endpoint \"${endpoint}\" not found` });\n return;\n }\n const { r, b, g } = rgb;\n rendererModel.renderer = getRenderer({\n mode: \"color\",\n data: {\n r,\n g,\n b,\n },\n });\n\n rendererModel.startStreaming();\n res.status?.(200).send({ status: \"OK\" });\n }\n\n @post(\"/api/ui/canvas/endpoint\")\n async handleEndpointCreation(\n req: KosRequest<\"/api/ui/canvas/endpoint\">,\n res: KosResponse\n ) {\n const data: EndpointData = req.body;\n\n if (!data.apiPath || !data.id) {\n res.status?.(400).send({ error: \"Name and path are required\" });\n return;\n }\n\n this.addNamedEndpoint(data.id, data);\n\n res.status?.(200).send({ status: \"OK\" });\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async load(context?: KosContext): Promise<void> {\n const patternData = context?.get(CanvasDispatcher.loader);\n if (patternData) {\n patternData.patterns?.forEach((pattern: RenderSpecification<any>) => {\n if (!pattern.id || !pattern.type || !pattern.data) {\n this.logger.warn(`Invalid pattern data: ${JSON.stringify(pattern)}`);\n return;\n }\n this.addPattern(pattern.id, pattern);\n });\n }\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { CanvasDispatcherModel } from \"./canvas-dispatcher-model\";\nimport {\n CanvasDispatcherModelImpl,\n MODEL_TYPE,\n} from \"./canvas-dispatcher-model\";\nimport type { CanvasDispatcherOptions } from \"./types\";\n\n/**\n * # CanvasDispatcher\n *\n * The registration bean includes convenience methods for creating and working with CanvasDispatcherModel 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: CanvasDispatcher.type, id: \"canvasDispatcherId\"})\n * private canvasDispatcherModel: CanvasDispatcherModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new CanvasDispatcherModel 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 = CanvasDispatcher.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 CanvasDispatcherModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (CanvasDispatcher.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to CanvasDispatcherModel\n * // and the compiler will know that the model has the CanvasDispatcherModel 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 { CanvasDispatcher } 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(CanvasDispatcher);\n * ```\n *\n * ## registration.singleton\n \n * The canvasDispatcher 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 CanvasDispatcher = new SingletonKosModelRegistrationFactory<\n CanvasDispatcherModel,\n CanvasDispatcherOptions\n>({\n class: CanvasDispatcherModelImpl,\n type: MODEL_TYPE,\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 * KOS Device Model - Device Identity and Node Configuration Management\n *\n * The Device model provides centralized management of device identity, node configuration,\n * and hardware identification within KOS systems. It handles device serial numbers,\n * names, and node topology information essential for system coordination and administration.\n *\n * ## Key Features\n *\n * ### Device Identity Management\n * - **Serial Number Tracking**: Hardware-based device identification\n * - **Name Management**: Human-readable device naming for administration\n * - **Node Configuration**: Multi-node deployment topology handling\n *\n * ### Real-time Synchronization\n * - **Critical Data Events**: Automatic updates on system data changes\n * - **WebSocket Integration**: Live device state synchronization\n * - **Lazy Loading**: Efficient data retrieval when needed\n *\n * ### Node Topology Support\n * - **Node Type/Name Parsing**: Automatic node identifier decomposition\n * - **Multi-node Deployments**: Support for complex system architectures\n * - **Role-based Configuration**: Node-specific parameter management\n *\n * ## Common Integration Patterns\n *\n * ### System Administration Dashboards\n * ```typescript\n * const device = Device.factory({\n * serialNumber: 'KOS-DEV-001',\n * name: 'Production Dispenser Alpha',\n * nodeId: 'primary-main'\n * });\n *\n * // Access device identity\n * console.log(`Device: ${device.name}`);\n * console.log(`Serial: ${device.serialNumber}`);\n * console.log(`Node: ${device.nodeType}-${device.nodeName}`);\n * ```\n *\n * ### Multi-node System Coordination\n * ```typescript\n * const primaryDevice = Device.factory({\n * nodeId: 'primary-controller'\n * });\n *\n * const secondaryDevice = Device.factory({\n * nodeId: 'secondary-backup'\n * });\n *\n * // Coordinate based on node roles\n * if (primaryDevice.nodeType === 'primary') {\n * // Handle primary node logic\n * }\n * ```\n *\n * ### Device Registration and Setup\n * ```typescript\n * const newDevice = Device.factory({\n * serialNumber: await getHardwareSerial(),\n * name: userProvidedName,\n * nodeId: deploymentConfiguration.nodeId\n * });\n *\n * // Device automatically loads additional data\n * // from critical data events\n * ```\n *\n * ## Real-time Updates\n *\n * The Device model automatically responds to critical data changes:\n * - Monitors `/kos/criticalData/changed` and `/kos/criticalData/available` topics\n * - Updates serial number and configuration when system data becomes available\n * - Maintains consistency across device restarts and configuration changes\n *\n * ## Singleton Behavior\n *\n * Device models use singleton pattern - each device type has one instance:\n * - Subsequent factory calls return the existing instance\n * - Options are ignored after first creation\n * - Ensures system-wide device identity consistency\n *\n * This is an alias for the implementation {@link DeviceModelImpl}.\n *\n * @interface\n * @group KOS Model\n * @category Device Data\n * @useDeclaredType\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 /**\n * Hardware-based device serial number for unique identification.\n *\n * Returns the device's hardware serial number or \"unassigned\" if not yet loaded.\n * Serial numbers are typically retrieved from the device's hardware identification\n * system during critical data events.\n *\n * @example\n * ```typescript\n * const device = Device.factory({});\n *\n * // Check if serial number is available\n * if (device.serialNumber !== \"unassigned\") {\n * console.log(`Device Serial: ${device.serialNumber}`);\n * }\n * ```\n */\n get serialNumber(): string | \"unassigned\" {\n return this._serialNumber;\n }\n\n private _name: string | \"unassigned\";\n\n /**\n * Human-readable device name for administrative identification.\n *\n * Returns the configured device name or \"unassigned\" if not yet set.\n * Device names are typically configured during device setup and used\n * in administrative interfaces for device identification and management.\n *\n * @example\n * ```typescript\n * const device = Device.factory({\n * name: 'Main Production Dispenser'\n * });\n *\n * console.log(`Device Name: ${device.name}`);\n * // Output: \"Device Name: Main Production Dispenser\"\n * ```\n */\n get name(): string | \"unassigned\" {\n return this._name;\n }\n\n private _nodeId: string | \"unassigned\";\n\n /**\n * Full node identifier within the KOS deployment.\n *\n * Returns the complete node ID or \"unassigned\" if not yet configured.\n * Node IDs follow the pattern \"type-instance\" (e.g., \"primary-main\", \"secondary-backup\")\n * and identify the specific node role and instance within multi-node deployments.\n *\n * @example\n * ```typescript\n * const device = Device.factory({\n * nodeId: 'primary-controller'\n * });\n *\n * console.log(`Node ID: ${device.nodeId}`);\n * // Output: \"Node ID: primary-controller\"\n * ```\n *\n * @see {@link nodeType} for extracting the node type portion\n * @see {@link nodeName} for extracting the node name portion\n */\n get nodeId(): string | \"unassigned\" {\n return this._nodeId;\n }\n\n /**\n * Node type extracted from the node identifier.\n *\n * Returns the first part of the node ID (before the hyphen).\n * For node ID \"primary-controller\", this returns \"primary\".\n * Used for role-based logic and node coordination.\n *\n * @example\n * ```typescript\n * const device = Device.factory({\n * nodeId: 'primary-controller'\n * });\n *\n * console.log(`Node Type: ${device.nodeType}`);\n * // Output: \"Node Type: primary\"\n *\n * // Role-based coordination\n * if (device.nodeType === 'primary') {\n * // Handle primary node responsibilities\n * }\n * ```\n */\n get nodeType(): string {\n const [nodeType] = this.nodeId.split(\"-\");\n return nodeType;\n }\n\n /**\n * Node name extracted from the node identifier.\n *\n * Returns the second part of the node ID (after the hyphen).\n * For node ID \"primary-controller\", this returns \"controller\".\n * Used for instance-specific identification within node types.\n *\n * @example\n * ```typescript\n * const device = Device.factory({\n * nodeId: 'secondary-backup'\n * });\n *\n * console.log(`Node Name: ${device.nodeName}`);\n * // Output: \"Node Name: backup\"\n *\n * // Instance-specific logic\n * if (device.nodeName === 'backup') {\n * // Handle backup node configuration\n * }\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 device model with new configuration options.\n *\n * Allows dynamic updating of device identity and node configuration.\n * Any undefined values will be set to \"unassigned\". This method is typically\n * called internally during device data loading or external configuration changes.\n *\n * @param options - Device configuration options to apply\n *\n * @example\n * ```typescript\n * const device = Device.factory({});\n *\n * // Update with new device information\n * device.updateModel({\n * serialNumber: 'KOS-DEVICE-12345',\n * name: 'Updated Dispenser Name',\n * nodeId: 'primary-main'\n * });\n *\n * console.log(device.serialNumber); // \"KOS-DEVICE-12345\"\n * console.log(device.name); // \"Updated Dispenser Name\"\n * console.log(device.nodeId); // \"primary-main\"\n * ```\n *\n * @example Partial Updates\n * ```typescript\n * // Only update specific fields\n * device.updateModel({\n * name: 'New Device Name'\n * // serialNumber and nodeId remain unchanged\n * });\n * ```\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 /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing device ${this.id}`);\n }\n\n /**\n * @internal\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 Model Registration Factory\n *\n * **KOS Device Identity and Node Configuration Management**\n *\n * The Device registration factory provides convenient methods for creating and working with DeviceModel instances.\n * Device models handle device identity, hardware serial numbers, and node configuration within KOS deployments.\n *\n * ## Core Registration Properties\n *\n * ### type\n *\n * Model type identifier used for dependency injection and type narrowing.\n * Essential for declaring model dependencies in other components.\n *\n * @example Model Dependency Declaration\n * ```typescript\n * @kosDependency({modelType: Device.type, id: \"deviceId\"})\n * private deviceModel: DeviceModel;\n * ```\n *\n * ### factory\n *\n * Creates DeviceModel instances with singleton behavior. Multiple calls return the same instance,\n * ensuring system-wide device identity consistency.\n *\n * **Singleton Behavior**: Subsequent factory calls return existing instance; options ignored after first creation.\n *\n * @example Device Creation and Identity Access\n * ```typescript\n * const device = Device.factory({\n * serialNumber: 'KOS-DEVICE-001',\n * name: 'Production Dispenser Alpha',\n * nodeId: 'primary-controller'\n * });\n *\n * // Access device identity\n * console.log(`Device: ${device.name} (${device.serialNumber})`);\n * console.log(`Node: ${device.nodeType}-${device.nodeName}`);\n * ```\n *\n * @example Multi-node System Coordination\n * ```typescript\n * const primaryDevice = Device.factory({ nodeId: 'primary-main' });\n * const backupDevice = Device.factory({ nodeId: 'secondary-backup' });\n *\n * // Coordinate based on node roles\n * if (primaryDevice.nodeType === 'primary') {\n * // Handle primary node responsibilities\n * }\n * ```\n *\n * ### predicate\n *\n * [TypeScript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n * for identifying and narrowing models to DeviceModel instances.\n *\n * @example Type Narrowing for Device Operations\n * ```typescript\n * const model: IKosDataModel = getModel(); // some model\n *\n * if (Device.predicate(model)) {\n * // Compiler now knows model is DeviceModel\n * console.log(`Device Serial: ${model.serialNumber}`);\n * model.updateModel({ name: 'Updated Name' });\n * }\n * ```\n *\n * ### registration\n *\n * Registration object for model registry integration. Provides all required information\n * for registering the DeviceModelImpl implementation with the model registry.\n *\n * @example Model Registry Configuration\n * ```typescript\n * // registration.ts\n * import { Device } from \"@kos-ui/project-models\";\n * import { KosModelRegistry } from \"@kosdev-code/kos-dispense-sdk\";\n *\n * KosModelRegistry.dispense\n * .models()\n * .model(Device);\n * ```\n *\n * ## Singleton Architecture\n *\n * **Device models use singleton pattern** ensuring system-wide consistency:\n * - Each device type has exactly one instance\n * - Subsequent factory calls return existing instance\n * - Options are ignored after initial creation\n * - Uses model type as unique identifier\n * - Guarantees device identity consistency across system\n *\n * @group KOS Model\n * @category Device Data\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\n/**\n * NetworkInterface - Network interface management and monitoring for KOS devices.\n *\n * The NetworkInterface model provides comprehensive network interface management capabilities, including\n * WiFi and Ethernet configuration, IP settings, and real-time network state monitoring. This model is\n * essential for applications that need to display network status, configure network connections, or\n * manage network interfaces on KOS devices.\n *\n * ## Key Features\n * - **Network Interface Discovery** - Automatically discovers and tracks available network interfaces\n * - **WiFi Management** - Access WiFi connection details, signal strength, and access point information\n * - **Ethernet Monitoring** - Track Ethernet connection status, speed, and duplex settings\n * - **IP Configuration** - Monitor and manage IPv4 settings including addresses, gateways, and DNS\n * - **Connection State Tracking** - Real-time monitoring of network device states and connectivity\n * - **Hardware Information** - Access to MAC addresses, MTU settings, and device capabilities\n *\n * ## Network Interface Categories\n * The model categorizes interfaces for easier management:\n * - **INTERNAL** - Internal system interfaces (loopback, etc.)\n * - **INTEGRATION** - Integration-specific interfaces\n * - **EXTERNAL** - User-facing network interfaces (WiFi, Ethernet)\n * - **NONE** - Uncategorized interfaces\n *\n * ## Common Use Cases\n * - **Network Status Display** - Show current connection status and network details in UI\n * - **Connection Management** - Allow users to view and configure network settings\n * - **Network Diagnostics** - Provide detailed network interface information for troubleshooting\n * - **System Integration** - Monitor network connectivity for automated systems\n * - **Configuration Interfaces** - Build network configuration screens with current state\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const networkInterface = NetworkInterface.instance('eth0')\n * .options({\n * name: 'eth0',\n * type: 'ethernet',\n * configured: true,\n * category: 'EXTERNAL'\n * })\n * .build();\n *\n * console.log(networkInterface.name); // 'eth0'\n * console.log(networkInterface.configured); // true\n * ```\n *\n * @group KOS Model\n * @category Network Interfaces\n * @useDeclaredType\n *\n * @see {@link NetworkInterfaceContainer} - Container model for managing multiple network interfaces\n * @see {@link NetworkInterfaceOptions} - Configuration options interface\n * @see {@link EthernetData} - Ethernet-specific interface data\n * @see {@link WifiData} - WiFi-specific interface data\n * @see {@link Ip44Settings} - IPv4 configuration settings\n */\nexport type NetworkInterfaceModel =\n PublicModelInterface<NetworkInterfaceModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class NetworkInterfaceModelImpl\n implements IKosDataModel, IKosIdentifiable, NetworkInterfaceData\n{\n /** Unique identifier for the model instance */\n id: string;\n\n /** Network interface name (e.g., 'eth0', 'wlan0', 'lo') */\n name: string;\n\n /** Interface type identifier (e.g., 'ethernet', 'wifi', 'loopback') */\n type: string;\n\n /** NetworkManager device state code indicating connection status */\n nmdevicestate: number;\n\n /** Hardware MAC address of the network interface */\n hwaddress: string;\n\n /** Maximum Transmission Unit size for the interface */\n mtu: number;\n\n /** Whether the interface is currently configured and active */\n configured: boolean;\n\n /** WiFi-specific connection data including SSID, signal strength, and security */\n wifi?: WifiData;\n\n /** Ethernet-specific connection data including carrier status, speed, and duplex */\n ethernet?: EthernetData;\n\n /** IPv4 network settings including address, gateway, and DNS configuration */\n ip4settings?: Ip44Settings;\n\n /** Interface categorization for organizational purposes */\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 /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing network-interface ${this.id}`);\n }\n\n /**\n * @internal\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 * @group KOS Model\n * @category Network Interfaces\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\";\nimport { getKosConnectionId } from \"../../../utils/get-kos-connection-id\";\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\n/**\n * Network interface categories for organizational purposes.\n * @group KOS Model\n * @category Network Interfaces\n */\nexport type NetworkInterfaceCategory =\n | \"INTERNAL\"\n | \"INTEGRATION\"\n | \"EXTERNAL\"\n | \"NONE\";\n\n/**\n * Ethernet-specific interface data including connection status and performance metrics.\n * @group KOS Model\n * @category Network Interfaces\n */\nexport interface EthernetData {\n /** Whether the Ethernet cable is connected (link up/down status) */\n carrier: boolean;\n /** Connection speed in Mbps (e.g., 10, 100, 1000) */\n speed: number;\n /** Duplex mode - 'full' for full-duplex, 'half' for half-duplex */\n duplex: string;\n}\n\n/**\n * WiFi-specific interface data including access point details and signal metrics.\n * @group KOS Model\n * @category Network Interfaces\n */\nexport interface WifiData {\n /** Access Point flags indicating capabilities and features */\n apFlags: number;\n /** BSSID (MAC address) of the connected access point */\n bssid: string;\n /** WPA security flags for the connection */\n wpaFlags: number;\n /** Connection bitrate in bits per second */\n bitrate: number;\n /** Network name (Service Set Identifier) */\n ssid: string;\n /** Signal strength percentage (0-100) */\n signal: number;\n /** RSN (Robust Security Network) flags for WPA2/WPA3 */\n rsnFlags: number;\n /** Time in seconds since the access point was last seen */\n lastSeenAgo: number;\n /** WiFi frequency in MHz (e.g., 2437 for 2.4GHz, 5220 for 5GHz) */\n frequency: number;\n}\n\n/**\n * IPv4 network configuration settings including addressing and DNS.\n * @group KOS Model\n * @category Network Interfaces\n */\nexport interface Ip44Settings {\n /** Subnet prefix length (e.g., 24 for /24 subnet mask) */\n prefix: number;\n /** List of address/prefix combinations in CIDR notation */\n addressprefixlist: string[];\n /** Primary IP address assigned to the interface */\n address: string;\n /** IP configuration method ('auto' for DHCP, 'manual' for static) */\n method: string;\n /** Default gateway IP address for routing */\n gateway: string;\n /** List of DNS server IP addresses */\n dnslist: string[];\n}\n\n/**\n * Complete network interface data structure containing all interface properties.\n * This is the main interface that NetworkInterfaceModel implements.\n * @group KOS Model\n * @category Network Interfaces\n */\nexport interface NetworkInterfaceData {\n /** Network interface name (e.g., 'eth0', 'wlan0', 'lo') */\n name: string;\n /** Interface type identifier (e.g., 'ethernet', 'wifi', 'loopback') */\n type: string;\n /** NetworkManager device state code indicating connection status */\n nmdevicestate: number;\n /** Hardware MAC address of the network interface */\n hwaddress: string;\n /** Maximum Transmission Unit size for the interface */\n mtu: number;\n /** Whether the interface is currently configured and active */\n configured: boolean;\n /** WiFi-specific connection data (only present for WiFi interfaces) */\n wifi?: WifiData;\n /** Ethernet-specific connection data (only present for Ethernet interfaces) */\n ethernet?: EthernetData;\n /** IPv4 network settings (present when interface has IP configuration) */\n ip4settings?: Ip44Settings;\n /** Interface categorization for organizational purposes */\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 const destinationAddress = getKosConnectionId();\n log.debug(\"sending GET for copy-logs\");\n\n try {\n const response = await getAll<NetworkInterfaceData>({\n destinationAddress,\n });\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\n/**\n * NetworkInterfaceContainer - Centralized management of multiple network interfaces on KOS devices.\n *\n * The NetworkInterfaceContainer model provides comprehensive management of all network interfaces\n * available on a KOS device, including automatic discovery, categorization, and real-time updates.\n * This container model is essential for applications that need to manage multiple network interfaces,\n * build network configuration screens, or monitor overall network connectivity status.\n *\n * ## Key Features\n * - **Automatic Interface Discovery** - Loads and manages all available network interfaces from the device\n * - **Category-Based Indexing** - Organizes interfaces by category (INTERNAL, INTEGRATION, EXTERNAL, NONE)\n * - **Real-Time Refresh** - Updates interface data with current network state\n * - **Unified Interface Management** - Single point of access for all network interface operations\n * - **Dynamic Interface Tracking** - Handles interface addition/removal as network state changes\n * - **Service Integration** - Automatically fetches interface data from KOS network services\n *\n * ## Interface Categories\n * The container automatically organizes interfaces into categories:\n * - **EXTERNAL** - User-facing interfaces (WiFi adapters, Ethernet ports)\n * - **INTERNAL** - System interfaces (loopback, virtual interfaces)\n * - **INTEGRATION** - Integration-specific network interfaces\n * - **NONE** - Uncategorized interfaces\n *\n * ## Common Use Cases\n * - **Network Configuration UI** - Build comprehensive network settings interfaces\n * - **System Monitoring** - Track overall network connectivity and interface health\n * - **Interface Selection** - Allow users to choose from available network interfaces\n * - **Network Diagnostics** - Provide detailed system-wide network interface information\n * - **Automated Network Management** - Programmatically manage multiple interfaces\n *\n * @example Basic Usage\n * ```typescript\n * const networkContainer = NetworkInterfaceContainer.instance('system-interfaces')\n * .build();\n *\n * // Access all network interfaces and get specific interface\n * const allInterfaces = networkContainer.models;\n * const ethInterface = networkContainer.getModel('eth0');\n * ```\n *\n * @group KOS Model\n * @category Network Interfaces\n * @interface\n * @useDeclaredType\n *\n * @see {@link NetworkInterface} - Individual network interface model\n * @see {@link NetworkInterfaceOptions} - Network interface configuration options\n * @see {@link getNetworkInterfaces} - Service function for loading interface data\n */\nexport type NetworkInterfaceContainerModel =\n PublicModelInterface<NetworkInterfaceContainerModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class NetworkInterfaceContainerModelImpl\n implements\n IKosIdentifiable,\n IKosModelHolder<NetworkInterfaceModel>,\n IKosDataModel\n{\n /** Unique identifier for the container model instance */\n id: string;\n /** Context logger for debugging and network interface operations */\n private logger: KosContextLogger;\n /** Container for managing NetworkInterface model instances with category indexing */\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 /**\n * @internal\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 /**\n * @internal\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 * @group KOS Model\n * @category Network Interfaces\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 deviceType?: \"disk\" | \"partition\";\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\n/**\n * StorageDevice - Manages individual USB/external storage device information and state.\n *\n * The StorageDevice model represents individual storage devices (USB drives, SD cards,\n * external drives) connected to the KOS system. It tracks device hardware information,\n * mount status, and provides access to device metadata including vendor, model, runtime\n * statistics, and file system details.\n *\n * ## Key Features\n * - **Hardware Information** - Vendor, model, and system path details\n * - **Mount Management** - Track mount directory and removal status\n * - **Runtime Statistics** - Device runtime and usage metrics\n * - **Node Awareness** - Multi-node device distribution tracking\n * - **File System Integration** - Label and mount point management\n * - **Parent-Aware Architecture** - Designed for container model management\n *\n * ## Device Properties\n * Storage devices expose comprehensive hardware and state information:\n * - **Physical Details**: vendor, model, syspath for hardware identification\n * - **Mount Information**: mountDir, label for file system access\n * - **Status Tracking**: removed flag, local/remote node distribution\n * - **Runtime Metrics**: runTimeMs for usage analytics\n *\n * ## Common Use Cases\n * - **Storage Management UI** - Display available storage devices and capacity\n * - **File Transfer Operations** - Access mount points for file operations\n * - **System Monitoring** - Track device insertion/removal events\n * - **Backup Management** - Identify backup destination devices\n * - **Multi-node Systems** - Manage storage across distributed KOS nodes\n * - **Device Diagnostics** - Runtime statistics and health monitoring\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const usbDrive = StorageDevice.instance('usb-drive-1')\n * .options({\n * mountDir: '/media/usb1',\n * vendor: 'SanDisk',\n * model: 'Ultra USB 3.0',\n * label: 'BACKUP_DRIVE',\n * nodeId: 'primary',\n * local: true,\n * removed: false,\n * runTimeMs: 1800000,\n * syspath: '/sys/devices/usb1'\n * })\n * .build();\n *\n * // Access device properties\n * console.log(`${usbDrive.vendor} ${usbDrive.model} at ${usbDrive.mountDir}`);\n * ```\n *\n * @group KOS Model\n * @category Device Management\n * @useDeclaredType\n *\n * @see {@link StorageDeviceOptions} - Configuration options for StorageDevice instances\n * @see {@link StorageDeviceContainerModel} - Container for managing multiple storage devices\n * @see {@link StorageDeviceResponse} - API response structure for device data\n */\nexport type StorageDevice = PublicModelInterface<StorageDeviceModelImpl>;\n\nexport type StorageDeviceModel = PublicModelInterface<StorageDeviceModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosParentAware()\n@kosModel(MODEL_TYPE)\nexport class StorageDeviceModelImpl implements IKosDataModel, IKosIdentifiable {\n /** Unique identifier for the storage device model instance */\n id: string;\n /** File system mount directory path where device is accessible */\n mountDir: string;\n /** Whether the device has been physically removed from the system */\n removed: boolean;\n /** Device manufacturer name (e.g., 'SanDisk', 'Western Digital') */\n vendor: string;\n /** Total device runtime in milliseconds for usage tracking */\n runTimeMs: number;\n /** Device model name or identifier (e.g., 'Ultra USB 3.0', 'My Passport') */\n model: string;\n /** KOS node identifier where this device is connected */\n nodeId: string;\n /** Whether the device is connected to the local node */\n local: boolean;\n /** File system label or volume name for the device */\n label: string;\n /** System path for hardware identification and low-level access */\n syspath: string;\n /** Context logger for debugging and diagnostics */\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 /**\n * Updates the storage device model with new configuration options.\n * @param options New configuration options to apply to the device\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 /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing storage-device ${this.id}`);\n }\n\n /**\n * @internal\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\n/**\n * StorageDeviceContainer - Manages collections of storage devices with real-time discovery.\n *\n * The StorageDeviceContainer model provides centralized management of multiple storage devices\n * connected to KOS systems. It automatically discovers devices through REST API calls and\n * maintains real-time synchronization via WebSocket topics, handling device insertion,\n * removal, and state updates across the entire storage ecosystem.\n *\n * ## Key Features\n * - **Automatic Device Discovery** - Scans and loads all available storage devices\n * - **Real-time Synchronization** - WebSocket updates for insertion/removal events\n * - **Collection Management** - Add, remove, and query storage device collections\n * - **Availability Monitoring** - Track overall storage availability status\n * - **Volume Access** - Direct access to managed storage device instances\n * - **Parent-Child Architecture** - Proper lifecycle management for contained devices\n *\n * ## Topic-Based Reactivity\n * The model listens to these KOS topics for real-time synchronization:\n * - **`/kos/storage`** - Storage device availability changes (insertion/removal events)\n * - Payload: `StorageDeviceResponse[]` - Array of current storage device states\n * - Triggers automatic model updates, additions, and removals\n * - Handles both physical device changes and mount/unmount operations\n *\n * ## Storage Management Operations\n * The container provides comprehensive storage device management:\n * - **Device Lifecycle**: Automatic creation and cleanup of StorageDevice models\n * - **State Synchronization**: Real-time updates from system storage changes\n * - **Collection Queries**: Access devices by ID, status, or availability\n * - **Volume Tracking**: Monitor mounted and available storage volumes\n *\n * ## Common Use Cases\n * - **Storage Management Dashboard** - Display all connected storage devices\n * - **File Transfer Interface** - Select available storage for operations\n * - **System Monitoring** - Track storage availability and health\n * - **Backup Management** - Identify backup destination devices\n * - **Multi-node Storage** - Manage distributed storage across KOS nodes\n * - **Device Diagnostics** - Monitor storage device runtime and status\n *\n * @example Basic Storage Container Usage\n * ```typescript\n * // Create storage device container for system management\n * const storageContainer = StorageDeviceContainer.instance('main-storage')\n * .options({}) // Empty configuration - behavior driven by discovery\n * .build();\n *\n * // Check overall storage availability\n * console.log(`Storage available: ${storageContainer.isStorageInserted}`);\n * console.log(`Total volumes: ${storageContainer.volumes.length}`);\n *\n * // Access individual storage devices\n * const usbDevice = storageContainer.getModel('usb-drive-1');\n * if (usbDevice && !usbDevice.removed) {\n * console.log(`USB device mounted at: ${usbDevice.mountDir}`);\n * }\n * ```\n *\n * @example Storage Device Discovery and Management\n * ```typescript\n * // Container automatically handles device discovery\n * const storageManager = StorageDeviceContainer.instance('storage-mgr')\n * .options({})\n * .build();\n *\n * // Monitor storage changes with reactive patterns\n * const monitorStorageChanges = () => {\n * // Container automatically updates via /kos/storage topic\n * const availableDevices = storageManager.data.filter(device =>\n * !device.removed && device.mountDir\n * );\n *\n * const localDevices = availableDevices.filter(device => device.local);\n * const remoteDevices = availableDevices.filter(device => !device.local);\n *\n * console.log(`Available storage: ${availableDevices.length} devices`);\n * console.log(`Local: ${localDevices.length}, Remote: ${remoteDevices.length}`);\n *\n * return {\n * total: availableDevices.length,\n * local: localDevices.length,\n * remote: remoteDevices.length,\n * devices: availableDevices\n * };\n * };\n * ```\n *\n * @example React Storage Management Interface\n * ```typescript\n * const StorageManagerComponent: React.FC = kosComponent(() => {\n * const storageContainer = useModel(StorageDeviceContainer, 'storage-manager');\n *\n * // Reactive data automatically updates via WebSocket\n * const availableDevices = storageContainer.volumes.filter(device =>\n * !device.removed && device.mountDir\n * );\n *\n * const removedDevices = storageContainer.volumes.filter(device =>\n * device.removed\n * );\n *\n * return (\n * <div className=\"storage-manager\">\n * <div className=\"storage-status\">\n * <h2>Storage Overview</h2>\n * <div className=\"status-indicator\">\n * <span className={storageContainer.isStorageInserted ? 'online' : 'offline'}>\n * {storageContainer.isStorageInserted ? 'Storage Available' : 'No Storage'}\n * </span>\n * </div>\n * <div className=\"device-count\">\n * Total Devices: {storageContainer.volumes.length}\n * </div>\n * </div>\n *\n * <div className=\"device-sections\">\n * <section className=\"available-devices\">\n * <h3>Available Storage ({availableDevices.length})</h3>\n * {availableDevices.map(device => (\n * <StorageDeviceCard key={device.id} device={device} />\n * ))}\n * </section>\n *\n * {removedDevices.length > 0 && (\n * <section className=\"removed-devices\">\n * <h3>Recently Removed ({removedDevices.length})</h3>\n * {removedDevices.map(device => (\n * <StorageDeviceCard key={device.id} device={device} />\n * ))}\n * </section>\n * )}\n * </div>\n * </div>\n * );\n * });\n * ```\n *\n * @example Storage Device Filtering and Queries\n * ```typescript\n * // Create storage container for advanced device management\n * const storageController = StorageDeviceContainer.instance('storage-ctrl')\n * .options({})\n * .build();\n *\n * // Helper functions for device filtering\n * const getStorageQueries = (container: StorageDeviceContainer) => ({\n * // Get all available (mounted and not removed) devices\n * getAvailableDevices: () =>\n * container.data.filter(device => !device.removed && device.mountDir),\n *\n * // Get devices by specific node\n * getDevicesByNode: (nodeId: string) =>\n * container.data.filter(device => device.nodeId === nodeId),\n *\n * // Get local vs remote devices\n * getLocalDevices: () =>\n * container.data.filter(device => device.local),\n *\n * // Get devices by vendor\n * getDevicesByVendor: (vendor: string) =>\n * container.data.filter(device =>\n * device.vendor.toLowerCase().includes(vendor.toLowerCase())\n * ),\n *\n * // Get backup-suitable devices (available with sufficient runtime)\n * getBackupDevices: () =>\n * container.data.filter(device =>\n * !device.removed &&\n * device.mountDir &&\n * device.runTimeMs > 300000 // More than 5 minutes runtime\n * ),\n *\n * // Get device statistics\n * getStorageStats: () => {\n * const devices = container.data;\n * return {\n * total: devices.length,\n * available: devices.filter(d => !d.removed && d.mountDir).length,\n * removed: devices.filter(d => d.removed).length,\n * local: devices.filter(d => d.local).length,\n * remote: devices.filter(d => !d.local).length,\n * averageRuntime: devices.reduce((sum, d) => sum + d.runTimeMs, 0) / devices.length\n * };\n * }\n * });\n *\n * // Usage examples\n * const queries = getStorageQueries(storageController);\n *\n * console.log('Storage Statistics:', queries.getStorageStats());\n * console.log('Available Devices:', queries.getAvailableDevices().length);\n * console.log('Backup-Ready Devices:', queries.getBackupDevices().length);\n * ```\n *\n * @example WebSocket Topic Synchronization\n * ```typescript\n * // The container automatically handles /kos/storage topic updates\n * const storageSync = StorageDeviceContainer.instance('sync-demo')\n * .options({})\n * .build();\n *\n * // Topic payload structure: StorageDeviceResponse[]\n * // Example payload when device is inserted:\n * // [\n * // {\n * // id: \"usb-drive-new\",\n * // mountDir: \"/media/usb-new\",\n * // vendor: \"Kingston\",\n * // model: \"DataTraveler\",\n * // label: \"KINGSTON_32GB\",\n * // nodeId: \"primary\",\n * // local: true,\n * // removed: false,\n * // runTimeMs: 0,\n * // syspath: \"/sys/devices/usb/new\"\n * // }\n * // ]\n *\n * // Container automatically:\n * // 1. Compares payload with existing models\n * // 2. Removes models not in payload (device unplugged)\n * // 3. Updates existing models with new state\n * // 4. Creates new models for discovered devices\n * // 5. Maintains parent-child relationships\n *\n * // Monitor changes reactively\n * const logStorageChanges = () => {\n * const currentDevices = storageSync.data.map(device => ({\n * id: device.id,\n * vendor: device.vendor,\n * mounted: !!device.mountDir,\n * removed: device.removed\n * }));\n *\n * console.log('Current Storage State:', currentDevices);\n * };\n * ```\n *\n * @example Multi-Node Storage Architecture\n * ```typescript\n * // Container manages storage across distributed KOS nodes\n * const distributedStorage = StorageDeviceContainer.instance('distributed')\n * .options({})\n * .build();\n *\n * // Analyze storage distribution across nodes\n * const analyzeStorageDistribution = () => {\n * const nodeGroups = distributedStorage.data.reduce((groups, device) => {\n * const nodeId = device.nodeId;\n * if (!groups[nodeId]) {\n * groups[nodeId] = {\n * nodeId,\n * devices: [],\n * available: 0,\n * totalRuntime: 0\n * };\n * }\n *\n * groups[nodeId].devices.push(device);\n * if (!device.removed && device.mountDir) {\n * groups[nodeId].available++;\n * }\n * groups[nodeId].totalRuntime += device.runTimeMs;\n *\n * return groups;\n * }, {} as Record<string, any>);\n *\n * // Display node distribution\n * Object.values(nodeGroups).forEach((node: any) => {\n * const avgRuntime = node.totalRuntime / node.devices.length;\n * console.log(`Node ${node.nodeId}:`);\n * console.log(` Devices: ${node.devices.length}`);\n * console.log(` Available: ${node.available}`);\n * console.log(` Avg Runtime: ${Math.round(avgRuntime / 60000)}min`);\n * });\n *\n * return nodeGroups;\n * };\n * ```\n *\n * @group KOS Model\n * @category Device Management\n *\n * @see {@link StorageDevice} - Individual storage device model\n * @see {@link StorageDeviceOptions} - Configuration options for storage devices\n * @see {@link StorageDeviceContainerOptions} - Container configuration options\n * @see {@link StorageDeviceResponse} - API response structure for device discovery\n */\nexport type StorageDeviceContainer =\n PublicModelInterface<StorageDeviceContainerModelImpl>;\n\nexport type StorageDeviceContainerModel =\n PublicModelInterface<StorageDeviceContainerModelImpl>;\n\n/**\n * @ignore\n * @internal\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 // Only add partitions or storage devices with no deviceType (for backward compatibility)\n if (storageDevice.deviceType !== \"disk\") {\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}\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 private _isSearching = false;\n private _hasSearched = false;\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 get isSearchingUpdates(): boolean {\n return this._isSearching;\n }\n\n get noAvailableUpdates(): boolean {\n return (\n this.isUsbInserted &&\n this._hasSearched &&\n !this._isSearching &&\n this._models.data.length === 0\n );\n }\n\n async syncAvailableUpdates() {\n kosAction(() => {\n this._isSearching = true;\n });\n\n try {\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 } finally {\n kosAction(() => {\n this._isSearching = false;\n this._hasSearched = true;\n });\n }\n }\n\n @kosModelEffect({\n dependencies: (model) => [\n model.isUsbInserted,\n model.storageService.data.length,\n ],\n })\n usbInsertedEffect() {\n if (this.isUsbInserted) {\n this.syncAvailableUpdates();\n } else {\n this._models.clear();\n this.clearActiveUpdate();\n kosAction(() => {\n this._hasSearched = false;\n this._isSearching = false;\n });\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","/**\n * @fileoverview Translation service functions for internationalization and localization.\n *\n * This module provides service functions for loading translation data, managing locale\n * descriptors, and handling multi-language content in KOS applications. Supports both\n * static file-based translations and dynamic translation service integration.\n *\n * @module TranslationServices\n */\n\nimport {\n KosLog,\n ServiceFactory,\n getQueryParams,\n resolveServiceUrl,\n} from \"../../../../core\";\n\n/** Base URL for translation service endpoints */\nconst { URL } = resolveServiceUrl(\"TRANSLATION_SERVICE\");\n\n/** Pre-configured service methods for translation operations */\nconst { getOne } = ServiceFactory.build({\n basePath: `${URL}/api/translation`,\n});\n\n/** Logger instance for translation service operations */\nconst log = KosLog.createLogger({\n name: \"translation-service\",\n group: \"Services\",\n});\n\n/**\n * Generic translation data response format.\n *\n * Represents the structure of translation data returned from various translation\n * endpoints, supporting flexible key-value structures for different locales\n * and translation namespaces.\n *\n * @group KOS Model\n * @category i18n\n */\nexport type TranslationResponse = Record<string, any>;\n\n/**\n * Locale descriptor defining translation file location and fallback behavior.\n *\n * Describes how to locate and load translation files for a specific locale,\n * including fallback chains for graceful degradation when translations are\n * missing or incomplete.\n *\n * @group KOS Model\n * @category i18n\n */\nexport interface LocaleDescriptor {\n /** Default locale to use when this locale's translations are unavailable */\n defaultLocale: string;\n /** Path to the translation file for this locale */\n file: string;\n /** Optional array of fallback locales to try in order */\n fallbacks?: string[];\n}\n\n/**\n * Complete localization configuration for organizing translation namespaces.\n *\n * Defines the structure for managing multiple translation namespaces with\n * locale-specific configurations. Enables organized translation management\n * across different features or components of an application.\n *\n * @group KOS Model\n * @category i18n\n */\nexport interface Localization {\n /**\n * Translation namespaces organized by feature or component.\n * Each namespace contains locale configurations and file paths.\n */\n namespaces: {\n [key: string]: {\n /** Locale-specific configuration for this namespace */\n locales: {\n [key: string]: LocaleDescriptor;\n };\n /** Base path for translation files in this namespace */\n basePath: string;\n };\n };\n /** Root path for the localization configuration */\n path: string;\n}\n\n/**\n * Determines the default host URL for translation file requests.\n *\n * Resolves the base URL for loading translation files, checking query parameters\n * for host overrides before falling back to the current window location. Used\n * internally for constructing complete URLs to translation resources.\n *\n * @returns Default host URL for translation requests\n * @internal\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/**\n * Loads translation data from a specified URL.\n *\n * Fetches translation JSON files from static resources or translation services.\n * Handles network errors gracefully by returning empty objects rather than\n * throwing exceptions, enabling fallback behavior in translation systems.\n *\n * @param url - Relative or absolute URL to the translation file\n * @param root - Optional root URL override (defaults to current window origin)\n * @returns Promise resolving to translation data object\n *\n * @throws {Error} When network request fails unexpectedly (non-200 responses return empty object)\n *\n * @example Load Translation File\n * ```typescript\n * const frenchTranslations = await getTranslations('/assets/locales/fr/common.json');\n * console.log('Welcome message:', frenchTranslations.welcome);\n *\n * const customTranslations = await getTranslations('/api/translations/dashboard', 'https://translations.example.com');\n * ```\n *\n * @group KOS Model\n * @category i18n\n */\nexport const getTranslations = async (url: string, root?: string) => {\n log.debug(`Loading translations from: ${url}`);\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\n/**\n * Retrieves the system-wide localization configuration descriptor.\n *\n * Fetches the complete localization configuration from the KOS system,\n * including namespace definitions, locale mappings, and file path information.\n * Used for initializing translation containers with proper configuration.\n *\n * @returns Promise resolving to complete localization descriptor\n *\n * @throws {Error} When service request fails or returns non-200 status\n *\n * @example Initialize Translation System\n * ```typescript\n * const localizationConfig = await getLocalizationDescriptor();\n * const translationContainer = TranslationContainer.instance('app-i18n')\n * .options({\n * lang: 'en',\n * descriptor: localizationConfig\n * })\n * .build();\n * ```\n *\n * @group KOS Model\n * @category i18n\n */\nexport const getLocalizationDescriptor = async () => {\n log.debug(\"Getting system 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 localization descriptor ${response?.status}`\n );\n }\n return response.data;\n};\n\n/**\n * Creates a context-specific localization descriptor retrieval function.\n *\n * Returns a curried function that fetches localization configuration for a\n * specific context from the KOS system. Useful for creating context-aware\n * translation loaders that can be configured once and used multiple times.\n *\n * @param context - Context identifier for localization configuration\n * @returns Async function that retrieves context-specific localization descriptor\n *\n * @throws {Error} When service request fails or context is not found\n *\n * @example Create Context-Specific Loader\n * ```typescript\n * const getStudioTranslations = getKosLocalizationDescriptor('studio');\n * const studioConfig = await getStudioTranslations();\n *\n * const getDeviceTranslations = getKosLocalizationDescriptor('device');\n * const deviceConfig = await getDeviceTranslations();\n *\n * // Use in translation container initialization\n * const container = TranslationContainer.instance('context-aware')\n * .options({\n * lang: 'es',\n * descriptor: studioConfig\n * })\n * .build();\n * ```\n *\n * @group KOS Model\n * @category i18n\n */\nexport const getKosLocalizationDescriptor = (context: string) => async () => {\n log.debug(`Getting KOS localization descriptor for context: ${context}`);\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 KOS localization descriptor ${response?.status}`\n );\n }\n return response.data[context];\n};\n","/**\n * Folding several localization contexts into the one descriptor a\n * TranslationContainer is built from.\n *\n * Extracted from KosTranslationProvider so the rules are reachable without a\n * DOM: this is where \"what happens when you add another context to the array\"\n * is actually decided, and it is the only place that decides it.\n */\nimport type { Localization } from \"./services\";\n\n/** A locale code paired with its name, rendered in that locale's own language. */\nexport interface LocaleOption {\n locale: string;\n label: string;\n}\n\n/**\n * Fold contexts into one descriptor, EARLIER ENTRIES WINNING.\n *\n * Precedence is per NAMESPACE, not per key or per locale: a namespace declared\n * by two contexts is taken whole from the earlier one, and the later context's\n * locales for that namespace are dropped even where the winner has none. Adding\n * a context therefore only ever ADDS namespaces the earlier ones did not\n * declare — it can never extend or patch one they did.\n *\n * Each namespace's `basePath` is set to its own context's `path`, so namespaces\n * from different contexts keep resolving against the URL their context is\n * served from.\n *\n * The merged descriptor carries no top-level `path`: with namespaces from\n * several contexts there is no single one, and `basePath` already carries it\n * per namespace, which is what `defaultResolver` reads.\n */\nexport function mergeLocalizationDescriptors(\n descriptors: Localization[]\n): Localization {\n const merged: Localization[\"namespaces\"] = {};\n\n // Reverse, so the first context's namespaces are applied last and win.\n for (const descriptor of [...descriptors].reverse()) {\n for (const [name, namespace] of Object.entries(\n descriptor.namespaces ?? {}\n )) {\n merged[name] = { ...namespace, basePath: descriptor.path };\n }\n }\n\n return { namespaces: merged } as Localization;\n}\n\n/**\n * Every locale any namespace offers, as picker options.\n *\n * A UNION across namespaces, so one namespace translated into a locale is\n * enough to offer that locale for the whole app; namespaces without it fall\n * back at resolve time. Excluded namespaces contribute nothing — that is how a\n * content-bearing namespace (a brandset) is kept from advertising locales the\n * UI itself cannot render.\n *\n * Labels come from `Intl.DisplayNames`, not from any KAB, and are rendered in\n * the locale's own language (\"italiano\", not \"Italian\").\n */\nexport function collectLocaleOptions(\n descriptors: Localization[],\n excludeNamespaces: string[] = []\n): LocaleOption[] {\n const codes = new Set<string>();\n\n for (const descriptor of descriptors) {\n for (const [name, namespace] of Object.entries(\n descriptor.namespaces ?? {}\n )) {\n if (excludeNamespaces.includes(name)) continue;\n for (const locale of Object.keys(namespace.locales ?? {})) {\n codes.add(locale);\n }\n }\n }\n\n return Array.from(codes).map((locale) => {\n return {\n locale,\n label: new Intl.DisplayNames([locale], { type: \"language\" }).of(\n locale\n ) as string,\n };\n });\n}\n","export const CONTEXT_LANG_RESOLVER = \"langResolver\";\n","/**\n * @ignore\n * @internal\n */\nimport { IReactionDisposer } 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 kosModelEffect,\n kosParentAware,\n} from \"../../../core\";\nimport type { PublicModelInterface } from \"../../../core/types\";\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>;\n/**\n * Translation - Individual namespace translations with automatic locale switching and interpolation.\n *\n * The Translation model provides access to localized text for a specific namespace within a KOS\n * application. It handles locale switching, fallback chains, variable interpolation, and context-aware\n * translations for building truly international device interfaces that adapt to user language preferences\n * automatically.\n *\n * ## Key Features\n * - **Namespace Isolation** - Translations organized by functional area or feature\n * - **Automatic Locale Switching** - React to parent container locale changes\n * - **Fallback Chains** - Graceful degradation through locale hierarchy (pt-BR → pt → es → en)\n * - **Variable Interpolation** - Support for both template (`{{variable}}`) and macro (`__variable__`) substitution\n * - **Context-Aware Keys** - Conditional translations based on context (e.g., `title_edit` vs `title`)\n * - **Real-time Updates** - Automatic UI updates when locale or translations change\n * - **Bundle Resolution** - Custom loading strategies for different deployment scenarios\n *\n * ## Variable Interpolation Patterns\n * The model supports two interpolation patterns for dynamic content:\n * - **Template Variables** (`{{variable}}`) - Context-based substitution passed via options\n * - **Macro Variables** (`__variable__`) - Data-based substitution from nested objects\n *\n * ## Fallback Resolution\n * When translations are missing, the system follows a sophisticated fallback chain:\n * 1. **Current locale** (e.g., `pt-BR`)\n * 2. **Parent locale** (e.g., `pt`)\n * 3. **Fallback locales** (configured per locale, e.g., `es`)\n * 4. **Default locale** (typically `en`)\n * 5. **Provided default value** or raw key\n *\n * ## Common Use Cases\n * - **Feature-Specific UI** - Isolated translations for dashboards, settings, alerts\n * - **Form Validation** - Localized error messages with variable interpolation\n * - **Status Displays** - Dynamic content with device state and user context\n * - **Multi-Language Interfaces** - Complete internationalization for global deployments\n * - **Context-Aware Content** - Mode-specific text (create vs edit, online vs offline)\n * - **Rich Text Support** - Integration with Trans component for formatted content\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const statusTranslations = Translation.instance('device-status')\n * .options({\n * namespace: 'device-status',\n * currentLocale: 'es',\n * defaultLocale: 'en',\n * descriptor: {\n * 'es': { fallbacks: ['en'] },\n * 'en': { fallbacks: [] }\n * }\n * })\n * .build();\n *\n * // Resolve localized keys with fallback support\n * const title = statusTranslations.resolveKey('title');\n * ```\n *\n * @group KOS Model\n * @category i18n\n * @useDeclaredType\n *\n * @see {@link TranslationOptions} - Configuration options for Translation instances\n * @see {@link TranslationContainerModel} - Container for managing multiple translation namespaces\n * @see {@link useKosTranslation} - React hook for accessing translations in components\n * @see {@link Trans} - React component for rich text translations with markup\n */\nexport type TranslationModel = PublicModelInterface<TranslationModelImpl>;\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 (\n typeof obj[key] === \"object\" &&\n obj[key] !== null &&\n !Array.isArray(obj[key])\n ) {\n const flattenedChild = flattenObject(obj[key], newKey);\n return { ...acc, ...flattenedChild };\n } else {\n return { ...acc, [newKey]: obj[key] };\n }\n }, {});\n}\n/**\n * Overlay one locale's bundle onto the accumulated one.\n *\n * Objects merge key by key, so a locale translating part of a nested group\n * inherits the rest. Arrays REPLACE: a translated list is one unit, and merging\n * two by index would splice a base-locale tail onto a shorter translation.\n * Arrays must be tested before the object branch, since `typeof [] === \"object\"`.\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 !Array.isArray(overlay[key]) &&\n typeof base[key] === \"object\" &&\n base[key] !== null &&\n !Array.isArray(base[key])\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(regex, (match, key) => {\n const trimmedKey = key.trim();\n\n // First, try to look up the raw key as-is\n if (Object.prototype.hasOwnProperty.call(context || {}, trimmedKey)) {\n return context?.[trimmedKey];\n }\n\n // If not found and key contains a dot, traverse the dotted path\n if (trimmedKey.includes(\".\")) {\n const parts = trimmedKey.split(\".\");\n let value: any = context;\n\n // Fail-fast traversal along the dotted path\n for (const part of parts) {\n if (\n value &&\n typeof value === \"object\" &&\n Object.prototype.hasOwnProperty.call(value, part)\n ) {\n value = value[part];\n } else {\n // Path traversal failed, return original match\n return match;\n }\n }\n\n // Successfully traversed the path\n return value;\n }\n\n // Key not found, return original match\n return match;\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 /** Unique identifier for the model instance */\n id: string;\n /** Namespace identifier for translation key isolation */\n namespace: string;\n /** Locale descriptor configuration mapping locales to fallback chains */\n descriptor: Record<string, LocaleDescriptor>;\n /** Default locale to use when no translation is found in fallback chain */\n defaultLocale: string;\n /** Currently active locale for translation resolution */\n currentLocale: string;\n /** Custom bundle resolver for loading translation data */\n bundleResolver?: (\n namespace: string,\n locale: string,\n context?: KosContext\n ) => Promise<TranslationResponse>;\n /** Flattened translation data for efficient key lookup */\n private data: Record<string, any>;\n /** Context logger for debugging and diagnostics */\n private logger: KosContextLogger;\n /** Path resolver function for translation bundle location */\n private resolver: (namespace: string, locale: string) => string;\n /** Reaction disposer for locale change monitoring */\n private disposer?: IReactionDisposer;\n /** Parent translation container reference for namespace resolution */\n private context: TranslationContainerModel;\n /** Base URL for loading translation resources */\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 /**\n * Builds the fallback chain for a given locale.\n * @param locale The locale to get translation fallback chain for\n * @returns Array of locales in priority order\n * @private\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 /**\n * Loads and merges translations for all locales in the fallback chain.\n * @private\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 /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing translation ${this.id}`);\n }\n\n /**\n * Checks if a translation key exists in the current namespace.\n * @param _key Translation key, optionally with namespace prefix\n * @returns True if the key exists\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 /**\n * Resolves a translation key with optional variable interpolation.\n * @param _key Translation key, optionally with namespace prefix\n * @param options Options for interpolation and fallback\n * @returns Resolved translation string or array\n */\n resolveKey<T = string>(\n _key: string,\n options?: ResolveTranslationOptions<T> | string\n ) {\n if (!_key) {\n this.logger.debug(`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 defaultValue ?? 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[key];\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 /**\n * @internal\n */\n unload(): void {\n this.logger.debug(`unloading translation ${this.id}`);\n if (this.disposer) {\n this.disposer();\n }\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading translation ${this.id}`);\n await this.loadTranslations();\n }\n\n /**\n * @internal\n */\n async ready(): Promise<void> {\n this.logger.debug(`ready translation ${this.id}`);\n }\n\n @kosModelEffect({\n dependencies: (model) => [model.currentLocale],\n })\n async handleCurrentLocaleChange() {\n await this.loadTranslations();\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 whenReady,\n} from \"../../../core\";\n\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { CONTEXT_LANG_RESOLVER } from \"./constants\";\nimport { Localization } from \"./services\";\nimport type { TranslationModel } from \"./translation-model\";\nimport { Translation } from \"./translation-registration\";\nimport type { TranslationContainerOptions, TranslationOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"translation-container-model\";\n\n/**\n * TranslationContainer - Multi-namespace translation management with automatic locale switching.\n *\n * The TranslationContainer model serves as the central orchestrator for internationalization in KOS\n * applications. It manages multiple translation namespaces, handles global locale switching, and provides\n * namespace resolution with fallback chains. This container enables building sophisticated multi-language\n * interfaces that adapt automatically to user language preferences across all application features.\n *\n * ## Key Features\n * - **Multi-Namespace Management** - Organize translations by feature areas (dashboard, alerts, settings)\n * - **Global Locale Control** - Centralized locale switching affects all contained translation models\n * - **Automatic Discovery** - Dynamic namespace loading and registration as features request translations\n * - **Fallback Resolution** - Sophisticated locale fallback chains for graceful degradation\n * - **Custom Resolvers** - Flexible translation loading strategies for different deployment scenarios\n * - **Reload Capability** - Dynamic translation updates without application restart\n * - **Default Namespace** - Optional primary namespace for application-wide common translations\n *\n * ## Namespace Organization\n * Translation namespaces organize translations by functional areas:\n * - **Feature-Based**: dashboard, device-config, maintenance, alerts\n * - **Component-Based**: forms, modals, navigation, status-displays\n * - **Common**: common, shared, ui-elements for cross-cutting concerns\n *\n * ## Locale Management Architecture\n * The container manages locale switching across all child translation models:\n * 1. **Centralized Control**: Single point for locale changes\n * 2. **Automatic Propagation**: All child models receive locale updates\n * 3. **Reactive Loading**: Translation files loaded automatically on locale switch\n * 4. **Fallback Coordination**: Container coordinates fallback chains across namespaces\n *\n * ## Common Use Cases\n * - **Application Initialization** - Bootstrap internationalization system with locale descriptors\n * - **User Language Switching** - Provide language selector that updates entire application\n * - **Feature Translation Loading** - Dynamic namespace registration as features are accessed\n * - **Multi-Tenant Systems** - Different translation sets for different deployments\n * - **Development Workflows** - Hot-reload translations during development\n * - **Global Device Interfaces** - Centralized management for device control applications\n *\n * @example Basic Usage\n * ```typescript\n * const translationContainer = TranslationContainer.instance('app-translations')\n * .options({\n * lang: 'es',\n * defaultNamespace: 'common',\n * descriptor: {\n * namespaces: {\n * 'common': {\n * basePath: '/assets/locales',\n * locales: {\n * 'en': { file: 'en/common.json', defaultLocale: 'en' },\n * 'es': { file: 'es/common.json', defaultLocale: 'en' }\n * }\n * }\n * }\n * }\n * })\n * .build();\n *\n * // Access translations and switch language\n * const commonTranslations = translationContainer.getModel('common');\n * translationContainer.currentLocale = 'fr';\n * ```\n *\n * @group KOS Model\n * @category i18n\n * @interface\n * @useDeclaredType\n *\n * @see {@link TranslationContainerOptions} - Configuration options for TranslationContainer instances\n * @see {@link TranslationModel} - Individual translation namespace model\n * @see {@link useKosTranslation} - React hook for accessing container translations\n * @see {@link useKosTranslationContext} - React hook for container-level operations\n */\nexport type TranslationContainerModel =\n PublicModelInterface<TranslationContainerModelImpl>;\n\nconst pathJoin = (parts: string[], 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/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class TranslationContainerModelImpl\n implements\n IKosIdentifiable,\n IKosModelHolder<TranslationModel>,\n IKosDataModel,\n ReloadAware\n{\n /** Unique identifier for the container model instance */\n id: string;\n /** Currently active locale for all managed translation namespaces */\n lang: string;\n /** Base URL for loading translation resources */\n private rootUrl?: string;\n /** Localization descriptor defining namespace configuration and locale mappings */\n descriptor: Localization;\n /** Optional default namespace identifier for primary application translations */\n private _defaultNamespace?: string;\n /** Path resolver function for constructing translation file URLs */\n private resolver: (\n this: TranslationContainerModel,\n namespace: string,\n locale: string\n ) => string;\n /** Context logger for debugging translation operations */\n private logger: KosContextLogger;\n /** URL for dynamically loading localization descriptors */\n private descriptorUrl?: string;\n /** Array tracking registered namespace identifiers */\n private namespaces: string[] = [];\n /** Container-wide bundle loader, handed to every namespace it resolves */\n private bundleResolver?: TranslationOptions[\"bundleResolver\"];\n /** Container for managing Translation model instances */\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 this.bundleResolver = options.bundleResolver;\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 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 bundleResolver: this.bundleResolver,\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 bundleResolver: this.bundleResolver,\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 /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(\n \"initializing translation-container container \" + this.id\n );\n }\n\n /**\n * @internal\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 * @group KOS Model\n * @category i18n\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 { 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","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\";\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 { KosLogManager, LogStreamContainer } from \"../models\";\nimport { BrowserRouter } from \"../models/browser-router\";\nimport { CanvasDispatcher } from \"../models/canvas-dispatcher\";\nimport { CanvasRenderer } from \"../models/canvas-renderer\";\nimport { ConfigBean } from \"../models/config-bean/config-bean-model\";\nimport { Device } from \"../models/device\";\nimport { KeyValue } from \"../models/key-value\";\nimport { KosExpressionEvaluator } from \"../models/kos-expression-evaluator\";\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\";\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(CanvasDispatcher)\n .model(CanvasRenderer)\n .model(KosExpressionEvaluator)\n .model(BrowserRouter, PRELOAD)\n .model(LogStreamContainer)\n .model(KosLogManager);\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 {\n ExtensionManager,\n ExtensionOptions,\n PropertyMapper,\n type DataLoader,\n} from \"../../core\";\nimport { KosCoreModelPropertyMapper } from \"../constants\";\nimport type { IConfigBeanModel, RegionInfoModel } from \"../models\";\nimport { CanvasDispatcher } from \"../models/canvas-dispatcher\";\nimport type { TroubleResponse } from \"../models/trouble/services\";\n\nexport type TroubleRankMapper = PropertyMapper<TroubleResponse, number, any>;\n\nexport type TroubleColorMapper = PropertyMapper<TroubleResponse, string, any>;\n\nexport type TroubleRoleMapper = PropertyMapper<TroubleResponse, string, any>;\n\nexport type RegionServicePathMapper = PropertyMapper<\n RegionInfoModel,\n string,\n any\n>;\n\nexport type ConfigServicePathMapper = PropertyMapper<\n IConfigBeanModel,\n string,\n any\n>;\nexport class CoreExtensionManager {\n /**\n * Maps the rank property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleRankMapper - Mapping function that derives a numeric rank from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleRankMapper(\n troubleRankMapper: TroubleRankMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRank,\n troubleRankMapper,\n options\n );\n return this;\n }\n\n /**\n * Maps the role property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleRoleMapper - Mapping function that derives a role string from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleRoleMapper(\n troubleRoleMapper: TroubleRoleMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRole,\n troubleRoleMapper,\n options\n );\n return this;\n }\n\n /**\n * Maps the color property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleColorMapper - Mapping function that derives a color string from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleColorMapper(\n troubleColorMapper: TroubleColorMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleColor,\n troubleColorMapper,\n options\n );\n return this;\n }\n\n /**\n * Registers a data loader for a given model id. The loader is invoked during model\n * initialization to fetch data that is provided as context to associated mappers.\n *\n * @param id - The model identifier to associate the loader with\n * @param loader - Async function that loads and returns data for the model\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on loader failure.\n * Set to `\"continue\"` to log the error and return `undefined` instead.\n */\n registerModelLoader(\n id: string,\n loader: DataLoader,\n options?: ExtensionOptions\n ) {\n ExtensionManager.loader.registerLoader(id, loader, options);\n }\n\n registerRegionServicePathMapper(\n regionServicePathMapper: RegionServicePathMapper\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.RegionServicePath,\n regionServicePathMapper\n );\n return this;\n }\n\n /**\n * Registers a data loader for the {@link CanvasDispatcher} pattern data.\n *\n * @param loader - Async function that loads canvas pattern data\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on loader failure.\n * Set to `\"continue\"` to log the error and return `undefined` instead.\n */\n registerCanvasPatternLoader(loader: DataLoader, options?: ExtensionOptions) {\n ExtensionManager.loader.registerLoader(\n CanvasDispatcher.loader,\n loader,\n options\n );\n }\n\n registerConfigServicePathMapper(\n configServicePathMapper: ConfigServicePathMapper\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.ConfigServicePath,\n configServicePathMapper\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","/**\n * Public accessor for the KOS API service client.\n *\n * Encapsulates the dynamic import of the internal `service` module,\n * preserving the lazy-load pattern while providing a stable import\n * path for external consumers (e.g., @matrica-code/kos-declarative-model).\n */\nexport async function getKosServiceApi() {\n const { default: API } = await import(\"./service\");\n return API;\n}\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Methods a response type can be derived for — the lowercase subset of\n * HttpMethod. The uppercase spellings HttpMethod also permits do not match the\n * keys of an OpenAPI `paths` object, so they would silently yield `unknown`.\n */\nexport type SupportedMethod = \"get\" | \"post\" | \"put\" | \"delete\";\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends SupportedMethod = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\",\n Transformed = ApiResponse<Path, SupportedMethod & Method>\n> = KosExecutionContext<paths, Path, Method, Transformed>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with kos API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/daily/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * One endpoint of the kos API: a path and the method it is called with.\n */\nexport interface Endpoint {\n path: ApiPath;\n method: SupportedMethod;\n}\n\n/**\n * Declare an endpoint once. The decorator config, the execution context type\n * and the response type are all derived from the result, so a path string is\n * never restated — and never drifts between the three.\n *\n * @example\n * ```typescript\n * export const BoardApi = {\n * list: endpoint(\"/api/board\", \"get\"),\n * update: endpoint(\"/api/board/{id}\", \"put\"),\n * } as const;\n * ```\n */\nexport function endpoint<Path extends ApiPath, Method extends SupportedMethod>(\n path: Path,\n method: Method\n) {\n return { path, method } as const;\n}\n\n/**\n * Execution context for an endpoint — the method-driven `$ctx` parameter type.\n * Pass `Transformed` when the decorator declares a `transform`, so what the\n * method receives is typed as the mapper's output rather than the raw response.\n */\nexport type EndpointCtx<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n> = ExecutionContext<E[\"path\"], E[\"method\"], Transformed>;\n\n/** Response body type for an endpoint. */\nexport type EndpointResponse<E extends Endpoint> = ApiResponse<\n E[\"path\"],\n E[\"method\"]\n>;\n\n/**\n * @kosServiceRequest preconfigured from an endpoint descriptor, defaulting to\n * log-and-continue error handling. Pass overrides (lifecycle, errorHandler,\n * cache, …) as the second argument.\n *\n * A `transform` narrows what the model receives: its return type becomes the\n * handler's data type, so the raw response shape stops at the mapper.\n *\n * @example\n * ```typescript\n * @serviceRequest(BoardApi.update)\n * async renameBoard(name: string, $ctx?: EndpointCtx<typeof BoardApi.update>) {\n * const data = await executeServiceRequest(this, $ctx, {\n * pathParams: { id: this.id },\n * body: { name },\n * });\n * if (!data) return;\n * }\n * ```\n */\nexport function serviceRequest<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n>(\n ep: E,\n opts?: Partial<\n IKosServiceRequestParams<\n paths,\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >\n >\n) {\n return kosServiceRequest<\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >({\n path: ep.path,\n method: ep.method,\n errorHandler: { strategy: \"log\", defaultValue: null },\n ...opts,\n });\n}\n\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with kos API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.6.5/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with kos API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.8.1/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with kos API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.9.x/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Methods a response type can be derived for — the lowercase subset of\n * HttpMethod. The uppercase spellings HttpMethod also permits do not match the\n * keys of an OpenAPI `paths` object, so they would silently yield `unknown`.\n */\nexport type SupportedMethod = \"get\" | \"post\" | \"put\" | \"delete\";\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends SupportedMethod = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\",\n Transformed = ApiResponse<Path, SupportedMethod & Method>\n> = KosExecutionContext<paths, Path, Method, Transformed>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/daily/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * One endpoint of the vfs API: a path and the method it is called with.\n */\nexport interface Endpoint {\n path: ApiPath;\n method: SupportedMethod;\n}\n\n/**\n * Declare an endpoint once. The decorator config, the execution context type\n * and the response type are all derived from the result, so a path string is\n * never restated — and never drifts between the three.\n *\n * @example\n * ```typescript\n * export const BoardApi = {\n * list: endpoint(\"/api/board\", \"get\"),\n * update: endpoint(\"/api/board/{id}\", \"put\"),\n * } as const;\n * ```\n */\nexport function endpoint<Path extends ApiPath, Method extends SupportedMethod>(\n path: Path,\n method: Method\n) {\n return { path, method } as const;\n}\n\n/**\n * Execution context for an endpoint — the method-driven `$ctx` parameter type.\n * Pass `Transformed` when the decorator declares a `transform`, so what the\n * method receives is typed as the mapper's output rather than the raw response.\n */\nexport type EndpointCtx<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n> = ExecutionContext<E[\"path\"], E[\"method\"], Transformed>;\n\n/** Response body type for an endpoint. */\nexport type EndpointResponse<E extends Endpoint> = ApiResponse<\n E[\"path\"],\n E[\"method\"]\n>;\n\n/**\n * @kosServiceRequest preconfigured from an endpoint descriptor, defaulting to\n * log-and-continue error handling. Pass overrides (lifecycle, errorHandler,\n * cache, …) as the second argument.\n *\n * A `transform` narrows what the model receives: its return type becomes the\n * handler's data type, so the raw response shape stops at the mapper.\n *\n * @example\n * ```typescript\n * @serviceRequest(BoardApi.update)\n * async renameBoard(name: string, $ctx?: EndpointCtx<typeof BoardApi.update>) {\n * const data = await executeServiceRequest(this, $ctx, {\n * pathParams: { id: this.id },\n * body: { name },\n * });\n * if (!data) return;\n * }\n * ```\n */\nexport function serviceRequest<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n>(\n ep: E,\n opts?: Partial<\n IKosServiceRequestParams<\n paths,\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >\n >\n) {\n return kosServiceRequest<\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >({\n path: ep.path,\n method: ep.method,\n errorHandler: { strategy: \"log\", defaultValue: null },\n ...opts,\n });\n}\n\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.6.5/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.8.1/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.9.x/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\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 * Event name for timer-tick events.\n */\nexport const TOPIC_TIMER_TICK_EVENT = `/kos-timer-event/tick`;\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 get id() {\n return this.name;\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 this.notifyTick();\n }\n\n private notifyTick() {\n EventBus.publish(`${TOPIC_TIMER_TICK_EVENT}/${this.name}`, {\n name: this.name,\n remainingTime: this.remainingTime,\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","/**\n * @internal\n */\n// eslint-disable-next-line @nx/enforce-module-boundaries\nimport { FetchError, KosLog } from \"../../../../core\";\nimport { api, type BaseResponseType } from \"../../../utils\";\nimport { createCancellableService } from \"../../../utils/cancellable-service\";\nimport { getKosConnectionId } from \"../../../utils/get-kos-connection-id\";\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 * @param signal - Optional AbortSignal to cancel the request\n */\nexport const getSoftwareInfos = async (\n signal?: AbortSignal\n): Promise<DeviceSoftwareInfoResponse> => {\n const destinationAddress = getKosConnectionId();\n log.debug(\"sending GET for software-info\");\n const [error, response] = await api.get(\"/api/kos/manifest/info\", undefined, {\n signal,\n destinationAddress,\n });\n\n if (!response) {\n // Check if it was aborted\n if (signal?.aborted) {\n log.debug(\"Request was aborted\");\n throw new FetchError(\"Request was aborted\");\n }\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\n/**\n * Cancellable version of getSoftwareInfos\n * @example\n * ```typescript\n * // In your model\n * const data = await getSoftwareInfosWithCancel();\n *\n * // Cancel if needed\n * getSoftwareInfosWithCancel.cancel();\n *\n * // Check if active\n * if (getSoftwareInfosWithCancel.isActive()) {\n * console.log('Request in progress');\n * }\n * ```\n */\nexport const getSoftwareInfosWithCancel =\n createCancellableService(getSoftwareInfos);\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 type { PublicModelInterface } from \"../../../core/types\";\nimport { FetchError } from \"../../../core/util/service-factory\";\nimport { getSoftwareInfos } from \"./services\";\nimport type { ArtifactsType, NodeInfoType, SoftwareInfoOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"software-info-model\";\n\n/**\n * SoftwareInfo - System software version and artifact management for KOS devices.\n *\n * The SoftwareInfo model provides comprehensive visibility into installed software versions,\n * artifacts, and system components across all nodes in a KOS device. This model is essential\n * for applications that need to display system information, perform version checks, or\n * manage software compatibility and updates.\n *\n * ## Key Features\n * - **Node-Based Architecture** - Track software information across multiple device nodes\n * - **Artifact Management** - Complete visibility into installed software components and versions\n * - **Version Tracking** - Monitor KOS framework versions and application artifacts\n * - **Group Organization** - Automatic categorization of artifacts by functional groups\n * - **System Overview** - Comprehensive system software inventory and version reporting\n * - **Compatibility Checking** - Version information for dependency and compatibility validation\n *\n * ## Data Structure\n * The model organizes software information hierarchically:\n * - **Nodes** - Individual system nodes (primary, secondary, etc.)\n * - **Artifacts** - Software components installed on each node\n * - **Groups** - Logical grouping of related artifacts (core, ui, services, etc.)\n * - **Versions** - Specific version information for each artifact\n *\n * ## Common Use Cases\n * - **System Information Display** - Show installed software versions to users and administrators\n * - **Version Compatibility** - Check software versions before updates or feature activation\n * - **Support Diagnostics** - Provide detailed software information for troubleshooting\n * - **Update Planning** - Assess current software state before planning updates\n * - **Inventory Management** - Track and report on installed software components\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const softwareInfo = SoftwareInfo.instance('system-info').build();\n *\n * // Access system software information across nodes\n * const nodes = softwareInfo.nodes;\n * nodes?.forEach(node => {\n * console.log(`Node ${node.nodeName}: KOS ${node.kosVersion}`);\n * });\n * ```\n *\n * @group KOS Model\n * @category System Integration\n * @useDeclaredType\n *\n * @see {@link SoftwareInfoOptions} - Configuration options for SoftwareInfo model\n * @see {@link NodeInfoType} - Individual node software information\n * @see {@link ArtifactsType} - Software artifact information\n * @see {@link getSoftwareInfos} - Service function for loading software data\n */\nexport type SoftwareInfoModel = PublicModelInterface<SoftwareInfoModelImpl>;\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class SoftwareInfoModelImpl implements IKosDataModel {\n /** Unique identifier for the model instance */\n id: string;\n private logger: KosContextLogger;\n\n /** Software information for all device nodes, including KOS versions and artifacts */\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 /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing software-info ${this.id}`);\n }\n\n /**\n * Groups artifacts by a specified property for organization.\n * @param arr Array of artifacts to group\n * @param property Property to group by\n * @returns Grouped artifacts organized by the specified property\n * @private\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 /**\n * @internal\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\n const updatedList = nodeList.map((el) => {\n return {\n nodeName: el.nodeType,\n kosVersion: el.kosVersion,\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","import type { TroubleAware } from \"../types\";\n\n/**\n * Type guard function to check if an object implements the TroubleAware interface.\n *\n * This function performs runtime validation to determine whether a given object\n * has the necessary properties and structure to be considered trouble-aware.\n * It checks for the presence of both the `troubles` array and `troublesByType`\n * object, which are required by the TroubleAware interface.\n *\n * @category Utilities\n * @category Trouble Management\n *\n * @param obj - The object to check for trouble awareness. Can be any type.\n *\n * @returns `true` if the object implements TroubleAware interface, `false` otherwise.\n * When this function returns true, TypeScript will narrow the type of `obj`\n * to `TroubleAware` in the current scope.\n *\n * @example\n * ```typescript\n * // Basic type guard usage\n * function processModel(model: IKosDataModel) {\n * if (isTroubleAware(model)) {\n * // TypeScript now knows model has troubles property\n * console.log(`Found ${model.troubles.length} troubles`);\n * console.log(`Trouble status: ${model.troubleStatus}`);\n * } else {\n * console.log('Model is not trouble-aware');\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Using with React hooks for conditional trouble handling\n * const TroubleDisplay: React.FC<{ model: IKosDataModel }> = ({ model }) => {\n * if (!isTroubleAware(model)) {\n * return <div>No trouble tracking available</div>;\n * }\n *\n * // Safe to access trouble properties here\n * const criticalTroubles = model.troubles.filter(t => t.rank > 8);\n * const troubleTypes = Object.keys(model.troublesByType);\n *\n * return (\n * <div>\n * <h3>Trouble Status: {model.troubleStatus}</h3>\n * <p>Critical issues: {criticalTroubles.length}</p>\n * <p>Types: {troubleTypes.join(', ')}</p>\n * </div>\n * );\n * };\n * ```\n *\n * @example\n * ```typescript\n * // Filtering trouble-aware models from a collection\n * const models: IKosDataModel[] = getAllModels();\n * const troubleAwareModels = models.filter(isTroubleAware);\n *\n * // TypeScript knows troubleAwareModels is TroubleAware[]\n * troubleAwareModels.forEach(model => {\n * const troublesByType = model.troublesByType;\n * Object.entries(troublesByType).forEach(([type, troubles]) => {\n * console.log(`Type ${type}: ${troubles.length} troubles`);\n * });\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Early return pattern for non-trouble-aware models\n * function calculateTroubleSeverity(model: any): number {\n * if (!isTroubleAware(model)) {\n * return 0; // No troubles means no severity\n * }\n *\n * // Calculate weighted severity based on trouble ranks\n * return model.troubles.reduce((total, trouble) => {\n * return total + (trouble.rank * (trouble.deferred ? 0.5 : 1));\n * }, 0);\n * }\n * ```\n *\n * @remarks\n * - This is a runtime check, not a compile-time check\n * - The function checks for structural compatibility, not nominal typing\n * - It validates that `troubles` is specifically an Array instance, not just array-like\n * - The `troublesByType` property must be an object (not null or undefined)\n * - Does not validate the contents of the arrays or object, only their presence and type\n * - This function is commonly used as a guard before accessing trouble-related properties\n *\n * @see {@link TroubleAware} - The interface this function checks for\n * @see {@link useTroubleDecoration} - Hook that uses this guard internally\n */\nexport function isTroubleAware(obj?: any): obj is TroubleAware {\n return (\n obj?.troubles !== undefined &&\n obj?.troubles instanceof Array &&\n obj?.troublesByType !== undefined &&\n typeof obj?.troublesByType === \"object\"\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","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\n\nimport {\n kosLoggerAware,\n KosLoggerAware,\n kosModel,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\n\nimport type { GpioPinOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-pin-model\";\n\nexport type GpioPinModel = PublicModelInterface<GpioPinModelImpl>;\n\n// Interface merging for decorator type safety\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioPinModelImpl extends KosLoggerAware {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosLoggerAware()\nexport class GpioPinModelImpl implements IKosDataModel, IKosIdentifiable {\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<GpioPinModel, GpioPinOptions>;\n\n id: string;\n pinNum: number;\n chipNum: number;\n name: string;\n status: \"bound\" | \"pending\" | \"invalid\" | \"free\";\n connected: boolean;\n // logger property is automatically provided by @kosLoggerAware decorator\n\n constructor(modelId: string, options: GpioPinOptions) {\n this.id = modelId;\n this.chipNum = options.chipNum;\n this.pinNum = options.pinNum;\n this.name = options.name;\n this.status = \"free\";\n this.connected = options.connected ?? false;\n }\n\n updateModel(\n options: Partial<Omit<GpioPinOptions, \"chipNum\" | \"pinNum\" | \"name\">>\n ): void {\n this.status = options.status ?? this.status;\n this.connected = options.connected ?? this.connected;\n\n // Update model properties here.\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-pin ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-pin ${this.id}`);\n }\n}\n\nexport const GpioPin = GpioPinModelImpl.Registration;\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport {\n kosContainerAware,\n kosLoggerAware,\n kosModel,\n type KosContainerAware,\n type KosLoggerAware,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\n\nimport { GpioPin, type GpioPinModel } from \"./gpio-pin-model\";\nimport type { GpioPinContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-pin-container-model\";\n\nexport type GpioPinContainerModel =\n PublicModelInterface<GpioPinContainerModelImpl>;\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioPinContainerModelImpl\n extends KosLoggerAware,\n KosContainerAware<GpioPinModel> {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosContainerAware<GpioPinModel>({\n containerOptions: {\n sortKey: \"pinNum\",\n },\n})\n@kosLoggerAware()\nexport class GpioPinContainerModelImpl\n implements IKosIdentifiable, IKosDataModel\n{\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<\n GpioPinContainerModel,\n GpioPinContainerOptions\n >;\n\n id: string;\n\n constructor(modelId: string, _options: GpioPinContainerOptions) {\n this.id = modelId;\n // Container is automatically injected with parentId: modelId\n }\n\n updateModel(_options: GpioPinContainerOptions): void {\n // Update model properties here.\n }\n\n getPin(pinNum: number) {\n const pin = this.data[pinNum];\n if (!pin) {\n this.logger.warn(\n `Pin number ${pinNum} not found in container ${this.id}`\n );\n return undefined;\n }\n if (pin.pinNum !== pinNum) {\n this.logger.warn(\n `Pin number mismatch for pin ${pin.id} in container ${this.id}: expected ${pinNum}, got ${pin.pinNum}`\n );\n return undefined;\n }\n return this.data[pinNum];\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-pin-container container ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-pin-container container ${this.id}`);\n }\n}\nexport const GpioPinContainer = GpioPinContainerModelImpl.Registration;\n\nGpioPinContainer.addRelatedModel(GpioPin);\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\n\nimport {\n kosChild,\n kosLoggerAware,\n KosLoggerAware,\n kosModel,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { GpioPinContainer, type GpioPinContainerModel } from \"../gpio-pin\";\n\nimport type { GpioChipOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-chip-model\";\n\nexport type GpioChipModel = PublicModelInterface<GpioChipModelImpl>;\n\n// Interface merging for decorator type safety\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioChipModelImpl extends KosLoggerAware {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosLoggerAware()\nexport class GpioChipModelImpl implements IKosDataModel, IKosIdentifiable {\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<GpioChipModel, GpioChipOptions>;\n\n id: string;\n\n num: number;\n devName: string;\n name: string;\n pinCount: number;\n pinNames: string[];\n\n @kosChild private _pins: GpioPinContainerModel;\n // logger property is automatically provided by @kosLoggerAware decorator\n\n constructor(modelId: string, options: GpioChipOptions) {\n this.id = modelId;\n // logger is automatically injected by @kosLoggerAware decorator\n\n this.num = options.num;\n this.devName = options.devName;\n this.name = options.name;\n this.pinCount = options.pinCount;\n this.pinNames = options.pinNames;\n this._pins = GpioPinContainer.instance(`${this.id}-pins`)\n .options({})\n .build();\n }\n\n get pinManager() {\n return this._pins;\n }\n\n updateModel(_options: GpioChipOptions): void {\n // Update model properties here.\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async handleGpioChipLoad(): Promise<void> {}\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-chip ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-chip ${this.id}`);\n }\n}\n\nexport const GpioChip = GpioChipModelImpl.Registration;\n","import { KOS_SERVICE_1_9_X as KOS_SERVICE } from \"../../../utils/services-index\";\n\nexport const GPIO_CHIP_PATH: KOS_SERVICE.ApiPath = \"/api/kos/gpio/chips\";\nexport type GpioChipContainerResponse = KOS_SERVICE.ApiResponse<\n typeof GPIO_CHIP_PATH,\n \"get\"\n>;\n\nexport const GPIO_PIN_PATH: KOS_SERVICE.ApiPath = \"/api/kos/gpio/pins\";\nexport type GpioPinContainerResponse = KOS_SERVICE.ApiResponse<\n typeof GPIO_PIN_PATH,\n \"get\"\n>;\n\nexport const gpioServiceRequest = KOS_SERVICE.kosServiceRequest;\nexport const gpioApi = KOS_SERVICE.api;\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport type { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport {\n kosContainerAware,\n kosLoggerAware,\n kosModel,\n type KosContainerAware,\n type KosLoggerAware,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport {\n DependencyLifecycle,\n type PublicModelInterface,\n} from \"../../../core/types\";\nimport { GpioPin } from \"../gpio-pin\";\n\nimport { GpioChip, type GpioChipModel } from \"./gpio-chip-model\";\nimport {\n GPIO_CHIP_PATH,\n gpioApi,\n gpioServiceRequest,\n type GpioChipContainerResponse,\n} from \"./services\";\nimport type { GpioChipContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-chip-container-model\";\n\nexport type GpioChipContainerModel =\n PublicModelInterface<GpioChipContainerModelImpl>;\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioChipContainerModelImpl\n extends KosLoggerAware,\n KosContainerAware<GpioChipModel> {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: true })\n@kosContainerAware<GpioChipModel>({\n containerOptions: {\n sortKey: \"num\",\n },\n})\n@kosLoggerAware()\nexport class GpioChipContainerModelImpl\n implements IKosIdentifiable, IKosDataModel\n{\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: SingletonKosModelRegistrationFactory<\n GpioChipContainerModel,\n GpioChipContainerOptions\n >;\n\n id: string;\n destinationAddress: string;\n\n constructor(modelId: string, options: GpioChipContainerOptions) {\n this.id = modelId;\n this.destinationAddress = options.destinationAddress ?? \"\";\n }\n\n updateModel(_options: GpioChipContainerOptions): void {\n // Update model properties here.\n }\n // -------------------LIFECYCLE----------------------------\n\n @gpioServiceRequest({\n path: GPIO_CHIP_PATH,\n method: \"get\",\n errorHandler: {\n strategy: \"log\",\n defaultValue: [],\n },\n lifecycle: DependencyLifecycle.INIT,\n requestOptions: (model) => {\n return {\n destinationAddress: (model as GpioChipContainerModelImpl)\n .destinationAddress,\n };\n },\n })\n async handleGpioChipInit(\n _error: never,\n response: Record<string, GpioChipContainerResponse>\n ): Promise<void> {\n const [error, pinData] = await gpioApi.get(\n \"/api/kos/gpio/pins\",\n undefined,\n {\n destinationAddress: this.destinationAddress,\n }\n );\n\n if (error) {\n this.logger.error(\"Failed to fetch GPIO pins\", error);\n return;\n }\n\n Object.entries(response).forEach(([_key, value]) => {\n value.forEach((chip) => {\n if (!chip.num && chip.num !== 0) {\n this.logger.warn(\"Skipping GPIO chip with missing number\", chip);\n return;\n }\n const chipModel = GpioChip.instance(`${GpioChip.type}-${chip.num}}`)\n .options({\n num: chip.num,\n devName: chip.devName ?? \"\",\n name: chip.name ?? \"\",\n pinCount: chip.pinCount ?? 0,\n pinNames: chip.pinNames ?? [],\n })\n .build();\n chip.pinNames?.forEach((pinName, index) => {\n const pinModel = GpioPin.instance(`${chipModel.name}-${pinName}`)\n .options({\n name: pinName,\n pinNum: index,\n chipNum: chip.num!,\n })\n .build();\n chipModel.pinManager.addModel(pinModel);\n });\n this.addModel(chipModel);\n });\n });\n\n const statuses = [\"bound\", \"pending\", \"invalid\", \"free\"] as const;\n for (const status of statuses) {\n Object.entries(pinData as Record<string, any>).forEach(\n ([_key, value]) => {\n value?.[status]?.forEach((pin) => {\n const pinNum = pin.pinNum;\n const chipNum = pin.chipNum;\n if (chipNum === undefined || pinNum === undefined) {\n this.logger.warn(\n \"Skipping pin with missing chipNum or pinNum\",\n pin\n );\n return;\n }\n const chipModel = this.data[chipNum];\n if (!chipModel || chipModel.num !== chipNum) {\n this.logger.warn(\n `No chip model found for chipNum ${chipNum} when processing pin ${pinNum}`\n );\n return;\n }\n const pinModel = chipModel.pinManager.getPin(pinNum);\n if (!pinModel) {\n this.logger.warn(\n `No pin model found for pinNum ${pinNum} in chipNum ${chipNum}`\n );\n return;\n }\n\n pinModel.updateModel({\n connected: pin.connected,\n status: status,\n });\n });\n }\n );\n }\n }\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-chip-container container ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-chip-container container ${this.id}`);\n }\n}\nexport const GpioChipContainer = GpioChipContainerModelImpl.Registration;\n\nGpioChipContainer.addRelatedModel(GpioChip);\n","import { KosLog, type ServiceResponse } from \"../../../../core\";\nimport API, { type ApiPath, type ApiResponse } from \"../../../utils/service\";\n\nconst log = KosLog.createLogger({\n name: \"studio-properties-service\",\n group: \"Services\",\n});\n\nconst SERVICE_PATH: ApiPath = \"/api/kos/studio/properties\";\nexport type StudioPropertiesClientResponse = ApiResponse<\n typeof SERVICE_PATH,\n \"get\"\n>;\nexport interface StudioPropertiesResponse {\n data?: Record<string, any>;\n}\n\n/**\n * @category Service\n * Retrieves the initial studio-properties data.\n */\nexport const getStudioProperties = async (\n connectionId: string\n): Promise<ServiceResponse<StudioPropertiesResponse>> => {\n log.debug(\"sending GET for studio-properties\");\n if (!connectionId) {\n log.error(\"connectionId is undefined\");\n throw new Error(\"connectionId is undefined\");\n }\n return await API.get(\n SERVICE_PATH,\n {},\n {\n destinationAddress: connectionId,\n timeout: 500,\n }\n );\n};\n","import {\n kosComputed,\n KosLog,\n ObservableData,\n WebSocketTransport,\n type KosData,\n} from \"../../../core\";\nimport { 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 { getStudioProperties } from \"./services\";\n\nimport type { StudioPropertiesOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"studio-properties-model\";\n\nconst TOPIC_PROPERTIES = \"/kos/studio/properties\";\n\n/**\n * StudioPropertiesModel - Real-time KOS Studio properties management with WebSocket synchronization.\n *\n * This model provides centralized access to KOS Studio's runtime properties and configuration\n * values, enabling applications to access Studio-specific settings, tool states, and integration\n * parameters. Properties are synchronized in real-time via WebSocket topics, ensuring all\n * connected clients maintain consistent Studio state information.\n *\n * ## Key Features\n * - **Real-time synchronization** - Properties update automatically via `/kos/studio/properties` topic\n * - **Connection-scoped access** - Properties are specific to individual Studio VM connections\n * - **Fallback handling** - Graceful degradation with default values when Studio is unavailable\n * - **Observable properties** - Create reactive computed values for any property key\n * - **Session management** - Automatic WebSocket session lifecycle with proper cleanup\n *\n * ## Topic-Based Reactivity\n * The model listens to this KOS topic for real-time synchronization:\n * - **`/kos/studio/properties`** - Broadcasts Studio property changes with connection-specific routing\n *\n * ## Common Use Cases\n * - **Studio integration status** - Check if legacy tools or specific Studio features are enabled\n * - **Tool configuration** - Access Studio tool settings and preferences for UI adaptation\n * - **Connection management** - Track Studio connection state and properties for diagnostics\n * - **Feature flags** - Access Studio-specific feature toggles and experimental settings\n *\n * @interface\n * @example Basic Usage\n * ```typescript\n * const studioProps = StudioPropertiesModel.instance('studio-conn-1')\n * .options({ connectionId: 'vm-connection-abc123' })\n * .build();\n *\n * await studioProps.initializePropertiesSession();\n * const legacyToolSupport = studioProps.get('kos.studio.tool.legacy');\n * ```\n *\n * @group KOS Model\n * @category System Integration\n * @useDeclaredType\n *\n * @see {@link StudioPropertiesOptions} - Configuration options for StudioPropertiesModel instances\n */\nexport type StudioPropertiesModel =\n PublicModelInterface<StudioPropertiesModelImpl>;\n\nconst DEFAULT_STUDIO_PROPERTIES = {\n \"kos.studio.tool.legacy\": 1,\n};\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class StudioPropertiesModelImpl\n implements IKosDataModel, IKosIdentifiable\n{\n /** Unique identifier for the model instance */\n id: string;\n /** Studio VM connection identifier for property routing */\n connectionId: string;\n /** WebSocket subscription cleanup function */\n private unsubscribe: VoidFunction | null = null;\n /** Context logger for debugging and diagnostics */\n private logger: KosContextLogger;\n /** Observable data store for Studio properties */\n private data: KosData<Record<string, any>>;\n constructor(\n modelId: string,\n options: StudioPropertiesOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n this.data = ObservableData();\n this.connectionId = options.connectionId;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing studio-properties ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading studio-properties ${this.id}`);\n }\n\n /**\n * Terminates the WebSocket session for Studio properties.\n * Cleans up subscriptions to prevent memory leaks.\n */\n async terminatePropertiesSession(): Promise<void> {\n this.unsubscribe?.();\n }\n\n /**\n * Initializes WebSocket session for real-time Studio property synchronization.\n * Loads initial properties and subscribes to update topics.\n */\n async initializePropertiesSession() {\n this.unsubscribe = WebSocketTransport.getInstance().subscribeTopic({\n topic: TOPIC_PROPERTIES,\n destinationAddress: this.connectionId,\n callback: (msg) => {\n this.logger.error(\n `Received studio-properties message for connection ${\n this.connectionId\n }: ${JSON.stringify(msg)}`\n );\n },\n });\n const [error, data] = await getStudioProperties(this.connectionId);\n if (error) {\n this.logger.error(`Error loading studio-properties: ${error}`);\n this.data.setValues(DEFAULT_STUDIO_PROPERTIES);\n return;\n }\n if (data) {\n const update = Object.keys(data).reduce((acc, key) => {\n acc[key] = data[key] ?? key;\n return acc;\n }, {});\n this.data.setValues(update ?? DEFAULT_STUDIO_PROPERTIES);\n KosLog.ifDebug(() =>\n this.logger.debug(`studio-properties loaded: ${JSON.stringify(update)}`)\n );\n }\n }\n\n /**\n * Retrieves a Studio property value by key.\n * @param key Property key to retrieve\n * @returns The property value or undefined if not set\n */\n get(key: string): any {\n return this.data[key];\n }\n\n /**\n * Creates an observable computed property for reactive updates.\n * @param key Property key to observe\n * @returns Observable that emits when the property changes\n */\n createObservableProperty(key: string) {\n return kosComputed(() => this.get(key));\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { StudioPropertiesOptions } from \"./types\";\nimport {\n StudioPropertiesModelImpl,\n MODEL_TYPE,\n} from \"./studio-properties-model\";\nimport type { StudioPropertiesModel } from \"./studio-properties-model\";\n\n/**\n * # StudioProperties\n *\n * The registration bean includes convenience methods for creating and working with StudioPropertiesModel 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: StudioProperties.type, id: \"studioPropertiesId\"})\n * private studioPropertiesModel: StudioPropertiesModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new StudioPropertiesModel 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 = StudioProperties.factory(\"studioPropertiesId\")({\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 StudioPropertiesModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (StudioProperties.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to StudioPropertiesModel\n * // and the compiler will know that the model has the StudioPropertiesModel 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 { StudioProperties } 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(StudioProperties);\n * ```\n *\n * ## registration.singleton\n \n * The studioProperties 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 StudioProperties = new KosModelRegistrationFactory<\n StudioPropertiesModel,\n StudioPropertiesOptions\n>({\n class: StudioPropertiesModelImpl,\n type: MODEL_TYPE,\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 { createPortal } from \"react-dom\";\nimport { loadingDot } from \"./loading-message-styles\";\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 theme?: \"light\" | \"dark\";\n}\nfunction LoadingMessage({\n message = \"Wait a moment while we load your app.\",\n theme = \"light\",\n}: Props) {\n return (\n <Portal>\n <MessageContainer theme={theme}>\n {message}\n <div css={loadingDot}>.</div>\n </MessageContainer>\n </Portal>\n );\n}\n\nexport default LoadingMessage;\n\nconst MessageContainer = styled.div<{ theme: \"light\" | \"dark\" }>`\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 color: ${({ theme }) => (theme === \"light\" ? \"black\" : \"white\")};\n z-index: 10000;\n`;\n","import React, { ErrorInfo } from \"react\";\nimport { KosLog } from \"../../../core\";\n\nconst log = KosLog.createLogger({ name: \"error-boundary\" });\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 /** Names the guarded region so a caught error is traceable to its seam. */\n name?: string;\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 /**\n * Recovers during the render phase. Without this React renders the boundary\n * with `null` children and waits for `componentDidCatch` to schedule a\n * fallback, and a second error in the same batch escalates past the boundary\n * to the root, unmounting the whole tree.\n */\n static getDerivedStateFromError(\n error: Error\n ): Pick<ErrorBoundaryState, \"error\"> {\n return { error };\n }\n\n override componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n // A boundary that swallows the cause leaves nothing to diagnose, so the\n // error is reported before the fallback replaces the subtree.\n const seam = this.props.name ? ` in ${this.props.name}` : \"\";\n // The message carries the cause inline: an Error passed as a bare argument\n // serialises to `{}` under some log sinks.\n log.error(\n `Error boundary caught${seam}: ${error?.message ?? error}`,\n error,\n errorInfo.componentStack\n );\n this.setState({\n error: error,\n errorInfo: errorInfo,\n });\n }\n\n override render() {\n // Keyed on `error` because that is what the render phase sets; `errorInfo`\n // only arrives later, from the commit phase.\n if (this.state.error) {\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.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 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, useMemo } 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.isOnline);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setOnline(kosCore.isOnline);\n });\n\n return () => {\n disposer();\n };\n }, [kosCore]);\n\n const value = useMemo<IKosContext>(() => {\n return { kosCore, online };\n }, [kosCore, online]);\n\n return <KosContext.Provider value={value}>{children}</KosContext.Provider>;\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","/**\n * sessionStorage key used to signal to the next page load that a\n * reload-on-disconnect recovery just occurred. Overlay components read it\n * on mount so the \"reconnecting\" UI can persist across the reload without\n * a visible gap.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport const KOS_RECOVERING_SESSION_KEY = \"kos:recovering\";\n","import { useEffect, useRef } from \"react\";\nimport { EventBus } from \"../../common\";\nimport { WebSocketEvents } from \"../../core/core/transport/base-message-transport\";\nimport { KosLog } from \"../../core/core/log\";\nimport { KOS_RECOVERING_SESSION_KEY } from \"./constants\";\n\n/**\n * Metadata the policy records about the triggering disconnect.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport interface ReloadOnDisconnectInfo {\n code: number;\n reason: string;\n wasClean: boolean;\n at: number;\n}\n\n/**\n * Props for ReloadOnDisconnectPolicy.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport interface ReloadOnDisconnectPolicyProps {\n /**\n * Delay before reloading, in milliseconds. Lets rapid-fire reconnect\n * attempts settle without stacking reloads. Default: 3000.\n */\n graceMs?: number;\n /**\n * Called synchronously immediately before the reload. Useful for\n * telemetry. Do not perform async work here — the reload may preempt it.\n */\n onBeforeReload?: (info: ReloadOnDisconnectInfo) => void;\n /**\n * Test seam. Replace the reload function. Defaults to\n * () => window.location.reload().\n */\n reloadFn?: () => void;\n}\n\nconst DEFAULT_GRACE_MS = 3000;\n\nconst defaultReloadFn = () => {\n window.location.reload();\n};\n\n/**\n * Mounts a connection-recovery policy: when the WebSocket disconnects, wait\n * a short grace window, record the disconnect in sessionStorage, then\n * `window.location.reload()` the page. Renders nothing.\n *\n * The grace window exists only to de-bounce rapid disconnect/reconnect\n * flapping — it is NOT a signal to trust fast recoveries. Even a sub-second\n * reconnect triggers the reload, because the data layer has no way to\n * guarantee freshness across the gap.\n *\n * Apps that want different behavior (e.g. Studio, which prefers\n * reconcile-on-reconnect) simply do not mount this policy.\n *\n * Pair with an overlay that reads `KOS_RECOVERING_SESSION_KEY` on mount to\n * keep a \"reconnecting\" message visible across the reload boundary.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport const ReloadOnDisconnectPolicy: React.FC<\n ReloadOnDisconnectPolicyProps\n> = ({\n graceMs = DEFAULT_GRACE_MS,\n onBeforeReload,\n reloadFn = defaultReloadFn,\n}) => {\n const pendingReloadRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n if (pendingReloadRef.current) {\n return;\n }\n\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (!payload || typeof payload.code !== \"number\") {\n return;\n }\n\n const info: ReloadOnDisconnectInfo = {\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n };\n\n try {\n sessionStorage.setItem(\n KOS_RECOVERING_SESSION_KEY,\n JSON.stringify(info)\n );\n } catch (err) {\n KosLog.warn(\n \"ReloadOnDisconnectPolicy: failed to write sessionStorage\",\n err\n );\n }\n\n KosLog.warn(\n `ReloadOnDisconnectPolicy: scheduling reload in ${graceMs}ms ` +\n `(code=${info.code}, wasClean=${info.wasClean})`\n );\n\n pendingReloadRef.current = setTimeout(() => {\n pendingReloadRef.current = null;\n try {\n onBeforeReload?.(info);\n } catch (err) {\n KosLog.error(\"ReloadOnDisconnectPolicy: onBeforeReload threw\", err);\n }\n reloadFn();\n }, graceMs);\n }\n );\n\n return () => {\n unsubscribe();\n if (pendingReloadRef.current) {\n clearTimeout(pendingReloadRef.current);\n pendingReloadRef.current = null;\n }\n };\n }, [graceMs, onBeforeReload, reloadFn]);\n\n return null;\n};\n","import { useEffect, useState } from \"react\";\nimport { EventBus } from \"../../../common\";\nimport { WebSocketEvents } from \"../../../core/core/transport/base-message-transport\";\nimport { useKosCore } from \"../../contexts/kos-core-context\";\nimport {\n KOS_RECOVERING_SESSION_KEY,\n type ReloadOnDisconnectInfo,\n} from \"../../policies\";\n\n/**\n * Snapshot of the overlay's state, returned by useReconnectingOverlayState.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport interface ReconnectingOverlayState {\n /** Whether the overlay should currently be displayed. */\n visible: boolean;\n /** Details of the disconnect, if one is being recovered from. */\n info: ReloadOnDisconnectInfo | null;\n /** Milliseconds since the tracked disconnect, or null. */\n sinceMs: number | null;\n /** Force-hide the overlay. Does not clear `info`. */\n dismiss: () => void;\n}\n\n/**\n * Options for useReconnectingOverlayState.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport interface UseReconnectingOverlayStateOptions {\n /**\n * Predicate evaluated after a CONNECTED event. When true, the overlay\n * hides. Defaults to `({ online }) => online`, i.e. hide as soon as KOS\n * Core reports online. Apps that need to wait for specific model state\n * can pass a stricter predicate.\n */\n isReady?: (state: {\n online: boolean;\n info: ReloadOnDisconnectInfo | null;\n }) => boolean;\n /**\n * Whether to read `sessionStorage[KOS_RECOVERING_SESSION_KEY]` on mount\n * to carry overlay state across a page reload. Default: true. Set false\n * for apps that don't use the reload-on-disconnect policy.\n */\n readSessionStorage?: boolean;\n}\n\nconst defaultIsReady = ({ online }: { online: boolean }) => online;\n\nconst readRecoveringInfo = (): ReloadOnDisconnectInfo | null => {\n try {\n const raw = sessionStorage.getItem(KOS_RECOVERING_SESSION_KEY);\n if (!raw) return null;\n sessionStorage.removeItem(KOS_RECOVERING_SESSION_KEY);\n const parsed = JSON.parse(raw);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n typeof parsed.code === \"number\"\n ) {\n return parsed as ReloadOnDisconnectInfo;\n }\n } catch {\n // sessionStorage may be unavailable or payload malformed; ignore\n }\n return null;\n};\n\n/**\n * Headless state hook for the reconnecting overlay.\n *\n * Becomes `visible` when a WebSocket disconnect is observed, or when the\n * page load carries a `KOS_RECOVERING_SESSION_KEY` in sessionStorage from\n * a prior reload-on-disconnect cycle. Becomes hidden when the ready\n * predicate reports the app is fully connected again.\n *\n * Returns { visible, info, sinceMs, dismiss }. Apps pair this with their\n * own overlay markup, or use the default `<ReconnectingOverlay />`.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport const useReconnectingOverlayState = (\n options: UseReconnectingOverlayStateOptions = {}\n): ReconnectingOverlayState => {\n const { isReady = defaultIsReady, readSessionStorage = true } = options;\n const { online } = useKosCore();\n\n const [info, setInfo] = useState<ReloadOnDisconnectInfo | null>(() =>\n readSessionStorage ? readRecoveringInfo() : null\n );\n const [dismissed, setDismissed] = useState(false);\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (!payload || typeof payload.code !== \"number\") return;\n setInfo({\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n });\n setDismissed(false);\n }\n );\n return () => {\n unsubscribe();\n };\n }, []);\n\n const ready = isReady({ online, info });\n const visible = !dismissed && !!info && !ready;\n\n return {\n visible,\n info,\n sinceMs: info ? Date.now() - info.at : null,\n dismiss: () => setDismissed(true),\n };\n};\n","import { css, keyframes } from \"@emotion/react\";\n\nconst spin = keyframes`\n to { transform: rotate(360deg); }\n`;\n\nexport const overlayRoot = css`\n position: fixed;\n inset: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 16px;\n background: rgba(0, 0, 0, 0.72);\n color: #ffffff;\n font-family: system-ui, -apple-system, \"Segoe UI\", sans-serif;\n z-index: 2147483647;\n pointer-events: auto;\n user-select: none;\n`;\n\nexport const spinner = css`\n width: 48px;\n height: 48px;\n border-radius: 50%;\n border: 4px solid rgba(255, 255, 255, 0.25);\n border-top-color: #ffffff;\n animation: ${spin} 1s linear infinite;\n`;\n\nexport const message = css`\n font-size: 18px;\n font-weight: 500;\n letter-spacing: 0.02em;\n`;\n","import type React from \"react\";\nimport {\n useReconnectingOverlayState,\n type ReconnectingOverlayState,\n type UseReconnectingOverlayStateOptions,\n} from \"./use-reconnecting-overlay-state\";\nimport { message, overlayRoot, spinner } from \"./reconnecting-overlay-styles\";\n\nexport {\n useReconnectingOverlayState,\n type ReconnectingOverlayState,\n type UseReconnectingOverlayStateOptions,\n} from \"./use-reconnecting-overlay-state\";\n\n/**\n * Props for the default ReconnectingOverlay.\n *\n * @kosService core.reconnecting-overlay\n * @kosApiLevel 23\n */\nexport interface ReconnectingOverlayProps\n extends UseReconnectingOverlayStateOptions {\n /** Override the default message (\"Reconnecting…\"). */\n messageText?: string;\n /**\n * Fully replace the rendered content with a custom renderer. Receives the\n * overlay state. If provided, the default layout (spinner + message) is\n * not rendered.\n */\n renderContent?: (state: ReconnectingOverlayState) => React.ReactNode;\n className?: string;\n}\n\n/**\n * Minimal, unbranded overlay that displays while the app is recovering\n * from a WebSocket disconnect (or immediately after a reload triggered by\n * ReloadOnDisconnectPolicy). Pair with that policy — or use in isolation\n * for apps that want to show the overlay without reloading.\n *\n * Apps with design-system requirements should wrap\n * `useReconnectingOverlayState` in their own component rather than relying\n * on these default styles.\n *\n * @kosService core.reconnecting-overlay\n * @kosApiLevel 23\n */\nexport const ReconnectingOverlay: React.FC<ReconnectingOverlayProps> = ({\n messageText = \"Reconnecting…\",\n renderContent,\n className,\n isReady,\n readSessionStorage,\n}) => {\n const state = useReconnectingOverlayState({ isReady, readSessionStorage });\n\n if (!state.visible) return null;\n\n return (\n <div\n css={overlayRoot}\n className={className}\n role=\"alertdialog\"\n aria-live=\"assertive\"\n aria-label=\"Reconnecting\"\n >\n {renderContent ? (\n renderContent(state)\n ) : (\n <>\n <div css={spinner} aria-hidden=\"true\" />\n <div css={message}>{messageText}</div>\n </>\n )}\n </div>\n );\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 {\n clearModelHookCacheEntry,\n destroyKosModel,\n modelHookCache,\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 { isUpdateable } from \"../../core/core/registration/model-registration\";\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 forceUpdate?: 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\n/**\n * Reads a model out of the suspense cache, suspending or rethrowing as the\n * entry requires. Exported for tests.\n */\nexport function readModelHookEntry(\n key: string,\n fetcher: () => Promise<unknown>\n) {\n const entry = modelHookCache.get(key);\n\n if (entry) {\n if (entry.status === \"finished\") {\n const kosModel = KosCore.getInstance().modelManager.getModelById(key);\n return { kosModel, model: kosModel?.modelData };\n }\n\n // An error entry has no promise to suspend on, so rethrow the cause.\n if (entry.status === \"error\") {\n throw entry.error;\n }\n\n throw entry.promise;\n }\n\n const promise = fetcher().then(\n () => {\n modelHookCache.set(key, { status: \"finished\", key });\n },\n (error) => {\n modelHookCache.set(key, { status: \"error\", error });\n throw error;\n }\n );\n\n modelHookCache.set(key, { status: \"pending\", promise });\n\n throw promise;\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 = readModelHookEntry(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 } = 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}\n/**\n * Primary hook for consuming KOS models in React components.\n *\n * @kosService core.use-kos-model\n * @kosApiLevel 2\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\n useEffect(() => {\n if (modelOptions.forceUpdate && model) {\n if (isUpdateable(model)) {\n model.updateModel(modelOptions.options || {});\n }\n }\n }, [model]);\n useEffect(() => {\n async function waitForModel() {\n try {\n await kosCoreContext.kosCore.whenReady();\n if (activate) {\n await kosModel?.fsm.transitionTo(\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 throw e;\n }\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?.fsm\n .transitionTo(KosModelEvents.GO_INACTIVE, KosModelState.INACTIVE)\n .then(() => {\n if (destroyOnUnmount) {\n const modelId = model.id;\n destroyKosModel(model).then(() => {\n clearModelHookCacheEntry(modelId);\n disposer?.();\n });\n }\n });\n }\n } else {\n if (destroyOnUnmount && model) {\n destroyKosModel(model).then(() => {\n clearModelHookCacheEntry(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\n/**\n * Hook for accessing the KOS time model.\n *\n * @kosService core.use-kos-time\n * @kosApiLevel 2\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\n/**\n * Hook for accessing the KOS software info model.\n *\n * @kosService core.use-software-info\n * @kosApiLevel 2\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 collectLocaleOptions,\n getKosLocalizationDescriptor,\n mergeLocalizationDescriptors,\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 allLocales: { locale: string; label: string }[];\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 excludeNamespaces?: string[];\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,\n locale = \"en\",\n resolver,\n rootUrl,\n descriptorResolver,\n excludeNamespaces = [],\n}) => {\n const [ready, setReady] = useState(false);\n const [localization, setLocalization] = useState<Localization>();\n const [translations, setTranslations] = useState<TranslationContainerModel>();\n const [allLocales, setAllLocales] = useState<\n { locale: string; label: string }[]\n >([]);\n const resolvedRootUrl = rootUrl || getDefaultHost();\n const _appContext = useMemo(() => appContext ?? \"app/system\", [appContext]);\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 setLocalization(mergeLocalizationDescriptors(descriptors));\n setAllLocales(collectLocaleOptions(descriptors, excludeNamespaces));\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 }, [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 allLocales,\n };\n }\n return {\n setLocale: () => {\n throw new Error(\"Translations not ready\");\n },\n allLocales: [],\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 {\n CanvasDispatcher,\n type CanvasDispatcherModel,\n type CanvasDispatcherOptions,\n} from \"../../../../../models/models/canvas-dispatcher\";\nimport { useKosModel } from \"../../../../hooks/use-kos-model\";\n\nexport const useCanvasDispatcher = () => {\n const modelId = CanvasDispatcher.type;\n const result = useKosModel<CanvasDispatcherModel, CanvasDispatcherOptions>({\n modelId,\n modelType: CanvasDispatcher.type,\n options: {},\n });\n\n return result;\n};\n","import type { CanvasDispatcherModel } from \"../../../../../models/models/canvas-dispatcher\";\nimport { useCanvasDispatcher } from \"./use-canvas-dispatcher\";\n\ninterface CanvasDispatcherProps {\n canvasDispatcher: CanvasDispatcherModel;\n}\n\ntype HoCCanvasDispatcherProps = CanvasDispatcherProps;\n// react HOC to provide a CanvasDispatcher to a component\nexport function withCanvasDispatcher<\n T extends HoCCanvasDispatcherProps = HoCCanvasDispatcherProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof CanvasDispatcherProps>) => {\n const { model, status, KosModelLoader } = useCanvasDispatcher();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} canvasDispatcher={model} />\n </KosModelLoader>\n );\n };\n}\n","export const decodeBase64RGB = (\n base64: string,\n width: number,\n height: number\n): Uint8ClampedArray => {\n const binary = atob(base64);\n const rgba = new Uint8ClampedArray(width * height * 4);\n for (let i = 0, j = 0; i < binary.length && j < rgba.length; i += 3, j += 4) {\n rgba[j] = binary.charCodeAt(i);\n rgba[j + 1] = binary.charCodeAt(i + 1);\n rgba[j + 2] = binary.charCodeAt(i + 2);\n rgba[j + 3] = 255;\n }\n return rgba;\n};\n\nexport const decodeRGB332 = (\n data: string,\n width: number,\n height: number\n): Uint8ClampedArray => {\n const rgba = new Uint8ClampedArray(width * height * 4);\n for (let i = 0; i < data.length; i++) {\n const byte = data.charCodeAt(i);\n const r = (((byte >> 5) & 0x07) * 255) / 7;\n const g = (((byte >> 2) & 0x07) * 255) / 7;\n const b = ((byte & 0x03) * 255) / 3;\n const j = i * 4;\n rgba[j] = r;\n rgba[j + 1] = g;\n rgba[j + 2] = b;\n rgba[j + 3] = 255;\n }\n return rgba;\n};\n\n/**\n * Renders a decoded preview onto a canvas context by decoding image data\n * from a specified format and scaling it to the desired size.\n *\n * @param ctx - The 2D rendering context of the target canvas.\n * @param format - The format of the input data string. Can be either 'base64' or 'rgb332'.\n * @param dataString - The encoded image data as a string.\n * @param width - The width of the image in pixels.\n * @param height - The height of the image in pixels.\n * @param pixelSize - The scaling factor for each pixel in the rendered image.\n *\n * @remarks\n * - If `format` is 'base64', the `dataString` is decoded using `decodeBase64RGB`.\n * - If `format` is 'rgb332', the `dataString` is decoded using `decodeRGB332`.\n * - The function creates a temporary canvas to decode and render the image data\n * before scaling it onto the target canvas.\n * - Image smoothing is disabled to preserve the pixelated appearance of the image.\n */\nexport function renderDecodedPreview({\n ctx,\n format,\n dataString,\n width,\n height,\n pixelSize,\n}: {\n ctx: CanvasRenderingContext2D;\n format: \"base64\" | \"rgb332\";\n dataString: string;\n width: number;\n height: number;\n pixelSize: number;\n}) {\n const decode =\n format === \"base64\"\n ? decodeBase64RGB(dataString, width, height)\n : decodeRGB332(dataString, width, height);\n\n const img = new ImageData(\n decode as unknown as Uint8ClampedArray<ArrayBuffer>,\n width,\n height\n );\n const tempCanvas = document.createElement(\"canvas\");\n tempCanvas.width = width;\n tempCanvas.height = height;\n const tempCtx = tempCanvas.getContext(\"2d\");\n tempCtx?.putImageData(img, 0, 0);\n ctx.imageSmoothingEnabled = false;\n ctx.clearRect(0, 0, width * pixelSize, height * pixelSize);\n ctx.drawImage(tempCanvas, 0, 0, width * pixelSize, height * pixelSize);\n}\n","import styled from \"@emotion/styled\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { observer as kosComponent } from \"mobx-react-lite\";\nimport { createPortal } from \"react-dom\";\nimport { KosLog } from \"../../../../../core\";\nimport type { CanvasDispatcherModel } from \"../../../../../models/models/canvas-dispatcher\";\nimport type { CanvasRendererModel } from \"../../../../../models/models/canvas-renderer\";\nimport { withCanvasDispatcher } from \"../../hooks/canvas-dispatcher\";\nimport { renderDecodedPreview } from \"../../utils/preview-decoder\";\n\nconst log = KosLog.createLogger({ name: \"canvas-streamer\" });\nlog.debug(\"main-view component loaded\");\nconst PIXEL_SIZE = 10;\n\ninterface CanvasStreamerProps {\n height?: number;\n width?: number;\n defaultFps?: number;\n showPreview?: boolean;\n name: string;\n apiPath?: string;\n canvasDispatcher: CanvasDispatcherModel;\n}\n\nexport const CanvasStreamerBase: React.FunctionComponent<CanvasStreamerProps> =\n kosComponent(\n ({\n canvasDispatcher,\n height = 30,\n width = 50,\n defaultFps = 10,\n showPreview = false,\n name,\n apiPath = \"/api/system/canvas\",\n }) => {\n const canvasRef = useRef<HTMLCanvasElement>(null);\n\n const [renderer, setRenderer] = useState<CanvasRendererModel>();\n\n useEffect(() => {\n const _endpoint = canvasDispatcher.addNamedEndpoint(name, {\n apiPath,\n fps: defaultFps,\n width,\n height,\n id: name,\n });\n\n setRenderer(_endpoint);\n }, [canvasDispatcher]);\n /**\n * Callback function to handle frame processing.\n *\n * @param rgba - A `Uint8ClampedArray` representing the RGBA pixel data of the frame.\n *\n * This function performs the following operations:\n * If a preview canvas is available and `showPreview` is enabled, renders a decoded\n * preview of the frame onto the canvas using `renderDecodedPreview`.\n *\n * Dependencies:\n * - `width` and `height`: Dimensions of the grid for encoding and rendering.\n * - `showPreview`: A flag to determine whether to render a preview.\n * - `canvasRef`: A reference to the preview canvas element.\n * - `PIXEL_SIZE`: The size of each pixel in the preview rendering.\n */\n const onFrame = useCallback(\n (dataString: string) => {\n if (canvasRef.current && showPreview) {\n const previewCtx = canvasRef.current.getContext(\"2d\");\n if (previewCtx) {\n renderDecodedPreview({\n ctx: previewCtx,\n format: \"base64\",\n dataString,\n height,\n width,\n pixelSize: PIXEL_SIZE,\n });\n }\n }\n },\n [width, height, showPreview]\n );\n\n useEffect(() => {\n if (!renderer) return;\n renderer.onFrame = onFrame;\n renderer.width = width;\n renderer.height = height;\n renderer.fps = defaultFps;\n }, [renderer, onFrame, width, height, defaultFps]);\n\n return (\n showPreview &&\n createPortal(\n <Main>\n <PreviewContainer>\n <canvas\n ref={canvasRef}\n width={width * PIXEL_SIZE}\n height={height * PIXEL_SIZE}\n style={{ border: \"1px solid black\" }}\n />\n </PreviewContainer>\n </Main>,\n document.body\n )\n );\n }\n );\n\nexport const CanvasStreamer = withCanvasDispatcher(CanvasStreamerBase);\n\nconst Main = styled.div`\n display: flex;\n flex-direction: column;\n gap: 8px;\n\n width: 100%;\n justify-content: space-between;\n align-items: center;\n`;\n\nconst PreviewContainer = styled.div`\n display: flex;\n flex-direction: column;\n align-items: center;\n`;\n","import { Device, DeviceModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS device model.\n *\n * @kosService core.use-device\n * @kosApiLevel 2\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\n/**\n * Hook for accessing the KOS network interface container model.\n *\n * @kosService core.use-network\n * @kosApiLevel 2\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\n/**\n * Hook for accessing the KOS OTA (over-the-air update) model.\n *\n * @kosService core.use-ota\n * @kosApiLevel 2\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\n/**\n * Hook for accessing the KOS storage device container model.\n *\n * @kosService core.use-storage\n * @kosApiLevel 2\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 { useCallback, useEffect } from \"react\";\nimport { EventBus } from \"../../../common\";\nimport { KosLog } from \"../../../core\";\nimport {\n KosTimer,\n TIMER_END,\n TIMER_EVENT,\n TimerEvent,\n TimerManager,\n TOPIC_TIMER_TICK_EVENT,\n} from \"../../../models\";\n\nconst LOG = KosLog.createLogger({ name: \"use-timer\" });\ninterface TimerHookProps {\n timerName: string;\n onTimerExpired: (event: TimerHookEvent) => void;\n onTimerTick?: (event: TimerTickEvent) => void;\n timerEventActions?: Record<string, (event: TimerHookEvent) => void>;\n autoStart?: boolean;\n}\ntype TimerHookEvent = TimerEvent & { timer: KosTimer };\n\ntype TimerTickEvent = Omit<TimerHookEvent, \"action\"> & {\n timer: KosTimer;\n};\nexport const useTimer = ({\n timerName,\n onTimerExpired,\n onTimerTick,\n timerEventActions,\n autoStart,\n}: TimerHookProps) => {\n const t = TimerManager.getTimer(timerName);\n\n useEffect(() => {\n if (!t) {\n console.warn(`Timer with name ${timerName} does not exist.`);\n return undefined;\n }\n const result = EventBus.subscribe(TIMER_EVENT, (data) => {\n const { name, action, remainingTime } =\n data?.body as unknown as TimerEvent;\n if (name === timerName) {\n if (action === TIMER_END) {\n onTimerExpired({ name, action, remainingTime, timer: t });\n } else if (timerEventActions?.[action]) {\n timerEventActions[action]({ name, action, remainingTime, timer: t });\n }\n }\n });\n if (autoStart) t.start();\n return () => {\n result.unsubscribe();\n };\n }, [autoStart, onTimerExpired, timerEventActions, timerName, t]);\n\n useEffect(() => {\n if (!t || !onTimerTick) {\n return undefined;\n }\n const TOPIC_TIMER_TICK = `${TOPIC_TIMER_TICK_EVENT}/${timerName}`;\n const result = EventBus.subscribe(TOPIC_TIMER_TICK, (data) => {\n const { name, remainingTime } = data?.body as unknown as TimerEvent;\n if (name === timerName) {\n onTimerTick({ name, remainingTime, timer: t });\n }\n });\n return () => {\n result.unsubscribe();\n };\n }, [onTimerTick, timerName, t]);\n\n const start = useCallback(() => {\n if (t) {\n t.start();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n const reset = useCallback(() => {\n if (t) {\n t.reset();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n const pause = useCallback(() => {\n if (t) {\n t.pause();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n return {\n timer: t,\n start,\n reset,\n pause,\n };\n};\n","import React, { type ReactNode, type ReactElement } from \"react\";\nimport { TFunction } from \"./use-translation\";\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\n/**\n * React component for rendering translated strings with embedded components or markup.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\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 }\n\n // An error entry has no promise to suspend on, so rethrow the cause.\n if (entry.status === \"error\") {\n throw entry.error;\n }\n\n throw entry.promise;\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}\n/**\n * Primary hook for consuming KOS translations in React components.\n * Resolves a translation namespace and returns a `t` function for key lookup.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\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\n/**\n * Hook for accessing the KOS translation container model.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\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/**\n * Higher-order component that injects a `TranslationContainerModel` into a wrapped component.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\n */\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\n/**\n * Hook for accessing the KOS USB update container model.\n *\n * @kosService core.use-usb-update\n * @kosApiLevel 2\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 const [isSearching, setIsSearching] = useState<boolean>(false);\n const [noUpdates, setNoUpdates] = useState<boolean>(false);\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 setIsSearching(result.model?.isSearchingUpdates ?? false);\n setNoUpdates(result.model?.noAvailableUpdates ?? false);\n });\n\n return () => {\n disposer();\n };\n }, [result.model]);\n\n return {\n ...result,\n inserted,\n updateAvailable,\n updates,\n isSearching,\n noUpdates,\n };\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}\n/**\n * Hook for binding to a KOS configuration bean.\n *\n * @kosService core.use-config-property\n * @kosApiLevel 2\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};\n/**\n * Hook for binding to a KOS configuration property.\n *\n * @kosService core.use-config-property\n * @kosApiLevel 2\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","import { useEffect, useState } from \"react\";\nimport { EventBus } from \"../../common\";\nimport { WebSocketEvents } from \"../../core/core/transport/base-message-transport\";\nimport { useKosCore } from \"../contexts/kos-core-context\";\n\n/**\n * Details of the most recent WebSocket close event.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport interface DisconnectInfo {\n code: number;\n reason: string;\n wasClean: boolean;\n /** Wall-clock time (Date.now()) when the disconnect was observed. */\n at: number;\n}\n\n/**\n * Current KOS Core connection state plus info about the last disconnect.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport interface ConnectionState {\n online: boolean;\n lastDisconnect: DisconnectInfo | null;\n /** Milliseconds since the last disconnect, or null if none observed. */\n sinceLastDisconnectMs: number | null;\n}\n\n/**\n * Observes KOS Core connection state.\n *\n * Returns the current `online` status plus information about the most recent\n * disconnect (code, reason, wasClean, timestamp). `sinceLastDisconnectMs` is\n * recomputed on each render; components that need it to tick continuously\n * should re-render themselves via an interval.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport const useConnectionState = (): ConnectionState => {\n const { online } = useKosCore();\n const [lastDisconnect, setLastDisconnect] = useState<DisconnectInfo | null>(\n null\n );\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (\n payload &&\n typeof payload === \"object\" &&\n typeof payload.code === \"number\"\n ) {\n setLastDisconnect({\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n });\n }\n }\n );\n return () => {\n unsubscribe();\n };\n }, []);\n\n return {\n online,\n lastDisconnect,\n sinceLastDisconnectMs: lastDisconnect\n ? Date.now() - lastDisconnect.at\n : null,\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 { useEffect } from \"react\";\n\n// A warmup marker to simulate a special execution path\n/**\n * Represents a marker type used to indicate that a function or process\n * has been warmed up and is ready for use.\n *\n * This type is typically used as a flag or annotation in scenarios\n * where initialization or preparation steps are required before\n * execution.\n */\nexport type WarmupMarker = { __warmup: true };\n\n// Accepts a function that takes 0 or 1 argument\ntype Warmupable<T extends (arg?: any) => any> = (\n arg?: any | WarmupMarker\n) => ReturnType<T>;\n\ninterface UseFunctionWarmupOptions {\n intervalMs?: number; // How often to re-warm (ms)\n immediate?: boolean; // Should warmup run on mount\n}\n\n/**\n * A React hook that periodically invokes a given function to keep it \"warmed up.\"\n * This can be useful for functions that require initialization or caching to\n * improve performance during actual usage.\n *\n * @template T - The type of the function to be warmed up.\n * @param fn - The function to be warmed up. It should accept an optional argument\n * and handle a special warmup call with `{ __warmup: true }`.\n * @param options - Configuration options for the warmup behavior.\n * @param options.intervalMs - The interval in milliseconds at which the function\n * should be warmed up. Defaults to 5 minutes (300,000 ms).\n * If set to `null` or `0`, periodic warmup is disabled.\n * @param options.immediate - Whether to perform an immediate warmup when the hook\n * is first invoked. Defaults to `true`.\n *\n * @returns void\n *\n * @remarks\n * - If the `immediate` option is enabled, the function will be warmed up immediately\n * using `requestIdleCallback` if available, or a `setTimeout` fallback.\n * - Errors thrown during the warmup process are caught and ignored.\n * - The periodic warmup is cleaned up automatically when the component unmounts.\n *\n * @example\n * ```tsx\n * import { useFunctionWarmup } from './use-function-warmup';\n *\n * const myFunction = (arg?: any) => {\n * if (arg?.__warmup) {\n * console.log('Warming up...');\n * } else {\n * console.log('Executing function...');\n * }\n * };\n *\n * function MyComponent() {\n * useFunctionWarmup(myFunction, { intervalMs: 60000, immediate: true });\n *\n * return <div>My Component</div>;\n * }\n * ```\n */\nexport function useFunctionWarmup<T extends (arg?: any) => any>(\n fn: Warmupable<T>,\n options: UseFunctionWarmupOptions = {}\n) {\n const { intervalMs = 5 * 60 * 1000, immediate = true } = options;\n\n useEffect(() => {\n const warmup = () => {\n try {\n fn({ __warmup: true });\n } catch {\n // ignore errors from warmup path\n }\n };\n\n if (immediate) {\n if (\"requestIdleCallback\" in window) {\n requestIdleCallback(warmup);\n } else {\n setTimeout(warmup, 1);\n }\n }\n\n const id = intervalMs ? setInterval(warmup, intervalMs) : null;\n return () => {\n if (id) clearInterval(id);\n };\n }, [fn, intervalMs, immediate]);\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 });\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 { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n hasReadyHook,\n isDisposable,\n} from \"../../../core/core/decorators/kos-view-model\";\n\n/**\n * Configuration options for the useViewModel hook.\n */\nexport interface UseViewModelOptions {\n /**\n * When true, calls the ViewModel's dispose() method on unmount\n * and when dependencies change causing recreation.\n * Default: true (if dispose method exists)\n */\n disposeOnUnmount?: boolean;\n}\n\n/**\n * Result returned by useViewModel when the ViewModel implements IKosViewModelReady.\n */\nexport interface UseViewModelResult<T> {\n /** The ViewModel instance */\n viewModel: T;\n /** Whether the ViewModel's ready() hook has completed */\n ready: boolean;\n /** Error from the ready() hook, if any */\n error: Error | undefined;\n}\n\n/**\n * React hook for creating and managing ViewModel instances.\n *\n * The hook:\n * - Creates the ViewModel using the provided factory function\n * - Calls ready() if the ViewModel implements IKosViewModelReady\n * - Automatically calls dispose() on unmount (if the method exists)\n * - Re-creates the ViewModel when dependencies change\n * - Disposes the previous ViewModel when recreating\n *\n * @param factory - Function that creates the ViewModel instance\n * @param deps - Dependency array (similar to useEffect/useMemo)\n * @param options - Optional configuration\n * @returns UseViewModelResult with viewModel, ready state, and error\n *\n * @example\n * ```typescript\n * // Basic usage (no ready hook)\n * function Counter() {\n * const { viewModel: vm, ready } = useViewModel(() => new CounterViewModel(), []);\n *\n * return (\n * <div>\n * <span>{vm.count}</span>\n * <button onClick={() => vm.increment()}>+</button>\n * </div>\n * );\n * }\n *\n * // With ready hook for async initialization\n * function OrderSummary({ orderId }: Props) {\n * const { model: order } = useKosModel<IOrderModel>({ modelId: orderId });\n * const { model: inventory } = useKosModel<IInventoryModel>({ modelId: 'inventory' });\n *\n * const { viewModel: vm, ready, error } = useViewModel(\n * () => new OrderSummaryViewModel(order!, inventory!),\n * [order, inventory]\n * );\n *\n * if (error) return <ErrorDisplay error={error} />;\n * if (!ready) return <Loading />;\n *\n * return <div>Total: ${vm.total}</div>;\n * }\n *\n * // Disable auto-disposal\n * const { viewModel: vm } = useViewModel(\n * () => new MyViewModel(),\n * [],\n * { disposeOnUnmount: false }\n * );\n * ```\n *\n * @category KOS React Hook\n */\nexport function useViewModel<T>(\n factory: () => T,\n deps: React.DependencyList,\n options: UseViewModelOptions = {}\n): UseViewModelResult<T> {\n const { disposeOnUnmount = true } = options;\n\n // Track ready state and errors\n const [ready, setReady] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n\n // Track the current ViewModel for disposal\n const viewModelRef = useRef<T | null>(null);\n const isFirstRender = useRef(true);\n // Track ready call to prevent duplicate calls\n const readyCalledRef = useRef(false);\n\n // Create ViewModel (memoized based on deps)\n const viewModel = useMemo(() => {\n // Dispose previous instance if deps changed (not on first render)\n if (\n !isFirstRender.current &&\n viewModelRef.current &&\n disposeOnUnmount &&\n isDisposable(viewModelRef.current)\n ) {\n const previous = viewModelRef.current;\n // Run dispose asynchronously to avoid React warnings during render\n Promise.resolve().then(() => {\n if (isDisposable(previous)) {\n previous.dispose();\n }\n });\n }\n\n isFirstRender.current = false;\n // Reset ready state for new instance\n readyCalledRef.current = false;\n\n // Create new instance\n const instance = factory();\n viewModelRef.current = instance;\n return instance;\n }, deps);\n\n // Handle ready() hook\n useEffect(() => {\n // Skip if already called for this instance\n if (readyCalledRef.current) return;\n\n // If ViewModel has ready hook, call it\n if (hasReadyHook(viewModel)) {\n readyCalledRef.current = true;\n setReady(false);\n setError(undefined);\n\n viewModel\n .ready()\n .then(() => {\n setReady(true);\n })\n .catch((err: Error) => {\n setError(err);\n setReady(false);\n });\n } else {\n // No ready hook - immediately ready\n setReady(true);\n setError(undefined);\n }\n }, [viewModel]);\n\n // Handle cleanup on unmount\n useEffect(\n () => () => {\n if (\n disposeOnUnmount &&\n viewModelRef.current &&\n isDisposable(viewModelRef.current)\n ) {\n viewModelRef.current.dispose();\n }\n viewModelRef.current = null;\n },\n [disposeOnUnmount]\n );\n\n return { viewModel, ready, error };\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","import { registerApiLevels } from \"@kosdev-code/kos-api-levels\";\n\n// Registers the package-level API integer for this SDK.\n// The level history (which tag boundaries changed the public surface and why) lives in\n// kos-api-levels/generated/api-archaeology-report.md, produced by the archaeology scanner.\nregisterApiLevels({ \"kos-ui-sdk\": 24 });\n\nexport * from \"./common\";\nexport * from \"./core\";\nexport * from \"./models\";\nexport * from \"./models/models/canvas-renderer\";\nexport * from \"./models/models/gpio-chip\";\nexport * from \"./models/models/gpio-pin\";\nexport * from \"./models/models/kos-expression-evaluator\";\nexport * from \"./models/models/kos-log-manager\";\nexport * from \"./models/models/log-block\";\nexport * from \"./models/models/studio-properties\";\nexport * from \"./ui\";\n"],"names":["subscribe","debounce","buffer","sub","request","publish","ChildModels","ParentModel","OptionsRequired","CompanionParentModel","ContainerAwareSetup","KosContextManager","params","FutureContainerSetup","MultipleFutureContainerSetup","LogConfig","LoggerSetup","KosViewModelSymbol","KosLoggerFactory","ModelEffects","ReferenceConfig","KosFetchMethods","TroubleAwareSetup","DependencyModels","DependencyLifecycle","ExtensionManager","condition","SubscriptionHandlers","action","runInAction","reaction","autorun","StateMachineSetup","injectStateMachineSupport","initializeStateMachine","makeAutoObservable","ViewModelConfig","KosModelVisitor","index","getDaysInMonth","kosAction","KosCore","sendKosMessageResponse","KosLog","EventBus.subscribe","log","uuid","EventBus.publish","INDEX_RECORD_SYMBOL","INDEX_COLLECTION_KEY","KosContainerIndexEvents","isIndexableItem","Kos","isKosModel","token","KosCoreModelPropertyMapper","Topics","URL","BASE_URL","postModel","getOne","ServiceFactory","flattenObject","Logger","PATH_PROP","DESTINATION_PROP","servicePathMapper","modifyConfigBean","modifyConfigBeanService","getConfigBean","getConfigBeanService","ObservableData","__decorateClass","kosTopicHandler","kosModel","KosModelRegistrationFactory","resolveServiceUrl","getAll","UnitTupleKeys","acc","MODEL_TYPE","REGION_SETTINGS_PATH","REGION_PATH","Registration","getKosModelSync","RegionInfo","isKosModelReady","format","formatter","result","KosConfigPropertySpec","buildFutureModel","FutureEndState","deleteModel","modelFactory","whenReady","kosAutoEffect","isKosExecutionContext","KOS_EXECUTION_CONTEXT","registerExtensionPoint","EXTENSION_FUTURE_LIFECYCLE_WRAPPER","FutureService","FutureAliases","kosObservable","data","sendKosHttpMessageResponse","SingletonKosModelRegistrationFactory","FutureModel","kosWhen","destroyKosModel","KOS_MODEL_ID","FutureContainerModel","deleteFuture","deleteFutureService","addFuture","addFutureService","KosModelContainer","model","n2","args","argCount","n1","f","i","div","__publicField","SERVICE_PATH","API","KosDataContainer","logger","_logger","get","getQueryParams","kosEffect","block","troubleMappers","FutureHandler","resolveKosCompanion","cancelFuture","api","createClient","kosFetch","Base","hexToRgb","p","q","EXTENSION_CANVAS_RENDERER","pattern","endpoint","post","FetchError","getDefaultHost","WsEventModel","observable","KosWsEvents","registerKosModel","registerLegacyModel","RegistrationManager","troubleRankMapper","troubleRoleMapper","troubleColorMapper","REGION_ATTRIBUTE","REGION_ID","kosServiceRequest","baseKosServiceRequest","serviceRequest","TIMEZONE_ATTRIBUTE","REGION_TIMEZONE_ID","configResponse","KOS_SERVICE.kosServiceRequest","KOS_SERVICE.api","WebSocketTransport","kosComputed","keyframes","css","createPortal","message","jsx","jsxs","createContext","useContext","useState","useCallback","addModel","filter","useMemo","ErrorBoundaryWithFallback","Suspense","useEffect","Fragment","observer","useRef","WebSocketEvents","modelHookCache","useSuspenseData","fetchModel","isUpdateable","KosModelEvents","KosModelState","modelId","clearModelHookCacheEntry","KosModelLoader","translations","locale","kosComponent","getKosModel","useReducer","DateDisplayFormat","nextMonth","nextYear","parseISO","setDate","DEFAULT_FORMAT_MAP","useGesture","setTime","date"],"mappings":";;;;;;;;;;;;;AAAA,MAAM,8BAAc,IAAA;AAYb,SAAS,eACd,SACA,WACA,mBACA,aACA,eACM;AACN,MACE,OAAO,YAAY,eACnB,QAAQ,IAAI,UAAU,MAAM,cAC5B;AACA;AAAA,EACF;AACA,MAAI,QAAQ,IAAI,OAAO,EAAG;AAC1B,UAAQ,IAAI,OAAO;AACnB,UAAQ;AAAA,IACN,UAAU,OAAO,yBAAyB,SAAS,UAAU,iBAAiB,UACpE,WAAW,uCAAuC,aAAa;AAAA,EAAA;AAE7E;AC7BA,MAAM,YAAyB,CAAA;AASxB,SAAS,kBAAkB,QAA2B;AAC3D,SAAO,OAAO,WAAW,MAAM;AACjC;ACIO,SAAS,KACd,WACA,UACY;AACZ,QAAM,eAAeA,UAAAA,UAAU,WAAW,CAAC,QAAY;AAErD,iBAAa,YAAA;AACb,aA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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[81]}
1
+ {"version":3,"file":"index.cjs","sources":["../../../packages/kos-api-levels/src/deprecation.ts","../../../packages/kos-api-levels/src/registry.ts","../../../packages/kos-ui-sdk/src/common/events/eventBus.functional.ts","../../../packages/kos-ui-sdk/src/common/file-utils.ts","../../../packages/kos-ui-sdk/src/core/core/api/wrapPromise.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-companion.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-context.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-execute-service-request.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-multiple-future-aware.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-log.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-mixin.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-reference.ts","../../../packages/kos-ui-sdk/src/core/types/utils/kos-fetch.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-trouble-aware.ts","../../../packages/kos-ui-sdk/src/core/core/extension/initialize-extension.ts","../../../packages/kos-ui-sdk/src/core/core/extension/plugin-extension-manager.ts","../../../packages/kos-ui-sdk/src/core/util/debounce.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kosSubscribe.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-view-model.ts","../../../packages/kos-ui-sdk/src/core/util/ancestor-path-visitor.ts","../../../packages/kos-ui-sdk/src/core/util/apply-mixins.ts","../../../packages/kos-ui-sdk/src/core/util/array-utils.ts","../../../packages/kos-ui-sdk/src/core/util/date-utils.ts","../../../packages/kos-ui-sdk/src/core/util/hsl-to-hex.ts","../../../packages/kos-ui-sdk/src/core/util/middleware.ts","../../../packages/kos-ui-sdk/src/core/util/model-registration-utils.ts","../../../packages/kos-ui-sdk/src/core/util/paired-client-heartbeat.ts","../../../packages/kos-ui-sdk/src/core/util/retry-with-exponential-backoff.ts","../../../packages/kos-ui-sdk/src/core/util/service-response.ts","../../../packages/kos-ui-sdk/src/core/util/wait-for-request.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/kos-index-aware.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/kos-container-index-aware.ts","../../../packages/kos-ui-sdk/src/core/core/kos-registration.ts","../../../packages/kos-ui-sdk/src/core/core/kos-singleton-registration.ts","../../../packages/kos-ui-sdk/src/core/core/models/kos-token/index.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-config-bean.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-config-bean-prop.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-state-bean.ts","../../../packages/kos-ui-sdk/src/models/decorators/kos-state-prop.ts","../../../packages/kos-ui-sdk/src/models/types/cancellable-promise.ts","../../../packages/kos-ui-sdk/src/models/utils/cancellable-future-call.ts","../../../packages/kos-ui-sdk/src/models/models/translation/descriptor-merge.ts","../../../packages/kos-ui-sdk/src/models/models/translation/translation-context.ts","../../../packages/kos-ui-sdk/src/models/utils/extension-manager.ts","../../../packages/kos-ui-sdk/src/models/utils/persistence-store.ts","../../../packages/kos-ui-sdk/src/models/utils/region-utils.ts","../../../packages/kos-ui-sdk/src/models/utils/service-accessor.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/daily/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.6.5/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.8.1/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/kos/1.9.x/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/daily/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.6.5/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.8.1/service.ts","../../../packages/kos-ui-sdk/src/models/utils/services/vfs/1.9.x/service.ts","../../../packages/kos-ui-sdk/src/models/utils/timezone-utils.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/utils/is-trouble-aware.ts","../../../packages/kos-ui-sdk/src/models/services/login/index.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-pin/gpio-pin-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-pin/gpio-pin-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/gpio-chip-model.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/services/gpio-chip-services.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/gpio-chip-builders.ts","../../../packages/kos-ui-sdk/src/models/models/gpio-chip/gpio-chip-container-model.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/services/studio-properties-services.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/studio-properties-model.ts","../../../packages/kos-ui-sdk/src/models/models/studio-properties/studio-properties-registration.ts","../../../packages/kos-ui-sdk/src/ui/components/loading-message/loading-message-styles.ts","../../../packages/kos-ui-sdk/src/ui/components/loading-message/index.tsx","../../../packages/kos-ui-sdk/src/ui/components/error-boundary/error-boundary.tsx","../../../packages/kos-ui-sdk/src/ui/components/progress-bar/progress-bar.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-context.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-hierarchy-context.tsx","../../../packages/kos-ui-sdk/src/ui/components/kos-model-loader/kos-model-loader.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/fetch-kos-core.ts","../../../packages/kos-ui-sdk/src/ui/contexts/kos-core-context.tsx","../../../packages/kos-ui-sdk/src/ui/policies/constants.ts","../../../packages/kos-ui-sdk/src/ui/policies/reload-on-disconnect-policy.tsx","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/use-reconnecting-overlay-state.ts","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/reconnecting-overlay-styles.ts","../../../packages/kos-ui-sdk/src/ui/components/reconnecting-overlay/index.tsx","../../../packages/kos-ui-sdk/src/ui/components/connection-dev-button/use-connection-dev-state.ts","../../../packages/kos-ui-sdk/src/ui/components/connection-dev-button/connection-dev-button-styles.ts","../../../packages/kos-ui-sdk/src/ui/components/connection-dev-button/index.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/create-model-context.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/kos-time/use-kos-time.ts","../../../packages/kos-ui-sdk/src/ui/contexts/kos-time/kos-time-provider.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/software-info/use-software-info.ts","../../../packages/kos-ui-sdk/src/ui/hooks/software-info/with-software-info.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/software-info/software-info-provider.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/token-context.tsx","../../../packages/kos-ui-sdk/src/ui/contexts/translation-container/kos-translations-provider.tsx","../../../packages/kos-ui-sdk/src/ui/features/canvas/hooks/canvas-dispatcher/use-canvas-dispatcher.ts","../../../packages/kos-ui-sdk/src/ui/features/canvas/hooks/canvas-dispatcher/with-canvas-dispatcher.tsx","../../../packages/kos-ui-sdk/src/ui/features/canvas/utils/preview-decoder.ts","../../../packages/kos-ui-sdk/src/ui/features/canvas/components/canvas-streamer/canvas-streamer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/device/use-device.ts","../../../packages/kos-ui-sdk/src/ui/hooks/device/with-device.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/fetch-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/kos-time/with-kos-time.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/network-interface-container/use-network-interface-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/network-interface-container/with-network-interface-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/ota/use-ota.ts","../../../packages/kos-ui-sdk/src/ui/hooks/ota/with-ota.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/outside-alerter.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/state-prop/use-state-prop.ts","../../../packages/kos-ui-sdk/src/ui/hooks/storage-device-container/use-storage-device-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/storage-device-container/with-storage-device-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/timer/use-timer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/trans.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/use-translation.ts","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/use-translation-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/translation-container/with-translation-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-visibility.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/trouble/with-trouble-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/usb-update-container/use-usb-update-container.ts","../../../packages/kos-ui-sdk/src/ui/hooks/usb-update-container/with-usb-update-container.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-config-bean.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-config-property.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-connection-state.ts","../../../packages/kos-ui-sdk/src/ui/utils/date.ts","../../../packages/kos-ui-sdk/src/ui/utils/date-utils.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-date-props.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-date-relative-prop.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-function-warmup.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-date-formats.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-region-timezones.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-regions.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-kos-time-formats.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-local-computed.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-mutation-observer.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-press-gesture/strategy/dom-intersection-strategy.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-press-gesture/use-press-gesture.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-project-reloading.ts","../../../packages/kos-ui-sdk/src/ui/hooks/use-time-props.tsx","../../../packages/kos-ui-sdk/src/ui/hooks/use-region-time-props.ts","../../../packages/kos-ui-sdk/src/ui/hooks/view-model/use-view-model.ts","../../../packages/kos-ui-sdk/src/ui/hooks/with-project-reload.tsx","../../../packages/kos-ui-sdk/src/index.ts"],"sourcesContent":["const _warned = new Set<string>();\n\n/**\n * Emits a one-time console warning in non-production environments when a\n * deprecated API is used.\n *\n * @param apiName - The name of the deprecated API (e.g. `@kosSubscribe`)\n * @param serviceId - The service the API belongs to (e.g. `core.subscribe`)\n * @param deprecatedAtLevel - The API level at which this API was deprecated\n * @param replacement - The recommended replacement (e.g. `@kosTopicHandler`)\n * @param removeAtLevel - The API level at which this API will be removed\n */\nexport function warnDeprecated(\n apiName: string,\n serviceId: string,\n deprecatedAtLevel: number,\n replacement: string,\n removeAtLevel: number\n): void {\n if (\n typeof process !== \"undefined\" &&\n process.env[\"NODE_ENV\"] === \"production\"\n ) {\n return;\n }\n if (_warned.has(apiName)) return;\n _warned.add(apiName);\n console.warn(\n `[KOS] \"${apiName}\" is deprecated since ${serviceId} level ${deprecatedAtLevel}. ` +\n `Use \"${replacement}\" instead. Will be removed at level ${removeAtLevel}.`\n );\n}\n","import type { ApiLevelMap } from \"./types\";\n\nconst _registry: ApiLevelMap = {};\n\n/**\n * Registers API levels for an SDK package. Each SDK package calls this on\n * import to populate the in-memory registry. Works in browser and Node.js.\n * The call lives in each package's index.ts; the release scanner\n * (`scanner/generate-release.ts`) updates its level number.\n */\nexport function registerApiLevels(levels: ApiLevelMap): void {\n Object.assign(_registry, levels);\n}\n\nexport function getRegistry(): Readonly<ApiLevelMap> {\n return _registry;\n}\n","/**\n * Functional programming utilities for the EventBus\n * Provides reactive and promise-based patterns for event handling\n */\n\nimport { ApiCallback, EventCallback, publish, subscribe } from \"./eventBus\";\n\n/**\n * Subscribe to an event that will automatically unsubscribe after the first occurrence\n *\n * @param eventType - The event type to listen for\n * @param callback - The callback to execute once\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function once<T = ApiCallback>(\n eventType: string,\n callback: EventCallback<T>\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n // Unsubscribe immediately after first call\n subscription.unsubscribe();\n callback(msg);\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Wait for a specific event to occur, returning a Promise\n *\n * @param eventType - The event type to wait for\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the event data\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function waitFor<T = ApiCallback>(\n eventType: string,\n timeout?: number\n): Promise<T> {\n return new Promise((resolve, reject) => {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const unsubscribe = once(eventType, (msg?: T) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n resolve(msg!);\n });\n\n if (timeout) {\n timeoutId = setTimeout(() => {\n unsubscribe();\n reject(new Error(`Timeout waiting for event: ${eventType}`));\n }, timeout);\n }\n });\n}\n\n/**\n * Wait for multiple events to occur (Promise.all pattern)\n *\n * @param eventTypes - Array of event types to wait for\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves when all events have occurred\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function waitForAll<T = ApiCallback>(\n eventTypes: string[],\n timeout?: number\n): Promise<T[]> {\n const promises = eventTypes.map((eventType) =>\n waitFor<T>(eventType, timeout)\n );\n return Promise.all(promises);\n}\n\n/**\n * Wait for the first event to occur from a list (Promise.race pattern)\n *\n * @param eventTypes - Array of event types to race\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the first event\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function race<T = ApiCallback>(\n eventTypes: string[],\n timeout?: number\n): Promise<{ eventType: string; data: T }> {\n return new Promise((resolve, reject) => {\n const unsubscribers: (() => void)[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n let resolved = false;\n\n const cleanup = () => {\n unsubscribers.forEach((unsub) => unsub());\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n };\n\n eventTypes.forEach((eventType) => {\n const unsubscribe = once(eventType, (msg?: T) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n resolve({ eventType, data: msg! });\n }\n });\n unsubscribers.push(unsubscribe);\n });\n\n if (timeout) {\n timeoutId = setTimeout(() => {\n if (!resolved) {\n resolved = true;\n cleanup();\n reject(\n new Error(`Timeout waiting for any event: ${eventTypes.join(\", \")}`)\n );\n }\n }, timeout);\n }\n });\n}\n\n/**\n * Filter events based on a predicate function\n *\n * @param eventType - The event type to filter\n * @param predicate - Function to test each event\n * @param callback - Callback for events that pass the filter\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function filter<T = ApiCallback>(\n eventType: string,\n predicate: (msg: T) => boolean,\n callback: EventCallback<T>\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg && predicate(msg)) {\n callback(msg);\n }\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Transform events using a map function\n *\n * @param eventType - The event type to transform\n * @param transform - Function to transform the event data\n * @param callback - Callback for transformed events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function map<T = ApiCallback, R = any>(\n eventType: string,\n transform: (msg: T) => R,\n callback: (msg: R) => void\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n const transformed = transform(msg);\n callback(transformed);\n }\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Debounce events - only emit after a period of inactivity\n *\n * @param eventType - The event type to debounce\n * @param delay - Delay in milliseconds\n * @param callback - Callback for debounced events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function debounce<T = ApiCallback>(\n eventType: string,\n delay: number,\n callback: EventCallback<T>\n): () => void {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n callback(msg);\n }, delay);\n });\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Throttle events - limit emissions to once per interval\n *\n * @param eventType - The event type to throttle\n * @param interval - Minimum interval between emissions in milliseconds\n * @param callback - Callback for throttled events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function throttle<T = ApiCallback>(\n eventType: string,\n interval: number,\n callback: EventCallback<T>\n): () => void {\n let lastEmit = 0;\n let pendingTimeout: NodeJS.Timeout | null = null;\n\n const subscription = subscribe(eventType, (msg?: T) => {\n const now = Date.now();\n const timeSinceLastEmit = now - lastEmit;\n\n if (timeSinceLastEmit >= interval) {\n lastEmit = now;\n callback(msg);\n } else if (!pendingTimeout) {\n // Schedule emission for the remaining time\n pendingTimeout = setTimeout(() => {\n lastEmit = Date.now();\n callback(msg);\n pendingTimeout = null;\n }, interval - timeSinceLastEmit);\n }\n });\n\n return () => {\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Buffer events and emit them as an array\n *\n * @param eventType - The event type to buffer\n * @param bufferTime - Time window to collect events in milliseconds\n * @param callback - Callback for buffered events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function buffer<T = ApiCallback>(\n eventType: string,\n bufferTime: number,\n callback: (events: T[]) => void\n): () => void {\n let buffer: T[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n\n const flush = () => {\n if (buffer.length > 0) {\n callback([...buffer]);\n buffer = [];\n }\n };\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n buffer.push(msg);\n\n if (!timeoutId) {\n timeoutId = setTimeout(() => {\n flush();\n timeoutId = null;\n }, bufferTime);\n }\n }\n });\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n flush(); // Emit any remaining buffered events\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Create a replay subject that remembers the last N events\n *\n * @param eventType - The event type to replay\n * @param bufferSize - Number of events to remember\n * @returns Object with subscribe method that replays buffered events\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function replay<T = ApiCallback>(eventType: string, bufferSize = 1) {\n const buffer: T[] = [];\n\n // Subscribe to capture events\n subscribe(eventType, (msg?: T) => {\n if (msg) {\n buffer.push(msg);\n if (buffer.length > bufferSize) {\n buffer.shift();\n }\n }\n });\n\n return {\n subscribe: (callback: EventCallback<T>) => {\n // Replay buffered events immediately\n buffer.forEach((event) => callback(event));\n\n // Then subscribe for future events\n return subscribe(eventType, callback);\n },\n };\n}\n\n/**\n * Merge multiple event streams into one\n *\n * @param eventTypes - Array of event types to merge\n * @param callback - Callback for all merged events\n * @returns Unsubscribe function for all subscriptions\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function merge<T = ApiCallback>(\n eventTypes: string[],\n callback: (eventType: string, msg: T) => void\n): () => void {\n const subscriptions = eventTypes.map((eventType) =>\n subscribe(eventType, (msg?: T) => {\n if (msg) {\n callback(eventType, msg);\n }\n })\n );\n\n return () => {\n subscriptions.forEach((sub) => sub.unsubscribe());\n };\n}\n\n/**\n * Create a state machine that transitions based on events\n *\n * @param initialState - The initial state\n * @param transitions - Object mapping states to event handlers\n * @returns Object with current state and unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function stateMachine<TState extends string, T = ApiCallback>(\n initialState: TState,\n transitions: Record<TState, Record<string, (msg: T) => TState>>\n) {\n let currentState = initialState;\n const subscriptions: (() => void)[] = [];\n\n // Subscribe to all events mentioned in transitions\n const allEvents = new Set<string>();\n Object.values(transitions).forEach((stateTransitions) => {\n Object.keys(stateTransitions as Record<string, any>).forEach((event) => {\n allEvents.add(event);\n });\n });\n\n allEvents.forEach((eventType) => {\n const { unsubscribe } = subscribe(eventType, (msg?: T) => {\n const stateTransitions = transitions[currentState];\n if (stateTransitions && stateTransitions[eventType]) {\n const nextState = stateTransitions[eventType](msg!);\n currentState = nextState;\n }\n });\n subscriptions.push(unsubscribe);\n });\n\n return {\n get state() {\n return currentState;\n },\n unsubscribe: () => {\n subscriptions.forEach((unsub) => unsub());\n },\n };\n}\n\n/**\n * Utility to create a promise that can be resolved by publishing an event\n *\n * @param requestEvent - Event type to publish the request\n * @param responseEvent - Event type to wait for the response\n * @param request - The request data to publish\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the response\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function request<TRequest = any, TResponse = ApiCallback>(\n requestEvent: string,\n responseEvent: string,\n request: TRequest,\n timeout?: number\n): Promise<TResponse> {\n const responsePromise = waitFor<TResponse>(responseEvent, timeout);\n publish(requestEvent, request);\n return responsePromise;\n}\n\n/**\n * Create an async iterator for events\n *\n * @param eventType - The event type to iterate\n * @returns Async iterator for use with for-await-of\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport async function* eventIterator<T = ApiCallback>(\n eventType: string\n): AsyncIterableIterator<T> {\n const queue: T[] = [];\n const waiters: ((value: T) => void)[] = [];\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n if (waiters.length > 0) {\n const waiter = waiters.shift()!;\n waiter(msg);\n } else {\n queue.push(msg);\n }\n }\n });\n\n try {\n while (true) {\n if (queue.length > 0) {\n yield queue.shift()!;\n } else {\n yield await new Promise<T>((resolve) => {\n waiters.push(resolve);\n });\n }\n }\n } finally {\n subscription.unsubscribe();\n }\n}\n\n/**\n * Namespace collecting all functional event bus utilities.\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport const EventBusFunctional = {\n once,\n waitFor,\n waitForAll,\n race,\n filter,\n map,\n debounce,\n throttle,\n buffer,\n replay,\n merge,\n stateMachine,\n request,\n eventIterator,\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","/* eslint-disable no-param-reassign */\nimport type { DependencyLifecycle } from \"../../types\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport { kosParentAware } from \"./kos-parent\";\nimport { CompanionParentModel } from \"./propKeys\";\n\n/**\n * @kosService core.companion\n * @kosApiLevel 13\n */\nexport interface KosCompanionOptions {\n /**\n * Pattern mode:\n * - 'decorator': Proxy all parent properties transparently (default)\n * - 'composition': Only provide getCompanionParent() and the parentProperty getter\n */\n mode?: \"decorator\" | \"composition\";\n /** Properties to exclude from proxying (only applies in decorator mode). Default: [] */\n excludeProperties?: string[];\n /** Custom parent property name. Default: 'companionParent' */\n parentProperty?: string;\n /**\n * Lifecycle phase of the parent at which this companion is created. Defaults to INIT\n * (created during parent instantiation); LOAD creates it after the parent's load()\n * completes, READY after ready(), and so on.\n *\n * @kosApiLevel 15\n */\n lifecycle?: DependencyLifecycle;\n}\n\n/**\n * Base interface for all companion models.\n * Provides the getCompanionParent() method available in both decorator and composition modes.\n *\n * @kosService core.companion\n * @kosApiLevel 13\n */\nexport interface KosCompanionAware<\n TParent extends IKosDataModel = IKosDataModel\n> {\n /**\n * Gets the companion's parent model instance.\n * Available in both decorator and composition modes.\n * Provides access to the model this companion extends.\n *\n * @returns The parent model instance that this companion enhances\n */\n getCompanionParent(): TParent;\n}\n\n/**\n * Members injected into a companion in composition mode. Declare an interface with the\n * same name as the class that extends this type (TypeScript interface merging).\n *\n * @kosService core.companion\n */\nexport type KosCompanionComposition<\n TParent extends IKosDataModel = IKosDataModel\n> = KosCompanionAware<TParent>;\n\n/**\n * Members injected into a companion in decorator mode (the default). Declare an\n * interface with the same name as the class that extends this type (TypeScript\n * interface merging); to type the proxied parent members as well, also extend the\n * parent model's interface.\n *\n * @kosService core.companion\n */\nexport type KosCompanionDecorator<\n TParent extends IKosDataModel = IKosDataModel\n> = KosCompanionAware<TParent>;\n\n/**\n * Class decorator that makes a KOS model a companion of a parent model, extending it\n * with behavior that lives in a separate model.\n *\n * Both modes provide `getCompanionParent()` and a read-only `companionParent` (or\n * `parentProperty`) getter.\n * - **decorator** (default): the parent's properties and methods are also proxied onto\n * the companion, so it can stand in for the parent. Lifecycle methods, topic\n * handlers, `_`-prefixed members, `excludeProperties` and members the companion\n * defines itself are not proxied.\n * - **composition**: the parent is reachable only through those two accessors.\n *\n * The decorator also applies @kosParentAware.\n *\n * @param options Configuration options for the companion decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * interface ServiceCompanionModelImpl extends KosCompanionComposition<ServiceModel> {}\n *\n * @kosModel(\"service-companion\")\n * @kosCompanion({ mode: 'composition' })\n * class ServiceCompanionModelImpl implements IKosDataModel {\n * get serviceInfo() {\n * return `Service: ${this.getCompanionParent().serviceName}`;\n * }\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.1.0\n * @kosService core.companion\n * @kosApiLevel 2\n */\nexport function kosCompanion(options?: KosCompanionOptions): ClassDecorator {\n return (target: any) => {\n const mode = options?.mode || \"decorator\";\n const parentProperty = options?.parentProperty || \"companionParent\";\n const excludeProperties = options?.excludeProperties || [];\n const lifecycle = options?.lifecycle;\n\n // Companions by definition have parent relationships - automatically apply kosParentAware\n kosParentAware()(target);\n\n // Add the companion configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[CompanionParentModel] = {\n mode,\n parentProperty,\n excludeProperties,\n lifecycle,\n };\n\n return target;\n };\n}\n","/**\n * @internal\n */\nimport { KosContextManager } from \"../context/kos-context-manager\";\n\n/**\n * Method decorator that injects the current KOS execution context into a method call.\n *\n * @kosService core.context\n * @kosApiLevel 2\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","import type { ClientResponse } from \"../../util/kos-service-request\";\nimport type { KosExecutionContext } from \"./kos-execution-context\";\nimport type { KosLoggerAware } from \"./kos-logger-aware\";\nimport type { HttpMethod, ServiceRequestExecutor } from \"./kos-service-request\";\n\n/**\n * Runs a method-driven service request: checks the injected context, awaits the\n * error-first tuple, logs a failure and treats an empty body as a failure, so the\n * caller handles only the success path.\n *\n * ```typescript\n * const data = await executeServiceRequest(this, $ctx, {\n * body: { id: cartridgeId },\n * });\n * if (!data) return;\n * ```\n *\n * Failures are logged against the method name the decorator puts on `$ctx.$name`.\n *\n * Use it only with a @kosServiceRequest that has no `lifecycle`. A lifecycle-driven\n * handler receives `(error, data)` with the request already performed and never gets\n * a context.\n *\n * @param host Model the request belongs to; supplies the logger.\n * @param $ctx Context the decorator injected as the method's last parameter.\n * @param params `pathParams` / `queryParams` / `body` / `requestOptions`.\n * @returns The response body, or `undefined` when the request could not run,\n * failed, or came back empty.\n *\n * @kosService core.service-request\n * @kosApiLevel 24\n */\nexport async function executeServiceRequest<\n Paths extends Record<string, any>,\n Path extends keyof Paths,\n Method extends HttpMethod = \"get\",\n Transformed = ClientResponse<Paths, Path, Method>\n>(\n host: KosLoggerAware,\n $ctx: KosExecutionContext<Paths, Path, Method, Transformed> | undefined,\n params?: Parameters<ServiceRequestExecutor<Paths, Path, Method>>[0]\n): Promise<NonNullable<Transformed> | undefined> {\n const name = $ctx?.$name ?? \"service request\";\n if (!$ctx?.$request) {\n // Almost always a decorator with a `lifecycle`, which gets no context; say so,\n // because the symptom is a method that silently does nothing.\n host.logger.error(\n `${name}: missing execution context — executeServiceRequest is for method-driven requests; ` +\n `a @kosServiceRequest with a lifecycle receives (error, data) instead and needs no helper`\n );\n return undefined;\n }\n\n const [error, data] = await $ctx.$request(params);\n if (error) {\n host.logger.error(`${name}: request failed`, error);\n return undefined;\n }\n if (data == null) {\n host.logger.error(`${name}: no data returned`);\n return undefined;\n }\n // The context's Transformed type is the raw response, or the transform's output.\n return data as NonNullable<Transformed>;\n}\n","/* eslint-disable no-param-reassign */\nimport type { MultipleFutureHandler } from \"../../../models/models/future/future-aware\";\nimport type { IFutureModel } from \"../../../models/models/future/future-types\";\nimport { MultipleFutureContainerSetup } from \"./propKeys\";\n\n/**\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport interface KosMultipleFutureAwareOptions {\n /** Setup mode: 'full' includes all UI properties, 'minimal' only futureHandler. Default: 'full' */\n mode?: \"full\" | \"minimal\";\n /** Custom futureHandler property name. Default: 'futureHandler' */\n handlerProperty?: string;\n}\n\n/**\n * Members injected by @kosMultipleFutureAware in minimal mode. Minimal mode also\n * injects an `<alias>Future` getter per @kosFuture alias; declare the ones you read on\n * the merged interface.\n *\n * @example\n * ```typescript\n * interface MaintenanceModelImpl extends KosMultipleFutureAwareMinimal {\n * calibrationFuture?: IFutureModel;\n * }\n * ```\n *\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport interface KosMultipleFutureAwareMinimal {\n /**\n * Container that tracks the model's concurrent Future operations by alias.\n */\n futureHandler: MultipleFutureHandler;\n}\n\n/**\n * Utility types to generate future property names for multiple futures (for internal use)\n */\ntype FutureGetters<T extends string> = {\n readonly [K in T as `${K}Future`]?: IFutureModel;\n};\n\ntype ProgressGetters<T extends string> = {\n readonly [K in T as `${K}Progress`]: number;\n};\n\ntype StatusGetters<T extends string> = {\n readonly [K in T as `${K}Status`]: string;\n};\n\ntype IsRunningGetters<T extends string> = {\n readonly [K in T as `${K}IsRunning`]: boolean;\n};\n\ntype IsCancelledGetters<T extends string> = {\n readonly [K in T as `${K}IsCancelled`]: boolean;\n};\n\ntype CancelMethods<T extends string> = {\n readonly [K in T as `cancel${Capitalize<K>}`]: () => Promise<void>;\n};\n\n/**\n * @kosService core.future-aware\n */\nexport type MultipleFutureProperties<T extends string> = FutureGetters<T> &\n ProgressGetters<T> &\n StatusGetters<T> &\n IsRunningGetters<T> &\n IsCancelledGetters<T> &\n CancelMethods<T>;\n\n/**\n * Members injected by @kosMultipleFutureAware in full mode (the default), where `T` is\n * the union of @kosFuture aliases. Declare an interface with the same name as the\n * class that extends this type (TypeScript interface merging).\n *\n * @kosService core.future-aware\n */\nexport type KosMultipleFutureAwareFull<T extends string = string> =\n KosMultipleFutureAwareMinimal & MultipleFutureProperties<T>;\n\n/**\n * Class decorator that lets a KOS model track several concurrent Futures, one per\n * @kosFuture `alias`. For a single Future, use @kosFutureAware.\n *\n * The model gets a `futureHandler` container and an `<alias>Future` getter per alias.\n * Full mode also adds `<alias>Progress`, `<alias>Status`, `<alias>IsRunning`,\n * `<alias>IsCancelled` and `cancel<Alias>()`. An optional\n * `onFutureUpdate(future, alias)` method on the model is called as each Future\n * progresses.\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * interface IceAgitatorModelImpl extends KosMultipleFutureAwareFull<\"pour\" | \"agitate\"> {}\n *\n * @kosModel(\"ice-agitator-model\")\n * @kosMultipleFutureAware()\n * class IceAgitatorModelImpl implements IKosDataModel {\n * @kosFuture({ alias: \"pour\" })\n * async pourIce(): Promise<FutureResponse | undefined> {\n * return startPourService();\n * }\n *\n * @kosFuture({ alias: \"agitate\" })\n * async agitate(): Promise<FutureResponse | undefined> {\n * return startAgitateService();\n * }\n * }\n * // this.pourProgress, this.agitateIsRunning, this.cancelPour(), ...\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.0.0\n * @kosService core.future-aware\n * @kosApiLevel 14\n */\nexport function kosMultipleFutureAware(\n options?: KosMultipleFutureAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const mode = options?.mode || \"full\";\n const handlerProperty = options?.handlerProperty || \"futureHandler\";\n\n // Add the MultipleFutureContainerSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[MultipleFutureContainerSetup] = {\n mode,\n handlerProperty,\n };\n\n return target;\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}\n/**\n * @kosService core.logging\n * @kosApiLevel 2\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 type { IKosDataModel } from \"../kosModel\";\nimport type { KosModelRegistrationFactory } from \"../registration/base-kos-model-registration\";\nimport type { KosCompanionAware } from \"./kos-companion\";\nimport { CompanionParentModel, MixinModels } from \"./propKeys\";\n\n/**\n * A mixin declared on a host, keyed by the property that holds it.\n *\n * @internal\n */\nexport interface KosMixinDefinition {\n registration: KosModelRegistrationFactory<any, any>;\n options?: unknown;\n}\n\n/**\n * The host interface a mixin requires.\n *\n * @kosService core.mixin\n * @kosApiLevel 25\n */\nexport type KosMixinHost<TMixin> = TMixin extends KosCompanionAware<infer THost>\n ? THost\n : IKosDataModel;\n\n/**\n * The options a host passes to its mixin. Any option can be a prop key, resolved from the\n * host's data when the mixin is created.\n *\n * @kosService core.mixin\n * @kosApiLevel 25\n */\nexport type KosMixinOptions<O> = O extends { data?: infer D }\n ? { [K in keyof D]: D[K] | string }\n : never;\n\n/**\n * Mixes a reusable behaviour into a model. The host gets its own instance of the mixin\n * in the decorated property, there from the moment the host is created and observable,\n * so the host's effects can react to it.\n *\n * The mixin calls back into the host through a `host` getter (`parentProperty: \"host\"`),\n * typed by the host interface it declares; a host that does not implement that\n * interface does not compile.\n *\n * @param mixin The mixin model's registration.\n * @param options The mixin's model options, received as `options.data`. Any option can\n * be a prop key (`createPropKey`), resolved from the host's data when the mixin is\n * created.\n *\n * @example\n * ```typescript\n * interface DirtyHost extends IKosDataModel { onDirtyChanged?(dirty: boolean): void }\n * interface DirtyTrackingImpl extends KosCompanionComposition<DirtyHost> {\n * readonly host: DirtyHost;\n * }\n *\n * @kosModel(\"dirty-tracking\")\n * @kosCompanion({ mode: \"composition\", parentProperty: \"host\" })\n * class DirtyTrackingImpl implements IKosDataModel { ... }\n *\n * @kosModel(\"recipe\")\n * class RecipeImpl implements IKosDataModel, DirtyHost {\n * @kosMixin(DirtyTracking, { fields: [\"name\"] })\n * dirty!: DirtyTrackingModel;\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.mixin\n * @kosApiLevel 25\n */\nexport function kosMixin<TMixin extends IKosDataModel, O extends object>(\n mixin: KosModelRegistrationFactory<TMixin, O>,\n options?: KosMixinOptions<O>\n) {\n return (target: KosMixinHost<TMixin>, propertyKey: string): void => {\n const companion = mixin.class.prototype[CompanionParentModel];\n if (companion?.mode !== \"composition\") {\n throw new Error(\n `Mixin ${mixin.type} must be a @kosCompanion({ mode: \"composition\" }) model`\n );\n }\n if (companion.lifecycle !== undefined) {\n throw new Error(\n `Mixin ${mixin.type} cannot set a companion lifecycle; mixins are created with their host`\n );\n }\n\n const host = target as any;\n host[MixinModels] = host[MixinModels] || {};\n const mixins: Record<string, KosMixinDefinition> = host[MixinModels];\n if (Object.values(mixins).some((m) => m.registration.type === mixin.type)) {\n throw new Error(\n `Mixin ${mixin.type} is already mixed into this model; a host holds one instance of each mixin`\n );\n }\n mixins[propertyKey] = { registration: mixin, options };\n };\n}\n","/**\n * @ignore\n * @deprecated\n */\nimport { warnDeprecated } from \"@kosdev-code/kos-api-levels\";\nimport { ReferenceConfig } from \"./propKeys\";\n\n/**\n * @kosService core.reference\n * @kosApiLevel 2\n */\ninterface ReferenceProps {\n modelType: string;\n}\n\n/**\n * @kosService core.reference\n * @kosApiLevel 2\n * @kosDeprecated {replacement: @kosDependency, removeAt: 3}\n */\nexport const kosReference =\n (props: ReferenceProps) =>\n (target: {} | any, name: PropertyKey): any => {\n warnDeprecated(\"@kosReference\", \"core.reference\", 1, \"@kosDependency\", 3);\n target[ReferenceConfig] = target[ReferenceConfig] || {};\n target[ReferenceConfig][name] = props;\n };\n","/**\n * @kosService core.fetch\n * @kosApiLevel 1\n */\nexport enum KosFetchMethods {\n GET = `GET`,\n PUT = `PUT`,\n POST = `POST`,\n DELETE = `DELETE`,\n}\n\ntype FetchMethodStrings = keyof typeof KosFetchMethods;\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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 * Configuration for retrying failed service requests with exponential backoff.\n *\n * @kosService core.fetch\n *\n * Applies to requests made through the service-request client. Setting `retry`\n * to `true` on {@link KosFetchOptions} uses the defaults below; a partial\n * `RetryConfig` overrides only the fields it sets:\n * - `maxAttempts`: 3\n * - `baseDelayMs`: 350\n * - `backoffFactor`: 2\n * - `retryMutations`: false (POST, PUT, DELETE and PATCH are not retried)\n * - `retryOn`: unset, so every error response is retried\n *\n * Only error responses are retried; timeouts and aborts are returned at once.\n *\n * @example\n * ```typescript\n * retry: { maxAttempts: 5, retryOn: (response) => response.status === 503 }\n * ```\n *\n * @category Service Request\n * @kosApiLevel 22\n */\nexport interface RetryConfig {\n /** Maximum number of attempts (including the initial request). @default 3 */\n maxAttempts?: number;\n\n /** Base delay in milliseconds before the first retry. @default 350 */\n baseDelayMs?: number;\n\n /** Multiplier applied to the delay after each attempt. @default 2 */\n backoffFactor?: number;\n\n /**\n * Whether to retry mutating methods (POST, PUT, DELETE, PATCH).\n * Set to `true` only if the endpoint is idempotent.\n * @default false\n */\n retryMutations?: boolean;\n\n /**\n * Predicate called with the error {@link Response} to decide whether to\n * retry. Return `true` to retry, `false` to stop immediately. When omitted,\n * every error response is retried up to `maxAttempts`.\n */\n retryOn?: (response: Response) => boolean;\n}\n\n/**\n * Represents the configuration options for performing a Kos WebSocket fetch operation.\n *\n * @kosService core.fetch\n * @kosApiLevel 2\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 - can be string, ArrayBuffer, Blob, or FormData.\n */\n body?: string | ArrayBuffer | Blob | FormData | Uint8Array;\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 /**\n * Timeout budget for the entire call, in milliseconds: waiting for the\n * transport to become ready plus the request itself.\n *\n * A request issued while the socket is down rejects with a\n * `TransportNotReadyError` if the transport does not become ready within the\n * budget. Otherwise the remaining budget applies to the request, which\n * rejects with a `TimeoutError` `DOMException` when it runs out. The two\n * errors are distinct so callers can tell a slow service from a down\n * transport.\n *\n * Defaults to the `KOS_WS_TIMEOUT` environment value, or 30000. Pass `0` or\n * `Infinity` to queue until the transport recovers; such a request does not\n * settle while the socket is down.\n */\n timeout?: number;\n\n /**\n * @kosApiLevel 5\n */\n headers?: Record<string, string>;\n\n /**\n * Enable streaming mode for large responses\n * @kosApiLevel 11\n */\n stream?: boolean;\n\n /**\n * Response type hint for binary data handling\n * @kosApiLevel 11\n */\n responseType?: \"text\" | \"json\" | \"arraybuffer\" | \"blob\";\n\n /**\n * Retry configuration for transient failures.\n *\n * - `true`: enable retry with all defaults\n * - `RetryConfig`: partial overrides (unspecified fields use defaults)\n * - omitted: no retry\n *\n * Mutating methods (POST, PUT, DELETE, PATCH) are retried only when\n * `retryMutations` is `true`.\n * @kosApiLevel 22\n */\n retry?: boolean | RetryConfig;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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 * @kosApiLevel 5\n */\n headers?: Record<string, string | number | boolean>;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosMessageRequest\n extends Omit<KosFetchReqeust, \"method\" | \"path\" | \"requestId\"> {\n requestType: string;\n requestId?: string;\n headers?: Record<string, string>;\n}\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosBroadcastRequest {\n topic: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosMessageOptions extends KosBroadcastRequest {\n destinationAddress?: string;\n responseId?: string;\n type?: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosHttpMessageOptions {\n destinationAddress: string;\n sourceAddress: string;\n responseId: string;\n status: number;\n type: string;\n contentType?: string;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchResponseParams {\n path: string;\n responseId?: string;\n destinationAddress: string;\n status: string | number | boolean;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosFetchPostReqeust extends KosFetchReqeust {\n body?: string;\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { DependencyModels, TroubleAwareSetup } from \"./propKeys\";\n\n/**\n * @kosService core.trouble-aware\n * @kosApiLevel 13\n */\nexport interface KosTroubleAwareOptions {\n /** Path property name to use for trouble resolution. Default: 'path' */\n pathProperty?: string;\n}\n\n/**\n * Class decorator that makes a KOS model TroubleAware: it gets reactive `troubles`\n * (the troubles whose path matches the model's path), `troublesByType` and\n * `troubleStatus` (an empty string by default). The trouble container is added as a\n * dependency automatically.\n *\n * The model must expose its device path on `path`, or on the property named by\n * `pathProperty`. Declare an interface with the same name as the class that extends\n * `TroubleAware` (TypeScript interface merging) so the members are typed.\n *\n * @param options Configuration options for the decorator\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * interface HolderModelImpl extends TroubleAware {}\n *\n * @kosModel(\"holder-model\")\n * @kosTroubleAware()\n * class HolderModelImpl implements IKosDataModel {\n * path: string;\n *\n * constructor(modelId: string, options: HolderOptions) {\n * this.path = options.path;\n * }\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.0.0\n * @kosService core.trouble-aware\n * @kosApiLevel 13\n */\nexport function kosTroubleAware(\n options?: KosTroubleAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const pathProperty = options?.pathProperty || \"path\";\n\n // Add the TroubleAwareSetup configuration to the prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[TroubleAwareSetup] = {\n pathProperty,\n };\n\n // Add troubleContainer as a managed dependency\n target.prototype[DependencyModels] =\n target.prototype[DependencyModels] || {};\n target.prototype[DependencyModels][\"troubleContainer\"] = {\n modelType: \"trouble-container-model\",\n id: \"trouble-container-model\", // TroubleContainer is a singleton\n options: {},\n lazy: false, // Ensure it's created immediately\n };\n\n return target;\n };\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { KosContext } from \"../context\";\nimport { ExtensionManager } from \"../extension\";\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport interface ExtensionPointOptions {\n extension: string;\n}\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport interface InitializeContextExtensionPointOptions\n extends ExtensionPointOptions {\n context?: KosContext;\n}\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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 * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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 * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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 * */\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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","/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const PLUGIN_EXTENSION_NAME = \"Extensions\";\n\n/**\n * Represents the type for the extensions.\n */\n/**\n * @kosService core.extension\n */\nexport interface PluginExtensionsType {\n [k: string]: {\n [k: string]: {\n component?: string;\n remote?: string;\n };\n };\n}\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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","/**\n * Debounces a function so it runs once the timeout has passed since the last call.\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 * @kosService core.utils\n * @kosApiLevel 2\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","/**\n * @deprecated\n * @internal\n */\nimport { warnDeprecated } from \"@kosdev-code/kos-api-levels\";\nimport { action } from \"mobx\";\nimport debounce from \"../../util/debounce\";\nimport { SubscriptionHandlers } from \"./propKeys\";\n\n/**\n * @kosService core.subscribe\n * @kosApiLevel 2\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\n/**\n * @kosService core.subscribe\n * @kosApiLevel 2\n * @kosDeprecated {replacement: @kosTopicHandler, removeAt: 3}\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 warnDeprecated(\"@kosSubscribe\", \"core.subscribe\", 1, \"@kosTopicHandler\", 3);\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 { autorun, makeAutoObservable, reaction, runInAction } from \"mobx\";\nimport { DependencyLifecycle } from \"../../types\";\nimport type { KosContextLogger } from \"../kosModel\";\nimport {\n initializeStateMachine,\n injectStateMachineSupport,\n} from \"./fsm-injection-utils\";\nimport {\n KosViewModelSymbol,\n ModelEffects,\n StateMachineSetup,\n ViewModelConfig,\n} from \"./propKeys\";\n\n/**\n * Configuration options for the @kosViewModel decorator.\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface KosViewModelOptions {\n /**\n * Optional type identifier for this ViewModel.\n * Used for logging, debugging, and optional DevTools registration.\n * If not provided, defaults to the class name.\n */\n typeId?: string;\n\n /**\n * When true, registers this ViewModel with KOS DevTools for inspection.\n * Default: false (ViewModels are not tracked by default)\n */\n devToolsEnabled?: boolean;\n}\n\n/**\n * Interface for ViewModels that support cleanup. `useViewModel` calls `dispose()` when\n * the ViewModel is replaced or the component unmounts.\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface IKosViewModelDisposable {\n dispose(): void | Promise<void>;\n}\n\n/**\n * Interface for ViewModels that require async initialization, such as waiting for the\n * models they wrap to be ready. `useViewModel` calls `ready()` after construction and\n * reports its progress through the `ready` and `error` fields of its result.\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface IKosViewModelReady {\n ready(): Promise<void>;\n}\n\n/**\n * Type guard to check if an object implements IKosViewModelReady.\n */\nexport function hasReadyHook(obj: unknown): obj is IKosViewModelReady {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"ready\" in obj &&\n typeof (obj as IKosViewModelReady).ready === \"function\"\n );\n}\n\n/**\n * Members injected by @kosLoggerAware into a ViewModel. Declare an interface with the\n * same name as the class that extends this type (TypeScript interface merging).\n *\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport interface KosViewModelLoggerAware {\n logger: KosContextLogger;\n}\n\n/**\n * Type guard to check if an object implements IKosViewModelDisposable.\n */\nexport function isDisposable(obj: unknown): obj is IKosViewModelDisposable {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"dispose\" in obj &&\n typeof (obj as IKosViewModelDisposable).dispose === \"function\"\n );\n}\n\n// Counter for generating unique instance IDs\nlet viewModelCounter = 0;\n\n// Symbol for storing effect disposers on ViewModel instances\nconst ViewModelEffectDisposers = Symbol(\"ViewModelEffectDisposers\");\n\n/**\n * Checks if a ViewModel has model effects defined.\n */\nfunction hasViewModelEffects(instance: Record<string, unknown>): boolean {\n const effects = instance[ModelEffects as unknown as string];\n return !!effects && Object.keys(effects as object).length > 0;\n}\n\n/**\n * Injects model effect support into a ViewModel instance.\n * Effects are set up immediately and disposers are stored for cleanup.\n */\nfunction injectViewModelEffects(\n instance: Record<string, unknown>,\n typeId: string\n): void {\n if (!hasViewModelEffects(instance)) return;\n\n const modelEffects = instance[ModelEffects as unknown as string] as Record<\n string,\n {\n value: (...args: unknown[]) => void;\n dependencies?: (model: unknown) => unknown[];\n options?: { fireImmediately?: boolean };\n }\n >;\n\n const disposers: VoidFunction[] = [];\n\n for (const effectName of Object.keys(modelEffects)) {\n const { value, dependencies, options } = modelEffects[effectName];\n const handler = value.bind(instance);\n\n const effectHandler = () => {\n runInAction(() => handler());\n };\n\n const disposer = dependencies\n ? reaction(() => dependencies(instance), effectHandler, {\n fireImmediately: !!options?.fireImmediately,\n })\n : autorun(effectHandler);\n\n disposers.push(disposer);\n }\n\n // Store disposers for cleanup\n // configurable: true so makeAutoObservable can redefine it\n Object.defineProperty(instance, ViewModelEffectDisposers, {\n value: disposers,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n // Cast to any for dynamic property access\n const inst = instance as unknown as Record<string, unknown>;\n const originalDispose = inst[\"dispose\"] as\n | ((...args: unknown[]) => void | Promise<void>)\n | undefined;\n\n // Create effect disposal function\n const disposeEffects = () => {\n for (const dispose of disposers) {\n try {\n dispose();\n } catch (e) {\n console.warn(\n `[kosViewModel] Failed to dispose effect for ${typeId}:`,\n e\n );\n }\n }\n };\n\n // If the instance already has a dispose method, wrap it to also dispose effects\n if (typeof originalDispose === \"function\") {\n inst[\"dispose\"] = function (this: unknown) {\n disposeEffects();\n return originalDispose.call(this);\n };\n } else {\n // Add a dispose method that cleans up effects\n inst[\"dispose\"] = disposeEffects;\n }\n}\n\n/**\n * Injects state machine support into a ViewModel instance and initializes it.\n * ViewModels have no lifecycle phases, so the FSM initializes at construction:\n * the state property holds `initial`, `isFsmInitialized` is true, and the\n * entry handler for `initial` runs once.\n * Logs a warning if initializeAt was given explicitly with a value other than\n * INIT, since it has no effect on a ViewModel.\n */\nfunction injectViewModelStateMachine(\n instance: Record<string, unknown>,\n typeId: string\n): void {\n const fsmSetup = instance[StateMachineSetup as unknown as string] as\n | {\n config: { initializeAt?: DependencyLifecycle };\n initializeAtExplicit?: boolean;\n }\n | undefined;\n if (!fsmSetup) return;\n\n const { config, initializeAtExplicit } = fsmSetup;\n\n if (\n initializeAtExplicit &&\n config.initializeAt !== DependencyLifecycle.INIT\n ) {\n console.warn(\n `[kosViewModel] ViewModel \"${typeId}\" has @kosStateMachine with ` +\n `initializeAt: ${config.initializeAt}. ViewModels do not have lifecycle phases, ` +\n `so the FSM will initialize immediately. Consider removing initializeAt or using ` +\n `@kosModel if lifecycle-aware FSM initialization is required.`\n );\n }\n\n injectStateMachineSupport(instance);\n initializeStateMachine(instance, config.initializeAt as string);\n}\n\n/**\n * Safely wraps makeAutoObservable with error handling.\n */\nfunction makeSafeObservable<T extends object>(instance: T): T {\n try {\n return makeAutoObservable(instance);\n } catch (e) {\n console.error(\"[kosViewModel] Failed to make observable:\", e);\n return instance;\n }\n}\n\n/**\n * Proxy handler for ViewModel construction.\n * Intercepts new() calls to inject observability.\n */\nconst viewModelConstructorProxy: ProxyHandler<any> = {\n construct(TargetClass, args) {\n const config = (TargetClass.prototype[ViewModelConfig] ||\n {}) as KosViewModelOptions;\n const typeId = config.typeId || TargetClass.name;\n const instanceId = `${typeId}-${++viewModelCounter}`;\n\n // Create the instance\n const instance = new TargetClass(...args);\n\n // Inject state machine support if @kosStateMachine is stacked\n injectViewModelStateMachine(instance, typeId);\n\n // Inject model effect support if @kosModelEffect is used\n injectViewModelEffects(instance, typeId);\n\n // Store metadata as non-enumerable properties for debugging\n // configurable: true so makeAutoObservable can redefine it\n Object.defineProperty(instance, \"__viewModelTypeId\", {\n value: typeId,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n Object.defineProperty(instance, \"__viewModelInstanceId\", {\n value: instanceId,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n // Make the instance observable\n const observableInstance = makeSafeObservable(instance);\n\n // Optional DevTools registration\n if (\n config.devToolsEnabled &&\n (globalThis as any).__KOS_DEVTOOLS__?.registerViewModel\n ) {\n (globalThis as any).__KOS_DEVTOOLS__.registerViewModel(\n instanceId,\n observableInstance\n );\n }\n\n return observableInstance;\n },\n};\n\n/**\n * Class decorator for a ViewModel: a plain class made into a reactive model without the\n * KOS model lifecycle.\n *\n * Use it for state derived from one or more KOS models for a component. Dependencies\n * are passed to the constructor, instances are created with `new` (usually inside\n * `useViewModel`), and there are no lifecycle phases or dependency resolution. A\n * ViewModel may also use @kosLoggerAware, @kosModelEffect and @kosStateMachine; its\n * state machine initializes at construction.\n *\n * @param options Configuration options for the ViewModel\n * @returns A class decorator\n *\n * @example\n * ```typescript\n * @kosViewModel({ typeId: 'order-summary' })\n * export class OrderSummaryViewModel {\n * constructor(private readonly order: IOrderModel) {}\n *\n * get total(): number {\n * return this.order.items.reduce((sum, i) => sum + i.price, 0);\n * }\n * }\n *\n * const OrderSummary = kosComponent(({ order }: Props) => {\n * const { viewModel } = useViewModel(() => new OrderSummaryViewModel(order), [order]);\n * return <p>Total: {viewModel.total}</p>;\n * });\n * ```\n *\n * @category KOS ViewModel Decorator\n * @kosService core.view-model\n * @kosApiLevel 20\n */\nexport function kosViewModel(options?: KosViewModelOptions): ClassDecorator {\n return (target: any) => {\n const config = options || {};\n const typeId = config.typeId || target.name;\n\n // Store configuration on prototype for the proxy to access\n // Use same structure as KosModelSymbol for @kosLoggerAware compatibility\n target.prototype[KosViewModelSymbol] = { type: typeId };\n target.prototype[ViewModelConfig] = config;\n\n // Preserve class name for debugging\n const ProxiedClass = new Proxy(target, viewModelConstructorProxy);\n Object.defineProperty(ProxiedClass, \"name\", { value: target.name });\n\n return ProxiedClass;\n };\n}\n","/**\n * (C) Copyright 2025, TCCC, All rights reserved.\n */\n\nimport type { IKosDataModel, IKosModel } from \"../core/kosModel\";\nimport { KosModelVisitor } from \"./kos-model-visitor\";\n\n/**\n * Visitor that finds the ids of a target model's ancestors in any KOS model\n * hierarchy that implements the visitor pattern.\n *\n * It walks the tree depth-first and tracks the current path, so when the\n * target is found the accumulated path is the ancestor list. The traversal\n * visits every model until the target is found, which suits hierarchies of\n * up to a few hundred models.\n *\n * @example\n * ```typescript\n * const visitor = new AncestorPathVisitor(\"target-item-id\");\n * visitor.start(rootContainerModel);\n * const ancestors = visitor.getAncestorPath(); // [\"root\", \"parent\"]\n * ```\n *\n * @category Core\n * @kosService core.utils\n * @kosApiLevel 20\n */\nexport class AncestorPathVisitor extends KosModelVisitor {\n private targetId: string;\n private currentPath: string[] = [];\n private foundPath: string[] | null = null;\n\n constructor(targetId: string) {\n super();\n this.targetId = targetId;\n }\n\n /**\n * Wraps the visit with path tracking: push the model, check whether it is\n * the target, visit its children, then pop it again if the target was not\n * found in this subtree.\n *\n * The base class logic is inlined rather than calling super.visit() so the\n * push and pop happen at the right points relative to cycle detection and\n * child traversal.\n */\n override visit(model: IKosModel): void {\n // Cycle detection from base class\n if (this.visitedModels.has(model.modelId)) {\n return;\n }\n\n // Push to path BEFORE processing\n this.currentPath.push(model.modelId);\n\n // Mark as visited\n this.visitedModels.add(model.modelId);\n\n // Check if this is the target\n const stopVisiting = !!this.visitModel(model.modelData);\n\n if (!stopVisiting) {\n // Visit children (depth-first)\n model.getChildren?.().forEach((child) => {\n // Early exit if target was found in a sibling subtree\n if (this.foundPath) {\n return;\n }\n child.accept?.(this);\n });\n }\n\n // Backtrack: pop from path if target not found in this subtree\n if (!this.foundPath) {\n this.currentPath.pop();\n }\n }\n\n /**\n * Called for each model during traversal.\n * Returns true to stop traversal when target is found.\n */\n visitModel<T extends IKosDataModel>(model: T): boolean | void {\n // Check if this is the target\n if (model.id === this.targetId) {\n // Save ancestor path (everything except the target itself)\n this.foundPath = this.currentPath.slice(0, -1);\n return true; // Stop traversal\n }\n\n // Continue depth-first traversal\n return false;\n }\n\n /**\n * Get the ancestor path (IDs from root to parent, not including target).\n * Returns empty array if target not found or target is at root level.\n */\n getAncestorPath(): string[] {\n return this.foundPath ?? [];\n }\n\n /**\n * Check if target was found during traversal.\n */\n wasFound(): boolean {\n return this.foundPath !== null;\n }\n}\n","/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport 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","/**\n * @kosService core.utils\n * @kosApiLevel 5\n */\nexport function arraysEqual(_a?: any[], _b?: any[]): boolean {\n const a = _a ?? [];\n const b = _b ?? [];\n if (a.length !== b.length) return false;\n return a.every((val, index) => val === b[index]);\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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const isLeapYear = (year: number): boolean =>\n (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const getDaysInMonth = (year: number, month: number): number =>\n [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][\n month\n ];\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const addMonthsToDate = (date: Date, value: number) => {\n const d = new Date(date),\n n = date.getDate();\n d.setDate(1);\n d.setMonth(d.getMonth() + value);\n d.setDate(Math.min(n, getDaysInMonth(d.getFullYear(), d.getMonth())));\n return d;\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 3\n */\nexport const addDaysToDate = (date: Date, value: number) => {\n const d = new Date(date);\n d.setDate(d.getDate() + value);\n return d;\n};\n\nconst DEFAULT_LOCALE = \"en-US\";\n\ninterface FormatDateOptions {\n dateStyle?: \"short\" | \"medium\" | \"long\" | \"full\";\n locales?: string | string[];\n}\n\ninterface FormatTimeOptions {\n timeStyle?: \"short\" | \"medium\" | \"long\" | \"full\";\n locales?: string | string[];\n}\n\ninterface FormatDateTimeOptions extends FormatDateOptions, FormatTimeOptions {}\n\ninterface FormatOptions {\n year?: \"numeric\" | \"2-digit\";\n month?: \"short\" | \"long\" | \"numeric\" | \"2-digit\" | \"narrow\";\n day?: \"numeric\" | \"2-digit\";\n weekday?: \"short\" | \"long\" | \"narrow\";\n hour?: \"numeric\" | \"2-digit\";\n minute?: \"numeric\" | \"2-digit\";\n second?: \"numeric\" | \"2-digit\";\n hour12?: boolean;\n timeZoneName?:\n | \"short\"\n | \"long\"\n | \"shortOffset\"\n | \"longOffset\"\n | \"shortGeneric\"\n | \"longGeneric\";\n}\n\nconst dateStyleMap: Record<\n NonNullable<FormatDateTimeOptions[\"dateStyle\"]>,\n Partial<FormatOptions>\n> = {\n short: { year: \"numeric\", month: \"2-digit\", day: \"2-digit\" },\n medium: { year: \"numeric\", month: \"short\", day: \"2-digit\" },\n long: { year: \"numeric\", month: \"long\", day: \"numeric\" },\n full: {\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n weekday: \"long\",\n },\n};\n\nconst timeStyleMap: Record<\n NonNullable<FormatDateTimeOptions[\"timeStyle\"]>,\n Partial<FormatOptions>\n> = {\n short: { hour: \"2-digit\", minute: \"2-digit\", hour12: true },\n medium: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: true,\n },\n long: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: true,\n timeZoneName: \"short\",\n },\n full: {\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: true,\n timeZoneName: \"long\",\n },\n};\n\n/**\n * Formats a date with `Intl.DateTimeFormat` according to `dateStyle` and locale.\n *\n * `\"short\"` uses a numeric year with two-digit month and day in the locale's\n * order (`12/31/2025` in en-US); the other styles use the built-in `Intl` styles.\n *\n * @param date - The date object or timestamp to format.\n * @param options - Options to customize formatting.\n * @param options.dateStyle - One of `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or array of locale strings.\n * @returns A formatted date string.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatDate = (\n date?: Date | number,\n { dateStyle = \"short\", locales = DEFAULT_LOCALE }: FormatDateOptions = {\n dateStyle: \"short\",\n locales: DEFAULT_LOCALE,\n }\n) => {\n const options = dateStyle === \"short\" ? dateStyleMap.short : { dateStyle }; // Let Intl handle medium/long/full\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n\n/**\n * Formats a time with `Intl.DateTimeFormat` according to `timeStyle` and\n * locale. All styles use a 12-hour clock; `\"medium\"` and `\"long\"` add seconds,\n * and `\"long\"` and `\"full\"` add the time zone name.\n *\n * @param date - The date object or timestamp to extract the time from.\n * @param options - Options to customize time formatting.\n * @param options.timeStyle - One of `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or locale array.\n * @returns A formatted time string.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatTime = (\n date?: Date | number,\n { locales = DEFAULT_LOCALE, timeStyle = \"short\" }: FormatTimeOptions = {\n locales: DEFAULT_LOCALE,\n timeStyle: \"short\",\n }\n) => {\n const options = timeStyleMap[timeStyle];\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n\n/**\n * Formats a date and time in one string with `Intl.DateTimeFormat`. It takes\n * the same `dateStyle` and `timeStyle` names as {@link formatDate} and\n * {@link formatTime}; both default to `\"short\"` (`12/31/2025, 11:59 PM` in en-US).\n *\n * @param date - The `Date` object or timestamp to format.\n * @param options - Formatting options.\n * @param options.dateStyle - Custom date format: `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.timeStyle - Custom time format: `\"short\"`, `\"medium\"`, `\"long\"`, or `\"full\"`.\n * @param options.locales - Optional locale string or locale array.\n * @returns A string representing the formatted date and/or time.\n *\n * @kosService core.utils\n * @kosApiLevel 3\n */\n\nexport const formatDateTime = (\n date?: Date | number,\n {\n dateStyle = \"short\",\n locales = DEFAULT_LOCALE,\n timeStyle = \"short\",\n }: FormatDateTimeOptions = {\n dateStyle: \"short\",\n locales: DEFAULT_LOCALE,\n timeStyle: \"short\",\n }\n) => {\n const options: FormatOptions = {\n ...(dateStyle && dateStyleMap[dateStyle]),\n ...(timeStyle && timeStyleMap[timeStyle]),\n };\n return new Intl.DateTimeFormat(locales, options).format(date);\n};\n","/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport 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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const resolveVariable = (element: Element, variable: string) =>\n getComputedStyle(element).getPropertyValue(variable);\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const variableToHex = (element: Element, variable: string) =>\n hslStringToHex(resolveVariable(element, variable));\n","/**\n * @kosService core.middleware\n */\nexport 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\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\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;\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\n */\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\n/**\n * @kosService core.middleware\n * @kosApiLevel 2\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 { KosCore } from \"../core/kosCore\";\nimport type { KosCompanionModelType } from \"../core/types/registration\";\nimport type { BaseKosModelRegistrationBean } from \"../types/model\";\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport const updateModelRegistration = <\n T extends BaseKosModelRegistrationBean<any, any>\n>(\n modelRegistration: T\n): void => {\n KosCore.getInstance().modelManager.registerModel(modelRegistration);\n};\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\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 { 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 * @kosService core.utils\n * @kosApiLevel 2\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","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 *\n * @kosService core.fetch\n * @kosApiLevel 2\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","import type {\n ApiPath,\n HttpMethod,\n} from \"../core/decorators/kos-service-request\";\nimport type { IKosDataModel } from \"../core/kosModel\";\n\n/**\n * Helpers for reading and clearing the responses that `@kosServiceRequest`\n * methods cache on a model. Responses are keyed by HTTP method and the\n * resolved request path.\n */\n\n/**\n * Returns the response data a `@kosServiceRequest` method cached for the given\n * path and method. The return type defaults to `any`; pass a type parameter to\n * type the result. For a path with parameters, pass the resolved path.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n * @returns The cached response data, or undefined if not found/expired\n *\n * @kosService core.service-response\n *\n * @example\n * ```typescript\n * const status = getServiceResponse<DeviceStatus>(this, PATH_DEVICE_STATUS);\n * ```\n * @kosApiLevel 15\n */\nexport function getServiceResponse<T = any>(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): T | undefined {\n const store = (model as any).serviceResponses;\n if (!store) {\n return undefined;\n }\n\n return store.getByPath(path, method);\n}\n\n/**\n * Checks whether an unexpired cached response exists for the given path and method.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n * @returns true if a valid cached response exists\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function hasCachedResponse(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): boolean {\n const store = (model as any).serviceResponses;\n if (!store) {\n return false;\n }\n\n return store.has(`${method.toUpperCase()}:${path}`);\n}\n\n/**\n * Clears the cached response for one path and method.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n * @param method - The HTTP method (defaults to 'get')\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function clearServiceResponse(\n model: IKosDataModel,\n path: ApiPath,\n method: HttpMethod = \"get\"\n): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.delete(`${method.toUpperCase()}:${path}`);\n}\n\n/**\n * Clears the cached responses for a path across all HTTP methods.\n *\n * @param model - The KOS model instance\n * @param path - The API path constant\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function clearPath(model: IKosDataModel, path: ApiPath): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.clearPath(path);\n}\n\n/**\n * Clears every cached service response on the model.\n *\n * @param model - The KOS model instance\n *\n * @kosService core.service-response\n * @kosApiLevel 15\n */\nexport function clearAllServiceResponses(model: IKosDataModel): void {\n const store = (model as any).serviceResponses;\n if (!store) {\n return;\n }\n\n store.clear();\n}\n","import log from \"loglevel\";\nimport { EventBus } from \"../../common\";\n\nimport { uuid } from \"./api-request-id\";\nimport { KosServiceResponse } from \"./kos-fetch\";\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport interface ErrorResponse {\n error?: string;\n}\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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}\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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","/* eslint-disable no-param-reassign */\n/**\n * Item-level decorator that makes a model contribute to the kos-ui-sdk\n * container indexing system.\n *\n * It installs an accessor at `INDEX_RECORD_SYMBOL` that returns the\n * instance's current index record (`KosModelContainer` reads it when\n * publishing ADDED, and containers re-read it on REQUEST_SEED), and a model\n * effect that publishes CHANGED when one of the declared `fields` changes.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\n\nimport * as EventBus from \"../../../common/events/eventBus\";\nimport { KosContextManager } from \"../context/kos-context-manager\";\nimport { ModelEffects } from \"../decorators/propKeys\";\n\nimport { KosContainerIndexEvents } from \"./topics\";\nimport {\n INDEX_COLLECTION_KEY,\n INDEX_RECORD_SYMBOL,\n type IndexChangedEvent,\n type IndexRecordContribution,\n} from \"./types\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Options\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface KosIndexAwareOptions {\n /**\n * Per-item collection tag. May be:\n *\n * - A static string.\n * - A function called with the instance, returning the tag\n * (heterogeneous case where one container holds items belonging\n * to multiple collections, distinguished by some item property).\n * - Undefined: the item resolves its collection from its\n * `KosContext`, walking up the parent chain. Under a\n * `@kosContainerIndexAware` container that declares a collection,\n * this picks up the container's value.\n */\n collection?: string | ((self: any) => string | undefined);\n\n /**\n * Field names projected into the index record and watched for\n * change. Empty/absent means no CHANGED events are emitted; the\n * record still exposes `id`, `modelType`, and `collection`.\n */\n fields?: string[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Companion interface for TS interface merging\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Merge this interface into a `@kosIndexAware` model class\n * (`interface MyItemModelImpl extends KosIndexAware {}`) to type the\n * index record accessor.\n */\nexport interface KosIndexAware {\n readonly [INDEX_RECORD_SYMBOL]: IndexRecordContribution;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Decorator\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Class decorator that registers a model as a publisher of index\n * records.\n *\n * The record always carries the instance's `id` and `modelTypeId`, plus the\n * resolved collection and the declared `fields`.\n *\n * @example\n * ```ts\n * interface VirtualMachineModelImpl extends KosIndexAware {}\n *\n * @kosModel(\"virtual-machine-model\")\n * @kosIndexAware({ collection: (self) => self.type, fields: [\"name\"] })\n * class VirtualMachineModelImpl implements IKosDataModel { ... }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.indexing\n * @kosApiLevel 22\n */\nexport function kosIndexAware(options?: KosIndexAwareOptions): ClassDecorator {\n return (target: any) => {\n const collection = options?.collection;\n const fields = options?.fields ?? [];\n\n installRecordAccessor(target, collection, fields);\n if (fields.length > 0) {\n installChangeEffect(target, fields);\n }\n\n return target;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction installRecordAccessor(\n target: any,\n collection: KosIndexAwareOptions[\"collection\"],\n fields: string[]\n): void {\n Object.defineProperty(target.prototype, INDEX_RECORD_SYMBOL, {\n get(): IndexRecordContribution {\n const record: IndexRecordContribution = {\n id: this.id,\n modelType: this.modelTypeId,\n };\n const resolved =\n typeof collection === \"function\" ? collection(this) : collection;\n // Fall back to the inherited context value when the item\n // declared nothing of its own. `KosContextManager.getContext`\n // looks up the bean by id; `.get` auto-walks the parent chain,\n // so a container-declared collection is visible here without\n // any explicit plumbing.\n const inherited =\n resolved === undefined\n ? (KosContextManager.getContext(this.id)?.get(\n INDEX_COLLECTION_KEY\n ) as string | undefined)\n : undefined;\n const finalCollection = resolved ?? inherited;\n if (finalCollection !== undefined) {\n record.collection = finalCollection;\n }\n for (const field of fields) {\n record[field] = this[field];\n }\n return record;\n },\n enumerable: false,\n configurable: true,\n });\n}\n\nfunction installChangeEffect(target: any, fields: string[]): void {\n target.prototype[ModelEffects] = target.prototype[ModelEffects] || {};\n target.prototype[ModelEffects].handleIndexFieldChange = {\n dependencies: (model: any) => fields.map((field) => model[field]),\n value: function (this: any) {\n const record: IndexRecordContribution = this[INDEX_RECORD_SYMBOL];\n // Skip if no collection resolved — neither item-declared nor\n // inherited from a container's context. Without a collection\n // the consumer can't route the record.\n if (!record.collection) {\n return;\n }\n const payload: IndexChangedEvent = {\n record: record as IndexChangedEvent[\"record\"],\n };\n EventBus.publish(KosContainerIndexEvents.CHANGED, payload);\n },\n };\n}\n","/* eslint-disable no-param-reassign */\n/**\n * Container-level decorator for the kos-ui-sdk container indexing system.\n * Works with `@kosContainerAware` or `@kosChild`-based containers; it needs\n * only an `itemsProperty` naming the array of items the container exposes.\n *\n * - On `init`, writes the declared collection onto the container's\n * `KosContext`, where items resolve it by walking up the parent chain.\n * - On `KosContainerIndexEvents.REQUEST_SEED`, publishes one SEED event with\n * the records of the current items, so consumers can subscribe at any time.\n * - On `unload`, publishes one PURGE per distinct collection in the current\n * items so consumers can drop those records.\n *\n * ADDED and REMOVED events come from `KosModelContainer` itself at the moment\n * of mutation.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\n\nimport * as EventBus from \"../../../common/events/eventBus\";\nimport type { KosContext } from \"../context/kos-context-manager\";\nimport { SubscriptionHandlers } from \"../decorators/propKeys\";\n\nimport { KosContainerIndexEvents } from \"./topics\";\nimport {\n INDEX_COLLECTION_KEY,\n INDEX_RECORD_SYMBOL,\n isIndexableItem,\n type IndexPurgeEvent,\n type IndexRecord,\n type IndexRecordContribution,\n type IndexSeedEvent,\n} from \"./types\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Options\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface KosContainerIndexAwareOptions {\n /**\n * Name of the property on the container that exposes its items\n * as an array, such as the `data` getter from `@kosContainerAware` or a\n * custom getter on a `@kosChild`-managed collection. Used for SEED and\n * PURGE; ADDED and REMOVED do not depend on it.\n */\n itemsProperty: string;\n\n /**\n * Collection tag written onto the container's own `KosContext`\n * so child items inherit it. Optional when items declare their own\n * `collection` through `@kosIndexAware`.\n */\n collection?: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Decorator\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Class decorator that wires a container model into the kos-ui-sdk\n * indexing system.\n *\n * @example\n * ```ts\n * @kosModel(\"image-container-model\")\n * @kosContainerAware<IImageModel>()\n * @kosContainerIndexAware({ itemsProperty: \"data\", collection: \"images\" })\n * class ImageContainerModelImpl implements IKosDataModel { ... }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.indexing\n * @kosApiLevel 22\n */\nexport function kosContainerIndexAware(\n options: KosContainerIndexAwareOptions\n): ClassDecorator {\n return (target: any) => {\n const itemsProperty = options.itemsProperty;\n const declaredCollection = options.collection;\n\n installContextWriter(target, declaredCollection);\n installRequestSeedHandler(target, itemsProperty);\n installPurgeOnUnload(target, itemsProperty);\n\n return target;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction installContextWriter(\n target: any,\n declaredCollection: string | undefined\n): void {\n if (declaredCollection === undefined) return;\n\n const originalInit = target.prototype.init;\n target.prototype.init = async function (context?: KosContext) {\n context?.set(INDEX_COLLECTION_KEY, declaredCollection);\n if (originalInit) {\n await originalInit.call(this, context);\n }\n };\n}\n\nfunction installRequestSeedHandler(target: any, itemsProperty: string): void {\n target.prototype[SubscriptionHandlers] =\n target.prototype[SubscriptionHandlers] || {};\n target.prototype[SubscriptionHandlers][KosContainerIndexEvents.REQUEST_SEED] =\n {\n websocket: false,\n skipParse: true,\n // The subscription manager calls transform(body) before\n // condition/handler. For an internal EventBus event with a\n // plain object payload we just want to pass it through\n // untouched.\n transform: (payload: unknown) => payload,\n condition: () => true,\n handler: function (this: any) {\n const items = (this[itemsProperty] ?? []) as unknown[];\n const records = collectRecords(items);\n if (records.size === 0) return;\n const payload: IndexSeedEvent = {\n modelType: this.modelTypeId,\n items: Array.from(records.values()),\n };\n EventBus.publish(KosContainerIndexEvents.SEED, payload);\n },\n };\n}\n\nfunction installPurgeOnUnload(target: any, itemsProperty: string): void {\n const originalUnload = target.prototype.unload;\n target.prototype.unload = function (context?: KosContext) {\n const items = (this[itemsProperty] ?? []) as unknown[];\n const collections = new Set<string>();\n for (const item of items) {\n if (!isIndexableItem(item)) continue;\n const contribution: IndexRecordContribution = item[INDEX_RECORD_SYMBOL];\n if (contribution.collection) {\n collections.add(contribution.collection);\n }\n }\n for (const collection of collections) {\n const payload: IndexPurgeEvent = {\n modelType: this.modelTypeId,\n collection,\n };\n EventBus.publish(KosContainerIndexEvents.PURGE, payload);\n }\n if (originalUnload) {\n return originalUnload.call(this, context);\n }\n return undefined;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Record collection (shared with the request-seed handler)\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction collectRecords(items: unknown[]): Map<string, IndexRecord> {\n const result = new Map<string, IndexRecord>();\n for (const item of items) {\n if (!isIndexableItem(item)) continue;\n const contribution: IndexRecordContribution = item[INDEX_RECORD_SYMBOL];\n if (!contribution.collection) continue;\n result.set(contribution.id, contribution as IndexRecord);\n }\n return result;\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 type { 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 type { 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","/* eslint-disable no-param-reassign */\nimport { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { ConfigBean } from \"../models/config-bean\";\nimport { configBeanModelId } from \"../models/config-bean/config-bean-model\";\n\ninterface KosConfigParams {\n path: string;\n lazy?: boolean;\n serviceBasePath?: string;\n /**\n * Connection the bean's requests and topic subscription are routed to.\n * Accepts a prop key so a host model can bind it per device.\n * When set, the bean's model id includes it so beans never collide across devices.\n */\n destinationAddress?: string;\n}\n\nexport const kosConfigBean =\n ({ path, lazy, serviceBasePath, destinationAddress }: 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: configBeanModelId(path, destinationAddress),\n options: {\n path,\n serviceBasePath,\n destinationAddress,\n },\n lifecycle: DependencyLifecycle.INIT,\n lazy,\n };\n };\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 /**\n * Connection the property's bean is routed to. Accepts a prop key so a host\n * model can bind it per device; the property and bean ids include it.\n */\n destinationAddress?: 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 destinationAddress,\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: destinationAddress\n ? `${destinationAddress}-${path}-${attribute}`\n : `${path}-${attribute}`,\n options: {\n path,\n attribute,\n serviceBasePath,\n destinationAddress,\n converter: _converter,\n formatter,\n optionsExpander,\n },\n\n lifecycle: DependencyLifecycle.INIT,\n lazy,\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 { autorun as kosAutoEffect } from \"mobx\";\n\n/**\n * A long-running operation whose progress can be observed imperatively.\n *\n * Progress surfaces (notifications, status indicators, modals) depend on this\n * interface rather than on any producer. `awaitFutureCall` adapts a KOS Future\n * to it; an upload or an aggregate of several operations can implement it too.\n */\nexport interface ProgressOperation<T = unknown> extends Promise<T> {\n /**\n * Percent complete, 0-100. A value of 0 or less means the operation has not\n * reported progress yet, so consumers should show an indeterminate state.\n */\n readonly progress: number;\n\n /**\n * Current status of the operation.\n * Common values: \"NOT_ACTIVE\", \"IN_PROGRESS\", a terminal end state\n * (\"SUCCESS\" | \"FAIL\" | \"ABORT\" | \"CANCEL\"), or consumer-defined.\n */\n readonly status: string;\n\n /**\n * Whether the operation is currently running\n */\n readonly isRunning: boolean;\n\n /**\n * Human-readable time remaining (e.g. \"2 minutes\"), when the source can\n * estimate it. Empty/undefined when unknown.\n */\n readonly timeRemaining?: string;\n\n /**\n * Cancel this specific operation\n */\n cancel(): Promise<void>;\n\n /**\n * Whether the operation was cancelled. Treat a missing implementation as unknown.\n */\n isCancelled?(): boolean;\n\n /**\n * Subscribe to progress updates\n * Returns a dispose function to clean up the subscription\n */\n onProgressUpdate(\n callback: (progress: number, status: string) => void\n ): () => void;\n}\n\n/**\n * A Promise that can be cancelled and provides progress/state tracking\n */\nexport interface CancellablePromise<T> extends ProgressOperation<T> {\n /**\n * Get the underlying AbortController for this operation\n */\n getController(): AbortController | undefined;\n\n /**\n * Check if this operation is cancelled\n */\n isCancelled(): boolean;\n}\n\n/**\n * Options for creating a cancellable promise with progress tracking\n */\nexport interface CancellablePromiseOptions<T> {\n promise: Promise<T>;\n abortController?: AbortController;\n cancelFuture?: () => Promise<void>;\n future?: any; // The KOS Future object for progress tracking\n}\n\n/**\n * Create a cancellable promise wrapper with reactive progress tracking\n */\nexport function createCancellablePromise<T>(\n promise: Promise<T>,\n abortController?: AbortController,\n cancelFuture?: () => Promise<void>,\n future?: any\n): CancellablePromise<T>;\nexport function createCancellablePromise<T>(\n options: CancellablePromiseOptions<T>\n): CancellablePromise<T>;\nexport function createCancellablePromise<T>(\n promiseOrOptions: Promise<T> | CancellablePromiseOptions<T>,\n abortController?: AbortController,\n cancelFuture?: () => Promise<void>,\n future?: any\n): CancellablePromise<T> {\n // Handle both call signatures\n const options =\n promiseOrOptions instanceof Promise\n ? { promise: promiseOrOptions, abortController, cancelFuture, future }\n : promiseOrOptions;\n\n const {\n promise,\n abortController: controller,\n cancelFuture: cancelFn,\n future: futureRef,\n } = options;\n\n // Create the base promise\n const cancellablePromise = promise as CancellablePromise<T>;\n\n // Progress tracking state\n let currentProgress = 0;\n let currentStatus = \"PENDING\";\n let isRunning = true;\n const progressCallbacks = new Set<\n (progress: number, status: string) => void\n >();\n\n // Update progress from Future if available\n let effectDisposer: (() => void) | undefined;\n if (futureRef && typeof futureRef === \"object\") {\n // Use kosAutoEffect to track Future changes\n effectDisposer = kosAutoEffect(() => {\n const newProgress = futureRef.progress || 0;\n const newStatus = futureRef.status || \"PENDING\";\n const newIsRunning = !futureRef.endState;\n\n if (\n newProgress !== currentProgress ||\n newStatus !== currentStatus ||\n newIsRunning !== isRunning\n ) {\n currentProgress = newProgress;\n currentStatus = newStatus;\n isRunning = newIsRunning;\n\n // Notify all subscribers\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n }\n });\n }\n\n // Clean up effect when promise completes\n promise.finally(() => {\n isRunning = false;\n if (!controller?.signal.aborted) {\n currentStatus = \"COMPLETED\";\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n }\n if (effectDisposer) {\n effectDisposer();\n }\n progressCallbacks.clear();\n });\n\n // Add cancellation methods\n cancellablePromise.cancel = async () => {\n if (controller && !controller.signal.aborted) {\n controller.abort();\n }\n if (cancelFn) {\n await cancelFn();\n }\n isRunning = false;\n currentStatus = \"CANCELLED\";\n progressCallbacks.forEach((callback) => {\n try {\n callback(currentProgress, currentStatus);\n } catch (error) {\n console.warn(\"Progress callback error:\", error);\n }\n });\n if (effectDisposer) {\n effectDisposer();\n }\n };\n\n cancellablePromise.getController = () => controller;\n\n cancellablePromise.isCancelled = () => controller?.signal.aborted ?? false;\n\n // Add progress tracking properties\n Object.defineProperty(cancellablePromise, \"progress\", {\n get: () => currentProgress,\n enumerable: true,\n });\n\n Object.defineProperty(cancellablePromise, \"status\", {\n get: () => currentStatus,\n enumerable: true,\n });\n\n Object.defineProperty(cancellablePromise, \"isRunning\", {\n get: () => isRunning,\n enumerable: true,\n });\n\n cancellablePromise.onProgressUpdate = (\n callback: (progress: number, status: string) => void\n ) => {\n progressCallbacks.add(callback);\n\n // Call immediately with current state\n callback(currentProgress, currentStatus);\n\n // Return dispose function\n return () => progressCallbacks.delete(callback);\n };\n\n return cancellablePromise;\n}\n","/**\n * Helpers that make a @kosFuture method call cancellable without reaching for\n * the model's future.\n */\n\nimport { KosLog } from \"../../core\";\nimport type { FutureContainer } from \"../models/future/future-types\";\nimport type { CancellablePromise } from \"../types/cancellable-promise\";\nimport { createCancellablePromise } from \"../types/cancellable-promise\";\n\n/**\n * Calls a @kosFuture method and returns a CancellablePromise whose `cancel()`\n * cancels the future the call started.\n *\n * @example\n * ```typescript\n * const call = makeCancellable(model, (m) => m.performOperation(\"data\"));\n * await call.cancel();\n * ```\n */\nexport function makeCancellable<T extends FutureContainer, R>(\n model: T,\n methodCall: (model: T) => Promise<R>\n): CancellablePromise<R> {\n // Store the current future before the call\n const initialFuture = model.futureHandler.future;\n\n // Execute the method call\n const promise = methodCall(model);\n\n // Wait a tick to get the new future created by the method\n let newFuture: any = null;\n setTimeout(() => {\n newFuture = model.futureHandler.future;\n // Only use the new future if it's different from the initial one\n if (newFuture === initialFuture) {\n newFuture = null;\n }\n }, 0);\n\n return createCancellablePromise({\n promise,\n abortController: undefined, // No direct AbortController access\n cancelFuture: async () => {\n // Cancel through the Future system\n if (newFuture) {\n await newFuture.cancelFuture();\n } else {\n // Fallback to current future\n const currentFuture = model.futureHandler.future;\n if (currentFuture) {\n await currentFuture.cancelFuture();\n }\n }\n },\n future: newFuture, // Pass the future for progress tracking\n });\n}\n\n/**\n * {@link makeCancellable} for a method given by name and arguments.\n *\n * @example\n * ```typescript\n * const call = withCancellation(model, \"performOperation\", \"data\");\n * ```\n */\nexport function withCancellation<T extends FutureContainer, K extends keyof T>(\n model: T,\n methodName: K,\n ...args: T[K] extends (...args: infer A) => any ? A : never\n): CancellablePromise<\n T[K] extends (...args: any[]) => Promise<infer R> ? R : never\n> {\n const method = model[methodName];\n if (typeof method !== \"function\") {\n throw new Error(`${String(methodName)} is not a method`);\n }\n\n // Store the current future state\n const initialFuture = model.futureHandler.future;\n\n // Call the method\n const promise = (method as any).apply(model, args);\n\n // Get the new future after method execution\n let targetFuture: any = null;\n setTimeout(() => {\n const currentFuture = model.futureHandler.future;\n if (currentFuture && currentFuture !== initialFuture) {\n targetFuture = currentFuture;\n }\n }, 0);\n\n return createCancellablePromise({\n promise,\n abortController: undefined,\n cancelFuture: async () => {\n if (targetFuture) {\n await targetFuture.cancelFuture();\n } else {\n const fallbackFuture = model.futureHandler.future;\n if (fallbackFuture) {\n await fallbackFuture.cancelFuture();\n }\n }\n },\n future: targetFuture, // Pass the future for progress tracking\n });\n}\n\n/**\n * Collects cancellable calls so they can be cancelled together.\n *\n * @example\n * ```typescript\n * const batch = createCancellationBatch();\n * batch.add(model, (m) => m.performOperation());\n * await batch.cancelAll();\n * ```\n */\nexport class CancellationBatch {\n private operations: Array<CancellablePromise<any>> = [];\n\n add<T extends FutureContainer, R>(\n model: T,\n methodCall: (model: T) => Promise<R>\n ): CancellablePromise<R> {\n const cancellable = makeCancellable(model, methodCall);\n this.operations.push(cancellable);\n return cancellable;\n }\n\n async cancelAll(): Promise<void> {\n await Promise.all(\n this.operations.map((op) =>\n op.cancel().catch(() => {\n // Ignore cancellation errors, just log them if needed\n KosLog.warn(\"Cancellation failed for operation:\", op);\n })\n )\n );\n }\n\n getAllControllers(): Array<AbortController | undefined> {\n return this.operations.map((op) => op.getController());\n }\n\n getActiveCount(): number {\n return this.operations.filter((op) => !op.isCancelled()).length;\n }\n\n clear(): void {\n this.operations = [];\n }\n}\n\nexport function createCancellationBatch(): CancellationBatch {\n return new CancellationBatch();\n}\n","/**\n * Folds several localization contexts into the one descriptor a\n * TranslationContainer is built from. Kept separate from\n * KosTranslationProvider so the merge rules can be tested without a DOM.\n */\nimport type { Localization } from \"./services\";\n\n/** A locale code paired with its name, rendered in that locale's own language. */\nexport interface LocaleOption {\n locale: string;\n label: string;\n}\n\n/**\n * Fold contexts into one descriptor, earlier entries winning.\n *\n * Precedence is per namespace, not per key or per locale: a namespace declared\n * by two contexts is taken whole from the earlier one, and the later context's\n * locales for that namespace are dropped even where the winner has none. A later\n * context can add namespaces but cannot extend one an earlier context declared.\n *\n * Each namespace's `basePath` is set to its own context's `path`, so namespaces\n * from different contexts keep resolving against the URL their context is\n * served from. The merged descriptor has no top-level `path`, since\n * `defaultResolver` reads `basePath` per namespace.\n */\nexport function mergeLocalizationDescriptors(\n descriptors: Localization[]\n): Localization {\n const merged: Localization[\"namespaces\"] = {};\n\n // Reverse, so the first context's namespaces are applied last and win.\n for (const descriptor of [...descriptors].reverse()) {\n for (const [name, namespace] of Object.entries(\n descriptor.namespaces ?? {}\n )) {\n merged[name] = { ...namespace, basePath: descriptor.path };\n }\n }\n\n return { namespaces: merged } as Localization;\n}\n\n/**\n * Every locale any namespace offers, as picker options.\n *\n * The result is a union across namespaces: one namespace translated into a\n * locale is enough to offer it for the whole app, and namespaces without it fall\n * back at resolve time. Excluded namespaces contribute nothing, which keeps a\n * content-bearing namespace (a brandset) from advertising locales the UI itself\n * cannot render.\n *\n * Labels come from `Intl.DisplayNames` and are rendered in the locale's own\n * language (\"italiano\", not \"Italian\").\n */\nexport function collectLocaleOptions(\n descriptors: Localization[],\n excludeNamespaces: string[] = []\n): LocaleOption[] {\n const codes = new Set<string>();\n\n for (const descriptor of descriptors) {\n for (const [name, namespace] of Object.entries(\n descriptor.namespaces ?? {}\n )) {\n if (excludeNamespaces.includes(name)) continue;\n for (const locale of Object.keys(namespace.locales ?? {})) {\n codes.add(locale);\n }\n }\n }\n\n return Array.from(codes).map((locale) => {\n return {\n locale,\n label: new Intl.DisplayNames([locale], { type: \"language\" }).of(\n locale\n ) as string,\n };\n });\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","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n ExtensionManager,\n ExtensionOptions,\n PropertyMapper,\n type DataLoader,\n} from \"../../core\";\nimport { KosCoreModelPropertyMapper } from \"../constants\";\nimport type { IConfigBeanModel, RegionInfoModel } from \"../models\";\nimport { CanvasDispatcher } from \"../models/canvas-dispatcher\";\nimport type { TroubleResponse } from \"../models/trouble/services\";\n\nexport type TroubleRankMapper = PropertyMapper<TroubleResponse, number, any>;\n\nexport type TroubleColorMapper = PropertyMapper<TroubleResponse, string, any>;\n\nexport type TroubleRoleMapper = PropertyMapper<TroubleResponse, string, any>;\n\nexport type RegionServicePathMapper = PropertyMapper<\n RegionInfoModel,\n string,\n any\n>;\n\nexport type ConfigServicePathMapper = PropertyMapper<\n IConfigBeanModel,\n string,\n any\n>;\nexport class CoreExtensionManager {\n /**\n * Maps the rank property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleRankMapper - Mapping function that derives a numeric rank from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleRankMapper(\n troubleRankMapper: TroubleRankMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRank,\n troubleRankMapper,\n options\n );\n return this;\n }\n\n /**\n * Maps the role property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleRoleMapper - Mapping function that derives a role string from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleRoleMapper(\n troubleRoleMapper: TroubleRoleMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRole,\n troubleRoleMapper,\n options\n );\n return this;\n }\n\n /**\n * Maps the color property of the trouble into the {@link TroubleModel}.\n *\n * @param troubleColorMapper - Mapping function that derives a color string from a {@link TroubleResponse}\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on mapper failure.\n * Set to `\"continue\"` to log the error and return a fallback value instead.\n * @returns this instance for chaining\n * */\n registerTroubleColorMapper(\n troubleColorMapper: TroubleColorMapper,\n options?: ExtensionOptions\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleColor,\n troubleColorMapper,\n options\n );\n return this;\n }\n\n /**\n * Registers a data loader for a given model id. The loader is invoked during model\n * initialization to fetch data that is provided as context to associated mappers.\n *\n * @param id - The model identifier to associate the loader with\n * @param loader - Async function that loads and returns data for the model\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on loader failure.\n * Set to `\"continue\"` to log the error and return `undefined` instead.\n */\n registerModelLoader(\n id: string,\n loader: DataLoader,\n options?: ExtensionOptions\n ) {\n ExtensionManager.loader.registerLoader(id, loader, options);\n }\n\n registerRegionServicePathMapper(\n regionServicePathMapper: RegionServicePathMapper\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.RegionServicePath,\n regionServicePathMapper\n );\n return this;\n }\n\n /**\n * Registers a data loader for the {@link CanvasDispatcher} pattern data.\n *\n * @param loader - Async function that loads canvas pattern data\n * @param options - Optional {@link ExtensionOptions} to control failure behavior.\n * Defaults to `failurePolicy: \"throw\"`, which throws an {@link ExtensionException} on loader failure.\n * Set to `\"continue\"` to log the error and return `undefined` instead.\n */\n registerCanvasPatternLoader(loader: DataLoader, options?: ExtensionOptions) {\n ExtensionManager.loader.registerLoader(\n CanvasDispatcher.loader,\n loader,\n options\n );\n }\n\n registerConfigServicePathMapper(\n configServicePathMapper: ConfigServicePathMapper\n ) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.ConfigServicePath,\n configServicePathMapper\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 the 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","/**\n * Public accessor for the KOS API service client.\n *\n * Encapsulates the dynamic import of the internal `service` module,\n * preserving the lazy-load pattern while providing a stable import\n * path for external consumers (e.g., @matrica-code/kos-declarative-model).\n */\nexport async function getKosServiceApi() {\n const { default: API } = await import(\"./service\");\n return API;\n}\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Methods a response type can be derived for: the lowercase subset of\n * HttpMethod. The uppercase spellings HttpMethod also permits do not match the\n * keys of an OpenAPI `paths` object, so they would silently yield `unknown`.\n */\nexport type SupportedMethod = \"get\" | \"post\" | \"put\" | \"delete\";\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends SupportedMethod = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\",\n Transformed = ApiResponse<Path, SupportedMethod & Method>\n> = KosExecutionContext<paths, Path, Method, Transformed>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with kos API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/daily/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * One endpoint of the kos API: a path and the method it is called with.\n */\nexport interface Endpoint {\n path: ApiPath;\n method: SupportedMethod;\n}\n\n/**\n * Declare an endpoint once. The decorator config, the execution context type\n * and the response type are all derived from the result, so the path string\n * is written once and cannot drift between them.\n *\n * @example\n * ```typescript\n * export const BoardApi = {\n * list: endpoint(\"/api/board\", \"get\"),\n * update: endpoint(\"/api/board/{id}\", \"put\"),\n * } as const;\n * ```\n */\nexport function endpoint<Path extends ApiPath, Method extends SupportedMethod>(\n path: Path,\n method: Method\n) {\n return { path, method } as const;\n}\n\n/**\n * Execution context for an endpoint: the method-driven `$ctx` parameter type.\n * Pass `Transformed` when the decorator declares a `transform`, so what the\n * method receives is typed as the mapper's output rather than the raw response.\n */\nexport type EndpointCtx<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n> = ExecutionContext<E[\"path\"], E[\"method\"], Transformed>;\n\n/** Response body type for an endpoint. */\nexport type EndpointResponse<E extends Endpoint> = ApiResponse<\n E[\"path\"],\n E[\"method\"]\n>;\n\n/**\n * @kosServiceRequest preconfigured from an endpoint descriptor, defaulting to\n * log-and-continue error handling. Pass overrides (lifecycle, errorHandler,\n * cache, …) as the second argument.\n *\n * A `transform` narrows what the model receives: its return type becomes the\n * handler's data type, so the raw response shape stops at the mapper.\n *\n * @example\n * ```typescript\n * @serviceRequest(BoardApi.update)\n * async renameBoard(name: string, $ctx?: EndpointCtx<typeof BoardApi.update>) {\n * const data = await executeServiceRequest(this, $ctx, {\n * pathParams: { id: this.id },\n * body: { name },\n * });\n * if (!data) return;\n * }\n * ```\n */\nexport function serviceRequest<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n>(\n ep: E,\n opts?: Partial<\n IKosServiceRequestParams<\n paths,\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >\n >\n) {\n return kosServiceRequest<\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >({\n path: ep.path,\n method: ep.method,\n errorHandler: { strategy: \"log\", defaultValue: null },\n ...opts,\n });\n}\n\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with kos API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.6.5/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with kos API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.8.1/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for kos API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for kos API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for kos API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with kos API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the kos OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/kos/1.9.x/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on kos API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for kos\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Methods a response type can be derived for: the lowercase subset of\n * HttpMethod. The uppercase spellings HttpMethod also permits do not match the\n * keys of an OpenAPI `paths` object, so they would silently yield `unknown`.\n */\nexport type SupportedMethod = \"get\" | \"post\" | \"put\" | \"delete\";\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends SupportedMethod = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\",\n Transformed = ApiResponse<Path, SupportedMethod & Method>\n> = KosExecutionContext<paths, Path, Method, Transformed>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/daily/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * One endpoint of the vfs API: a path and the method it is called with.\n */\nexport interface Endpoint {\n path: ApiPath;\n method: SupportedMethod;\n}\n\n/**\n * Declare an endpoint once. The decorator config, the execution context type\n * and the response type are all derived from the result, so the path string\n * is written once and cannot drift between them.\n *\n * @example\n * ```typescript\n * export const BoardApi = {\n * list: endpoint(\"/api/board\", \"get\"),\n * update: endpoint(\"/api/board/{id}\", \"put\"),\n * } as const;\n * ```\n */\nexport function endpoint<Path extends ApiPath, Method extends SupportedMethod>(\n path: Path,\n method: Method\n) {\n return { path, method } as const;\n}\n\n/**\n * Execution context for an endpoint: the method-driven `$ctx` parameter type.\n * Pass `Transformed` when the decorator declares a `transform`, so what the\n * method receives is typed as the mapper's output rather than the raw response.\n */\nexport type EndpointCtx<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n> = ExecutionContext<E[\"path\"], E[\"method\"], Transformed>;\n\n/** Response body type for an endpoint. */\nexport type EndpointResponse<E extends Endpoint> = ApiResponse<\n E[\"path\"],\n E[\"method\"]\n>;\n\n/**\n * @kosServiceRequest preconfigured from an endpoint descriptor, defaulting to\n * log-and-continue error handling. Pass overrides (lifecycle, errorHandler,\n * cache, …) as the second argument.\n *\n * A `transform` narrows what the model receives: its return type becomes the\n * handler's data type, so the raw response shape stops at the mapper.\n *\n * @example\n * ```typescript\n * @serviceRequest(BoardApi.update)\n * async renameBoard(name: string, $ctx?: EndpointCtx<typeof BoardApi.update>) {\n * const data = await executeServiceRequest(this, $ctx, {\n * pathParams: { id: this.id },\n * body: { name },\n * });\n * if (!data) return;\n * }\n * ```\n */\nexport function serviceRequest<\n E extends Endpoint,\n Transformed = EndpointResponse<E>\n>(\n ep: E,\n opts?: Partial<\n IKosServiceRequestParams<\n paths,\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >\n >\n) {\n return kosServiceRequest<\n E[\"path\"],\n E[\"method\"],\n EndpointResponse<E>,\n Transformed\n >({\n path: ep.path,\n method: ep.method,\n errorHandler: { strategy: \"log\", defaultValue: null },\n ...opts,\n });\n}\n\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.6.5/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.8.1/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\n","import type { KosExecutionContext } from \"../../../../../core/core/decorators/kos-execution-context\";\nimport type {\n HttpMethod,\n IKosServiceRequestParams,\n} from \"../../../../../core/core/decorators/kos-service-request\";\nimport { kosServiceRequest as baseKosServiceRequest } from \"../../../../../core/core/decorators/kos-service-request\";\nimport type { ClientResponse } from \"../../../../../core/util/kos-service-request\";\nimport { createClient } from \"../../../../../core/util/kos-service-request\";\n\nimport type { PathsByMethod } from \"../../../../../core/util/kos-service-request\";\nimport type { paths } from \"./openapi\";\n\n/**\n * Type aliases for vfs API\n */\nexport type Api = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\n/**\n * Get client response type for vfs API\n */\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<paths, Path, Method>;\n\n/**\n * Get execution context type for vfs API\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with vfs API types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the vfs OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest } from '../../utils/services/vfs/1.9.x/service';\n * import { DependencyLifecycle } from '@kosdev-code/kos-ui-sdk';\n *\n * @kosServiceRequest({\n * path: '/api/...',\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD\n * })\n * private onDataLoaded(): void {\n * // Fully typed based on vfs API\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\n/**\n * Create an API client for vfs\n */\nexport const api = createClient<paths>();\n\nexport default api;\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 type { TroubleAware } from \"../types\";\n\n/**\n * Type guard for {@link TroubleAware}: true when `obj` has a `troubles` array\n * and a `troublesByType` object. It checks structure only, not the contents.\n *\n * @category Utilities\n * @category Trouble Management\n *\n * @param obj - The object to check\n * @returns `true` if the object implements TroubleAware\n *\n * @see {@link TroubleAware} - The interface this function checks for\n * @see {@link useTroubleDecoration} - Hook that uses this guard internally\n */\nexport function isTroubleAware(obj?: any): obj is TroubleAware {\n return (\n obj?.troubles !== undefined &&\n obj?.troubles instanceof Array &&\n obj?.troublesByType !== undefined &&\n typeof obj?.troublesByType === \"object\"\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","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\n\nimport {\n kosLoggerAware,\n KosLoggerAware,\n kosModel,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\n\nimport type { GpioPinOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-pin-model\";\n\nexport type GpioPinModel = PublicModelInterface<GpioPinModelImpl>;\n\n// Interface merging for decorator type safety\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioPinModelImpl extends KosLoggerAware {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosLoggerAware()\nexport class GpioPinModelImpl implements IKosDataModel, IKosIdentifiable {\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<GpioPinModel, GpioPinOptions>;\n\n id: string;\n pinNum: number;\n chipNum: number;\n name: string;\n status: \"bound\" | \"pending\" | \"invalid\" | \"free\";\n connected: boolean;\n // logger property is automatically provided by @kosLoggerAware decorator\n\n constructor(modelId: string, options: GpioPinOptions) {\n this.id = modelId;\n this.chipNum = options.chipNum;\n this.pinNum = options.pinNum;\n this.name = options.name;\n this.status = \"free\";\n this.connected = options.connected ?? false;\n }\n\n updateModel(\n options: Partial<Omit<GpioPinOptions, \"chipNum\" | \"pinNum\" | \"name\">>\n ): void {\n this.status = options.status ?? this.status;\n this.connected = options.connected ?? this.connected;\n\n // Update model properties here.\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-pin ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-pin ${this.id}`);\n }\n}\n\nexport const GpioPin = GpioPinModelImpl.Registration;\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport {\n kosContainerAware,\n kosLoggerAware,\n kosModel,\n type KosContainerAware,\n type KosLoggerAware,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\n\nimport { GpioPin, type GpioPinModel } from \"./gpio-pin-model\";\nimport type { GpioPinContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-pin-container-model\";\n\nexport type GpioPinContainerModel =\n PublicModelInterface<GpioPinContainerModelImpl>;\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioPinContainerModelImpl\n extends KosLoggerAware,\n KosContainerAware<GpioPinModel> {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosContainerAware<GpioPinModel>({\n containerOptions: {\n sortKey: \"pinNum\",\n },\n})\n@kosLoggerAware()\nexport class GpioPinContainerModelImpl\n implements IKosIdentifiable, IKosDataModel\n{\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<\n GpioPinContainerModel,\n GpioPinContainerOptions\n >;\n\n id: string;\n\n constructor(modelId: string, _options: GpioPinContainerOptions) {\n this.id = modelId;\n // Container is automatically injected with parentId: modelId\n }\n\n updateModel(_options: GpioPinContainerOptions): void {\n // Update model properties here.\n }\n\n getPin(pinNum: number) {\n const pin = this.data[pinNum];\n if (!pin) {\n this.logger.warn(\n `Pin number ${pinNum} not found in container ${this.id}`\n );\n return undefined;\n }\n if (pin.pinNum !== pinNum) {\n this.logger.warn(\n `Pin number mismatch for pin ${pin.id} in container ${this.id}: expected ${pinNum}, got ${pin.pinNum}`\n );\n return undefined;\n }\n return this.data[pinNum];\n }\n // -------------------LIFECYCLE----------------------------\n\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-pin-container container ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-pin-container container ${this.id}`);\n }\n}\nexport const GpioPinContainer = GpioPinContainerModelImpl.Registration;\n\nGpioPinContainer.addRelatedModel(GpioPin);\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\n\nimport {\n kosChild,\n kosLoggerAware,\n KosLoggerAware,\n kosModel,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { KosModelRegistrationType } from \"../../../core/core/registration/model-registration\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { GpioPinContainer, type GpioPinContainerModel } from \"../gpio-pin\";\n\nimport type { GpioChipOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"gpio-chip-model\";\n\nexport type GpioChipModel = PublicModelInterface<GpioChipModelImpl>;\n\n// Interface merging for decorator type safety\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioChipModelImpl extends KosLoggerAware {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: false })\n@kosLoggerAware()\nexport class GpioChipModelImpl implements IKosDataModel, IKosIdentifiable {\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: KosModelRegistrationType<GpioChipModel, GpioChipOptions>;\n\n id: string;\n\n num: number;\n devName: string;\n name: string;\n pinCount: number;\n pinNames: string[];\n\n @kosChild private _pins: GpioPinContainerModel;\n // logger property is automatically provided by @kosLoggerAware decorator\n\n constructor(modelId: string, options: GpioChipOptions) {\n this.id = modelId;\n // logger is automatically injected by @kosLoggerAware decorator\n\n this.num = options.num;\n this.devName = options.devName;\n this.name = options.name;\n this.pinCount = options.pinCount;\n this.pinNames = options.pinNames;\n this._pins = GpioPinContainer.instance(`${this.id}-pins`)\n .options({})\n .build();\n }\n\n get pinManager() {\n return this._pins;\n }\n\n updateModel(_options: GpioChipOptions): void {\n // Update model properties here.\n }\n\n // -------------------LIFECYCLE----------------------------\n\n async handleGpioChipLoad(): Promise<void> {}\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-chip ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-chip ${this.id}`);\n }\n}\n\nexport const GpioChip = GpioChipModelImpl.Registration;\n","import { KOS_SERVICE_1_9_X as KOS_SERVICE } from \"../../../utils/services-index\";\n\nexport const GPIO_CHIP_PATH: KOS_SERVICE.ApiPath = \"/api/kos/gpio/chips\";\nexport type GpioChipContainerResponse = KOS_SERVICE.ApiResponse<\n typeof GPIO_CHIP_PATH,\n \"get\"\n>;\n\nexport const GPIO_PIN_PATH: KOS_SERVICE.ApiPath = \"/api/kos/gpio/pins\";\nexport type GpioPinContainerResponse = KOS_SERVICE.ApiResponse<\n typeof GPIO_PIN_PATH,\n \"get\"\n>;\n\nexport const gpioServiceRequest = KOS_SERVICE.kosServiceRequest;\nexport const gpioApi = KOS_SERVICE.api;\n","import { GpioPin } from \"../gpio-pin\";\nimport { GpioChip, type GpioChipModel } from \"./gpio-chip-model\";\nimport { type GpioChipContainerResponse } from \"./services\";\nimport { type GpioChipOptions } from \"./types\";\n\nexport type GpioChipResponse = GpioChipContainerResponse[number];\n\nexport interface GpioChipDto extends GpioChipOptions {\n id: string;\n}\n\nexport function mapGpioChipToOptions(dto: GpioChipDto): GpioChipOptions {\n return dto;\n}\n\nexport function createGpioChipModel(dto: GpioChipDto): GpioChipModel {\n return GpioChip.instance(dto.id).options(mapGpioChipToOptions(dto)).build();\n}\n\nexport function updateGpioChipModel(\n dto: GpioChipDto,\n model: GpioChipModel\n): void {\n model.updateModel(mapGpioChipToOptions(dto));\n}\n\nexport function filterGpioChipDto(chip: GpioChipResponse): boolean {\n return !!chip.num || chip.num === 0;\n}\n\nexport function mapGpioChipId(chip: GpioChipResponse): GpioChipDto {\n return {\n id: `${GpioChip.type}-${chip.num}`,\n num: chip.num ?? 0,\n devName: chip.devName ?? \"\",\n name: chip.name ?? \"\",\n pinCount: chip.pinCount ?? 0,\n pinNames: chip.pinNames ?? [],\n };\n}\n\nexport function afterGpioChipCreated(\n model: GpioChipModel,\n dto: GpioChipDto\n): void {\n dto.pinNames.forEach((pinName, index) => {\n const pinModel = GpioPin.instance(`${model.name}-${pinName}`)\n .options({\n name: pinName,\n pinNum: index,\n chipNum: dto.num,\n })\n .build();\n model.pinManager.addModel(pinModel);\n });\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport type { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport {\n kosContainerAware,\n kosLoggerAware,\n kosModel,\n type KosContainerAware,\n type KosLoggerAware,\n} from \"../../../core/core/decorators\";\nimport type { IKosDataModel } from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport {\n DependencyLifecycle,\n type PublicModelInterface,\n} from \"../../../core/types\";\n\nimport { GpioChip, type GpioChipModel } from \"./gpio-chip-model\";\nimport {\n GPIO_CHIP_PATH,\n gpioApi,\n gpioServiceRequest,\n type GpioChipContainerResponse,\n} from \"./services\";\nimport type { GpioChipContainerOptions } from \"./types\";\nimport {\n afterGpioChipCreated,\n createGpioChipModel,\n filterGpioChipDto,\n mapGpioChipId,\n updateGpioChipModel,\n type GpioChipResponse,\n} from \"./gpio-chip-builders\";\n\nexport const MODEL_TYPE = \"gpio-chip-container-model\";\n\nexport type GpioChipContainerModel =\n PublicModelInterface<GpioChipContainerModelImpl>;\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GpioChipContainerModelImpl\n extends KosLoggerAware,\n KosContainerAware<GpioChipModel, GpioChipResponse> {}\n\n@kosModel({ modelTypeId: MODEL_TYPE, singleton: true })\n@kosContainerAware<GpioChipModel>({\n containerOptions: {\n sortKey: \"num\",\n },\n reconcile: {\n create: createGpioChipModel,\n update: updateGpioChipModel,\n filter: filterGpioChipDto,\n idMapper: mapGpioChipId,\n afterCreate: afterGpioChipCreated,\n },\n})\n@kosLoggerAware()\nexport class GpioChipContainerModelImpl\n implements IKosIdentifiable, IKosDataModel\n{\n // Registration property for type safety - actual value injected by @kosModel decorator\n static Registration: SingletonKosModelRegistrationFactory<\n GpioChipContainerModel,\n GpioChipContainerOptions\n >;\n\n id: string;\n destinationAddress: string;\n\n constructor(modelId: string, options: GpioChipContainerOptions) {\n this.id = modelId;\n this.destinationAddress = options.destinationAddress ?? \"\";\n }\n\n updateModel(_options: GpioChipContainerOptions): void {\n // Update model properties here.\n }\n // -------------------LIFECYCLE----------------------------\n\n @gpioServiceRequest({\n path: GPIO_CHIP_PATH,\n method: \"get\",\n errorHandler: {\n strategy: \"log\",\n defaultValue: [],\n },\n lifecycle: DependencyLifecycle.INIT,\n requestOptions: (model) => {\n return {\n destinationAddress: (model as GpioChipContainerModelImpl)\n .destinationAddress,\n };\n },\n })\n async handleGpioChipInit(\n _error: never,\n response: Record<string, GpioChipContainerResponse>\n ): Promise<void> {\n const [error, pinData] = await gpioApi.get(\n \"/api/kos/gpio/pins\",\n undefined,\n {\n destinationAddress: this.destinationAddress,\n }\n );\n\n if (error) {\n this.logger.error(\"Failed to fetch GPIO pins\", error);\n return;\n }\n\n this.reconcile(Object.values(response).flat());\n\n const statuses = [\"bound\", \"pending\", \"invalid\", \"free\"] as const;\n for (const status of statuses) {\n Object.entries(pinData as Record<string, any>).forEach(\n ([_key, value]) => {\n value?.[status]?.forEach((pin) => {\n const pinNum = pin.pinNum;\n const chipNum = pin.chipNum;\n if (chipNum === undefined || pinNum === undefined) {\n this.logger.warn(\n \"Skipping pin with missing chipNum or pinNum\",\n pin\n );\n return;\n }\n const chipModel = this.data[chipNum];\n if (!chipModel || chipModel.num !== chipNum) {\n this.logger.warn(\n `No chip model found for chipNum ${chipNum} when processing pin ${pinNum}`\n );\n return;\n }\n const pinModel = chipModel.pinManager.getPin(pinNum);\n if (!pinModel) {\n this.logger.warn(\n `No pin model found for pinNum ${pinNum} in chipNum ${chipNum}`\n );\n return;\n }\n\n pinModel.updateModel({\n connected: pin.connected,\n status: status,\n });\n });\n }\n );\n }\n }\n async init(): Promise<void> {\n this.logger.debug(`initializing gpio-chip-container container ${this.id}`);\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading gpio-chip-container container ${this.id}`);\n }\n}\nexport const GpioChipContainer = GpioChipContainerModelImpl.Registration;\n\nGpioChipContainer.addRelatedModel(GpioChip);\n","import { KosLog, type ServiceResponse } from \"../../../../core\";\nimport API, { type ApiPath, type ApiResponse } from \"../../../utils/service\";\n\nconst log = KosLog.createLogger({\n name: \"studio-properties-service\",\n group: \"Services\",\n});\n\nconst SERVICE_PATH: ApiPath = \"/api/kos/studio/properties\";\nexport type StudioPropertiesClientResponse = ApiResponse<\n typeof SERVICE_PATH,\n \"get\"\n>;\nexport interface StudioPropertiesResponse {\n data?: Record<string, any>;\n}\n\n/**\n * @category Service\n * Retrieves the initial studio-properties data.\n */\nexport const getStudioProperties = async (\n connectionId: string\n): Promise<ServiceResponse<StudioPropertiesResponse>> => {\n log.debug(\"sending GET for studio-properties\");\n if (!connectionId) {\n log.error(\"connectionId is undefined\");\n throw new Error(\"connectionId is undefined\");\n }\n return await API.get(\n SERVICE_PATH,\n {},\n {\n destinationAddress: connectionId,\n timeout: 500,\n }\n );\n};\n","import {\n kosComputed,\n KosLog,\n ObservableData,\n WebSocketTransport,\n type KosData,\n} from \"../../../core\";\nimport { 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 { getStudioProperties } from \"./services\";\n\nimport type { StudioPropertiesOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"studio-properties-model\";\n\nconst TOPIC_PROPERTIES = \"/kos/studio/properties\";\n\n/**\n * Runtime properties of one KOS Studio connection, such as which Studio tools\n * are enabled. `initializePropertiesSession` loads the properties for the\n * connection and subscribes to its `/kos/studio/properties` topic; when the\n * properties cannot be loaded it falls back to defaults.\n * `terminatePropertiesSession` ends the subscription.\n *\n * @interface\n * @example\n * ```typescript\n * const studioProps = StudioProperties.instance(\"studio-conn-1\")\n * .options({ connectionId })\n * .build();\n * await studioProps.initializePropertiesSession();\n * const legacyTools = studioProps.get(\"kos.studio.tool.legacy\");\n * ```\n *\n * @group KOS Model\n * @category System Integration\n * @useDeclaredType\n *\n * @see {@link StudioPropertiesOptions} - Configuration options for StudioPropertiesModel instances\n */\nexport type StudioPropertiesModel =\n PublicModelInterface<StudioPropertiesModelImpl>;\n\nconst DEFAULT_STUDIO_PROPERTIES = {\n \"kos.studio.tool.legacy\": 1,\n};\n\n/**\n * @ignore\n * @internal\n */\n@kosModel(MODEL_TYPE)\nexport class StudioPropertiesModelImpl\n implements IKosDataModel, IKosIdentifiable\n{\n /** Unique identifier for the model instance */\n id: string;\n /** Studio VM connection identifier for property routing */\n connectionId: string;\n /** WebSocket subscription cleanup function */\n private unsubscribe: VoidFunction | null = null;\n /** Context logger for debugging and diagnostics */\n private logger: KosContextLogger;\n /** Observable data store for Studio properties */\n private data: KosData<Record<string, any>>;\n constructor(\n modelId: string,\n options: StudioPropertiesOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n\n this.data = ObservableData();\n this.connectionId = options.connectionId;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n this.logger.debug(`initializing studio-properties ${this.id}`);\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n this.logger.debug(`loading studio-properties ${this.id}`);\n }\n\n /** Ends the `/kos/studio/properties` subscription. */\n async terminatePropertiesSession(): Promise<void> {\n this.unsubscribe?.();\n }\n\n /**\n * Loads the connection's properties and subscribes to its `/kos/studio/properties` topic.\n */\n async initializePropertiesSession() {\n this.unsubscribe = WebSocketTransport.getInstance().subscribeTopic({\n topic: TOPIC_PROPERTIES,\n destinationAddress: this.connectionId,\n callback: (msg) => {\n this.logger.error(\n `Received studio-properties message for connection ${\n this.connectionId\n }: ${JSON.stringify(msg)}`\n );\n },\n });\n const [error, data] = await getStudioProperties(this.connectionId);\n if (error) {\n this.logger.error(`Error loading studio-properties: ${error}`);\n this.data.setValues(DEFAULT_STUDIO_PROPERTIES);\n return;\n }\n if (data) {\n const update = Object.keys(data).reduce((acc, key) => {\n acc[key] = data[key] ?? key;\n return acc;\n }, {});\n this.data.setValues(update ?? DEFAULT_STUDIO_PROPERTIES);\n KosLog.ifDebug(() =>\n this.logger.debug(`studio-properties loaded: ${JSON.stringify(update)}`)\n );\n }\n }\n\n /**\n * Retrieves a Studio property value by key.\n * @param key Property key to retrieve\n * @returns The property value or undefined if not set\n */\n get(key: string): any {\n return this.data[key];\n }\n\n /**\n * A computed value that tracks one property.\n * @param key Property key to observe\n * @returns Computed value of the property\n */\n createObservableProperty(key: string) {\n return kosComputed(() => this.get(key));\n }\n}\n","import { KosModelRegistrationFactory } from \"../../../core/core/registration\";\nimport type { StudioPropertiesOptions } from \"./types\";\nimport {\n StudioPropertiesModelImpl,\n MODEL_TYPE,\n} from \"./studio-properties-model\";\nimport type { StudioPropertiesModel } from \"./studio-properties-model\";\n\n/**\n * Registration for {@link StudioPropertiesModel}.\n *\n * `type` identifies the model in the registry and in `@kosDependency` declarations.\n * `register()` adds the model to the registry. `instance(id)` builds the model, or returns the existing one when the id is already in use.\n *\n * @example\n * ```typescript\n * const model = StudioProperties.instance(\"studioPropertiesId\").options(options).build();\n * ```\n */\nexport const StudioProperties = new KosModelRegistrationFactory<\n StudioPropertiesModel,\n StudioPropertiesOptions\n>({\n class: StudioPropertiesModelImpl,\n type: MODEL_TYPE,\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 { createPortal } from \"react-dom\";\nimport { loadingDot } from \"./loading-message-styles\";\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 theme?: \"light\" | \"dark\";\n}\nfunction LoadingMessage({\n message = \"Wait a moment while we load your app.\",\n theme = \"light\",\n}: Props) {\n return (\n <Portal>\n <MessageContainer theme={theme}>\n {message}\n <div css={loadingDot}>.</div>\n </MessageContainer>\n </Portal>\n );\n}\n\nexport default LoadingMessage;\n\nconst MessageContainer = styled.div<{ theme: \"light\" | \"dark\" }>`\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 color: ${({ theme }) => (theme === \"light\" ? \"black\" : \"white\")};\n z-index: 10000;\n`;\n","import React, { ErrorInfo } from \"react\";\nimport { KosLog } from \"../../../core\";\n\nconst log = KosLog.createLogger({ name: \"error-boundary\" });\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 /** Names the guarded region so a caught error is traceable to its seam. */\n name?: string;\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 /**\n * Recovers during the render phase. Without this React renders the boundary\n * with `null` children and waits for `componentDidCatch` to schedule a\n * fallback, and a second error in the same batch escalates past the boundary\n * to the root, unmounting the whole tree.\n */\n static getDerivedStateFromError(\n error: Error\n ): Pick<ErrorBoundaryState, \"error\"> {\n return { error };\n }\n\n override componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n // A boundary that swallows the cause leaves nothing to diagnose, so the\n // error is reported before the fallback replaces the subtree.\n const seam = this.props.name ? ` in ${this.props.name}` : \"\";\n // The message carries the cause inline: an Error passed as a bare argument\n // serialises to `{}` under some log sinks.\n log.error(\n `Error boundary caught${seam}: ${error?.message ?? error}`,\n error,\n errorInfo.componentStack\n );\n this.setState({\n error: error,\n errorInfo: errorInfo,\n });\n }\n\n override render() {\n // Keyed on `error` because that is what the render phase sets; `errorInfo`\n // only arrives later, from the commit phase.\n if (this.state.error) {\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.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 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, useMemo } 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.isOnline);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setOnline(kosCore.isOnline);\n });\n\n return () => {\n disposer();\n };\n }, [kosCore]);\n\n const value = useMemo<IKosContext>(() => {\n return { kosCore, online };\n }, [kosCore, online]);\n\n return <KosContext.Provider value={value}>{children}</KosContext.Provider>;\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","/**\n * sessionStorage key used to signal to the next page load that a\n * reload-on-disconnect recovery just occurred. Overlay components read it\n * on mount so the \"reconnecting\" UI can persist across the reload without\n * a visible gap.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport const KOS_RECOVERING_SESSION_KEY = \"kos:recovering\";\n","import { useEffect, useRef } from \"react\";\nimport { EventBus } from \"../../common\";\nimport { WebSocketEvents } from \"../../core/core/transport/base-message-transport\";\nimport { KosLog } from \"../../core/core/log\";\nimport { KOS_RECOVERING_SESSION_KEY } from \"./constants\";\n\n/**\n * Metadata the policy records about the triggering disconnect.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport interface ReloadOnDisconnectInfo {\n code: number;\n reason: string;\n wasClean: boolean;\n at: number;\n}\n\n/**\n * Props for ReloadOnDisconnectPolicy.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport interface ReloadOnDisconnectPolicyProps {\n /**\n * Delay before reloading, in milliseconds. Lets rapid-fire reconnect\n * attempts settle without stacking reloads. Default: 3000.\n */\n graceMs?: number;\n /**\n * Called synchronously immediately before the reload. Useful for\n * telemetry. Keep it synchronous, since the reload may preempt async work.\n */\n onBeforeReload?: (info: ReloadOnDisconnectInfo) => void;\n /**\n * Test seam. Replace the reload function. Defaults to\n * () => window.location.reload().\n */\n reloadFn?: () => void;\n}\n\nconst DEFAULT_GRACE_MS = 3000;\n\nconst defaultReloadFn = () => {\n window.location.reload();\n};\n\n/**\n * Mounts a connection-recovery policy: when the WebSocket disconnects, wait\n * a short grace window, record the disconnect in sessionStorage, then\n * `window.location.reload()` the page. Renders nothing.\n *\n * The grace window only de-bounces rapid disconnect/reconnect flapping. Even\n * a sub-second reconnect triggers the reload, because the data layer cannot\n * guarantee freshness across the gap.\n *\n * Apps that reconcile on reconnect instead (Studio, for example) do not mount\n * this policy.\n *\n * Pair with an overlay that reads `KOS_RECOVERING_SESSION_KEY` on mount to\n * keep a \"reconnecting\" message visible across the reload boundary.\n *\n * @kosService core.reload-on-disconnect-policy\n * @kosApiLevel 23\n */\nexport const ReloadOnDisconnectPolicy: React.FC<\n ReloadOnDisconnectPolicyProps\n> = ({\n graceMs = DEFAULT_GRACE_MS,\n onBeforeReload,\n reloadFn = defaultReloadFn,\n}) => {\n const pendingReloadRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n if (pendingReloadRef.current) {\n return;\n }\n\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (!payload || typeof payload.code !== \"number\") {\n return;\n }\n\n const info: ReloadOnDisconnectInfo = {\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n };\n\n try {\n sessionStorage.setItem(\n KOS_RECOVERING_SESSION_KEY,\n JSON.stringify(info)\n );\n } catch (err) {\n KosLog.warn(\n \"ReloadOnDisconnectPolicy: failed to write sessionStorage\",\n err\n );\n }\n\n KosLog.warn(\n `ReloadOnDisconnectPolicy: scheduling reload in ${graceMs}ms ` +\n `(code=${info.code}, wasClean=${info.wasClean})`\n );\n\n pendingReloadRef.current = setTimeout(() => {\n pendingReloadRef.current = null;\n try {\n onBeforeReload?.(info);\n } catch (err) {\n KosLog.error(\"ReloadOnDisconnectPolicy: onBeforeReload threw\", err);\n }\n reloadFn();\n }, graceMs);\n }\n );\n\n return () => {\n unsubscribe();\n if (pendingReloadRef.current) {\n clearTimeout(pendingReloadRef.current);\n pendingReloadRef.current = null;\n }\n };\n }, [graceMs, onBeforeReload, reloadFn]);\n\n return null;\n};\n","import { useEffect, useState } from \"react\";\nimport { EventBus } from \"../../../common\";\nimport { WebSocketEvents } from \"../../../core/core/transport/base-message-transport\";\nimport { useKosCore } from \"../../contexts/kos-core-context\";\nimport {\n KOS_RECOVERING_SESSION_KEY,\n type ReloadOnDisconnectInfo,\n} from \"../../policies\";\n\n/**\n * Snapshot of the overlay's state, returned by useReconnectingOverlayState.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport interface ReconnectingOverlayState {\n /** Whether the overlay should currently be displayed. */\n visible: boolean;\n /** Details of the disconnect, if one is being recovered from. */\n info: ReloadOnDisconnectInfo | null;\n /** Milliseconds since the tracked disconnect, or null. */\n sinceMs: number | null;\n /** Force-hide the overlay. Does not clear `info`. */\n dismiss: () => void;\n}\n\n/**\n * Options for useReconnectingOverlayState.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport interface UseReconnectingOverlayStateOptions {\n /**\n * Predicate evaluated after a CONNECTED event. When true, the overlay\n * hides. Defaults to `({ online }) => online`, i.e. hide as soon as KOS\n * Core reports online. Apps that need to wait for specific model state\n * can pass a stricter predicate.\n */\n isReady?: (state: {\n online: boolean;\n info: ReloadOnDisconnectInfo | null;\n }) => boolean;\n /**\n * Whether to read `sessionStorage[KOS_RECOVERING_SESSION_KEY]` on mount\n * to carry overlay state across a page reload. Default: true. Set false\n * for apps that don't use the reload-on-disconnect policy.\n */\n readSessionStorage?: boolean;\n}\n\nconst defaultIsReady = ({ online }: { online: boolean }) => online;\n\nconst readRecoveringInfo = (): ReloadOnDisconnectInfo | null => {\n try {\n const raw = sessionStorage.getItem(KOS_RECOVERING_SESSION_KEY);\n if (!raw) return null;\n sessionStorage.removeItem(KOS_RECOVERING_SESSION_KEY);\n const parsed = JSON.parse(raw);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n typeof parsed.code === \"number\"\n ) {\n return parsed as ReloadOnDisconnectInfo;\n }\n } catch {\n // sessionStorage may be unavailable or payload malformed; ignore\n }\n return null;\n};\n\n/**\n * Headless state hook for the reconnecting overlay.\n *\n * Becomes `visible` when a WebSocket disconnect is observed, or when the\n * page load carries a `KOS_RECOVERING_SESSION_KEY` in sessionStorage from\n * a prior reload-on-disconnect cycle. Becomes hidden when the ready\n * predicate reports the app is fully connected again.\n *\n * Returns { visible, info, sinceMs, dismiss }. Apps pair this with their\n * own overlay markup, or use the default `<ReconnectingOverlay />`.\n *\n * @kosService core.use-reconnecting-overlay-state\n * @kosApiLevel 23\n */\nexport const useReconnectingOverlayState = (\n options: UseReconnectingOverlayStateOptions = {}\n): ReconnectingOverlayState => {\n const { isReady = defaultIsReady, readSessionStorage = true } = options;\n const { online } = useKosCore();\n\n const [info, setInfo] = useState<ReloadOnDisconnectInfo | null>(() =>\n readSessionStorage ? readRecoveringInfo() : null\n );\n const [dismissed, setDismissed] = useState(false);\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (!payload || typeof payload.code !== \"number\") return;\n setInfo({\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n });\n setDismissed(false);\n }\n );\n return () => {\n unsubscribe();\n };\n }, []);\n\n const ready = isReady({ online, info });\n const visible = !dismissed && !!info && !ready;\n\n return {\n visible,\n info,\n sinceMs: info ? Date.now() - info.at : null,\n dismiss: () => setDismissed(true),\n };\n};\n","import { css, keyframes } from \"@emotion/react\";\n\nconst spin = keyframes`\n to { transform: rotate(360deg); }\n`;\n\nexport const overlayRoot = css`\n position: fixed;\n inset: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 16px;\n background: rgba(0, 0, 0, 0.72);\n color: #ffffff;\n font-family: system-ui, -apple-system, \"Segoe UI\", sans-serif;\n z-index: 2147483647;\n pointer-events: auto;\n user-select: none;\n`;\n\nexport const spinner = css`\n width: 48px;\n height: 48px;\n border-radius: 50%;\n border: 4px solid rgba(255, 255, 255, 0.25);\n border-top-color: #ffffff;\n animation: ${spin} 1s linear infinite;\n`;\n\nexport const message = css`\n font-size: 18px;\n font-weight: 500;\n letter-spacing: 0.02em;\n`;\n","import type React from \"react\";\nimport {\n useReconnectingOverlayState,\n type ReconnectingOverlayState,\n type UseReconnectingOverlayStateOptions,\n} from \"./use-reconnecting-overlay-state\";\nimport { message, overlayRoot, spinner } from \"./reconnecting-overlay-styles\";\n\nexport {\n useReconnectingOverlayState,\n type ReconnectingOverlayState,\n type UseReconnectingOverlayStateOptions,\n} from \"./use-reconnecting-overlay-state\";\n\n/**\n * Props for the default ReconnectingOverlay.\n *\n * @kosService core.reconnecting-overlay\n * @kosApiLevel 23\n */\nexport interface ReconnectingOverlayProps\n extends UseReconnectingOverlayStateOptions {\n /** Override the default message (\"Reconnecting…\"). */\n messageText?: string;\n /**\n * Fully replace the rendered content with a custom renderer. Receives the\n * overlay state. If provided, the default layout (spinner + message) is\n * not rendered.\n */\n renderContent?: (state: ReconnectingOverlayState) => React.ReactNode;\n className?: string;\n}\n\n/**\n * Minimal, unbranded overlay that displays while the app is recovering\n * from a WebSocket disconnect (or immediately after a reload triggered by\n * ReloadOnDisconnectPolicy). Pair with that policy — or use in isolation\n * for apps that want to show the overlay without reloading.\n *\n * Apps with design-system requirements should wrap\n * `useReconnectingOverlayState` in their own component rather than relying\n * on these default styles.\n *\n * @kosService core.reconnecting-overlay\n * @kosApiLevel 23\n */\nexport const ReconnectingOverlay: React.FC<ReconnectingOverlayProps> = ({\n messageText = \"Reconnecting…\",\n renderContent,\n className,\n isReady,\n readSessionStorage,\n}) => {\n const state = useReconnectingOverlayState({ isReady, readSessionStorage });\n\n if (!state.visible) return null;\n\n return (\n <div\n css={overlayRoot}\n className={className}\n role=\"alertdialog\"\n aria-live=\"assertive\"\n aria-label=\"Reconnecting\"\n >\n {renderContent ? (\n renderContent(state)\n ) : (\n <>\n <div css={spinner} aria-hidden=\"true\" />\n <div css={message}>{messageText}</div>\n </>\n )}\n </div>\n );\n};\n","import { useEffect, useState } from \"react\";\nimport { KosCore, kosAutoEffect, type IKosCoreManager } from \"../../../core\";\n\n/**\n * Connection status shown by ConnectionDevButton.\n *\n * @kosService core.use-connection-dev-state\n * @kosApiLevel 25\n */\nexport type ConnectionDevStatus = \"online\" | \"offline\" | \"reconnecting\";\n\n/**\n * Snapshot of the connection, returned by useConnectionDevState.\n *\n * @kosService core.use-connection-dev-state\n * @kosApiLevel 25\n */\nexport interface ConnectionDevState {\n /**\n * `reconnecting` while KOS Core reloads or runs its reconnect sequence,\n * otherwise `online` or `offline` from the core's connection.\n */\n status: ConnectionDevStatus;\n}\n\nconst readStatus = (core: IKosCoreManager): ConnectionDevStatus => {\n if (core.reloading) return \"reconnecting\";\n return core.isOnline ? \"online\" : \"offline\";\n};\n\n/**\n * Headless state hook for ConnectionDevButton. Tracks KOS Core's `isOnline`\n * and `reloading` reactively and reports them as one status.\n *\n * @kosService core.use-connection-dev-state\n * @kosApiLevel 25\n */\nexport const useConnectionDevState = (): ConnectionDevState => {\n const [status, setStatus] = useState<ConnectionDevStatus>(() =>\n readStatus(KosCore.getInstance())\n );\n\n useEffect(() => {\n const core = KosCore.getInstance();\n const disposer = kosAutoEffect(() => {\n setStatus(readStatus(core));\n });\n return () => {\n disposer();\n };\n }, []);\n\n return { status };\n};\n","import { css } from \"@emotion/react\";\n\nconst OFFSET = \"16px\";\n\nexport const buttonRoot = css`\n position: fixed;\n display: inline-flex;\n align-items: center;\n gap: 8px;\n padding: 6px 12px;\n border: 1px solid rgba(255, 255, 255, 0.25);\n border-radius: 6px;\n background: rgba(0, 0, 0, 0.72);\n color: #ffffff;\n font-family: system-ui, -apple-system, \"Segoe UI\", sans-serif;\n font-size: 12px;\n line-height: 1.4;\n cursor: pointer;\n z-index: 2147483646;\n\n &:disabled {\n cursor: default;\n opacity: 0.6;\n }\n`;\n\nexport const positions = {\n \"bottom-left\": css`\n bottom: ${OFFSET};\n left: ${OFFSET};\n `,\n \"bottom-right\": css`\n bottom: ${OFFSET};\n right: ${OFFSET};\n `,\n \"top-left\": css`\n top: ${OFFSET};\n left: ${OFFSET};\n `,\n \"top-right\": css`\n top: ${OFFSET};\n right: ${OFFSET};\n `,\n} as const;\n\nexport const statusText = css`\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.04em;\n`;\n","import type React from \"react\";\nimport { KosCore } from \"../../../core\";\nimport {\n useConnectionDevState,\n type ConnectionDevState,\n} from \"./use-connection-dev-state\";\nimport {\n buttonRoot,\n positions,\n statusText,\n} from \"./connection-dev-button-styles\";\n\nexport {\n useConnectionDevState,\n type ConnectionDevState,\n type ConnectionDevStatus,\n} from \"./use-connection-dev-state\";\n\n/**\n * Props for ConnectionDevButton.\n *\n * @kosService core.connection-dev-button\n * @kosApiLevel 25\n */\nexport interface ConnectionDevButtonProps {\n /** Screen corner the button is fixed to. Default: \"bottom-right\". */\n position?: \"bottom-left\" | \"bottom-right\" | \"top-left\" | \"top-right\";\n /** Button label. Default: \"Drop connection\". */\n label?: string;\n className?: string;\n /**\n * Fully replace the button's content with a custom renderer. Receives the\n * connection state. If provided, the default label and status are not\n * rendered.\n */\n renderContent?: (state: ConnectionDevState) => React.ReactNode;\n}\n\n/**\n * Minimal, unbranded development button that drops the KOS websocket so the\n * reconnect path can be exercised from any KOS application. Shows the live\n * connection status and, on click, calls the transport's `dropConnection()`;\n * the transport reconnects on its own and KOS Core runs its reconnect\n * sequence. Disabled while the core is not online.\n *\n * Pair with ReconnectingOverlay to see the reconnect as users do.\n *\n * @kosService core.connection-dev-button\n * @kosApiLevel 25\n */\nexport const ConnectionDevButton: React.FC<ConnectionDevButtonProps> = ({\n position = \"bottom-right\",\n label = \"Drop connection\",\n className,\n renderContent,\n}) => {\n const state = useConnectionDevState();\n\n return (\n <button\n type=\"button\"\n css={[buttonRoot, positions[position]]}\n className={className}\n disabled={state.status !== \"online\"}\n onClick={() => KosCore.getInstance().transport.dropConnection()}\n >\n {renderContent ? (\n renderContent(state)\n ) : (\n <>\n <span>{label}</span>\n <span css={statusText}>{state.status}</span>\n </>\n )}\n </button>\n );\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 {\n clearModelHookCacheEntry,\n destroyKosModel,\n modelHookCache,\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 { isUpdateable } from \"../../core/core/registration/model-registration\";\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 forceUpdate?: 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\n/**\n * Reads a model out of the suspense cache, suspending or rethrowing as the\n * entry requires. Exported for tests.\n */\nexport function readModelHookEntry(\n key: string,\n fetcher: () => Promise<unknown>\n) {\n const entry = modelHookCache.get(key);\n\n if (entry) {\n if (entry.status === \"finished\") {\n const kosModel = KosCore.getInstance().modelManager.getModelById(key);\n return { kosModel, model: kosModel?.modelData };\n }\n\n // An error entry has no promise to suspend on, so rethrow the cause.\n if (entry.status === \"error\") {\n throw entry.error;\n }\n\n throw entry.promise;\n }\n\n const promise = fetcher().then(\n () => {\n modelHookCache.set(key, { status: \"finished\", key });\n },\n (error) => {\n modelHookCache.set(key, { status: \"error\", error });\n throw error;\n }\n );\n\n modelHookCache.set(key, { status: \"pending\", promise });\n\n throw promise;\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 = readModelHookEntry(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 } = 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}\n/**\n * Primary hook for consuming KOS models in React components.\n *\n * @kosService core.use-kos-model\n * @kosApiLevel 2\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\n useEffect(() => {\n if (modelOptions.forceUpdate && model) {\n if (isUpdateable(model)) {\n model.updateModel(modelOptions.options || {});\n }\n }\n }, [model]);\n useEffect(() => {\n async function waitForModel() {\n try {\n await kosCoreContext.kosCore.whenReady();\n if (activate) {\n await kosModel?.fsm.transitionTo(\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 throw e;\n }\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?.fsm\n .transitionTo(KosModelEvents.GO_INACTIVE, KosModelState.INACTIVE)\n .then(() => {\n if (destroyOnUnmount) {\n const modelId = model.id;\n destroyKosModel(model).then(() => {\n clearModelHookCacheEntry(modelId);\n disposer?.();\n });\n }\n });\n }\n } else {\n if (destroyOnUnmount && model) {\n destroyKosModel(model).then(() => {\n clearModelHookCacheEntry(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\n/**\n * Hook for accessing the KOS time model.\n *\n * @kosService core.use-kos-time\n * @kosApiLevel 2\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\n/**\n * Hook for accessing the KOS software info model.\n *\n * @kosService core.use-software-info\n * @kosApiLevel 2\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 collectLocaleOptions,\n getKosLocalizationDescriptor,\n mergeLocalizationDescriptors,\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 allLocales: { locale: string; label: string }[];\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 excludeNamespaces?: string[];\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,\n locale = \"en\",\n resolver,\n rootUrl,\n descriptorResolver,\n excludeNamespaces = [],\n}) => {\n const [ready, setReady] = useState(false);\n const [localization, setLocalization] = useState<Localization>();\n const [translations, setTranslations] = useState<TranslationContainerModel>();\n const [allLocales, setAllLocales] = useState<\n { locale: string; label: string }[]\n >([]);\n const resolvedRootUrl = rootUrl || getDefaultHost();\n const _appContext = useMemo(() => appContext ?? \"app/system\", [appContext]);\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 setLocalization(mergeLocalizationDescriptors(descriptors));\n setAllLocales(collectLocaleOptions(descriptors, excludeNamespaces));\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 }, [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 allLocales,\n };\n }\n return {\n setLocale: () => {\n throw new Error(\"Translations not ready\");\n },\n allLocales: [],\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 {\n CanvasDispatcher,\n type CanvasDispatcherModel,\n type CanvasDispatcherOptions,\n} from \"../../../../../models/models/canvas-dispatcher\";\nimport { useKosModel } from \"../../../../hooks/use-kos-model\";\n\nexport const useCanvasDispatcher = () => {\n const modelId = CanvasDispatcher.type;\n const result = useKosModel<CanvasDispatcherModel, CanvasDispatcherOptions>({\n modelId,\n modelType: CanvasDispatcher.type,\n options: {},\n });\n\n return result;\n};\n","import type { CanvasDispatcherModel } from \"../../../../../models/models/canvas-dispatcher\";\nimport { useCanvasDispatcher } from \"./use-canvas-dispatcher\";\n\ninterface CanvasDispatcherProps {\n canvasDispatcher: CanvasDispatcherModel;\n}\n\ntype HoCCanvasDispatcherProps = CanvasDispatcherProps;\n// react HOC to provide a CanvasDispatcher to a component\nexport function withCanvasDispatcher<\n T extends HoCCanvasDispatcherProps = HoCCanvasDispatcherProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof CanvasDispatcherProps>) => {\n const { model, status, KosModelLoader } = useCanvasDispatcher();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} canvasDispatcher={model} />\n </KosModelLoader>\n );\n };\n}\n","export const decodeBase64RGB = (\n base64: string,\n width: number,\n height: number\n): Uint8ClampedArray => {\n const binary = atob(base64);\n const rgba = new Uint8ClampedArray(width * height * 4);\n for (let i = 0, j = 0; i < binary.length && j < rgba.length; i += 3, j += 4) {\n rgba[j] = binary.charCodeAt(i);\n rgba[j + 1] = binary.charCodeAt(i + 1);\n rgba[j + 2] = binary.charCodeAt(i + 2);\n rgba[j + 3] = 255;\n }\n return rgba;\n};\n\nexport const decodeRGB332 = (\n data: string,\n width: number,\n height: number\n): Uint8ClampedArray => {\n const rgba = new Uint8ClampedArray(width * height * 4);\n for (let i = 0; i < data.length; i++) {\n const byte = data.charCodeAt(i);\n const r = (((byte >> 5) & 0x07) * 255) / 7;\n const g = (((byte >> 2) & 0x07) * 255) / 7;\n const b = ((byte & 0x03) * 255) / 3;\n const j = i * 4;\n rgba[j] = r;\n rgba[j + 1] = g;\n rgba[j + 2] = b;\n rgba[j + 3] = 255;\n }\n return rgba;\n};\n\n/**\n * Renders a decoded preview onto a canvas context by decoding image data\n * from a specified format and scaling it to the desired size.\n *\n * @param ctx - The 2D rendering context of the target canvas.\n * @param format - The format of the input data string. Can be either 'base64' or 'rgb332'.\n * @param dataString - The encoded image data as a string.\n * @param width - The width of the image in pixels.\n * @param height - The height of the image in pixels.\n * @param pixelSize - The scaling factor for each pixel in the rendered image.\n *\n * @remarks\n * - If `format` is 'base64', the `dataString` is decoded using `decodeBase64RGB`.\n * - If `format` is 'rgb332', the `dataString` is decoded using `decodeRGB332`.\n * - The function creates a temporary canvas to decode and render the image data\n * before scaling it onto the target canvas.\n * - Image smoothing is disabled to preserve the pixelated appearance of the image.\n */\nexport function renderDecodedPreview({\n ctx,\n format,\n dataString,\n width,\n height,\n pixelSize,\n}: {\n ctx: CanvasRenderingContext2D;\n format: \"base64\" | \"rgb332\";\n dataString: string;\n width: number;\n height: number;\n pixelSize: number;\n}) {\n const decode =\n format === \"base64\"\n ? decodeBase64RGB(dataString, width, height)\n : decodeRGB332(dataString, width, height);\n\n const img = new ImageData(\n decode as unknown as Uint8ClampedArray<ArrayBuffer>,\n width,\n height\n );\n const tempCanvas = document.createElement(\"canvas\");\n tempCanvas.width = width;\n tempCanvas.height = height;\n const tempCtx = tempCanvas.getContext(\"2d\");\n tempCtx?.putImageData(img, 0, 0);\n ctx.imageSmoothingEnabled = false;\n ctx.clearRect(0, 0, width * pixelSize, height * pixelSize);\n ctx.drawImage(tempCanvas, 0, 0, width * pixelSize, height * pixelSize);\n}\n","import styled from \"@emotion/styled\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { observer as kosComponent } from \"mobx-react-lite\";\nimport { createPortal } from \"react-dom\";\nimport { KosLog } from \"../../../../../core\";\nimport type { CanvasDispatcherModel } from \"../../../../../models/models/canvas-dispatcher\";\nimport type { CanvasRendererModel } from \"../../../../../models/models/canvas-renderer\";\nimport { withCanvasDispatcher } from \"../../hooks/canvas-dispatcher\";\nimport { renderDecodedPreview } from \"../../utils/preview-decoder\";\n\nconst log = KosLog.createLogger({ name: \"canvas-streamer\" });\nlog.debug(\"main-view component loaded\");\nconst PIXEL_SIZE = 10;\n\ninterface CanvasStreamerProps {\n height?: number;\n width?: number;\n defaultFps?: number;\n showPreview?: boolean;\n name: string;\n apiPath?: string;\n canvasDispatcher: CanvasDispatcherModel;\n}\n\nexport const CanvasStreamerBase: React.FunctionComponent<CanvasStreamerProps> =\n kosComponent(\n ({\n canvasDispatcher,\n height = 30,\n width = 50,\n defaultFps = 10,\n showPreview = false,\n name,\n apiPath = \"/api/system/canvas\",\n }) => {\n const canvasRef = useRef<HTMLCanvasElement>(null);\n\n const [renderer, setRenderer] = useState<CanvasRendererModel>();\n\n useEffect(() => {\n const _endpoint = canvasDispatcher.addNamedEndpoint(name, {\n apiPath,\n fps: defaultFps,\n width,\n height,\n id: name,\n });\n\n setRenderer(_endpoint);\n }, [canvasDispatcher]);\n /**\n * Callback function to handle frame processing.\n *\n * @param rgba - A `Uint8ClampedArray` representing the RGBA pixel data of the frame.\n *\n * This function performs the following operations:\n * If a preview canvas is available and `showPreview` is enabled, renders a decoded\n * preview of the frame onto the canvas using `renderDecodedPreview`.\n *\n * Dependencies:\n * - `width` and `height`: Dimensions of the grid for encoding and rendering.\n * - `showPreview`: A flag to determine whether to render a preview.\n * - `canvasRef`: A reference to the preview canvas element.\n * - `PIXEL_SIZE`: The size of each pixel in the preview rendering.\n */\n const onFrame = useCallback(\n (dataString: string) => {\n if (canvasRef.current && showPreview) {\n const previewCtx = canvasRef.current.getContext(\"2d\");\n if (previewCtx) {\n renderDecodedPreview({\n ctx: previewCtx,\n format: \"base64\",\n dataString,\n height,\n width,\n pixelSize: PIXEL_SIZE,\n });\n }\n }\n },\n [width, height, showPreview]\n );\n\n useEffect(() => {\n if (!renderer) return;\n renderer.onFrame = onFrame;\n renderer.width = width;\n renderer.height = height;\n renderer.fps = defaultFps;\n }, [renderer, onFrame, width, height, defaultFps]);\n\n return (\n showPreview &&\n createPortal(\n <Main>\n <PreviewContainer>\n <canvas\n ref={canvasRef}\n width={width * PIXEL_SIZE}\n height={height * PIXEL_SIZE}\n style={{ border: \"1px solid black\" }}\n />\n </PreviewContainer>\n </Main>,\n document.body\n )\n );\n }\n );\n\nexport const CanvasStreamer = withCanvasDispatcher(CanvasStreamerBase);\n\nconst Main = styled.div`\n display: flex;\n flex-direction: column;\n gap: 8px;\n\n width: 100%;\n justify-content: space-between;\n align-items: center;\n`;\n\nconst PreviewContainer = styled.div`\n display: flex;\n flex-direction: column;\n align-items: center;\n`;\n","import { Device, DeviceModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\n/**\n * Hook for accessing the KOS device model.\n *\n * @kosService core.use-device\n * @kosApiLevel 2\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\n/**\n * Hook for accessing the KOS network interface container model.\n *\n * @kosService core.use-network\n * @kosApiLevel 2\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\n/**\n * Hook for accessing the KOS OTA (over-the-air update) model.\n *\n * @kosService core.use-ota\n * @kosApiLevel 2\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\n/**\n * Hook for accessing the KOS storage device container model.\n *\n * @kosService core.use-storage\n * @kosApiLevel 2\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 { useCallback, useEffect } from \"react\";\nimport { EventBus } from \"../../../common\";\nimport { KosLog } from \"../../../core\";\nimport {\n KosTimer,\n TIMER_END,\n TIMER_EVENT,\n TimerEvent,\n TimerManager,\n TOPIC_TIMER_TICK_EVENT,\n} from \"../../../models\";\n\nconst LOG = KosLog.createLogger({ name: \"use-timer\" });\ninterface TimerHookProps {\n timerName: string;\n onTimerExpired: (event: TimerHookEvent) => void;\n onTimerTick?: (event: TimerTickEvent) => void;\n timerEventActions?: Record<string, (event: TimerHookEvent) => void>;\n autoStart?: boolean;\n}\ntype TimerHookEvent = TimerEvent & { timer: KosTimer };\n\ntype TimerTickEvent = Omit<TimerHookEvent, \"action\"> & {\n timer: KosTimer;\n};\nexport const useTimer = ({\n timerName,\n onTimerExpired,\n onTimerTick,\n timerEventActions,\n autoStart,\n}: TimerHookProps) => {\n const t = TimerManager.getTimer(timerName);\n\n useEffect(() => {\n if (!t) {\n console.warn(`Timer with name ${timerName} does not exist.`);\n return undefined;\n }\n const result = EventBus.subscribe(TIMER_EVENT, (data) => {\n const { name, action, remainingTime } =\n data?.body as unknown as TimerEvent;\n if (name === timerName) {\n if (action === TIMER_END) {\n onTimerExpired({ name, action, remainingTime, timer: t });\n } else if (timerEventActions?.[action]) {\n timerEventActions[action]({ name, action, remainingTime, timer: t });\n }\n }\n });\n if (autoStart) t.start();\n return () => {\n result.unsubscribe();\n };\n }, [autoStart, onTimerExpired, timerEventActions, timerName, t]);\n\n useEffect(() => {\n if (!t || !onTimerTick) {\n return undefined;\n }\n const TOPIC_TIMER_TICK = `${TOPIC_TIMER_TICK_EVENT}/${timerName}`;\n const result = EventBus.subscribe(TOPIC_TIMER_TICK, (data) => {\n const { name, remainingTime } = data?.body as unknown as TimerEvent;\n if (name === timerName) {\n onTimerTick({ name, remainingTime, timer: t });\n }\n });\n return () => {\n result.unsubscribe();\n };\n }, [onTimerTick, timerName, t]);\n\n const start = useCallback(() => {\n if (t) {\n t.start();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n const reset = useCallback(() => {\n if (t) {\n t.reset();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n const pause = useCallback(() => {\n if (t) {\n t.pause();\n } else {\n LOG.warn(`Timer with name ${timerName} does not exist.`);\n }\n }, [t, timerName]);\n\n return {\n timer: t,\n start,\n reset,\n pause,\n };\n};\n","import React, { type ReactNode, type ReactElement } from \"react\";\nimport { TFunction } from \"./use-translation\";\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\n/**\n * React component for rendering translated strings with embedded components or markup.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\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 }\n\n // An error entry has no promise to suspend on, so rethrow the cause.\n if (entry.status === \"error\") {\n throw entry.error;\n }\n\n throw entry.promise;\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}\n/**\n * Primary hook for consuming KOS translations in React components.\n * Resolves a translation namespace and returns a `t` function for key lookup.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\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\n/**\n * Hook for accessing the KOS translation container model.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\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/**\n * Higher-order component that injects a `TranslationContainerModel` into a wrapped component.\n *\n * @kosService core.use-translation\n * @kosApiLevel 2\n */\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\n/**\n * Hook for accessing the KOS USB update container model.\n *\n * @kosService core.use-usb-update\n * @kosApiLevel 2\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 const [isSearching, setIsSearching] = useState<boolean>(false);\n const [noUpdates, setNoUpdates] = useState<boolean>(false);\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 setIsSearching(result.model?.isSearchingUpdates ?? false);\n setNoUpdates(result.model?.noAvailableUpdates ?? false);\n });\n\n return () => {\n disposer();\n };\n }, [result.model]);\n\n return {\n ...result,\n inserted,\n updateAvailable,\n updates,\n isSearching,\n noUpdates,\n };\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}\n/**\n * Hook for binding to a KOS configuration bean.\n *\n * @kosService core.use-config-property\n * @kosApiLevel 2\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};\n/**\n * Hook for binding to a KOS configuration property.\n *\n * @kosService core.use-config-property\n * @kosApiLevel 2\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","import { useEffect, useState } from \"react\";\nimport { EventBus } from \"../../common\";\nimport { WebSocketEvents } from \"../../core/core/transport/base-message-transport\";\nimport { useKosCore } from \"../contexts/kos-core-context\";\n\n/**\n * Details of the most recent WebSocket close event.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport interface DisconnectInfo {\n code: number;\n reason: string;\n wasClean: boolean;\n /** Wall-clock time (Date.now()) when the disconnect was observed. */\n at: number;\n}\n\n/**\n * Current KOS Core connection state plus info about the last disconnect.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport interface ConnectionState {\n online: boolean;\n lastDisconnect: DisconnectInfo | null;\n /** Milliseconds since the last disconnect, or null if none observed. */\n sinceLastDisconnectMs: number | null;\n}\n\n/**\n * Observes KOS Core connection state.\n *\n * Returns the current `online` status plus information about the most recent\n * disconnect (code, reason, wasClean, timestamp). `sinceLastDisconnectMs` is\n * recomputed on each render; components that need it to tick continuously\n * should re-render themselves via an interval.\n *\n * @kosService core.use-connection-state\n * @kosApiLevel 23\n */\nexport const useConnectionState = (): ConnectionState => {\n const { online } = useKosCore();\n const [lastDisconnect, setLastDisconnect] = useState<DisconnectInfo | null>(\n null\n );\n\n useEffect(() => {\n const { unsubscribe } = EventBus.subscribe(\n WebSocketEvents.DISCONNECTED,\n (msg) => {\n const payload = msg?.body as\n | { code: number; reason: string; wasClean: boolean }\n | undefined;\n if (\n payload &&\n typeof payload === \"object\" &&\n typeof payload.code === \"number\"\n ) {\n setLastDisconnect({\n code: payload.code,\n reason: payload.reason,\n wasClean: payload.wasClean,\n at: Date.now(),\n });\n }\n }\n );\n return () => {\n unsubscribe();\n };\n }, []);\n\n return {\n online,\n lastDisconnect,\n sinceLastDisconnectMs: lastDisconnect\n ? Date.now() - lastDisconnect.at\n : null,\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 { useEffect } from \"react\";\n\n// A warmup marker to simulate a special execution path\n/**\n * Represents a marker type used to indicate that a function or process\n * has been warmed up and is ready for use.\n *\n * This type is typically used as a flag or annotation in scenarios\n * where initialization or preparation steps are required before\n * execution.\n */\nexport type WarmupMarker = { __warmup: true };\n\n// Accepts a function that takes 0 or 1 argument\ntype Warmupable<T extends (arg?: any) => any> = (\n arg?: any | WarmupMarker\n) => ReturnType<T>;\n\ninterface UseFunctionWarmupOptions {\n intervalMs?: number; // How often to re-warm (ms)\n immediate?: boolean; // Should warmup run on mount\n}\n\n/**\n * A React hook that periodically invokes a given function to keep it \"warmed up.\"\n * This can be useful for functions that require initialization or caching to\n * improve performance during actual usage.\n *\n * @template T - The type of the function to be warmed up.\n * @param fn - The function to be warmed up. It should accept an optional argument\n * and handle a special warmup call with `{ __warmup: true }`.\n * @param options - Configuration options for the warmup behavior.\n * @param options.intervalMs - The interval in milliseconds at which the function\n * should be warmed up. Defaults to 5 minutes (300,000 ms).\n * If set to `null` or `0`, periodic warmup is disabled.\n * @param options.immediate - Whether to perform an immediate warmup when the hook\n * is first invoked. Defaults to `true`.\n *\n * @returns void\n *\n * @remarks\n * - If the `immediate` option is enabled, the function will be warmed up immediately\n * using `requestIdleCallback` if available, or a `setTimeout` fallback.\n * - Errors thrown during the warmup process are caught and ignored.\n * - The periodic warmup is cleaned up automatically when the component unmounts.\n *\n * @example\n * ```tsx\n * const lookup = (arg?: string | WarmupMarker) => {\n * if (typeof arg === \"object\" && arg.__warmup) return;\n * // ...\n * };\n * useFunctionWarmup(lookup, { intervalMs: 60000 });\n * ```\n */\nexport function useFunctionWarmup<T extends (arg?: any) => any>(\n fn: Warmupable<T>,\n options: UseFunctionWarmupOptions = {}\n) {\n const { intervalMs = 5 * 60 * 1000, immediate = true } = options;\n\n useEffect(() => {\n const warmup = () => {\n try {\n fn({ __warmup: true });\n } catch {\n // ignore errors from warmup path\n }\n };\n\n if (immediate) {\n if (\"requestIdleCallback\" in window) {\n requestIdleCallback(warmup);\n } else {\n setTimeout(warmup, 1);\n }\n }\n\n const id = intervalMs ? setInterval(warmup, intervalMs) : null;\n return () => {\n if (id) clearInterval(id);\n };\n }, [fn, intervalMs, immediate]);\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 useKosDateFormats hook.\n * @typeParam T - the type of the options returned from the dateFormatMap function.\n */\nexport interface KosDateFormatHookData<T extends {} = any> {\n /** the ids of the available date formats. */\n raw: string[];\n\n /** the region info model. */\n regionModel?: RegionInfoModel;\n\n /** the currently selected date format. */\n selectedDateFormat: string;\n\n dateFormatId: string;\n /** updates the selected date format. */\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 * Manages the region's date format: the available formats, the selected\n * format, and props for a date format select box.\n *\n * @param dateFormatMap - maps a date format to a select-box option. The\n * default returns an `<option>` with the format as value and label.\n * @returns KosDateFormatHookData - the data returned from the hook.\n * @example\n * ```tsx\n * const { props } = useKosDateFormats();\n * const { options, ...selectAttributes } = props;\n * return <select {...selectAttributes}>{options}</select>;\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 * ```tsx\n * const TimeZonePicker = kosComponent(() => {\n * const { selectProps } = useKosTimeZones();\n * const { options, ...props } = selectProps;\n * return <select {...props}>{options}</select>;\n * });\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. Must extend `RegionServices.BaseRegionResponse`.\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 * Manages the device region: the available regions, the selected region and\n * its data, and props for a region select box.\n *\n * @typeParam RegionData - the region data returned from the backend service. Must extend `RegionServices.BaseRegionResponse`.\n * @param regionMap - maps a region string to a select-box option. The default\n * returns an `<option>` with the region as value and label. Pass a custom map\n * when a third-party select component expects a different option shape.\n * @returns KosRegionHookData - the data returned from the hook.\n * @example\n * ```tsx\n * const { regionSelectProps, selectedRegion } = useKosRegions();\n * const { options, ...selectAttributes } = regionSelectProps;\n * return <select {...selectAttributes}>{options}</select>;\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 });\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 useKosTimeFormats hook.\n * @typeParam T - the type of the options returned from the timeFormatMap function.\n */\nexport interface KosTimeFormatHookData<T extends {} = any> {\n /** the ids of the available time formats. */\n raw: string[];\n\n /** the region info model. */\n regionModel?: RegionInfoModel;\n\n /** the currently selected time format. */\n selectedTimeFormat: string;\n\n timeFormatId: string;\n /** updates the selected time format. */\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 * Manages the region's time format: the available formats, the selected\n * format, and props for a time format select box.\n *\n * @param timeFormatMap - maps a time format to a select-box option. The\n * default returns an `<option>` with the format as value and label.\n * @returns KosTimeFormatHookData - the data returned from the hook.\n * @example\n * ```tsx\n * const { props } = useKosTimeFormats();\n * const { options, ...selectAttributes } = props;\n * return <select {...selectAttributes}>{options}</select>;\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 { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n hasReadyHook,\n isDisposable,\n} from \"../../../core/core/decorators/kos-view-model\";\n\n/**\n * Configuration options for the useViewModel hook.\n */\nexport interface UseViewModelOptions {\n /**\n * When true, calls the ViewModel's dispose() method on unmount\n * and when dependencies change causing recreation.\n * Default: true (if dispose method exists)\n */\n disposeOnUnmount?: boolean;\n}\n\n/**\n * Result returned by useViewModel when the ViewModel implements IKosViewModelReady.\n */\nexport interface UseViewModelResult<T> {\n /** The ViewModel instance */\n viewModel: T;\n /** Whether the ViewModel's ready() hook has completed */\n ready: boolean;\n /** Error from the ready() hook, if any */\n error: Error | undefined;\n}\n\n/**\n * React hook for creating and managing ViewModel instances.\n *\n * The hook:\n * - Creates the ViewModel using the provided factory function\n * - Calls ready() if the ViewModel implements IKosViewModelReady\n * - Automatically calls dispose() on unmount (if the method exists)\n * - Re-creates the ViewModel when dependencies change\n * - Disposes the previous ViewModel when recreating\n *\n * @param factory - Function that creates the ViewModel instance\n * @param deps - Dependency array (similar to useEffect/useMemo)\n * @param options - Optional configuration\n * @returns UseViewModelResult with viewModel, ready state, and error\n *\n * @example\n * ```tsx\n * const OrderSummary = kosComponent(({ order }: Props) => {\n * const { viewModel: vm, ready, error } = useViewModel(\n * () => new OrderSummaryViewModel(order),\n * [order]\n * );\n * if (error) return <ErrorDisplay error={error} />;\n * if (!ready) return <Loading />;\n * return <div>Total: {vm.total}</div>;\n * });\n * ```\n *\n * @category KOS React Hook\n */\nexport function useViewModel<T>(\n factory: () => T,\n deps: React.DependencyList,\n options: UseViewModelOptions = {}\n): UseViewModelResult<T> {\n const { disposeOnUnmount = true } = options;\n\n // Track ready state and errors\n const [ready, setReady] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n\n // Track the current ViewModel for disposal\n const viewModelRef = useRef<T | null>(null);\n const isFirstRender = useRef(true);\n // Track ready call to prevent duplicate calls\n const readyCalledRef = useRef(false);\n\n // Create ViewModel (memoized based on deps)\n const viewModel = useMemo(() => {\n // Dispose previous instance if deps changed (not on first render)\n if (\n !isFirstRender.current &&\n viewModelRef.current &&\n disposeOnUnmount &&\n isDisposable(viewModelRef.current)\n ) {\n const previous = viewModelRef.current;\n // Run dispose asynchronously to avoid React warnings during render\n Promise.resolve().then(() => {\n if (isDisposable(previous)) {\n previous.dispose();\n }\n });\n }\n\n isFirstRender.current = false;\n // Reset ready state for new instance\n readyCalledRef.current = false;\n\n // Create new instance\n const instance = factory();\n viewModelRef.current = instance;\n return instance;\n }, deps);\n\n // Handle ready() hook\n useEffect(() => {\n // Skip if already called for this instance\n if (readyCalledRef.current) return;\n\n // If ViewModel has ready hook, call it\n if (hasReadyHook(viewModel)) {\n readyCalledRef.current = true;\n setReady(false);\n setError(undefined);\n\n viewModel\n .ready()\n .then(() => {\n setReady(true);\n })\n .catch((err: Error) => {\n setError(err);\n setReady(false);\n });\n } else {\n // No ready hook - immediately ready\n setReady(true);\n setError(undefined);\n }\n }, [viewModel]);\n\n // Handle cleanup on unmount\n useEffect(\n () => () => {\n if (\n disposeOnUnmount &&\n viewModelRef.current &&\n isDisposable(viewModelRef.current)\n ) {\n viewModelRef.current.dispose();\n }\n viewModelRef.current = null;\n },\n [disposeOnUnmount]\n );\n\n return { viewModel, ready, error };\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","import { registerApiLevels } from \"@kosdev-code/kos-api-levels\";\n\n// Registers the package-level API integer for this SDK.\n// The level history (which tag boundaries changed the public surface and why) lives in\n// kos-api-levels/generated/api-archaeology-report.md, produced by the archaeology scanner.\nregisterApiLevels({ \"kos-ui-sdk\": 24 });\n\nexport * from \"./common\";\nexport * from \"./core\";\nexport * from \"./models\";\nexport * from \"./models/models/canvas-renderer\";\nexport * from \"./models/models/gpio-chip\";\nexport * from \"./models/models/gpio-pin\";\nexport * from \"./models/models/kos-expression-evaluator\";\nexport * from \"./models/models/kos-log-manager\";\nexport * from \"./models/models/log-block\";\nexport * from \"./models/models/studio-properties\";\nexport * from \"./ui\";\n"],"names":["subscribe","debounce","buffer","request","publish","kosParentAware","CompanionParentModel","KosContextManager","MultipleFutureContainerSetup","LogConfig","MixinModels","ReferenceConfig","KosFetchMethods","TroubleAwareSetup","DependencyModels","ExtensionManager","SubscriptionHandlers","action","ModelEffects","runInAction","reaction","autorun","StateMachineSetup","DependencyLifecycle","injectStateMachineSupport","initializeStateMachine","makeAutoObservable","ViewModelConfig","KosViewModelSymbol","KosModelVisitor","index","getDaysInMonth","KosCore","sendKosMessageResponse","KosLog","EventBus.subscribe","log","uuid","EventBus.publish","INDEX_RECORD_SYMBOL","INDEX_COLLECTION_KEY","KosContainerIndexEvents","isIndexableItem","Kos","isKosModel","token","ConfigBean","configBeanModelId","formatter","KosConfigPropertySpec","StateBean","StateProp","kosAutoEffect","TranslationContainer","whenReady","KosCoreModelPropertyMapper","CanvasDispatcher","KeyValue","destroyKosModel","REGION_PATH","REGION_ATTRIBUTE","REGION_ID","kosServiceRequest","baseKosServiceRequest","endpoint","serviceRequest","api","createClient","REGION_SETTINGS_PATH","TIMEZONE_ATTRIBUTE","REGION_TIMEZONE_ID","BASE_URL","kosFetch","configResponse","MODEL_TYPE","__publicField","__decorateClass","kosModel","kosLoggerAware","kosContainerAware","kosChild","KOS_SERVICE.kosServiceRequest","KOS_SERVICE.api","API","ObservableData","WebSocketTransport","kosComputed","KosModelRegistrationFactory","keyframes","css","createPortal","message","jsx","jsxs","createContext","useContext","useState","useCallback","filter","useMemo","getKosModelSync","ErrorBoundaryWithFallback","Suspense","useEffect","Fragment","observer","useRef","WebSocketEvents","modelHookCache","useSuspenseData","fetchModel","isUpdateable","KosModelEvents","KosModelState","modelId","clearModelHookCacheEntry","KosTime","SoftwareInfo","KosModelLoader","getQueryParams","getKosLocalizationDescriptor","translations","locale","kosComponent","Device","NetworkInterfaceContainer","Ota","StorageDeviceContainer","TimerManager","TIMER_EVENT","TIMER_END","TOPIC_TIMER_TICK_EVENT","getKosModel","Trouble","TroubleContainer","UsbUpdateContainer","useReducer","format","DateDisplayFormat","nextMonth","nextYear","RegionInfo","parseISO","DEFAULT_FORMAT_MAP","useGesture","date"],"mappings":";;;;;;;;;;;;;AAAA,MAAM,8BAAc,IAAA;AAYb,SAAS,eACd,SACA,WACA,mBACA,aACA,eACM;AACN,MACE,OAAO,YAAY,eACnB,QAAQ,IAAI,UAAU,MAAM,cAC5B;AACA;AAAA,EACF;AACA,MAAI,QAAQ,IAAI,OAAO,EAAG;AAC1B,UAAQ,IAAI,OAAO;AACnB,UAAQ;AAAA,IACN,UAAU,OAAO,yBAAyB,SAAS,UAAU,iBAAiB,UACpE,WAAW,uCAAuC,aAAa;AAAA,EAAA;AAE7E;AC7BA,MAAM,YAAyB,CAAA;AAQxB,SAAS,kBAAkB,QAA2B;AAC3D,SAAO,OAAO,WAAW,MAAM;AACjC;ACKO,SAAS,KACd,WACA,UACY;AACZ,QAAM,eAAeA,UAAAA,UAAU,WAAW,CAAC,QAAY;AAErD,iBAAa,YAAA;AACb,aAAS,GAAG;AAAA,EACd,CAAC;AAED,SAAO,aAAa;AACtB;AAYO,SAAS,QACd,WACA,SACY;AACZ,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI,YAAmC;AAEvC,UAAM,cAAc,KAAK,WAAW,CAAC,QAAY;AAC/C,UAAI,WAAW;AACb,qBAAa,SAAS;AAAA,MACxB;AACA,cAAQ,GAAI;AAAA,I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