@kosdev-code/kos-ui-sdk 0.1.0-dev.5053
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/common/constants/index.d.ts +27 -0
- package/common/constants/index.d.ts.map +1 -0
- package/common/events/async-event-bus.d.ts +96 -0
- package/common/events/async-event-bus.d.ts.map +1 -0
- package/common/events/eventBus.d.ts +77 -0
- package/common/events/eventBus.d.ts.map +1 -0
- package/common/events/eventBus.functional.d.ts +150 -0
- package/common/events/eventBus.functional.d.ts.map +1 -0
- package/common/events/eventBus.state.d.ts +118 -0
- package/common/events/eventBus.state.d.ts.map +1 -0
- package/common/events/index.d.ts +18 -0
- package/common/events/index.d.ts.map +1 -0
- package/common/file-utils.d.ts +9 -0
- package/common/file-utils.d.ts.map +1 -0
- package/common/index.d.ts +4 -0
- package/common/index.d.ts.map +1 -0
- package/common/types/global.d.ts +19 -0
- package/core/core/api/index.d.ts +2 -0
- package/core/core/api/index.d.ts.map +1 -0
- package/core/core/api/wrapPromise.d.ts +14 -0
- package/core/core/api/wrapPromise.d.ts.map +1 -0
- package/core/core/context/index.d.ts +2 -0
- package/core/core/context/index.d.ts.map +1 -0
- package/core/core/context/kos-context-manager.d.ts +31 -0
- package/core/core/context/kos-context-manager.d.ts.map +1 -0
- package/core/core/decorators/index.d.ts +19 -0
- package/core/core/decorators/index.d.ts.map +1 -0
- package/core/core/decorators/kos-child.d.ts +19 -0
- package/core/core/decorators/kos-child.d.ts.map +1 -0
- package/core/core/decorators/kos-companion.d.ts +128 -0
- package/core/core/decorators/kos-companion.d.ts.map +1 -0
- package/core/core/decorators/kos-container-aware.d.ts +465 -0
- package/core/core/decorators/kos-container-aware.d.ts.map +1 -0
- package/core/core/decorators/kos-context.d.ts +2 -0
- package/core/core/decorators/kos-context.d.ts.map +1 -0
- package/core/core/decorators/kos-future-aware.d.ts +150 -0
- package/core/core/decorators/kos-future-aware.d.ts.map +1 -0
- package/core/core/decorators/kos-http-decorators.d.ts +110 -0
- package/core/core/decorators/kos-http-decorators.d.ts.map +1 -0
- package/core/core/decorators/kos-log.d.ts +11 -0
- package/core/core/decorators/kos-log.d.ts.map +1 -0
- package/core/core/decorators/kos-logger-aware.d.ts +96 -0
- package/core/core/decorators/kos-logger-aware.d.ts.map +1 -0
- package/core/core/decorators/kos-model-effect.d.ts +28 -0
- package/core/core/decorators/kos-model-effect.d.ts.map +1 -0
- package/core/core/decorators/kos-multiple-future-aware.d.ts +193 -0
- package/core/core/decorators/kos-multiple-future-aware.d.ts.map +1 -0
- package/core/core/decorators/kos-parent.d.ts +11 -0
- package/core/core/decorators/kos-parent.d.ts.map +1 -0
- package/core/core/decorators/kos-reference.d.ts +6 -0
- package/core/core/decorators/kos-reference.d.ts.map +1 -0
- package/core/core/decorators/kos-topic-handler-flow-control.d.ts +130 -0
- package/core/core/decorators/kos-topic-handler-flow-control.d.ts.map +1 -0
- package/core/core/decorators/kos-trouble-aware.d.ts +71 -0
- package/core/core/decorators/kos-trouble-aware.d.ts.map +1 -0
- package/core/core/decorators/kosDependency.d.ts +16 -0
- package/core/core/decorators/kosDependency.d.ts.map +1 -0
- package/core/core/decorators/kosModel.d.ts +16 -0
- package/core/core/decorators/kosModel.d.ts.map +1 -0
- package/core/core/decorators/kosSubscribe.d.ts +9 -0
- package/core/core/decorators/kosSubscribe.d.ts.map +1 -0
- package/core/core/decorators/kosTopicHandler.d.ts +220 -0
- package/core/core/decorators/kosTopicHandler.d.ts.map +1 -0
- package/core/core/decorators/propKeys.d.ts +20 -0
- package/core/core/decorators/propKeys.d.ts.map +1 -0
- package/core/core/decorators/resolve-parameters.d.ts +8 -0
- package/core/core/decorators/resolve-parameters.d.ts.map +1 -0
- package/core/core/dependency-manager.d.ts +9 -0
- package/core/core/dependency-manager.d.ts.map +1 -0
- package/core/core/extension/extension-manager.d.ts +45 -0
- package/core/core/extension/extension-manager.d.ts.map +1 -0
- package/core/core/extension/index.d.ts +4 -0
- package/core/core/extension/index.d.ts.map +1 -0
- package/core/core/extension/initialize-extension.d.ts +45 -0
- package/core/core/extension/initialize-extension.d.ts.map +1 -0
- package/core/core/extension/plugin-extension-manager.d.ts +23 -0
- package/core/core/extension/plugin-extension-manager.d.ts.map +1 -0
- package/core/core/kos-container-index.d.ts +34 -0
- package/core/core/kos-container-index.d.ts.map +1 -0
- package/core/core/kos-container-model.d.ts +77 -0
- package/core/core/kos-container-model.d.ts.map +1 -0
- package/core/core/kos-data-container.d.ts +54 -0
- package/core/core/kos-data-container.d.ts.map +1 -0
- package/core/core/kos-deletion-manager.d.ts +5 -0
- package/core/core/kos-deletion-manager.d.ts.map +1 -0
- package/core/core/kos-model-factory.d.ts +19 -0
- package/core/core/kos-model-factory.d.ts.map +1 -0
- package/core/core/kos-registration.d.ts +26 -0
- package/core/core/kos-registration.d.ts.map +1 -0
- package/core/core/kos-singleton-registration.d.ts +25 -0
- package/core/core/kos-singleton-registration.d.ts.map +1 -0
- package/core/core/kosCore.d.ts +80 -0
- package/core/core/kosCore.d.ts.map +1 -0
- package/core/core/kosModel.d.ts +155 -0
- package/core/core/kosModel.d.ts.map +1 -0
- package/core/core/kosModelManager.d.ts +207 -0
- package/core/core/kosModelManager.d.ts.map +1 -0
- package/core/core/lifecycle/constants.d.ts +37 -0
- package/core/core/lifecycle/constants.d.ts.map +1 -0
- package/core/core/lifecycle/index.d.ts +2 -0
- package/core/core/lifecycle/index.d.ts.map +1 -0
- package/core/core/lifecycle/kosCoreLifecycle.d.ts +86 -0
- package/core/core/lifecycle/kosCoreLifecycle.d.ts.map +1 -0
- package/core/core/lifecycle/kosModelLifecycle.d.ts +57 -0
- package/core/core/lifecycle/kosModelLifecycle.d.ts.map +1 -0
- package/core/core/lifecycle/model-active-machine.d.ts +31 -0
- package/core/core/lifecycle/model-active-machine.d.ts.map +1 -0
- package/core/core/lifecycle/model-machine.d.ts +28 -0
- package/core/core/lifecycle/model-machine.d.ts.map +1 -0
- package/core/core/lifecycle/model-online-machine.d.ts +19 -0
- package/core/core/lifecycle/model-online-machine.d.ts.map +1 -0
- package/core/core/log/index.d.ts +2 -0
- package/core/core/log/index.d.ts.map +1 -0
- package/core/core/log/log.d.ts +36 -0
- package/core/core/log/log.d.ts.map +1 -0
- package/core/core/model/apply-kos-dev-tool-support.d.ts +2 -0
- package/core/core/model/apply-kos-dev-tool-support.d.ts.map +1 -0
- package/core/core/model/kos-child-resolver.d.ts +10 -0
- package/core/core/model/kos-child-resolver.d.ts.map +1 -0
- package/core/core/model/kos-companion-model-manager.d.ts +14 -0
- package/core/core/model/kos-companion-model-manager.d.ts.map +1 -0
- package/core/core/model/kos-effects-manager.d.ts +14 -0
- package/core/core/model/kos-effects-manager.d.ts.map +1 -0
- package/core/core/model/kos-fsm-manager.d.ts +24 -0
- package/core/core/model/kos-fsm-manager.d.ts.map +1 -0
- package/core/core/model/kos-http-route-manager.d.ts +85 -0
- package/core/core/model/kos-http-route-manager.d.ts.map +1 -0
- package/core/core/model/kos-logger-factory.d.ts +9 -0
- package/core/core/model/kos-logger-factory.d.ts.map +1 -0
- package/core/core/model/kos-model-component-factory.d.ts +25 -0
- package/core/core/model/kos-model-component-factory.d.ts.map +1 -0
- package/core/core/model/kos-offline-queue.d.ts +17 -0
- package/core/core/model/kos-offline-queue.d.ts.map +1 -0
- package/core/core/model/kos-online-lifecycle-manager.d.ts +12 -0
- package/core/core/model/kos-online-lifecycle-manager.d.ts.map +1 -0
- package/core/core/model/kos-subscription-manager.d.ts +31 -0
- package/core/core/model/kos-subscription-manager.d.ts.map +1 -0
- package/core/core/model/logger-utils.d.ts +9 -0
- package/core/core/model/logger-utils.d.ts.map +1 -0
- package/core/core/model/model-introspection-utils.d.ts +6 -0
- package/core/core/model/model-introspection-utils.d.ts.map +1 -0
- package/core/core/model-cache.d.ts +28 -0
- package/core/core/model-cache.d.ts.map +1 -0
- package/core/core/model-instantiator.d.ts +15 -0
- package/core/core/model-instantiator.d.ts.map +1 -0
- package/core/core/model-registry.d.ts +16 -0
- package/core/core/model-registry.d.ts.map +1 -0
- package/core/core/models/index.d.ts +2 -0
- package/core/core/models/index.d.ts.map +1 -0
- package/core/core/models/kos-core/index.d.ts +12 -0
- package/core/core/models/kos-core/index.d.ts.map +1 -0
- package/core/core/models/kos-token/index.d.ts +11 -0
- package/core/core/models/kos-token/index.d.ts.map +1 -0
- package/core/core/registration/base-kos-model-registration.d.ts +10 -0
- package/core/core/registration/base-kos-model-registration.d.ts.map +1 -0
- package/core/core/registration/index.d.ts +5 -0
- package/core/core/registration/index.d.ts.map +1 -0
- package/core/core/registration/model-registration.d.ts +45 -0
- package/core/core/registration/model-registration.d.ts.map +1 -0
- package/core/core/registration/registration-manager.d.ts +41 -0
- package/core/core/registration/registration-manager.d.ts.map +1 -0
- package/core/core/registration/singleton-kos-model-registration-factory.d.ts +10 -0
- package/core/core/registration/singleton-kos-model-registration-factory.d.ts.map +1 -0
- package/core/core/services/app-startup-service.d.ts +74 -0
- package/core/core/services/app-startup-service.d.ts.map +1 -0
- package/core/core/services/browser-router.d.ts +66 -0
- package/core/core/services/browser-router.d.ts.map +1 -0
- package/core/core/services/index.d.ts +5 -0
- package/core/core/services/index.d.ts.map +1 -0
- package/core/core/services/intent-service.d.ts +55 -0
- package/core/core/services/intent-service.d.ts.map +1 -0
- package/core/core/transport/base-message-transport.d.ts +53 -0
- package/core/core/transport/base-message-transport.d.ts.map +1 -0
- package/core/core/transport/bridge-message-transport.d.ts +7 -0
- package/core/core/transport/bridge-message-transport.d.ts.map +1 -0
- package/core/core/transport/bridge-transport.d.ts +29 -0
- package/core/core/transport/bridge-transport.d.ts.map +1 -0
- package/core/core/transport/detect-wakeup.d.ts +2 -0
- package/core/core/transport/detect-wakeup.d.ts.map +1 -0
- package/core/core/transport/fos-message-transport.d.ts +7 -0
- package/core/core/transport/fos-message-transport.d.ts.map +1 -0
- package/core/core/transport/index.d.ts +3 -0
- package/core/core/transport/index.d.ts.map +1 -0
- package/core/core/transport/kos-message-transport.d.ts +7 -0
- package/core/core/transport/kos-message-transport.d.ts.map +1 -0
- package/core/core/transport/transport-factory.d.ts +27 -0
- package/core/core/transport/transport-factory.d.ts.map +1 -0
- package/core/core/transport/transport.d.ts +12 -0
- package/core/core/transport/transport.d.ts.map +1 -0
- package/core/core/transport/web-socket-transport-adapter.d.ts +6 -0
- package/core/core/transport/web-socket-transport-adapter.d.ts.map +1 -0
- package/core/core/transport/webSocketTransport.d.ts +84 -0
- package/core/core/transport/webSocketTransport.d.ts.map +1 -0
- package/core/core/types/index.d.ts +4 -0
- package/core/core/types/index.d.ts.map +1 -0
- package/core/core/types/kos-model-manager-types.d.ts +33 -0
- package/core/core/types/kos-model-manager-types.d.ts.map +1 -0
- package/core/core/types/model.d.ts +26 -0
- package/core/core/types/model.d.ts.map +1 -0
- package/core/core/types/registration.d.ts +54 -0
- package/core/core/types/registration.d.ts.map +1 -0
- package/core/core/types/serviceTypes.d.ts +9 -0
- package/core/core/types/serviceTypes.d.ts.map +1 -0
- package/core/index.d.ts +61 -0
- package/core/index.d.ts.map +1 -0
- package/core/lib/kos-ui-core.d.ts +2 -0
- package/core/lib/kos-ui-core.d.ts.map +1 -0
- package/core/mocks/browser.d.ts +3 -0
- package/core/mocks/browser.d.ts.map +1 -0
- package/core/mocks/handlers.d.ts +3 -0
- package/core/mocks/handlers.d.ts.map +1 -0
- package/core/mocks/server.d.ts +3 -0
- package/core/mocks/server.d.ts.map +1 -0
- package/core/types/global.d.ts +68 -0
- package/core/types/index.d.ts +4 -0
- package/core/types/index.d.ts.map +1 -0
- package/core/types/kos-dependency.d.ts +21 -0
- package/core/types/kos-dependency.d.ts.map +1 -0
- package/core/types/model.d.ts +100 -0
- package/core/types/model.d.ts.map +1 -0
- package/core/types/utils/kos-fetch.d.ts +134 -0
- package/core/types/utils/kos-fetch.d.ts.map +1 -0
- package/core/util/api-request-id.d.ts +2 -0
- package/core/util/api-request-id.d.ts.map +1 -0
- package/core/util/apply-mixins.d.ts +2 -0
- package/core/util/apply-mixins.d.ts.map +1 -0
- package/core/util/array-utils.d.ts +2 -0
- package/core/util/array-utils.d.ts.map +1 -0
- package/core/util/await-first-matching-when.d.ts +5 -0
- package/core/util/await-first-matching-when.d.ts.map +1 -0
- package/core/util/binary-utils.d.ts +44 -0
- package/core/util/binary-utils.d.ts.map +1 -0
- package/core/util/container-utils.d.ts +119 -0
- package/core/util/container-utils.d.ts.map +1 -0
- package/core/util/cycle-detection.d.ts +12 -0
- package/core/util/cycle-detection.d.ts.map +1 -0
- package/core/util/date-utils.d.ts +104 -0
- package/core/util/date-utils.d.ts.map +1 -0
- package/core/util/debounce.d.ts +19 -0
- package/core/util/debounce.d.ts.map +1 -0
- package/core/util/feature-flags.d.ts +16 -0
- package/core/util/feature-flags.d.ts.map +1 -0
- package/core/util/get-query-params.d.ts +2 -0
- package/core/util/get-query-params.d.ts.map +1 -0
- package/core/util/hsl-to-hex.d.ts +5 -0
- package/core/util/hsl-to-hex.d.ts.map +1 -0
- package/core/util/index.d.ts +32 -0
- package/core/util/index.d.ts.map +1 -0
- package/core/util/kos-config-init.d.ts +15 -0
- package/core/util/kos-config-init.d.ts.map +1 -0
- package/core/util/kos-core-utils.d.ts +4 -0
- package/core/util/kos-core-utils.d.ts.map +1 -0
- package/core/util/kos-data-mapper-utils.d.ts +14 -0
- package/core/util/kos-data-mapper-utils.d.ts.map +1 -0
- package/core/util/kos-fetch.d.ts +18 -0
- package/core/util/kos-fetch.d.ts.map +1 -0
- package/core/util/kos-message-utils.d.ts +34 -0
- package/core/util/kos-message-utils.d.ts.map +1 -0
- package/core/util/kos-model-formatter.d.ts +21 -0
- package/core/util/kos-model-formatter.d.ts.map +1 -0
- package/core/util/kos-model-utils.d.ts +101 -0
- package/core/util/kos-model-utils.d.ts.map +1 -0
- package/core/util/kos-model-visitor.d.ts +41 -0
- package/core/util/kos-model-visitor.d.ts.map +1 -0
- package/core/util/kos-service-request.d.ts +65 -0
- package/core/util/kos-service-request.d.ts.map +1 -0
- package/core/util/log-utils.d.ts +6 -0
- package/core/util/log-utils.d.ts.map +1 -0
- package/core/util/logger-plugin.d.ts +2 -0
- package/core/util/logger-plugin.d.ts.map +1 -0
- package/core/util/middleware.d.ts +14 -0
- package/core/util/middleware.d.ts.map +1 -0
- package/core/util/model-attribute-utils.d.ts +37 -0
- package/core/util/model-attribute-utils.d.ts.map +1 -0
- package/core/util/model-factory.d.ts +5 -0
- package/core/util/model-factory.d.ts.map +1 -0
- package/core/util/model-registration-utils.d.ts +6 -0
- package/core/util/model-registration-utils.d.ts.map +1 -0
- package/core/util/model-utils.d.ts +45 -0
- package/core/util/model-utils.d.ts.map +1 -0
- package/core/util/observable-proxy-map.d.ts +10 -0
- package/core/util/observable-proxy-map.d.ts.map +1 -0
- package/core/util/paired-client-heartbeat.d.ts +18 -0
- package/core/util/paired-client-heartbeat.d.ts.map +1 -0
- package/core/util/pipe.d.ts +4 -0
- package/core/util/pipe.d.ts.map +1 -0
- package/core/util/reference-cache.d.ts +17 -0
- package/core/util/reference-cache.d.ts.map +1 -0
- package/core/util/retry-with-exponential-backoff.d.ts +18 -0
- package/core/util/retry-with-exponential-backoff.d.ts.map +1 -0
- package/core/util/service-factory.d.ts +177 -0
- package/core/util/service-factory.d.ts.map +1 -0
- package/core/util/session-utils.d.ts +3 -0
- package/core/util/session-utils.d.ts.map +1 -0
- package/core/util/setRandomInterval.d.ts +5 -0
- package/core/util/setRandomInterval.d.ts.map +1 -0
- package/core/util/wait-for-request.d.ts +15 -0
- package/core/util/wait-for-request.d.ts.map +1 -0
- package/core/util/when-ready.d.ts +21 -0
- package/core/util/when-ready.d.ts.map +1 -0
- package/index.cjs +198 -0
- package/index.cjs.map +1 -0
- package/index.d.cts +10 -0
- package/index.d.ts +10 -0
- package/index.d.ts.map +1 -0
- package/index.js +17032 -0
- package/index.js.map +1 -0
- package/models/constants/index.d.ts +18 -0
- package/models/constants/index.d.ts.map +1 -0
- package/models/decorators/future-service.d.ts +14 -0
- package/models/decorators/future-service.d.ts.map +1 -0
- package/models/decorators/index.d.ts +6 -0
- package/models/decorators/index.d.ts.map +1 -0
- package/models/decorators/kos-config-bean-prop.d.ts +42 -0
- package/models/decorators/kos-config-bean-prop.d.ts.map +1 -0
- package/models/decorators/kos-config-bean.d.ts +8 -0
- package/models/decorators/kos-config-bean.d.ts.map +1 -0
- package/models/decorators/kos-state-bean.d.ts +6 -0
- package/models/decorators/kos-state-bean.d.ts.map +1 -0
- package/models/decorators/kos-state-prop.d.ts +10 -0
- package/models/decorators/kos-state-prop.d.ts.map +1 -0
- package/models/index.d.ts +13 -0
- package/models/index.d.ts.map +1 -0
- package/models/model.d.ts +7 -0
- package/models/models/browser-router/browser-router-model.d.ts +116 -0
- package/models/models/browser-router/browser-router-model.d.ts.map +1 -0
- package/models/models/browser-router/browser-router-registration.d.ts +89 -0
- package/models/models/browser-router/browser-router-registration.d.ts.map +1 -0
- package/models/models/browser-router/index.d.ts +4 -0
- package/models/models/browser-router/index.d.ts.map +1 -0
- package/models/models/browser-router/types/index.d.ts +25 -0
- package/models/models/browser-router/utils/index.d.ts +2 -0
- package/models/models/browser-router/utils/index.d.ts.map +1 -0
- package/models/models/browser-router/utils/init-kos-browser-router.d.ts +2 -0
- package/models/models/browser-router/utils/init-kos-browser-router.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/canvas-dispatcher-model.d.ts +29 -0
- package/models/models/canvas-dispatcher/canvas-dispatcher-model.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/canvas-dispatcher-registration.d.ts +89 -0
- package/models/models/canvas-dispatcher/canvas-dispatcher-registration.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/index.d.ts +5 -0
- package/models/models/canvas-dispatcher/index.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/services/canvas-dispatcher-services.d.ts +8 -0
- package/models/models/canvas-dispatcher/services/canvas-dispatcher-services.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/services/index.d.ts +2 -0
- package/models/models/canvas-dispatcher/services/index.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/types/index.d.ts +192 -0
- package/models/models/canvas-dispatcher/utils/color-utils.d.ts +34 -0
- package/models/models/canvas-dispatcher/utils/color-utils.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/encode-frame.d.ts +14 -0
- package/models/models/canvas-dispatcher/utils/encode-frame.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/base/canvas-2d-renderer.d.ts +37 -0
- package/models/models/canvas-dispatcher/utils/renderers/base/canvas-2d-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/base/gradient-base-renderer.d.ts +2 -0
- package/models/models/canvas-dispatcher/utils/renderers/base/gradient-base-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/base/video-base-renderer.d.ts +71 -0
- package/models/models/canvas-dispatcher/utils/renderers/base/video-base-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/base/webgl-base-renderer.d.ts +51 -0
- package/models/models/canvas-dispatcher/utils/renderers/base/webgl-base-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/drop-renderer.d.ts +60 -0
- package/models/models/canvas-dispatcher/utils/renderers/drop-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/gradient-renderer.d.ts +22 -0
- package/models/models/canvas-dispatcher/utils/renderers/gradient-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/image-renderer.d.ts +15 -0
- package/models/models/canvas-dispatcher/utils/renderers/image-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/looping-video-renderer.d.ts +30 -0
- package/models/models/canvas-dispatcher/utils/renderers/looping-video-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/matrix-renderer.d.ts +44 -0
- package/models/models/canvas-dispatcher/utils/renderers/matrix-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/mixins/one-shot-renderer-mixin.d.ts +5 -0
- package/models/models/canvas-dispatcher/utils/renderers/mixins/one-shot-renderer-mixin.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/overlay-renderer.d.ts +76 -0
- package/models/models/canvas-dispatcher/utils/renderers/overlay-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/renderer-factory.d.ts +25 -0
- package/models/models/canvas-dispatcher/utils/renderers/renderer-factory.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/scrolling-image-renderer.d.ts +46 -0
- package/models/models/canvas-dispatcher/utils/renderers/scrolling-image-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/scrolling-text-renderer.d.ts +56 -0
- package/models/models/canvas-dispatcher/utils/renderers/scrolling-text-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/sequence-renderer.d.ts +46 -0
- package/models/models/canvas-dispatcher/utils/renderers/sequence-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/solid-color-renderer.d.ts +21 -0
- package/models/models/canvas-dispatcher/utils/renderers/solid-color-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/sweep-renderer.d.ts +52 -0
- package/models/models/canvas-dispatcher/utils/renderers/sweep-renderer.d.ts.map +1 -0
- package/models/models/canvas-dispatcher/utils/renderers/swirl-renderer.d.ts +13 -0
- package/models/models/canvas-dispatcher/utils/renderers/swirl-renderer.d.ts.map +1 -0
- package/models/models/canvas-renderer/canvas-renderer-model.d.ts +49 -0
- package/models/models/canvas-renderer/canvas-renderer-model.d.ts.map +1 -0
- package/models/models/canvas-renderer/canvas-renderer-registration.d.ts +87 -0
- package/models/models/canvas-renderer/canvas-renderer-registration.d.ts.map +1 -0
- package/models/models/canvas-renderer/index.d.ts +4 -0
- package/models/models/canvas-renderer/index.d.ts.map +1 -0
- package/models/models/canvas-renderer/types/index.d.ts +8 -0
- package/models/models/config-bean/config-bean-model-builder.d.ts +59 -0
- package/models/models/config-bean/config-bean-model-builder.d.ts.map +1 -0
- package/models/models/config-bean/config-bean-model.d.ts +179 -0
- package/models/models/config-bean/config-bean-model.d.ts.map +1 -0
- package/models/models/config-bean/config-bean-types.d.ts +69 -0
- package/models/models/config-bean/config-bean-types.d.ts.map +1 -0
- package/models/models/config-bean/index.d.ts +4 -0
- package/models/models/config-bean/index.d.ts.map +1 -0
- package/models/models/config-bean/types/index.d.ts +33 -0
- package/models/models/config-bean-prop/config-bean-prop-model.d.ts +197 -0
- package/models/models/config-bean-prop/config-bean-prop-model.d.ts.map +1 -0
- package/models/models/config-bean-prop/config-options-factory.d.ts +6 -0
- package/models/models/config-bean-prop/config-options-factory.d.ts.map +1 -0
- package/models/models/config-bean-prop/index.d.ts +3 -0
- package/models/models/config-bean-prop/index.d.ts.map +1 -0
- package/models/models/config-bean-prop/types/index.d.ts +352 -0
- package/models/models/device/device-model.d.ts +258 -0
- package/models/models/device/device-model.d.ts.map +1 -0
- package/models/models/device/device-registration.d.ts +102 -0
- package/models/models/device/device-registration.d.ts.map +1 -0
- package/models/models/device/index.d.ts +5 -0
- package/models/models/device/index.d.ts.map +1 -0
- package/models/models/device/services/device-services.d.ts +21 -0
- package/models/models/device/services/device-services.d.ts.map +1 -0
- package/models/models/device/services/index.d.ts +2 -0
- package/models/models/device/services/index.d.ts.map +1 -0
- package/models/models/device/types/index.d.ts +46 -0
- package/models/models/future/future-aware.d.ts +115 -0
- package/models/models/future/future-aware.d.ts.map +1 -0
- package/models/models/future/future-factory.d.ts +5 -0
- package/models/models/future/future-factory.d.ts.map +1 -0
- package/models/models/future/future-model-builder.d.ts +76 -0
- package/models/models/future/future-model-builder.d.ts.map +1 -0
- package/models/models/future/future-model.d.ts +95 -0
- package/models/models/future/future-model.d.ts.map +1 -0
- package/models/models/future/future-types.d.ts +265 -0
- package/models/models/future/future-types.d.ts.map +1 -0
- package/models/models/future/index.d.ts +6 -0
- package/models/models/future/index.d.ts.map +1 -0
- package/models/models/future-container/future-container-factory.d.ts +5 -0
- package/models/models/future-container/future-container-factory.d.ts.map +1 -0
- package/models/models/future-container/future-container-model.d.ts +124 -0
- package/models/models/future-container/future-container-model.d.ts.map +1 -0
- package/models/models/future-container/future-container-types.d.ts +109 -0
- package/models/models/future-container/future-container-types.d.ts.map +1 -0
- package/models/models/future-container/index.d.ts +4 -0
- package/models/models/future-container/index.d.ts.map +1 -0
- package/models/models/index.d.ts +22 -0
- package/models/models/index.d.ts.map +1 -0
- package/models/models/key-value/index.d.ts +9 -0
- package/models/models/key-value/index.d.ts.map +1 -0
- package/models/models/key-value/key-value-model.d.ts +130 -0
- package/models/models/key-value/key-value-model.d.ts.map +1 -0
- package/models/models/key-value/key-value-registration.d.ts +89 -0
- package/models/models/key-value/key-value-registration.d.ts.map +1 -0
- package/models/models/key-value/services/index.d.ts +2 -0
- package/models/models/key-value/services/index.d.ts.map +1 -0
- package/models/models/key-value/services/key-value-services.d.ts +140 -0
- package/models/models/key-value/services/key-value-services.d.ts.map +1 -0
- package/models/models/key-value/types/index.d.ts +59 -0
- package/models/models/kos-core/index.d.ts +11 -0
- package/models/models/kos-core/index.d.ts.map +1 -0
- package/models/models/kos-expression-evaluator/index.d.ts +4 -0
- package/models/models/kos-expression-evaluator/index.d.ts.map +1 -0
- package/models/models/kos-expression-evaluator/kos-expression-evaluator-model.d.ts +209 -0
- package/models/models/kos-expression-evaluator/kos-expression-evaluator-model.d.ts.map +1 -0
- package/models/models/kos-expression-evaluator/services/index.d.ts +6 -0
- package/models/models/kos-expression-evaluator/services/index.d.ts.map +1 -0
- package/models/models/kos-expression-evaluator/services/kos-expression-evaluator-services.d.ts +15 -0
- package/models/models/kos-expression-evaluator/services/kos-expression-evaluator-services.d.ts.map +1 -0
- package/models/models/kos-expression-evaluator/types/index.d.ts +1 -0
- package/models/models/kos-log-manager/index.d.ts +5 -0
- package/models/models/kos-log-manager/index.d.ts.map +1 -0
- package/models/models/kos-log-manager/kos-log-manager-model.d.ts +139 -0
- package/models/models/kos-log-manager/kos-log-manager-model.d.ts.map +1 -0
- package/models/models/kos-log-manager/kos-log-manager-registration.d.ts +92 -0
- package/models/models/kos-log-manager/kos-log-manager-registration.d.ts.map +1 -0
- package/models/models/kos-log-manager/services/index.d.ts +2 -0
- package/models/models/kos-log-manager/services/index.d.ts.map +1 -0
- package/models/models/kos-log-manager/services/kos-log-manager-services.d.ts +12 -0
- package/models/models/kos-log-manager/services/kos-log-manager-services.d.ts.map +1 -0
- package/models/models/kos-log-manager/types/index.d.ts +201 -0
- package/models/models/kos-time/index.d.ts +5 -0
- package/models/models/kos-time/index.d.ts.map +1 -0
- package/models/models/kos-time/kos-time-model.d.ts +100 -0
- package/models/models/kos-time/kos-time-model.d.ts.map +1 -0
- package/models/models/kos-time/kos-time-registration.d.ts +87 -0
- package/models/models/kos-time/kos-time-registration.d.ts.map +1 -0
- package/models/models/kos-time/services/index.d.ts +2 -0
- package/models/models/kos-time/services/index.d.ts.map +1 -0
- package/models/models/kos-time/services/kos-time-services.d.ts +16 -0
- package/models/models/kos-time/services/kos-time-services.d.ts.map +1 -0
- package/models/models/kos-time/types/index.d.ts +93 -0
- package/models/models/kos-token/index.d.ts +11 -0
- package/models/models/kos-token/index.d.ts.map +1 -0
- package/models/models/log-block/index.d.ts +6 -0
- package/models/models/log-block/index.d.ts.map +1 -0
- package/models/models/log-block/log-block-container-model.d.ts +155 -0
- package/models/models/log-block/log-block-container-model.d.ts.map +1 -0
- package/models/models/log-block/log-block-container-registration.d.ts +87 -0
- package/models/models/log-block/log-block-container-registration.d.ts.map +1 -0
- package/models/models/log-block/log-block-model.d.ts +213 -0
- package/models/models/log-block/log-block-model.d.ts.map +1 -0
- package/models/models/log-block/log-block-registration.d.ts +87 -0
- package/models/models/log-block/log-block-registration.d.ts.map +1 -0
- package/models/models/log-block/types/index.d.ts +167 -0
- package/models/models/log-stream/index.d.ts +11 -0
- package/models/models/log-stream/index.d.ts.map +1 -0
- package/models/models/log-stream/log-stream-container-model.d.ts +97 -0
- package/models/models/log-stream/log-stream-container-model.d.ts.map +1 -0
- package/models/models/log-stream/log-stream-container-registration.d.ts +87 -0
- package/models/models/log-stream/log-stream-container-registration.d.ts.map +1 -0
- package/models/models/log-stream/log-stream-model.d.ts +93 -0
- package/models/models/log-stream/log-stream-model.d.ts.map +1 -0
- package/models/models/log-stream/log-stream-registration.d.ts +87 -0
- package/models/models/log-stream/log-stream-registration.d.ts.map +1 -0
- package/models/models/log-stream/services/index.d.ts +2 -0
- package/models/models/log-stream/services/index.d.ts.map +1 -0
- package/models/models/log-stream/services/log-stream-services.d.ts +23 -0
- package/models/models/log-stream/services/log-stream-services.d.ts.map +1 -0
- package/models/models/log-stream/types/index.d.ts +86 -0
- package/models/models/network-interface/index.d.ts +11 -0
- package/models/models/network-interface/index.d.ts.map +1 -0
- package/models/models/network-interface/network-interface-container-model.d.ts +83 -0
- package/models/models/network-interface/network-interface-container-model.d.ts.map +1 -0
- package/models/models/network-interface/network-interface-container-registration.d.ts +87 -0
- package/models/models/network-interface/network-interface-container-registration.d.ts.map +1 -0
- package/models/models/network-interface/network-interface-model.d.ts +102 -0
- package/models/models/network-interface/network-interface-model.d.ts.map +1 -0
- package/models/models/network-interface/network-interface-registration.d.ts +87 -0
- package/models/models/network-interface/network-interface-registration.d.ts.map +1 -0
- package/models/models/network-interface/services/index.d.ts +2 -0
- package/models/models/network-interface/services/index.d.ts.map +1 -0
- package/models/models/network-interface/services/network-interface-services.d.ts +100 -0
- package/models/models/network-interface/services/network-interface-services.d.ts.map +1 -0
- package/models/models/network-interface/types/index.d.ts +31 -0
- package/models/models/ota/index.d.ts +4 -0
- package/models/models/ota/index.d.ts.map +1 -0
- package/models/models/ota/ota-model.d.ts +105 -0
- package/models/models/ota/ota-model.d.ts.map +1 -0
- package/models/models/ota/ota-registration.d.ts +89 -0
- package/models/models/ota/ota-registration.d.ts.map +1 -0
- package/models/models/ota/services/index.d.ts +2 -0
- package/models/models/ota/services/index.d.ts.map +1 -0
- package/models/models/ota/services/ota-services.d.ts +8 -0
- package/models/models/ota/services/ota-services.d.ts.map +1 -0
- package/models/models/ota/types/index.d.ts +202 -0
- package/models/models/region-info/index.d.ts +5 -0
- package/models/models/region-info/index.d.ts.map +1 -0
- package/models/models/region-info/region-info-model.d.ts +99 -0
- package/models/models/region-info/region-info-model.d.ts.map +1 -0
- package/models/models/region-info/services/index.d.ts +2 -0
- package/models/models/region-info/services/index.d.ts.map +1 -0
- package/models/models/region-info/services/region-info-services.d.ts +48 -0
- package/models/models/region-info/services/region-info-services.d.ts.map +1 -0
- package/models/models/region-info/types/index.d.ts +296 -0
- package/models/models/region-info/types/index.d.ts.map +1 -0
- package/models/models/region-info/utils/unit-system-utils.d.ts +4 -0
- package/models/models/region-info/utils/unit-system-utils.d.ts.map +1 -0
- package/models/models/software-info/index.d.ts +4 -0
- package/models/models/software-info/index.d.ts.map +1 -0
- package/models/models/software-info/services/index.d.ts +2 -0
- package/models/models/software-info/services/index.d.ts.map +1 -0
- package/models/models/software-info/services/software-info-services.d.ts +44 -0
- package/models/models/software-info/services/software-info-services.d.ts.map +1 -0
- package/models/models/software-info/software-info-model.d.ts +86 -0
- package/models/models/software-info/software-info-model.d.ts.map +1 -0
- package/models/models/software-info/software-info-registration.d.ts +84 -0
- package/models/models/software-info/software-info-registration.d.ts.map +1 -0
- package/models/models/software-info/types/index.d.ts +67 -0
- package/models/models/state-bean/index.d.ts +4 -0
- package/models/models/state-bean/index.d.ts.map +1 -0
- package/models/models/state-bean/services/index.d.ts +2 -0
- package/models/models/state-bean/services/index.d.ts.map +1 -0
- package/models/models/state-bean/services/state-bean-services.d.ts +14 -0
- package/models/models/state-bean/services/state-bean-services.d.ts.map +1 -0
- package/models/models/state-bean/state-bean-model.d.ts +106 -0
- package/models/models/state-bean/state-bean-model.d.ts.map +1 -0
- package/models/models/state-bean/state-bean-registration.d.ts +84 -0
- package/models/models/state-bean/state-bean-registration.d.ts.map +1 -0
- package/models/models/state-bean/types/index.d.ts +132 -0
- package/models/models/state-prop/index.d.ts +4 -0
- package/models/models/state-prop/index.d.ts.map +1 -0
- package/models/models/state-prop/services/index.d.ts +2 -0
- package/models/models/state-prop/services/index.d.ts.map +1 -0
- package/models/models/state-prop/services/state-prop-services.d.ts +11 -0
- package/models/models/state-prop/services/state-prop-services.d.ts.map +1 -0
- package/models/models/state-prop/state-prop-model.d.ts +96 -0
- package/models/models/state-prop/state-prop-model.d.ts.map +1 -0
- package/models/models/state-prop/state-prop-registration.d.ts +84 -0
- package/models/models/state-prop/state-prop-registration.d.ts.map +1 -0
- package/models/models/state-prop/types/index.d.ts +68 -0
- package/models/models/storage-device/index.d.ts +7 -0
- package/models/models/storage-device/index.d.ts.map +1 -0
- package/models/models/storage-device/services/index.d.ts +2 -0
- package/models/models/storage-device/services/index.d.ts.map +1 -0
- package/models/models/storage-device/services/storage-device-services.d.ts +23 -0
- package/models/models/storage-device/services/storage-device-services.d.ts.map +1 -0
- package/models/models/storage-device/storage-device-container-model.d.ts +318 -0
- package/models/models/storage-device/storage-device-container-model.d.ts.map +1 -0
- package/models/models/storage-device/storage-device-container-registration.d.ts +86 -0
- package/models/models/storage-device/storage-device-container-registration.d.ts.map +1 -0
- package/models/models/storage-device/storage-device-model.d.ts +109 -0
- package/models/models/storage-device/storage-device-model.d.ts.map +1 -0
- package/models/models/storage-device/storage-device-registration.d.ts +87 -0
- package/models/models/storage-device/storage-device-registration.d.ts.map +1 -0
- package/models/models/storage-device/types/index.d.ts +132 -0
- package/models/models/studio-properties/index.d.ts +5 -0
- package/models/models/studio-properties/index.d.ts.map +1 -0
- package/models/models/studio-properties/services/index.d.ts +2 -0
- package/models/models/studio-properties/services/index.d.ts.map +1 -0
- package/models/models/studio-properties/services/studio-properties-services.d.ts +15 -0
- package/models/models/studio-properties/services/studio-properties-services.d.ts.map +1 -0
- package/models/models/studio-properties/studio-properties-model.d.ts +97 -0
- package/models/models/studio-properties/studio-properties-model.d.ts.map +1 -0
- package/models/models/studio-properties/studio-properties-registration.d.ts +87 -0
- package/models/models/studio-properties/studio-properties-registration.d.ts.map +1 -0
- package/models/models/studio-properties/types/index.d.ts +32 -0
- package/models/models/translation/constants.d.ts +2 -0
- package/models/models/translation/constants.d.ts.map +1 -0
- package/models/models/translation/index.d.ts +9 -0
- package/models/models/translation/index.d.ts.map +1 -0
- package/models/models/translation/services/index.d.ts +2 -0
- package/models/models/translation/services/index.d.ts.map +1 -0
- package/models/models/translation/services/translation-services.d.ts +151 -0
- package/models/models/translation/services/translation-services.d.ts.map +1 -0
- package/models/models/translation/translation-container-model.d.ts +126 -0
- package/models/models/translation/translation-container-model.d.ts.map +1 -0
- package/models/models/translation/translation-container-registration.d.ts +88 -0
- package/models/models/translation/translation-container-registration.d.ts.map +1 -0
- package/models/models/translation/translation-context.d.ts +12 -0
- package/models/models/translation/translation-context.d.ts.map +1 -0
- package/models/models/translation/translation-model.d.ts +154 -0
- package/models/models/translation/translation-model.d.ts.map +1 -0
- package/models/models/translation/translation-registration.d.ts +85 -0
- package/models/models/translation/translation-registration.d.ts.map +1 -0
- package/models/models/translation/types/index.d.ts +383 -0
- package/models/models/trouble/handlers/resolvable-trouble-handler.d.ts +16 -0
- package/models/models/trouble/handlers/resolvable-trouble-handler.d.ts.map +1 -0
- package/models/models/trouble/index.d.ts +9 -0
- package/models/models/trouble/index.d.ts.map +1 -0
- package/models/models/trouble/services/index.d.ts +2 -0
- package/models/models/trouble/services/index.d.ts.map +1 -0
- package/models/models/trouble/services/trouble-services.d.ts +23 -0
- package/models/models/trouble/services/trouble-services.d.ts.map +1 -0
- package/models/models/trouble/trouble-model.d.ts +43 -0
- package/models/models/trouble/trouble-model.d.ts.map +1 -0
- package/models/models/trouble/trouble-registration.d.ts +84 -0
- package/models/models/trouble/trouble-registration.d.ts.map +1 -0
- package/models/models/trouble/types/index.d.ts +373 -0
- package/models/models/trouble/utils/is-trouble-aware.d.ts +98 -0
- package/models/models/trouble/utils/is-trouble-aware.d.ts.map +1 -0
- package/models/models/trouble/utils/trouble-data-extension.d.ts +5 -0
- package/models/models/trouble/utils/trouble-data-extension.d.ts.map +1 -0
- package/models/models/trouble/utils/trouble-extension.d.ts +5 -0
- package/models/models/trouble/utils/trouble-extension.d.ts.map +1 -0
- package/models/models/trouble/utils/trouble-reducer.d.ts +4 -0
- package/models/models/trouble/utils/trouble-reducer.d.ts.map +1 -0
- package/models/models/trouble-container/index.d.ts +5 -0
- package/models/models/trouble-container/index.d.ts.map +1 -0
- package/models/models/trouble-container/trouble-container-model.d.ts +27 -0
- package/models/models/trouble-container/trouble-container-model.d.ts.map +1 -0
- package/models/models/trouble-container/trouble-utils.d.ts +5 -0
- package/models/models/trouble-container/trouble-utils.d.ts.map +1 -0
- package/models/models/trouble-container/types/index.d.ts +4 -0
- package/models/models/types/index.d.ts +3 -0
- package/models/models/types/index.d.ts.map +1 -0
- package/models/models/usb-update/index.d.ts +7 -0
- package/models/models/usb-update/index.d.ts.map +1 -0
- package/models/models/usb-update/services/index.d.ts +2 -0
- package/models/models/usb-update/services/index.d.ts.map +1 -0
- package/models/models/usb-update/services/usb-update-services.d.ts +22 -0
- package/models/models/usb-update/services/usb-update-services.d.ts.map +1 -0
- package/models/models/usb-update/types/index.d.ts +14 -0
- package/models/models/usb-update/usb-update-container-model.d.ts +34 -0
- package/models/models/usb-update/usb-update-container-model.d.ts.map +1 -0
- package/models/models/usb-update/usb-update-container-registration.d.ts +87 -0
- package/models/models/usb-update/usb-update-container-registration.d.ts.map +1 -0
- package/models/models/usb-update/usb-update-model.d.ts +30 -0
- package/models/models/usb-update/usb-update-model.d.ts.map +1 -0
- package/models/models/usb-update/usb-update-registration.d.ts +87 -0
- package/models/models/usb-update/usb-update-registration.d.ts.map +1 -0
- package/models/models/ws-event/index.d.ts +4 -0
- package/models/models/ws-event/index.d.ts.map +1 -0
- package/models/models/ws-event/types/index.d.ts +25 -0
- package/models/models/ws-event/types/index.d.ts.map +1 -0
- package/models/models/ws-event/ws-event-factory.d.ts +5 -0
- package/models/models/ws-event/ws-event-factory.d.ts.map +1 -0
- package/models/models/ws-event/ws-event-model.d.ts +15 -0
- package/models/models/ws-event/ws-event-model.d.ts.map +1 -0
- package/models/registration.d.ts +7 -0
- package/models/registration.d.ts.map +1 -0
- package/models/services/config-bean/index.d.ts +144 -0
- package/models/services/config-bean/index.d.ts.map +1 -0
- package/models/services/future/index.d.ts +98 -0
- package/models/services/future/index.d.ts.map +1 -0
- package/models/services/index.d.ts +4 -0
- package/models/services/index.d.ts.map +1 -0
- package/models/services/login/index.d.ts +78 -0
- package/models/services/login/index.d.ts.map +1 -0
- package/models/services/trouble/index.d.ts +59 -0
- package/models/services/trouble/index.d.ts.map +1 -0
- package/models/types/cancellable-promise.d.ts +49 -0
- package/models/types/cancellable-promise.d.ts.map +1 -0
- package/models/types/future-interfaces.d.ts +55 -0
- package/models/types/future-interfaces.d.ts.map +1 -0
- package/models/types/global.d.ts +19 -0
- package/models/types/index.d.ts +3 -0
- package/models/types/index.d.ts.map +1 -0
- package/models/utils/cancellable-future-call.d.ts +54 -0
- package/models/utils/cancellable-future-call.d.ts.map +1 -0
- package/models/utils/cancellable-service.d.ts +79 -0
- package/models/utils/cancellable-service.d.ts.map +1 -0
- package/models/utils/client.d.ts +79 -0
- package/models/utils/client.d.ts.map +1 -0
- package/models/utils/conversion-utils.d.ts +67 -0
- package/models/utils/conversion-utils.d.ts.map +1 -0
- package/models/utils/core-registration-manager.d.ts +21 -0
- package/models/utils/core-registration-manager.d.ts.map +1 -0
- package/models/utils/extension-manager.d.ts +23 -0
- package/models/utils/extension-manager.d.ts.map +1 -0
- package/models/utils/future-manager/index.d.ts +9 -0
- package/models/utils/future-manager/index.d.ts.map +1 -0
- package/models/utils/index.d.ts +12 -0
- package/models/utils/index.d.ts.map +1 -0
- package/models/utils/model-event-utils.d.ts +3 -0
- package/models/utils/model-event-utils.d.ts.map +1 -0
- package/models/utils/openapi.d.ts +9311 -0
- package/models/utils/persistence-store.d.ts +58 -0
- package/models/utils/persistence-store.d.ts.map +1 -0
- package/models/utils/prop-utils.d.ts +3 -0
- package/models/utils/prop-utils.d.ts.map +1 -0
- package/models/utils/region-utils.d.ts +2 -0
- package/models/utils/region-utils.d.ts.map +1 -0
- package/models/utils/service.d.ts +87 -0
- package/models/utils/service.d.ts.map +1 -0
- package/models/utils/timer-manager.d.ts +159 -0
- package/models/utils/timer-manager.d.ts.map +1 -0
- package/models/utils/timezone-utils.d.ts +2 -0
- package/models/utils/timezone-utils.d.ts.map +1 -0
- package/models/utils/trouble-utils.d.ts +6 -0
- package/models/utils/trouble-utils.d.ts.map +1 -0
- package/models/utils/types.d.ts +9637 -0
- package/models/utils/types.d.ts.map +1 -0
- package/package.json +42 -0
- package/ui/components/error-boundary/error-boundary.d.ts +16 -0
- package/ui/components/error-boundary/error-boundary.d.ts.map +1 -0
- package/ui/components/error-boundary/index.d.ts +2 -0
- package/ui/components/error-boundary/index.d.ts.map +1 -0
- package/ui/components/index.d.ts +5 -0
- package/ui/components/index.d.ts.map +1 -0
- package/ui/components/kos-model-loader/contexts/kos-model-context.d.ts +12 -0
- package/ui/components/kos-model-loader/contexts/kos-model-context.d.ts.map +1 -0
- package/ui/components/kos-model-loader/contexts/kos-model-hierarchy-context.d.ts +16 -0
- package/ui/components/kos-model-loader/contexts/kos-model-hierarchy-context.d.ts.map +1 -0
- package/ui/components/kos-model-loader/index.d.ts +4 -0
- package/ui/components/kos-model-loader/index.d.ts.map +1 -0
- package/ui/components/kos-model-loader/kos-model-loader.d.ts +13 -0
- package/ui/components/kos-model-loader/kos-model-loader.d.ts.map +1 -0
- package/ui/components/loading-message/index.d.ts +12 -0
- package/ui/components/loading-message/index.d.ts.map +1 -0
- package/ui/components/loading-message/loading-message-styles.d.ts +3 -0
- package/ui/components/loading-message/loading-message-styles.d.ts.map +1 -0
- package/ui/components/progress-bar/index.d.ts +2 -0
- package/ui/components/progress-bar/index.d.ts.map +1 -0
- package/ui/components/progress-bar/progress-bar.d.ts +11 -0
- package/ui/components/progress-bar/progress-bar.d.ts.map +1 -0
- package/ui/constants/index.d.ts +2 -0
- package/ui/constants/index.d.ts.map +1 -0
- package/ui/contexts/create-model-context.d.ts +28 -0
- package/ui/contexts/create-model-context.d.ts.map +1 -0
- package/ui/contexts/fetch-kos-core.d.ts +6 -0
- package/ui/contexts/fetch-kos-core.d.ts.map +1 -0
- package/ui/contexts/index.d.ts +7 -0
- package/ui/contexts/index.d.ts.map +1 -0
- package/ui/contexts/kos-core-context.d.ts +16 -0
- package/ui/contexts/kos-core-context.d.ts.map +1 -0
- package/ui/contexts/kos-model-context.d.ts +10 -0
- package/ui/contexts/kos-model-context.d.ts.map +1 -0
- package/ui/contexts/kos-time/index.d.ts +2 -0
- package/ui/contexts/kos-time/index.d.ts.map +1 -0
- package/ui/contexts/kos-time/kos-time-provider.d.ts +13 -0
- package/ui/contexts/kos-time/kos-time-provider.d.ts.map +1 -0
- package/ui/contexts/modal-context.d.ts +13 -0
- package/ui/contexts/modal-context.d.ts.map +1 -0
- package/ui/contexts/software-info/index.d.ts +2 -0
- package/ui/contexts/software-info/index.d.ts.map +1 -0
- package/ui/contexts/software-info/software-info-provider.d.ts +14 -0
- package/ui/contexts/software-info/software-info-provider.d.ts.map +1 -0
- package/ui/contexts/state-bean/index.d.ts +2 -0
- package/ui/contexts/state-bean/index.d.ts.map +1 -0
- package/ui/contexts/state-bean/state-bean-provider.d.ts +14 -0
- package/ui/contexts/state-bean/state-bean-provider.d.ts.map +1 -0
- package/ui/contexts/token-context.d.ts +9 -0
- package/ui/contexts/token-context.d.ts.map +1 -0
- package/ui/contexts/translation-container/index.d.ts +2 -0
- package/ui/contexts/translation-container/index.d.ts.map +1 -0
- package/ui/contexts/translation-container/kos-translations-provider.d.ts +18 -0
- package/ui/contexts/translation-container/kos-translations-provider.d.ts.map +1 -0
- package/ui/features/canvas/components/canvas-streamer/canvas-streamer.d.ts +15 -0
- package/ui/features/canvas/components/canvas-streamer/canvas-streamer.d.ts.map +1 -0
- package/ui/features/canvas/components/canvas-streamer/index.d.ts +2 -0
- package/ui/features/canvas/components/canvas-streamer/index.d.ts.map +1 -0
- package/ui/features/canvas/components/index.d.ts +2 -0
- package/ui/features/canvas/components/index.d.ts.map +1 -0
- package/ui/features/canvas/components/rgb-332-visualizer/rgb-332-visualizer.d.ts +5 -0
- package/ui/features/canvas/components/rgb-332-visualizer/rgb-332-visualizer.d.ts.map +1 -0
- package/ui/features/canvas/hooks/canvas-dispatcher/index.d.ts +3 -0
- package/ui/features/canvas/hooks/canvas-dispatcher/index.d.ts.map +1 -0
- package/ui/features/canvas/hooks/canvas-dispatcher/use-canvas-dispatcher.d.ts +14 -0
- package/ui/features/canvas/hooks/canvas-dispatcher/use-canvas-dispatcher.d.ts.map +1 -0
- package/ui/features/canvas/hooks/canvas-dispatcher/with-canvas-dispatcher.d.ts +9 -0
- package/ui/features/canvas/hooks/canvas-dispatcher/with-canvas-dispatcher.d.ts.map +1 -0
- package/ui/features/canvas/hooks/use-gradient-renderer.d.ts +14 -0
- package/ui/features/canvas/hooks/use-gradient-renderer.d.ts.map +1 -0
- package/ui/features/canvas/hooks/use-image-renderer.d.ts +22 -0
- package/ui/features/canvas/hooks/use-image-renderer.d.ts.map +1 -0
- package/ui/features/canvas/hooks/use-solid-color-renderer.d.ts +11 -0
- package/ui/features/canvas/hooks/use-solid-color-renderer.d.ts.map +1 -0
- package/ui/features/canvas/hooks/use-streamable-renderer.d.ts +17 -0
- package/ui/features/canvas/hooks/use-streamable-renderer.d.ts.map +1 -0
- package/ui/features/canvas/hooks/use-sweep-renderer.d.ts +32 -0
- package/ui/features/canvas/hooks/use-sweep-renderer.d.ts.map +1 -0
- package/ui/features/canvas/hooks/use-swirl-renderer.d.ts +22 -0
- package/ui/features/canvas/hooks/use-swirl-renderer.d.ts.map +1 -0
- package/ui/features/canvas/hooks/use-video-renderer.d.ts +24 -0
- package/ui/features/canvas/hooks/use-video-renderer.d.ts.map +1 -0
- package/ui/features/canvas/index.d.ts +2 -0
- package/ui/features/canvas/index.d.ts.map +1 -0
- package/ui/features/canvas/utils/preview-decoder.d.ts +29 -0
- package/ui/features/canvas/utils/preview-decoder.d.ts.map +1 -0
- package/ui/features/index.d.ts +2 -0
- package/ui/features/index.d.ts.map +1 -0
- package/ui/hooks/device/index.d.ts +3 -0
- package/ui/hooks/device/index.d.ts.map +1 -0
- package/ui/hooks/device/use-device.d.ts +14 -0
- package/ui/hooks/device/use-device.d.ts.map +1 -0
- package/ui/hooks/device/with-device.d.ts +9 -0
- package/ui/hooks/device/with-device.d.ts.map +1 -0
- package/ui/hooks/fetch-model.d.ts +6 -0
- package/ui/hooks/fetch-model.d.ts.map +1 -0
- package/ui/hooks/index.d.ts +31 -0
- package/ui/hooks/index.d.ts.map +1 -0
- package/ui/hooks/kos-time/index.d.ts +3 -0
- package/ui/hooks/kos-time/index.d.ts.map +1 -0
- package/ui/hooks/kos-time/use-kos-time.d.ts +14 -0
- package/ui/hooks/kos-time/use-kos-time.d.ts.map +1 -0
- package/ui/hooks/kos-time/with-kos-time.d.ts +8 -0
- package/ui/hooks/kos-time/with-kos-time.d.ts.map +1 -0
- package/ui/hooks/network-interface-container/index.d.ts +3 -0
- package/ui/hooks/network-interface-container/index.d.ts.map +1 -0
- package/ui/hooks/network-interface-container/use-network-interface-container.d.ts +14 -0
- package/ui/hooks/network-interface-container/use-network-interface-container.d.ts.map +1 -0
- package/ui/hooks/network-interface-container/with-network-interface-container.d.ts +9 -0
- package/ui/hooks/network-interface-container/with-network-interface-container.d.ts.map +1 -0
- package/ui/hooks/ota/index.d.ts +3 -0
- package/ui/hooks/ota/index.d.ts.map +1 -0
- package/ui/hooks/ota/use-ota.d.ts +14 -0
- package/ui/hooks/ota/use-ota.d.ts.map +1 -0
- package/ui/hooks/ota/with-ota.d.ts +9 -0
- package/ui/hooks/ota/with-ota.d.ts.map +1 -0
- package/ui/hooks/outside-alerter.d.ts +11 -0
- package/ui/hooks/outside-alerter.d.ts.map +1 -0
- package/ui/hooks/software-info/index.d.ts +3 -0
- package/ui/hooks/software-info/index.d.ts.map +1 -0
- package/ui/hooks/software-info/use-software-info.d.ts +14 -0
- package/ui/hooks/software-info/use-software-info.d.ts.map +1 -0
- package/ui/hooks/software-info/with-software-info.d.ts +8 -0
- package/ui/hooks/software-info/with-software-info.d.ts.map +1 -0
- package/ui/hooks/state-bean/use-state-bean.d.ts +14 -0
- package/ui/hooks/state-bean/use-state-bean.d.ts.map +1 -0
- package/ui/hooks/state-bean/with-state-bean.d.ts +8 -0
- package/ui/hooks/state-bean/with-state-bean.d.ts.map +1 -0
- package/ui/hooks/state-prop/index.d.ts +2 -0
- package/ui/hooks/state-prop/index.d.ts.map +1 -0
- package/ui/hooks/state-prop/use-state-prop.d.ts +15 -0
- package/ui/hooks/state-prop/use-state-prop.d.ts.map +1 -0
- package/ui/hooks/storage-device-container/index.d.ts +3 -0
- package/ui/hooks/storage-device-container/index.d.ts.map +1 -0
- package/ui/hooks/storage-device-container/use-storage-device-container.d.ts +16 -0
- package/ui/hooks/storage-device-container/use-storage-device-container.d.ts.map +1 -0
- package/ui/hooks/storage-device-container/with-storage-device-container.d.ts +9 -0
- package/ui/hooks/storage-device-container/with-storage-device-container.d.ts.map +1 -0
- package/ui/hooks/timer/index.d.ts +2 -0
- package/ui/hooks/timer/index.d.ts.map +1 -0
- package/ui/hooks/timer/use-timer.d.ts +23 -0
- package/ui/hooks/timer/use-timer.d.ts.map +1 -0
- package/ui/hooks/translation-container/index.d.ts +6 -0
- package/ui/hooks/translation-container/index.d.ts.map +1 -0
- package/ui/hooks/translation-container/trans.d.ts +21 -0
- package/ui/hooks/translation-container/trans.d.ts.map +1 -0
- package/ui/hooks/translation-container/use-translation-container.d.ts +14 -0
- package/ui/hooks/translation-container/use-translation-container.d.ts.map +1 -0
- package/ui/hooks/translation-container/use-translation.d.ts +14 -0
- package/ui/hooks/translation-container/use-translation.d.ts.map +1 -0
- package/ui/hooks/translation-container/with-translation-container.d.ts +9 -0
- package/ui/hooks/translation-container/with-translation-container.d.ts.map +1 -0
- package/ui/hooks/trouble/index.d.ts +5 -0
- package/ui/hooks/trouble/index.d.ts.map +1 -0
- package/ui/hooks/trouble/use-trouble-container.d.ts +14 -0
- package/ui/hooks/trouble/use-trouble-container.d.ts.map +1 -0
- package/ui/hooks/trouble/use-trouble-visibility.d.ts +16 -0
- package/ui/hooks/trouble/use-trouble-visibility.d.ts.map +1 -0
- package/ui/hooks/trouble/use-trouble.d.ts +14 -0
- package/ui/hooks/trouble/use-trouble.d.ts.map +1 -0
- package/ui/hooks/trouble/with-trouble-container.d.ts +8 -0
- package/ui/hooks/trouble/with-trouble-container.d.ts.map +1 -0
- package/ui/hooks/usb-update-container/index.d.ts +3 -0
- package/ui/hooks/usb-update-container/index.d.ts.map +1 -0
- package/ui/hooks/usb-update-container/use-usb-update-container.d.ts +17 -0
- package/ui/hooks/usb-update-container/use-usb-update-container.d.ts.map +1 -0
- package/ui/hooks/usb-update-container/with-usb-update-container.d.ts +9 -0
- package/ui/hooks/usb-update-container/with-usb-update-container.d.ts.map +1 -0
- package/ui/hooks/use-config-bean.d.ts +15 -0
- package/ui/hooks/use-config-bean.d.ts.map +1 -0
- package/ui/hooks/use-config-property.d.ts +29 -0
- package/ui/hooks/use-config-property.d.ts.map +1 -0
- package/ui/hooks/use-date-props.d.ts +169 -0
- package/ui/hooks/use-date-props.d.ts.map +1 -0
- package/ui/hooks/use-date-relative-prop.d.ts +49 -0
- package/ui/hooks/use-date-relative-prop.d.ts.map +1 -0
- package/ui/hooks/use-function-warmup.d.ts +61 -0
- package/ui/hooks/use-function-warmup.d.ts.map +1 -0
- package/ui/hooks/use-kos-date-formats.d.ts +57 -0
- package/ui/hooks/use-kos-date-formats.d.ts.map +1 -0
- package/ui/hooks/use-kos-model.d.ts +24 -0
- package/ui/hooks/use-kos-model.d.ts.map +1 -0
- package/ui/hooks/use-kos-region-timezones.d.ts +89 -0
- package/ui/hooks/use-kos-region-timezones.d.ts.map +1 -0
- package/ui/hooks/use-kos-regions.d.ts +59 -0
- package/ui/hooks/use-kos-regions.d.ts.map +1 -0
- package/ui/hooks/use-kos-time-formats.d.ts +58 -0
- package/ui/hooks/use-kos-time-formats.d.ts.map +1 -0
- package/ui/hooks/use-kos-token.d.ts +5 -0
- package/ui/hooks/use-kos-token.d.ts.map +1 -0
- package/ui/hooks/use-kos-unit-systems.d.ts +56 -0
- package/ui/hooks/use-kos-unit-systems.d.ts.map +1 -0
- package/ui/hooks/use-local-computed.d.ts +7 -0
- package/ui/hooks/use-local-computed.d.ts.map +1 -0
- package/ui/hooks/use-mutation-observer.d.ts +13 -0
- package/ui/hooks/use-mutation-observer.d.ts.map +1 -0
- package/ui/hooks/use-press-gesture/index.d.ts +4 -0
- package/ui/hooks/use-press-gesture/index.d.ts.map +1 -0
- package/ui/hooks/use-press-gesture/strategy/dom-intersection-strategy.d.ts +4 -0
- package/ui/hooks/use-press-gesture/strategy/dom-intersection-strategy.d.ts.map +1 -0
- package/ui/hooks/use-press-gesture/strategy/intersection-strategy.d.ts +9 -0
- package/ui/hooks/use-press-gesture/strategy/intersection-strategy.d.ts.map +1 -0
- package/ui/hooks/use-press-gesture/use-press-gesture.d.ts +17 -0
- package/ui/hooks/use-press-gesture/use-press-gesture.d.ts.map +1 -0
- package/ui/hooks/use-project-reloading.d.ts +2 -0
- package/ui/hooks/use-project-reloading.d.ts.map +1 -0
- package/ui/hooks/use-region-time-props.d.ts +27 -0
- package/ui/hooks/use-region-time-props.d.ts.map +1 -0
- package/ui/hooks/use-time-props.d.ts +68 -0
- package/ui/hooks/use-time-props.d.ts.map +1 -0
- package/ui/hooks/with-project-reload.d.ts +7 -0
- package/ui/hooks/with-project-reload.d.ts.map +1 -0
- package/ui/i18n/config.d.ts +11 -0
- package/ui/i18n/config.d.ts.map +1 -0
- package/ui/index.d.ts +7 -0
- package/ui/index.d.ts.map +1 -0
- package/ui/mocks/browser.d.ts +3 -0
- package/ui/mocks/browser.d.ts.map +1 -0
- package/ui/mocks/handlers.d.ts +3 -0
- package/ui/mocks/handlers.d.ts.map +1 -0
- package/ui/utils/date-utils.d.ts +34 -0
- package/ui/utils/date-utils.d.ts.map +1 -0
- package/ui/utils/date.d.ts +31 -0
- package/ui/utils/date.d.ts.map +1 -0
- package/ui/utils/index.d.ts +2 -0
- package/ui/utils/index.d.ts.map +1 -0
package/index.cjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../../../../packages/sdk/kos-ui-sdk/src/common/constants/index.ts","../../../../packages/sdk/kos-ui-sdk/src/common/events/eventBus.ts","../../../../packages/sdk/kos-ui-sdk/src/common/events/eventBus.functional.ts","../../../../packages/sdk/kos-ui-sdk/src/common/events/eventBus.state.ts","../../../../packages/sdk/kos-ui-sdk/src/common/file-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/api/wrapPromise.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/api-request-id.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/apply-mixins.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/array-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/container-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/date-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/debounce.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/extension/extension-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/extension/initialize-extension.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/extension/plugin-extension-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/get-query-params.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-config-init.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/log-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/log/log.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/feature-flags.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/hsl-to-hex.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-data-mapper-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-deletion-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/dependency-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/constants.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model-cache.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/propKeys.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-child.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/model-attribute-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-parent.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-companion.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-container-aware.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-context.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-future-aware.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-multiple-future-aware.ts","../../../../packages/sdk/kos-ui-sdk/src/core/types/kos-dependency.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-http-decorators.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-log.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/kos-logger-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-logger-aware.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-model-effect.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-reference.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-trouble-aware.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kosDependency.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future/future-aware.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/utils/trouble-reducer.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/observable-proxy-map.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-container-index.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/when-ready.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-model-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-model-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/registration/registration-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/registration/model-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/registration/base-kos-model-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/registration/singleton-kos-model-registration-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/resolve-parameters.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kosModel.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kosSubscribe.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kosTopicHandler.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/model-event-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/await-first-matching-when.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/model-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/apply-kos-dev-tool-support.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/kos-child-resolver.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/kos-companion-model-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/kos-effects-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/model-active-machine.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/model-online-machine.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/model-machine.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/kosModelLifecycle.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/kos-fsm-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/kos-http-route-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/kos-offline-queue.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/kos-online-lifecycle-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/common/events/async-event-bus.ts","../../../../packages/sdk/kos-ui-sdk/src/core/types/utils/kos-fetch.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-message-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/web-socket-transport-adapter.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/base-message-transport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/bridge-transport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/bridge-message-transport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/fos-message-transport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/kos-message-transport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/transport-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/transport/webSocketTransport.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/decorators/kos-topic-handler-flow-control.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/kos-subscription-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/logger-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/model-introspection-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model/kos-model-component-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kosModel.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/types/registration.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model-instantiator.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/model-registry.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kosModelManager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/lifecycle/kosCoreLifecycle.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kosCore.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/binary-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-fetch.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-model-visitor.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-service-request.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/middleware.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/model-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/model-registration-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/paired-client-heartbeat.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/pipe.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/retry-with-exponential-backoff.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/service-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/session-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/core/util/wait-for-request.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/context/kos-context-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-data-container.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/kos-singleton-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/models/kos-token/index.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/services/browser-router.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/services/intent-service.ts","../../../../packages/sdk/kos-ui-sdk/src/core/core/services/app-startup-service.ts","../../../../packages/sdk/kos-ui-sdk/src/core/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/constants/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/services/config-bean/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/prop-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/config-bean/config-bean-model-builder.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/config-bean/config-bean-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/decorators/kos-config-bean.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/region-info/services/region-info-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/region-info/types/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/region-info/utils/unit-system-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/region-info/region-info-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/conversion-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/config-bean-prop/config-options-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/config-bean-prop/config-bean-prop-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/decorators/kos-config-bean-prop.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future/future-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/models/services/future/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future/future-model-builder.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future/future-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/client.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/browser-router/browser-router-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/browser-router/browser-router-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future-container/future-container-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/future-manager/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/future-container/future-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/key-value/services/key-value-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/key-value/key-value-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/key-value/key-value-registration.ts","../../../../node_modules/expr-eval/dist/index.mjs","../../../../packages/sdk/kos-ui-sdk/src/models/models/kos-expression-evaluator/kos-expression-evaluator-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/kos-expression-evaluator/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/service.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/kos-log-manager/services/kos-log-manager-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/kos-log-manager/kos-log-manager-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/kos-log-manager/kos-log-manager-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/kos-time/services/kos-time-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/kos-time/kos-time-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/kos-time/kos-time-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-block/log-block-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-stream/services/log-stream-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-block/log-block-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-block/log-block-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-block/log-block-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-stream/log-stream-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-stream/log-stream-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-stream/log-stream-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/log-stream/log-stream-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/trouble-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/services/trouble-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/utils/trouble-data-extension.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/utils/trouble-extension.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble-container/trouble-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/handlers/resolvable-trouble-handler.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/trouble-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/trouble-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble-container/trouble-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble-container/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/ota/services/ota-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/ota/ota-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/ota/ota-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/cancellable-service.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/software-info/services/software-info-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/software-info/software-info-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/software-info/software-info-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-bean/services/state-bean-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-bean/state-bean-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-bean/state-bean-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-prop/state-prop-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-prop/state-prop-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/state-prop/services/state-prop-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/services/translation-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/constants.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/translation-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/translation-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/translation-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/translation-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/translation/translation-context.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/trouble/utils/is-trouble-aware.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/ws-event/ws-event-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/ws-event/ws-event-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/services/canvas-dispatcher-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/encode-frame.tsx","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-renderer/canvas-renderer-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-renderer/canvas-renderer-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/base/video-base-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/base/webgl-base-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/drop-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/base/canvas-2d-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/mixins/one-shot-renderer-mixin.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/gradient-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/image-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/looping-video-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/color-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/matrix-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/overlay-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/scrolling-image-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/scrolling-text-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/sequence-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/solid-color-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/sweep-renderer.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/utils/renderers/renderer-factory.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/canvas-dispatcher-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/canvas-dispatcher/canvas-dispatcher-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/device/services/device-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/device/device-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/device/device-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/network-interface/network-interface-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/network-interface/network-interface-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/network-interface/services/network-interface-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/network-interface/network-interface-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/network-interface/network-interface-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/storage-device/services/storage-device-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/storage-device/storage-device-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/storage-device/storage-device-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/storage-device/storage-device-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/storage-device/storage-device-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/usb-update/services/usb-update-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/usb-update/usb-update-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/usb-update/usb-update-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/usb-update/usb-update-container-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/usb-update/usb-update-container-registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/registration.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/core-registration-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/extension-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/persistence-store.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/region-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/timer-manager.ts","../../../../packages/sdk/kos-ui-sdk/src/models/utils/timezone-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/models/decorators/future-service.ts","../../../../packages/sdk/kos-ui-sdk/src/models/decorators/kos-state-bean.ts","../../../../packages/sdk/kos-ui-sdk/src/models/decorators/kos-state-prop.ts","../../../../packages/sdk/kos-ui-sdk/src/models/services/login/index.ts","../../../../packages/sdk/kos-ui-sdk/src/models/types/cancellable-promise.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/components/loading-message/loading-message-styles.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/components/loading-message/index.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/components/error-boundary/error-boundary.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/components/progress-bar/progress-bar.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-context.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/components/kos-model-loader/contexts/kos-model-hierarchy-context.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/components/kos-model-loader/kos-model-loader.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/create-model-context.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/fetch-kos-core.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/kos-core-context.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-kos-model.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/kos-time/use-kos-time.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/kos-time/kos-time-provider.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/software-info/use-software-info.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/software-info/with-software-info.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/software-info/software-info-provider.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/token-context.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/contexts/translation-container/kos-translations-provider.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/features/canvas/hooks/canvas-dispatcher/use-canvas-dispatcher.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/features/canvas/hooks/canvas-dispatcher/with-canvas-dispatcher.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/features/canvas/utils/preview-decoder.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/features/canvas/components/canvas-streamer/canvas-streamer.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/device/use-device.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/device/with-device.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/fetch-model.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/kos-time/with-kos-time.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/network-interface-container/use-network-interface-container.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/network-interface-container/with-network-interface-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/ota/use-ota.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/ota/with-ota.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/outside-alerter.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/state-prop/use-state-prop.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/storage-device-container/use-storage-device-container.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/storage-device-container/with-storage-device-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/timer/use-timer.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/translation-container/trans.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/translation-container/use-translation.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/translation-container/use-translation-container.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/translation-container/with-translation-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/trouble/use-trouble.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/trouble/use-trouble-visibility.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/trouble/with-trouble-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/usb-update-container/use-usb-update-container.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/usb-update-container/with-usb-update-container.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-config-bean.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-config-property.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/utils/date.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/utils/date-utils.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-date-props.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-date-relative-prop.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-function-warmup.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-kos-date-formats.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-kos-region-timezones.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-kos-regions.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-kos-time-formats.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-local-computed.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-mutation-observer.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-press-gesture/strategy/dom-intersection-strategy.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-press-gesture/use-press-gesture.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-project-reloading.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-time-props.tsx","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/use-region-time-props.ts","../../../../packages/sdk/kos-ui-sdk/src/ui/hooks/with-project-reload.tsx","../../../../packages/sdk/kos-ui-sdk/src/models/models/studio-properties/services/studio-properties-services.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/studio-properties/studio-properties-model.ts","../../../../packages/sdk/kos-ui-sdk/src/models/models/studio-properties/studio-properties-registration.ts"],"sourcesContent":["export const HEADER_METHOD = `method`;\nexport const HEADER_TOPIC = `topic`;\nexport const HEADER_URL = `url`;\nexport const HEADER_REQUEST_ID = `request-id`;\nexport const HEADER_RESPONSE_ID = `response-id`;\nexport const STATUS = `status`;\nexport const HEADER_DESTINATION_ADDR = `dst-addr`;\nexport const HEADER_SOURCE_ADDR = `src-addr`;\nexport const HEADER_REQUEST_TYPE = `type`;\nexport const HEADER_ORDERED = `ordered`;\nexport const HEADER_WORK_TRACKER = `tracker`;\nexport const HEADER_CONTENT_TYPE = `Content-Type`;\nexport const HEADER_CACHE_CONTROL = `Cache-Control`;\n\nexport const HEADER_FOS_REQUEST_ID = `requestId`;\nexport const LOGIN_HOST = process.env.KOS_LOGIN_URL || \"http://localhost\";\nexport const PORT = process.env.KOS_APP_PORT || \"8080\";\n\nexport const LOGIN_URL = `${LOGIN_HOST}:${PORT}`;\n\nexport const KOS_MODEL_ID = `{MODEL_ID}`;\n\nexport enum KosWsEvents {\n SEND = \"/ws/log/msg/send\",\n RECEIVED = \"/ws/log/msg/receive\",\n}\n\nexport enum KosMockEvents {\n MSG_RECEIVE = \"/mock/msg/receive\",\n}\nexport const EVENT_KOS_MODEL_READY = \"/kos/model/ready/\";\n","import log from \"loglevel\";\nlog.info(\"Initializing event bus\");\nglobalThis.kos = globalThis.kos || {};\nglobalThis.kos.subscriptions = globalThis.kos.subscriptions || {};\nconst subscriptions: Record<string, any> = globalThis.kos.subscriptions;\nconst getNextUniqueId = () => Symbol(`eventKey`);\n\nexport interface ApiCallback<T = string> {\n headers: Record<string, string>;\n body: T;\n}\nexport type EventCallback<T = ApiCallback> = (msg?: T) => void;\n\nexport interface PublishResponse {\n eventType: string;\n subscribers: number;\n}\n\nexport function hasEventSubscriptions(eventType: string): boolean {\n return (\n subscriptions[eventType] &&\n Object.getOwnPropertySymbols(subscriptions[eventType]).length > 0\n );\n}\n\n/**\n * Subscribes to a specific event type with a callback function.\n *\n * @template T - The type of the callback function, defaults to `ApiCallback`.\n *\n * @param eventType - The name of the event to subscribe to.\n * @param callback - The callback function to execute when the event is triggered.\n *\n * @returns An object containing:\n * - `count`: The number of active subscriptions for the event type.\n * - `unsubscribe`: A function to unsubscribe from the event, which also returns the updated subscription count.\n */\nexport function subscribe<T = ApiCallback>(\n eventType: string,\n callback: EventCallback<T>\n) {\n const id = getNextUniqueId();\n if (!subscriptions[eventType]) {\n log.debug(`Initializing subscription for ${eventType}`);\n subscriptions[eventType] = {};\n }\n\n log.debug(`Subscribing to ${eventType} with id ${id.toString()}`);\n subscriptions[eventType][id] = callback;\n\n return {\n count: subscriptions[eventType]\n ? Object.getOwnPropertySymbols(subscriptions[eventType]).length\n : 0,\n unsubscribe: () => {\n log.debug(`Unsubscribing from ${eventType} with id ${id.toString()}`);\n\n if (subscriptions[eventType] && subscriptions[eventType][id]) {\n delete subscriptions[eventType][id];\n }\n\n if (\n subscriptions[eventType] &&\n Object.getOwnPropertySymbols(subscriptions[eventType]).length === 0\n ) {\n delete subscriptions[eventType];\n }\n return {\n count: subscriptions[eventType]\n ? Object.getOwnPropertySymbols(subscriptions[eventType]).length\n : 0,\n };\n },\n };\n}\n\n/**\n * Publishes an event to all subscribers of the specified event type.\n *\n * @param eventType - The type of the event to publish.\n * @param msg - The message payload to send to subscribers.\n * @param headers - Optional headers to include with the event. If the \"sync\" header is provided,\n * the event will be published synchronously, and the response will be sent back\n * to the source using the specified sync ID.\n * @returns An object containing the event type and the number of subscribers the event was published to.\n *\n * The function checks if there are any subscriptions for the given event type. If no subscriptions\n * exist, it logs a debug message and returns an object indicating zero subscribers. Otherwise, it\n * iterates over the subscribers and publishes the event:\n * - If the \"sync\" header is present, the function waits for a response from the subscriber and\n * publishes the response back to the source using the sync ID.\n * - If the \"sync\" header is not present, the event is published asynchronously in a fire-and-forget manner.\n */\nexport function publish(\n eventType: string,\n msg: unknown,\n headers: Record<string, string> = {}\n): PublishResponse {\n if (\n !subscriptions[eventType] ||\n Object.getOwnPropertySymbols(subscriptions[eventType]).length === 0\n ) {\n log.debug(`No subscriptions for ${eventType}. Not publishing.`);\n return {\n eventType,\n subscribers: 0,\n };\n }\n\n const count = Object.getOwnPropertySymbols(subscriptions[eventType]).length;\n // eslint-disable-next-line max-len\n Object.getOwnPropertySymbols(subscriptions[eventType]).forEach((id) => {\n if (headers[\"sync\"]) {\n // wait for the response and send it back if sync\n const responseId = headers[\"sync\"];\n log.debug(\n `Performing sync publish for ${eventType} with sync id ${responseId}`\n );\n subscriptions[eventType][id]({ body: msg, headers }).then(\n (response: any) => {\n log.debug(\n `Response recieved for ${responseId}, publishing back to source.`\n );\n publish(responseId, response);\n }\n );\n } else {\n // fire and forget if not sync\n log.debug(`Performing async publish for ${eventType}`);\n subscriptions[eventType][id]({ body: msg, headers });\n }\n });\n return {\n eventType,\n subscribers: count,\n };\n}\n\n/**\n * Resets the event bus by clearing all existing subscriptions.\n * Logs a warning message indicating the reset operation.\n *\n * @remarks\n * This function iterates through all keys in the `subscriptions` object\n * and deletes them, effectively removing all event listeners.\n *\n * @example\n * ```typescript\n * reset(); // Clears all event subscriptions and logs a warning.\n * ```\n */\nexport function reset() {\n log.warn(\"Resetting event bus\");\n Object.keys(subscriptions).forEach((key) => delete subscriptions[key]);\n}\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 */\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 */\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 * 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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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// Export a namespace with all utilities for easier access\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","/**\n * State-aware event utilities that handle the race condition between\n * initial state and event subscriptions\n */\n\nimport { ApiCallback, EventCallback, subscribe, waitFor } from \"./eventBus\";\n\n/**\n * Options for state-aware event subscriptions\n */\nexport interface StateAwareOptions<T> {\n /** Function to fetch the current state */\n getCurrentState: () => Promise<T> | T;\n /** Optional transform function to normalize API response to event format */\n transformState?: (state: any) => T;\n /** Optional function to determine if we should use the fetched state */\n shouldUseFetchedState?: (state: T) => boolean;\n /** Timeout for waiting for events (ms) */\n timeout?: number;\n}\n\n/**\n * Wait for an event OR get the current state if the event already happened\n * This prevents race conditions where events fire before subscription\n *\n * @param eventType - The event type to wait for\n * @param options - Options for state fetching and transformation\n * @returns Promise that resolves with either the event data or current state\n */\nexport async function waitForOrGetState<T = ApiCallback>(\n eventType: string,\n options: StateAwareOptions<T>\n): Promise<T> {\n const { getCurrentState, transformState, shouldUseFetchedState, timeout } =\n options;\n\n // Set up event listener first to minimize race window\n const eventPromise = waitFor<T>(eventType, timeout);\n\n // Fetch current state\n const currentState = await getCurrentState();\n const normalizedState = transformState\n ? transformState(currentState)\n : currentState;\n\n // Check if we should use the fetched state\n if (shouldUseFetchedState) {\n if (shouldUseFetchedState(normalizedState)) {\n // Cancel the event wait and return current state\n eventPromise.catch(() => {}); // Ignore timeout error\n return normalizedState;\n }\n }\n\n // Race between the event and a small delay\n // This gives the event a chance to fire if it's in flight\n const result = await Promise.race([\n eventPromise,\n new Promise<T>((resolve) => {\n setTimeout(() => resolve(normalizedState), 100);\n }),\n ]);\n\n return result;\n}\n\n/**\n * Subscribe to events with initial state, ensuring no events are missed\n *\n * @param eventType - The event type to subscribe to\n * @param callback - Callback for state updates\n * @param options - Options for initial state fetching\n * @returns Unsubscribe function\n */\nexport function subscribeWithInitialState<T = ApiCallback>(\n eventType: string,\n callback: EventCallback<T>,\n options: StateAwareOptions<T>\n): () => void {\n const { getCurrentState, transformState } = options;\n let initialized = false;\n\n // Subscribe first to avoid missing events\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n initialized = true;\n callback(msg);\n }\n });\n\n // Fetch and emit initial state\n Promise.resolve(getCurrentState())\n .then((state) => {\n const normalizedState = transformState ? transformState(state) : state;\n\n // Only emit if we haven't received an event yet\n if (!initialized) {\n callback(normalizedState);\n }\n })\n .catch((error) => {\n console.error(\"Failed to fetch initial state:\", error);\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Create a state-synchronized event stream that combines initial state with events\n *\n * @param eventType - The event type for updates\n * @param stateApi - API endpoint or function to fetch current state\n * @returns Object with subscribe method and current state getter\n */\nexport function createStatefulEventStream<T = any>(\n eventType: string,\n stateApi: string | (() => Promise<T>)\n) {\n let currentState: T | undefined;\n const subscribers = new Set<(state: T) => void>();\n\n // Fetch initial state\n const fetchState = async () => {\n try {\n if (typeof stateApi === \"string\") {\n const response = await fetch(stateApi);\n currentState = await response.json();\n } else {\n currentState = await stateApi();\n }\n\n // Notify all subscribers of initial state\n subscribers.forEach((callback) => callback(currentState!));\n } catch (error) {\n console.error(\"Failed to fetch initial state:\", error);\n throw error;\n }\n };\n\n // Subscribe to events for updates\n subscribe(eventType, (msg?: ApiCallback<T>) => {\n if (msg?.body) {\n currentState = msg.body;\n subscribers.forEach((callback) => callback(currentState!));\n }\n });\n\n // Initialize state on first subscription\n let initialized = false;\n const ensureInitialized = () => {\n if (!initialized) {\n initialized = true;\n fetchState();\n }\n };\n\n return {\n /** Get current state synchronously (may be undefined if not loaded) */\n get state() {\n return currentState;\n },\n\n /** Get current state asynchronously (waits for initial load) */\n async getState(): Promise<T> {\n ensureInitialized();\n if (currentState === undefined) {\n await new Promise<void>((resolve) => {\n const checkState = () => {\n if (currentState !== undefined) {\n resolve();\n } else {\n setTimeout(checkState, 10);\n }\n };\n checkState();\n });\n }\n return currentState!;\n },\n\n /** Subscribe to state changes (includes initial state) */\n subscribe(callback: (state: T) => void): () => void {\n ensureInitialized();\n subscribers.add(callback);\n\n // Emit current state if available\n if (currentState !== undefined) {\n callback(currentState);\n }\n\n return () => {\n subscribers.delete(callback);\n };\n },\n\n /** Refresh state from API */\n async refresh(): Promise<T> {\n await fetchState();\n return currentState!;\n },\n };\n}\n\n/**\n * Wait for multiple events with shared state checking\n * Checks global state once to see if all conditions are already met\n *\n * @param eventTypes - Array of event types to wait for\n * @param options - Shared state checking options\n * @returns Promise that resolves when all events have occurred or state is ready\n */\nexport async function waitForAllWithState<T = ApiCallback>(\n eventTypes: string[],\n options: StateAwareOptions<T>\n): Promise<T>;\n\n/**\n * Wait for a single event with state checking (convenience overload)\n *\n * @param eventType - Single event type to wait for\n * @param options - State checking options\n * @returns Promise that resolves when event occurs or state is ready\n */\nexport async function waitForAllWithState<T = ApiCallback>(\n eventType: string,\n options: StateAwareOptions<T>\n): Promise<T>;\n\nexport async function waitForAllWithState<T = ApiCallback>(\n eventTypesOrType: string | string[],\n options: StateAwareOptions<T>\n): Promise<T> {\n // Handle single event case (most common)\n if (typeof eventTypesOrType === \"string\") {\n return waitForOrGetState(eventTypesOrType, options);\n }\n\n // Handle multiple events case\n const eventTypes = eventTypesOrType;\n const { getCurrentState, shouldUseFetchedState, timeout } = options;\n\n // Check global state first\n const currentState = await getCurrentState();\n const normalizedState = options.transformState\n ? options.transformState(currentState)\n : currentState;\n\n // If state shows we're already ready, return immediately\n if (shouldUseFetchedState && shouldUseFetchedState(normalizedState)) {\n return normalizedState;\n }\n\n // Otherwise wait for all events\n const eventPromises = eventTypes.map((eventType) =>\n waitFor<T>(eventType, timeout)\n );\n\n // Race between all events completing and a timeout\n const results = await Promise.all(eventPromises);\n\n // Return the last result (or could return all results if needed)\n return results[results.length - 1];\n}\n\n/**\n * Create a resilient event handler that can recover from missed events\n *\n * @param eventType - Event type to handle\n * @param handler - Event handler function\n * @param recoveryStrategy - Strategy for recovering missed events\n */\nexport function createResilientEventHandler<T = ApiCallback>(\n eventType: string,\n handler: (data: T) => void | Promise<void>,\n recoveryStrategy: {\n /** API to fetch missed events or current state */\n fetchMissedEvents: () => Promise<T[]> | Promise<T>;\n /** How often to check for missed events (ms) */\n checkInterval?: number;\n /** Whether to deduplicate events by ID */\n deduplicateById?: (event: T) => string;\n }\n) {\n const {\n fetchMissedEvents,\n checkInterval = 30000,\n deduplicateById,\n } = recoveryStrategy;\n const processedIds = new Set<string>();\n\n // Handle incoming events\n const subscription = subscribe(eventType, async (msg?: T) => {\n if (msg) {\n if (deduplicateById) {\n const id = deduplicateById(msg);\n if (processedIds.has(id)) {\n return; // Already processed\n }\n processedIds.add(id);\n\n // Keep set size manageable\n if (processedIds.size > 1000) {\n const idsArray = Array.from(processedIds);\n idsArray.slice(0, 500).forEach((id) => processedIds.delete(id));\n }\n }\n\n await handler(msg);\n }\n });\n\n // Periodically check for missed events\n const intervalId = setInterval(async () => {\n try {\n const missed = await fetchMissedEvents();\n const events = Array.isArray(missed) ? missed : [missed];\n\n for (const event of events) {\n if (deduplicateById) {\n const id = deduplicateById(event);\n if (!processedIds.has(id)) {\n processedIds.add(id);\n await handler(event);\n }\n } else {\n await handler(event);\n }\n }\n } catch (error) {\n console.error(\"Failed to fetch missed events:\", error);\n }\n }, checkInterval);\n\n // Return cleanup function\n return () => {\n subscription.unsubscribe();\n clearInterval(intervalId);\n };\n}\n\n/**\n * Pattern for handling connection state with events\n * Useful for WebSocket connections, plugin loading, etc.\n */\nexport interface ConnectionStateManager<T = any> {\n /** Current connection state */\n state: \"disconnected\" | \"connecting\" | \"connected\" | \"error\";\n /** Current data (if connected) */\n data?: T;\n /** Wait for connection to be established */\n waitForConnection(timeout?: number): Promise<T>;\n /** Subscribe to state changes */\n subscribe(callback: (state: ConnectionStateManager<T>) => void): () => void;\n /** Manually trigger reconnection */\n reconnect(): Promise<void>;\n}\n\n/**\n * Create a connection state manager that handles online/offline scenarios\n */\nexport function createConnectionStateManager<T = any>(config: {\n connectEvent: string;\n disconnectEvent: string;\n errorEvent?: string;\n dataEvent?: string;\n fetchInitialState: () => Promise<T>;\n reconnectDelay?: number;\n}): ConnectionStateManager<T> {\n const {\n connectEvent,\n disconnectEvent,\n errorEvent,\n dataEvent,\n fetchInitialState,\n reconnectDelay = 5000,\n } = config;\n\n const manager: ConnectionStateManager<T> = {\n state: \"disconnected\",\n data: undefined,\n\n async waitForConnection(timeout?: number): Promise<T> {\n if (manager.state === \"connected\" && manager.data) {\n return manager.data;\n }\n\n // Wait for connection event or fetch current state\n const result = await waitForOrGetState<T>(connectEvent, {\n getCurrentState: fetchInitialState,\n shouldUseFetchedState: (state) => !!state,\n timeout,\n });\n\n manager.state = \"connected\";\n manager.data = result;\n notifySubscribers();\n\n return result;\n },\n\n subscribe(\n callback: (state: ConnectionStateManager<T>) => void\n ): () => void {\n subscribers.add(callback);\n callback(manager); // Emit current state\n return () => {\n subscribers.delete(callback);\n };\n },\n\n async reconnect(): Promise<void> {\n manager.state = \"connecting\";\n notifySubscribers();\n\n try {\n const data = await fetchInitialState();\n manager.state = \"connected\";\n manager.data = data;\n notifySubscribers();\n } catch (error) {\n manager.state = \"error\";\n notifySubscribers();\n\n // Auto-retry after delay\n setTimeout(() => {\n if (manager.state === \"error\") {\n manager.reconnect();\n }\n }, reconnectDelay);\n }\n },\n };\n\n const subscribers = new Set<(state: ConnectionStateManager<T>) => void>();\n const notifySubscribers = () => {\n subscribers.forEach((callback) => callback(manager));\n };\n\n // Subscribe to connection events\n subscribe(connectEvent, (msg?: ApiCallback<T>) => {\n manager.state = \"connected\";\n if (msg?.body) {\n manager.data = msg.body;\n }\n notifySubscribers();\n });\n\n subscribe(disconnectEvent, () => {\n manager.state = \"disconnected\";\n notifySubscribers();\n\n // Auto-reconnect\n setTimeout(() => {\n if (manager.state === \"disconnected\") {\n manager.reconnect();\n }\n }, reconnectDelay);\n });\n\n if (errorEvent) {\n subscribe(errorEvent, () => {\n manager.state = \"error\";\n notifySubscribers();\n });\n }\n\n if (dataEvent) {\n subscribe(dataEvent, (msg?: ApiCallback<T>) => {\n if (msg?.body && manager.state === \"connected\") {\n manager.data = msg.body;\n notifySubscribers();\n }\n });\n }\n\n // Check initial state\n manager.reconnect();\n\n return manager;\n}\n\n// Export namespace for easier access\nexport const EventBusState = {\n waitForOrGetState,\n subscribeWithInitialState,\n createStatefulEventStream,\n waitForAllWithState,\n createResilientEventHandler,\n createConnectionStateManager,\n};\n","type Sizes = \"bytes\" | \"KB\" | \"MB\" | \"GB\" | \"TB\";\ninterface Convert {\n value: number;\n scale: Sizes;\n toString: () => string;\n}\nexport const convertFileSizeRaw = (bytes: number, decimals = 0): Convert => {\n if (!+bytes)\n return {\n value: 0,\n scale: \"bytes\",\n toString: () => `0 bytes`,\n };\n\n const k = 1024;\n const dm = decimals < 0 ? 0 : decimals;\n const sizes: Sizes[] = [\"bytes\", \"KB\", \"MB\", \"GB\", \"TB\"];\n\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n const value = parseFloat((bytes / Math.pow(k, i)).toFixed(dm));\n const scale = sizes[i];\n return {\n value,\n scale,\n toString: () => `${value} ${scale}`,\n };\n};\n","/**\n * Utility function that will wrap an arbitrary promise in order for it to\n * conform to the React Suspense API. By utilizing this higher order function\n * React components can participate in the Suspense workflow and enable the application\n * to display fallback behaviour while KOS data models or APIs are being fetched.\n *\n * @param promise The promise to be resolved\n * @returns an Object with a single `read` function that will be used to broadcast\n * status back to the React framework.\n */\nexport function wrapPromise<T>(promise: Promise<T>) {\n let status = `pending`;\n let response;\n\n const suspender = promise.then(\n (res) => {\n status = `success`;\n response = res;\n },\n (err) => {\n status = `error`;\n response = err;\n }\n );\n\n const read = (): T => {\n switch (status) {\n case `pending`:\n throw suspender;\n case `error`:\n throw response;\n default:\n return response;\n }\n };\n\n return { read };\n}\n","export function uuid() {\n return `xxxxxxxx-xxxx-4xxx-2xxx-xxxxxxxxxxxx`.replace(/[xy]/g, function (c) {\n const r = (Math.random() * 16) | 0;\n const v = c == `x` ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n","export function applyMixins(derivedCtor: any, baseCtors: any[]) {\n baseCtors.forEach((baseCtor) => {\n Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {\n const descriptor = Object.getOwnPropertyDescriptor(\n baseCtor.prototype,\n name\n );\n Object.defineProperty(\n derivedCtor.prototype,\n name,\n <PropertyDescriptor & ThisType<any>>descriptor\n );\n });\n });\n}\n","export 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","import { IKosModelContainer } from \"../core/kos-container-model\";\nimport { IKosContainerModel } from \"../core/kosModel\";\n\ninterface Identifiable {\n id: string;\n}\n\n/**\n * Utility function to calculate the list of ids that should be removed from the\n * current state in order to remain in sync.\n *\n * @param projectedModels - the new list of models representing the next state\n * @param currentModels - the current list of models to be compared against\n * @returns the list of ids that should be removed from the current state\n */\nconst deltas = (\n projectedModels: Identifiable[],\n currentModels: Identifiable[]\n) => {\n const newIds = projectedModels.map((entity) => entity.id);\n const currentIds = currentModels.map((entity) => entity.id);\n const toRemove = currentIds.filter((modelId) => !newIds.includes(modelId));\n\n return toRemove;\n};\n\n/**\n * Function that transforms an entity, typically to update its id property before container insertion.\n * Useful for normalizing ids or adding prefixes/suffixes.\n */\nexport type IdMapper = <D extends Identifiable = Identifiable>(entity: D) => D;\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 entity type with an id property\n */\ninterface ResolveParams<T extends Container, D> {\n /** The container to synchronize */\n container: T;\n /** Callback to create a new item when an entity is added */\n onAddItem: (entity: D) => 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: D, existingModel: any) => any;\n /** Optional mapper to transform entity ids before processing */\n idMapper?: IdMapper;\n}\n\nconst DEFAULT_REMOVE_MAPPER = (id: string) => id;\nconst DEFAULT_ID_MAPPER = (entity) => entity;\n\n/**\n * Creates a function that synchronizes a container with a new list of entities.\n * Handles additions, removals, and optional updates to keep the container in sync.\n *\n * @template T - Container type implementing IKosModelContainer\n * @template D - Entity type with an id property\n * @param params - Configuration for resolving deltas\n * @returns A function that accepts entities and synchronizes the container\n *\n * @example\n * const syncUsers = resolveContainerDeltas({\n * container: userContainer,\n * onAddItem: (user) => User.instance(user.id).options(user).build(),\n * onUpdateItem: (user, existing) => existing.update(user),\n * onRemoveItem: (id) => id\n * });\n * syncUsers(newUserList);\n */\nexport const resolveContainerDeltas =\n <T extends IKosModelContainer<any>, D extends Identifiable>({\n container,\n onAddItem,\n onUpdateItem,\n onRemoveItem = DEFAULT_REMOVE_MAPPER,\n idMapper = DEFAULT_ID_MAPPER,\n }: ResolveParams<T, D>) =>\n (entities: D[]) => {\n const mappedEntities = entities.map(idMapper);\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: D) => {\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 - Entity type with an id property\n * @param params - Configuration for resolving deltas\n * @returns A function that accepts entities and synchronizes by invoking callbacks\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 */\nexport const resolveListDeltas =\n <T extends IKosContainerModel<any, any>, D extends Identifiable>({\n container,\n onAddItem,\n onRemoveItem = DEFAULT_REMOVE_MAPPER,\n idMapper = DEFAULT_ID_MAPPER,\n }: ResolveParams<T, D>) =>\n (entities: D[]) => {\n const mappedLayers = entities.map(idMapper);\n const toRemove = deltas(mappedLayers, container.models);\n toRemove.forEach(onRemoveItem);\n mappedLayers.forEach(onAddItem);\n };\n\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 - New entity type with an id property\n */\ninterface ResolveItemsParams<T extends Identifiable, D> {\n /** The current array of items to synchronize */\n items: T[];\n /** Callback invoked for each entity to add */\n onAddItem: (entity: D) => 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;\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 - New entity type with an id property\n * @param params - Configuration including the items array and callbacks\n * @returns A function that accepts entities and synchronizes the array\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 */\nexport const resolveItemListDeltas =\n <T extends Identifiable, D extends Identifiable>({\n items,\n onAddItem,\n onRemoveItem,\n idMapper = (entity) => entity,\n }: ResolveItemsParams<T, D>) =>\n (entities: D[]) => {\n const mappedLayers = entities.map(idMapper);\n const toRemove = deltas(mappedLayers, items);\n toRemove.forEach(onRemoveItem);\n mappedLayers.forEach(onAddItem);\n };\n\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 */\nexport const processId = (id: string, prefix = \"parent-\") => {\n let _id = id;\n if (_id.startsWith(prefix)) {\n _id = _id.replace(prefix, \"\");\n }\n return _id;\n};\n","const formatter = new Intl.RelativeTimeFormat(undefined, {\n numeric: \"auto\",\n});\n\nconst DIVISIONS: { amount: number; name: Intl.RelativeTimeFormatUnit }[] = [\n { amount: 60, name: \"seconds\" },\n { amount: 60, name: \"minutes\" },\n { amount: 24, name: \"hours\" },\n { amount: 7, name: \"days\" },\n { amount: 4.34524, name: \"weeks\" },\n { amount: 12, name: \"months\" },\n { amount: Number.POSITIVE_INFINITY, name: \"years\" },\n];\n\nexport function formatDateSince(date: Date) {\n let duration = (date.getTime() - Date.now()) / 1000;\n\n for (let i = 0; i <= DIVISIONS.length; i++) {\n const division = DIVISIONS[i];\n if (Math.abs(duration) < division.amount) {\n return formatter.format(Math.round(duration), division.name);\n }\n duration /= division.amount;\n }\n return formatter.format(Math.round(duration), \"years\");\n}\n\nexport const isLeapYear = (year: number): boolean =>\n (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\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\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\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\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\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\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 * Debounces a function, ensuring it is called after a specified timeout\n * has passed since the last invocation.\n *\n * @param context - The context (this value) to be used when calling the debounced function.\n * @param func - The function to debounce.\n * @param timeout - The duration (in milliseconds) to wait after the last invocation before calling the function.\n * Defaults to 300 milliseconds.\n * @returns A debounced version of the provided function.\n *\n * @example\n * ```typescript\n * const debouncedFn = debounce(this, myFunction, 500);\n * debouncedFn(arg1, arg2);\n * ```\n */\nfunction debounce(context: any, func: Function, timeout = 300) {\n let timer: ReturnType<typeof setTimeout>;\n\n /**\n * Returns a debounced version of the provided function.\n *\n * @param args - The arguments to pass to the debounced function.\n */\n return (...args: any) => {\n /**\n * Clears the previous timer.\n */\n clearTimeout(timer);\n\n /**\n * Sets a new timer to call the provided function after the specified timeout.\n */\n timer = setTimeout(() => {\n func.apply(context, args);\n }, timeout);\n };\n}\n\nexport default debounce;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { RendererConstructor } from \"../../../models/models/canvas-dispatcher\";\nimport { IndexMapper } from \"../kos-container-index\";\nimport { IKosDataModel } from \"../kosModel\";\n\nexport type ExtensionType = number | string | boolean;\nexport type DataMapper<\n I extends object = any,\n O extends object = any,\n C extends object = any\n> = (input: I, context?: C) => Promise<O>;\n\nexport type PropertyMapper<\n I extends object = any,\n O extends ExtensionType = any,\n C extends object = any\n> = (input: I, context?: C) => O;\n\nexport type DataLoader<I extends object = any, O extends object = any> = (\n input: I\n) => Promise<O>;\n\nexport type IndexExtension<T extends IKosDataModel = any> = Record<\n string,\n keyof T | IndexMapper<any>\n>;\n\nexport const EXTENSION_CANVAS_RENDERER = \"canvas-renderer\";\nconst dataMappers = new Map<string, DataMapper[]>();\nconst dataLoaders = new Map<string, DataLoader>();\nconst propertyMappers = new Map<string, PropertyMapper>();\nconst indexExtensions = new Map<string, IndexExtension>();\n\nexport interface ExtensionPoint<\n Data extends object = any,\n Output extends object = any,\n Context extends object = any\n> {\n register: (id: string, extension: any) => void;\n execute: (id: string, data: Data, context?: Context) => Output;\n}\nexport const registerExtensionPoint = (\n id: string,\n extensionPoint: ExtensionPoint\n) => {\n _ExtensionManager[id] = extensionPoint;\n};\n\nconst _ExtensionManager = {\n indexExtension: {\n registerIndexExtension: (id: string, extension: IndexExtension) => {\n const extensions = indexExtensions.get(id) || {};\n Object.assign(extensions, extension);\n indexExtensions.set(id, extension);\n },\n\n loadIndexExtensions: (id: string) => indexExtensions.get(id) || {},\n },\n loader: {\n registerLoader: (id: string, loader: DataLoader) => {\n dataLoaders.set(id, loader);\n },\n executeLoader: async <T extends object = any>(id: string, data: T) => {\n const loader = dataLoaders.get(id);\n if (!loader) {\n return undefined;\n }\n return await loader(data);\n },\n },\n propertyMapper: {\n registerPropertyMapper: (id: string, mapper: PropertyMapper) => {\n propertyMappers.set(id, mapper);\n },\n hasMapper: (id: string) => propertyMappers.has(id),\n executeMapper: <\n T extends object = any,\n O extends ExtensionType = any,\n C extends object = any\n >(\n id: string,\n data: T,\n context?: C\n ) => {\n const mapper = propertyMappers.get(id);\n if (!mapper) {\n return \"\" as O;\n }\n\n return mapper(data, context) as O;\n },\n },\n dataMapper: {\n registerDataMapper: (id: string, mapper: DataMapper) => {\n const mappers = dataMappers.get(id) || [];\n mappers.push(mapper);\n\n dataMappers.set(id, mappers);\n },\n executeMapper: async <\n T extends object = any,\n O extends object = any,\n C extends object = any\n >(\n id: string,\n data: T,\n context?: C\n ): Promise<O> => {\n const mappers = dataMappers.get(id);\n if (!mappers) {\n return {} as O;\n }\n\n const result = {};\n for (const mapper of mappers) {\n const _interim = await mapper(data, context);\n Object.assign(result, _interim);\n }\n\n return result as O;\n },\n },\n canvas: {\n registerRenderer: (id: string, renderer: RendererConstructor) => {\n if (!ExtensionManager[EXTENSION_CANVAS_RENDERER]) {\n console.warn(\n `Canvas renderer extension point is not registered. Cannot register renderer \"${id}\".`\n );\n return;\n }\n ExtensionManager[EXTENSION_CANVAS_RENDERER].register(id, renderer);\n },\n },\n};\n\nexport interface IExtensionManager {}\ntype ExtensionManagerType = typeof _ExtensionManager &\n IExtensionManager & {\n [key: string]: ExtensionPoint;\n };\n\nexport const ExtensionManager = _ExtensionManager as ExtensionManagerType;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { KosContext } from \"../context\";\nimport { ExtensionManager } from \"../extension\";\n\nexport interface ExtensionPointOptions {\n extension: string;\n}\nexport interface InitializeContextExtensionPointOptions\n extends ExtensionPointOptions {\n context?: KosContext;\n}\n\nexport interface ContextDataExtensionPoint<D extends object, T extends object>\n extends ExtensionPointOptions {\n data: D;\n contextData: T;\n}\n/**\n * Executes an extension point and adds the value to the specified context\n * @param options The options for the extension point\n * @param options.context The KOS model context to add the value to. If not specified, the value will not be added to any context.\n * @param options.extension The extension point to execute\n *\n * @returns The value returned from the extension point\n * */\nexport const executeLoaderExtension = async ({\n context,\n extension,\n}: InitializeContextExtensionPointOptions) => {\n const contextData = await ExtensionManager.loader.executeLoader(\n extension,\n {}\n );\n\n context?.set(extension, contextData);\n\n return contextData;\n};\n\n/**\n * Executes a registered data transformation extension point. This extension point is used to transform data from the backend into a format that is\n * usable by the application.\n *\n * @param options The options for the extension point\n * @param options.contextData The context data to pass to the extension point\n * @param options.data The data to transform\n * @param options.extension The extension point to execute\n * @returns The transformed data\n * */\nexport const executeDataMapperExtension = async <\n D extends object = any,\n R extends object = any,\n T extends object = any\n>({\n extension,\n contextData,\n data,\n}: ContextDataExtensionPoint<D, T>) => {\n const transformed = await ExtensionManager.dataMapper.executeMapper<D, R>(\n extension,\n data,\n contextData\n );\n\n return transformed;\n};\n\n/**\n * Executes a registered data transformation extension point. This extension point is used to map a single property value and\n * is typically used to map a property value from the backend into a format that is usable by the application.\n *\n *\n * @param options The options for the extension point\n * @param options.contextData The context data to pass to the extension point\n * @param options.data The data to transform\n * @param options.extension The extension point to execute\n * @returns The transformed data\n * */\nexport const executePropertyMapperExtension = async <\n D extends object = any,\n T extends object = any\n>({\n extension,\n contextData,\n data,\n}: ContextDataExtensionPoint<D, T>) => {\n const value = await ExtensionManager.propertyMapper.executeMapper(\n extension,\n data,\n contextData\n );\n\n return value;\n};\n","export const PLUGIN_EXTENSION_NAME = \"Extensions\";\n\n/**\n * Represents the type for the extensions.\n */\nexport interface PluginExtensionsType {\n [k: string]: {\n [k: string]: {\n component?: string;\n remote?: string;\n };\n };\n}\nexport class PluginExtensionManager {\n private extensions: PluginExtensionsType;\n\n constructor() {\n this.extensions = {};\n }\n register(extensionPoint: string, name: string, component: string) {\n this.extensions[extensionPoint] = {} || this.extensions[extensionPoint];\n this.extensions[extensionPoint][name] = { component };\n }\n\n get(extension: string, id: string) {\n if (!this.extensions[extension]) {\n throw new Error(`Extension point ${extension} not found`);\n }\n return this.extensions[extension][id];\n }\n\n get allExtensions() {\n return this.extensions;\n }\n}\n","export const getQueryParams = (query = null) =>\n (query || window.location.search.replace(\"?\", \"\"))\n\n // get array of KeyValue pairs\n .split(\"&\")\n\n // Decode values\n .map((pair) => {\n const [key, val] = pair.split(\"=\");\n\n return [key, decodeURIComponent(val || \"\")];\n })\n\n // array to object\n .reduce((result, [key, val]) => {\n result[key] = val;\n return result;\n }, {});\n","interface KosConfig {\n logging: boolean;\n profiles: string[];\n [key: string]: boolean | string[] | string | number | undefined;\n}\n\nexport const PROFILE_TOOLS_PREVIEW = \"studio.tools.preview\";\nexport const PROFILE_RELAX_STORE_VALIDATION = \"studio.relax.store.validation\";\nexport const PROFILE_LOG_DEBUG = \"studio.log.debug\";\nexport const PROFILE_LOG_INFO = \"studio.log.info\";\nconst defaultConfig = {\n profiles: [PROFILE_TOOLS_PREVIEW],\n};\nconst config = globalThis.getKosConfig?.() || JSON.stringify(defaultConfig);\n\nconst configObj = JSON.parse(config);\n\nglobalThis.kosConfig = configObj;\n\nexport const KosGlobalConfig: KosConfig = configObj;\n\nexport const resolveKosProfiles = () => KosGlobalConfig.profiles || [];\n\nexport const hasKosProfile = (profile: string) =>\n resolveKosProfiles().includes(profile);\n\nexport const isKosLoggingEnabled = () => KosGlobalConfig.logging || false;\n","import { LogLevelDesc } from \"loglevel\";\nimport { getQueryParams } from \"../util/get-query-params\";\nimport {\n hasKosProfile,\n PROFILE_LOG_DEBUG,\n PROFILE_LOG_INFO,\n} from \"../util/kos-config-init\";\n\nconst resolveLogLevelProfile = (): LogLevelDesc | undefined => {\n const showDebugLogProfile = hasKosProfile(PROFILE_LOG_DEBUG);\n const showInfoLogProfile = hasKosProfile(PROFILE_LOG_INFO);\n return showDebugLogProfile\n ? \"DEBUG\"\n : showInfoLogProfile\n ? \"INFO\"\n : undefined;\n};\nexport const getLogLevel = (): LogLevelDesc => {\n const params = getQueryParams();\n\n const profileLogLevel = resolveLogLevelProfile();\n const logLevelParam = params[\"kosLogLevel\"];\n const logLevel =\n logLevelParam ??\n profileLogLevel ??\n window.kosLogLevel ??\n process.env.KOS_LOG_LEVEL;\n if (logLevel) {\n return logLevel as LogLevelDesc;\n }\n return \"WARN\";\n};\n\nexport const getKosMessageLogging = (): boolean => {\n const enableAll =\n window.kosMessageLogging || process.env.KOS_MESSAGE_LOGGING === \"true\";\n return enableAll;\n};\n\nexport const getLogMessageToStudio = (): boolean => {\n const enableAll =\n window.kosMessageStudioLogging ||\n process.env.KOS_MESSAGE_STUDIO_LOGGING === \"true\";\n return enableAll;\n};\n","import log, { LogLevel } from \"loglevel\";\nimport {\n getKosMessageLogging,\n getLogLevel,\n getLogMessageToStudio,\n} from \"../../util/log-utils\";\n\nconst WS_LOG = \"ws-log\";\nconst originalFactory = log.methodFactory;\n\nconst enableMessageLogging = getKosMessageLogging();\n\nconst enableStudioMessageLogging = getLogMessageToStudio();\nlog.methodFactory = function (methodName, logLevel, loggerName) {\n const rawMethod = originalFactory(methodName, logLevel, loggerName);\n\n return function (...args: any[]) {\n const _name = loggerName ? String(loggerName) : \"\";\n\n const prefix = _name\n ? `[${String(_name).substring(_name.lastIndexOf(\":\") + 1)}] | `\n : \"[root] | \";\n\n // Concatenate all arguments similar to console.log\n const message = args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg) : String(arg)\n )\n .join(\" \");\n\n rawMethod(`${prefix}${message}`);\n if (\n globalThis?.kosConfig?.logging &&\n globalThis.kosLog &&\n (loggerName !== WS_LOG ||\n (enableMessageLogging && enableStudioMessageLogging))\n ) {\n globalThis.kosLog(`UI: ${prefix}${message}`);\n }\n };\n};\nlet level = getLogLevel();\nlog.setLevel(level);\n\nwindow.setKosLogLevel = (_level: log.LogLevelDesc) => {\n level = _level;\n log.setLevel(_level);\n};\nconst wsLog = log.getLogger(WS_LOG);\nwindow.enableKosMessageLog = () => {\n wsLog.setLevel(log.levels.INFO);\n};\n\nwindow.disableKosMessageLog = () => {\n wsLog.setLevel(log.levels.ERROR);\n};\n\nif (enableMessageLogging) {\n window.enableKosMessageLog();\n} else {\n window.disableKosMessageLog();\n}\nconst styles = [\n \"color: black\",\n \"display: block\",\n \"background-color: lightgreen\",\n\n \"padding: 4px\",\n \"margin: 0\",\n \"text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)\",\n \"box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset\",\n\n \"font-weight: bold\",\n].join(\";\");\n\nconst received = [\n \"color: black\",\n \"display: block\",\n\n \"padding: 4px\",\n \"background-color: yellow\",\n \"margin: 0\",\n \"text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)\",\n \"box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset\",\n\n \"font-weight: bold\",\n].join(\";\");\n\nconst conditionallyLog =\n (level: LogLevel[keyof LogLevel]) => (fn: VoidFunction) => {\n if (log.getLevel() <= level) {\n fn();\n }\n };\nexport const KosLog = {\n ...log,\n\n ifDebug: conditionallyLog(log.levels.DEBUG),\n ifInfo: conditionallyLog(log.levels.INFO),\n ifWarn: conditionallyLog(log.levels.WARN),\n ifError: conditionallyLog(log.levels.ERROR),\n getLogger: (name: string) => log.getLogger(`kos::${name}`),\n getLoggers: () => log.getLoggers(),\n createLogger: ({ name, group }: { name: string; group?: string }) => {\n const loggerName = `${group ? `${group}:` : \"kos\"}::${name}`;\n const _log = log.getLogger(loggerName);\n let _level = globalThis.kos.logOverrides?.find(\n (override) => override.name === loggerName\n )?.level;\n if (_level) {\n _log.setLevel(_level);\n } else {\n _level = globalThis.kos.logOverrides?.find((override) =>\n loggerName.startsWith(override.name)\n )?.level;\n if (_level) {\n _log.setLevel(_level);\n }\n }\n return _log;\n },\n wsSend: (...msg: any[]) => {\n const str = String(msg).replace(/\\n/g, \"\\\\n\");\n wsLog.info(`%c⬆ ${str}`, styles);\n },\n wsReceive: (...msg: any[]) => {\n const str = String(msg).replace(/\\n/g, \"\\\\n\");\n wsLog.info(`%c⬇ ${str}`, received);\n },\n};\n","import { registerExtensionPoint } from \"../core/extension\";\nimport { KosLog } from \"../core/log\";\n\nexport const EXTENSION_FEATURE_FLAG_RESOLVER = \"featureFlagResolver\";\nexport type FlagResolver<T = any> = (input: T) => Promise<string[]>;\nconst flagResolvers = new Map<string, FlagResolver<any>[]>();\nregisterExtensionPoint(EXTENSION_FEATURE_FLAG_RESOLVER, {\n register: (id: string, mapper: FlagResolver) => {\n if (!flagResolvers.has(id)) {\n flagResolvers.set(id, []);\n }\n flagResolvers.get(id)?.push(mapper);\n },\n execute: async <T>(id: string, input: T) => {\n const resolver = flagResolvers.get(id);\n if (!resolver) {\n return [];\n }\n const promises = resolver.map((m) => m(input));\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(`Feature flag resolver ${id} failed: ${r.reason}`);\n return [];\n }\n })\n .flat();\n const uniquePaths = Array.from(new Set(paths)).reduce<FeatureFlags>(\n (acc, path) => {\n acc[path] = true;\n return acc;\n },\n {}\n );\n\n KosFeatureFlags.updateFlags(uniquePaths);\n return Object.keys(uniquePaths) as string[];\n },\n});\ntype FeatureFlags = Record<string, boolean>;\nexport const LOADER_FEATURE_FLAG = \"kos.loader.featureFlag\";\nexport class FeatureFlagService {\n private flags: Record<string, boolean> = {};\n\n constructor(initialFlags: FeatureFlags = {}) {\n this.flags = initialFlags;\n }\n\n // Check if a feature is enabled\n isFeatureEnabled(flag: string): boolean {\n return !!this.flags[flag];\n }\n\n // Enable a feature\n enableFeature(flag: string): void {\n this.flags[flag] = true;\n }\n\n // Disable a feature\n disableFeature(flag: string): void {\n this.flags[flag] = false;\n }\n\n // Toggle a feature\n toggleFeature(flag: string): void {\n this.flags[flag] = !this.flags[flag];\n }\n\n // Update multiple features at once\n updateFlags(newFlags: FeatureFlags): void {\n this.flags = { ...this.flags, ...newFlags };\n }\n}\n\nwindow.KosFeatureFlags = window.KosFeatureFlags ?? new FeatureFlagService();\n\nexport const KosFeatureFlags = window.KosFeatureFlags;\n","export const hslToHex = (h: number, s: number, l: number) => {\n l /= 100;\n const a = (s * Math.min(l, 1 - l)) / 100;\n const f = (n) => {\n const k = (n + h / 30) % 12;\n const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n return Math.round(255 * color)\n .toString(16)\n .padStart(2, \"0\"); // convert to Hex and prefix \"0\" if needed\n };\n return `#${f(0)}${f(8)}${f(4)}`;\n};\n\nexport const hslStringToHex = (hsl: string) => {\n const reg = new RegExp(\"hsl\\\\((\\\\d+),\\\\s+(\\\\d+)\\\\%,\\\\s+(\\\\d+)\\\\%\\\\)\");\n const match = reg.exec(hsl);\n if (!match) {\n throw Error(\"Invalid HSL string\");\n }\n return hslToHex(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]));\n};\n\nexport const resolveVariable = (element: Element, variable: string) =>\n getComputedStyle(element).getPropertyValue(variable);\nexport const variableToHex = (element: Element, variable: string) =>\n hslStringToHex(resolveVariable(element, variable));\n","import { runInAction as kosAction } from \"mobx\";\nimport { IKosDataModel } from \"../core/kosModel\";\n\nexport type KosDataMapper<\n D extends object = any,\n T extends IKosDataModel = IKosDataModel\n> = (data: D, model: T) => Partial<Omit<T, keyof IKosDataModel>>;\n\nexport type KosDataMapperUtils<\n D extends object,\n T extends IKosDataModel\n> = KosDataMapper<D, T>;\nconst defaultMapper = <D extends object, T extends IKosDataModel>(\n data: D,\n _model: T\n) => {\n const parsedData = { ...data };\n if ((parsedData as any).id) {\n delete (parsedData as any).id;\n }\n\n return parsedData;\n};\n\n/**\n * Utility function that can be used to map an arbitrary data object to a model.\n *\n * @param data - the input data for the mapping function\n * @param model - the target model to map the data to\n * @param mapper - a mapping function that takes the input data and the target model and returns a partial of the target model. The\n * results will be applied to the model.\n */\nexport const mapDataToModel = <D extends object, T extends IKosDataModel>(\n data: D,\n model: T,\n mapper: KosDataMapperUtils<D, T> = defaultMapper\n) => {\n const partial = mapper(data, model);\n kosAction(() => {\n Object.assign(model, partial);\n });\n};\n","const deletionMap = new Map<string, NodeJS.Timeout[]>();\nexport const KosDeletionManager = {\n addToDeletionQueue: (modelId: string, timeout: NodeJS.Timeout) => {\n const timeouts = deletionMap.get(modelId) || [];\n timeouts.push(timeout);\n deletionMap.set(modelId, timeouts);\n },\n\n cancelDeletion: (modelId: string) => {\n const timeouts = deletionMap.get(modelId);\n if (timeouts) {\n timeouts.forEach((timeout) => {\n clearTimeout(timeout);\n });\n }\n },\n};\n","// dependency-manager.ts\n\nimport { KosDeletionManager } from \"./kos-deletion-manager\";\nimport { KosLog } from \"./log\";\n\nconst log = KosLog.createLogger({ name: \"kos-dependency-manager\" });\n\nexport class KosDependencyManager {\n private _usedByCache = new Map<string, string[]>();\n private _usesCache = new Map<string, string[]>();\n\n add(modelId: string, dependencyId: string) {\n KosDeletionManager.cancelDeletion(dependencyId);\n\n const usedBy = this._usedByCache.get(dependencyId) || [];\n if (!usedBy.includes(modelId)) usedBy.push(modelId);\n this._usedByCache.set(dependencyId, usedBy);\n\n const uses = this._usesCache.get(modelId) || [];\n if (!uses.includes(dependencyId)) uses.push(dependencyId);\n this._usesCache.set(modelId, uses);\n }\n\n remove(modelId: string, dependencyId: string) {\n const usedBy = this._usedByCache.get(dependencyId) || [];\n this._usedByCache.set(\n dependencyId,\n usedBy.filter((id) => id !== modelId)\n );\n\n const uses = this._usesCache.get(modelId) || [];\n this._usesCache.set(\n modelId,\n uses.filter((id) => id !== dependencyId)\n );\n }\n\n canDestroy(modelId: string): boolean {\n const usedBy = this._usedByCache.get(modelId);\n if (usedBy?.length) {\n log.info(`Model ${modelId} is still used by: ${usedBy.join(\", \")}`);\n return false;\n }\n return true;\n }\n\n clear() {\n this._usedByCache.clear();\n this._usesCache.clear();\n }\n}\n","export enum KosModelState {\n CREATING = `creating`,\n CREATED = `created`,\n INITIALIZING = `initializing`,\n INITIALIZED = `initialized`,\n LOADING = `loading`,\n LOADED = `loaded`,\n ONLINE = `online`,\n READYING = `readying`,\n READY = `ready`,\n READY_FAILED = `ready_failed`,\n RESETTING = `resetting`,\n RESET = `reset`,\n OFFLINE = `offline`,\n UNLOADING = `unloading`,\n UNLOADED = `unloaded`,\n FAILED = `failed`,\n INACTIVE = \"inactive\",\n ACTIVE = \"active\",\n ACTIVATING = \"activating\",\n DEACTIVATING = \"deactivating\",\n}\n\nexport enum KosModelEvents {\n CREATE = `create`,\n INITIALIZE = `init`,\n LOAD = `load`,\n READY = `ready`,\n GO_ONLINE = `go_online`,\n GO_OFFLINE = `go_offline`,\n RESET = `go_offline`,\n UNLOAD = `unload`,\n FAILED = \"failed\",\n GO_ACTIVE = \"go_active\",\n GO_INACTIVE = \"go_inactive\",\n TIMEOUT = \"timeout\",\n}\n","// model-cache.ts\n\nimport { observable } from \"mobx\";\nimport type { IKosDataModel, IKosModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-cache\" });\n\nexport type KosModelCacheHandler = Pick<\n KosModelCache,\n \"hasModel\" | \"restoreFromDeleteCache\" | \"addModel\" | \"getModelById\"\n>;\n\nexport class KosModelCache {\n private _modelsById = observable.map<string, IKosModel>(new Map());\n private _toDelete = new Map<string, IKosModel>();\n private _preloaded: IKosModel[] = [];\n private _isPreloaded = false;\n\n constructor(\n private preloadKeys: (\n | string\n | { modelType: string; modelId?: string; options?: Record<string, any> }\n )[] = []\n ) {}\n\n get models(): IKosModel[] {\n return Array.from(this._modelsById.values())\n .map((model) => model as IKosModel)\n .filter((model) => !this._toDelete.has(model.modelId));\n }\n getModelById<T extends IKosDataModel = IKosDataModel>(\n id: string\n ): IKosModel<T> | undefined {\n if (!id) return undefined;\n if (this._toDelete.has(id)) return undefined;\n return this._modelsById.get(id) as IKosModel<T>;\n }\n\n addModel<T extends IKosModel>(model: T): T {\n const existing = this.getModelById(model.modelId) || model;\n this._modelsById.set(existing.modelId, existing);\n return existing as T;\n }\n\n removeModel(modelId: string): void {\n this._modelsById.delete(modelId);\n this._toDelete.delete(modelId);\n }\n\n hasModel(modelId?: string): boolean {\n return (\n !!modelId && this._modelsById.has(modelId) && !this._toDelete.has(modelId)\n );\n }\n\n restoreFromDeleteCache(modelId?: string): void {\n if (modelId && this._toDelete.has(modelId)) {\n const model = this._toDelete.get(modelId);\n this._toDelete.delete(modelId);\n this._modelsById.set(modelId, model!);\n }\n }\n\n markForDeletion(model: IKosModel): void {\n this._modelsById.delete(model.modelId);\n this._toDelete.set(model.modelId, model);\n }\n\n preload(\n createFn: (\n key:\n | string\n | { modelType: string; modelId?: string; options?: Record<string, any> }\n ) => IKosModel | undefined\n ): IKosModel[] {\n if (this._isPreloaded) {\n log.debug(\"Returning cached preloaded models\");\n return this._preloaded;\n }\n this._preloaded = this.preloadKeys\n .map((key) => {\n log.debug(\n `Preloading model: ${typeof key === \"string\" ? key : key.modelType}`\n );\n return createFn(key);\n })\n .filter((model): model is IKosModel => !!model);\n this._isPreloaded = true;\n return this._preloaded;\n }\n}\n","/**\n * @internal\n */\nexport const SubscriptionHandlers = Symbol(`SubscriptionHandlers`);\nexport const DependencyModels = Symbol(`DependencyModels`);\nexport const FutureService = Symbol(`FutureService`);\nexport const ChildModels = Symbol(`ChildModels`);\nexport const ParentModel = Symbol(`ParentModel`);\nexport const LogConfig = Symbol(`LogConfig`);\nexport const ReferenceConfig = Symbol(`ReferenceConfig`);\nexport const KosModelSymbol = Symbol(`KosModelSymbol`);\nexport const ModelEffects = Symbol(`ModelEffects`);\nexport const CompanionParentModel = Symbol(`CompanionParentModel`);\nexport const FutureContainerSetup = Symbol(`FutureContainerSetup`);\nexport const MultipleFutureContainerSetup = Symbol(\n `MultipleFutureContainerSetup`\n);\nexport const FutureAliases = Symbol(`FutureAliases`);\nexport const TroubleAwareSetup = Symbol(`TroubleAwareSetup`);\nexport const LoggerSetup = Symbol(`LoggerSetup`);\nexport const ContainerAwareSetup = Symbol(`ContainerAwareSetup`);\n","import { ChildModels } from \"./propKeys\";\n\n/**\n * Decorator for marking a property as a child model within a Kos Data Model class.\n *\n * If a property is marked as a child model, it will be automatically included in the model's\n * lifecycle management. This means that when the parent model will not transition to a ready state\n * until all of its child models are ready.\n *\n * Similarly, when the parent model is destroyed, all of its child models will be destroyed as well.\n *\n * If the property is a KosModelContainer then all of the underlying child models will be included in the\n * child model lifecycle management.\n *\n * @param target - The target object or class.\n * @param name - The name of the property to be marked as a child model.\n * @returns A decorator function that marks the property as a child model.\n * @category KOS Model Decorator\n */\nexport const kosChild = (target: {} | any, name: PropertyKey): any => {\n target[ChildModels] = target[ChildModels] || {};\n target[ChildModels][name] = true;\n};\n","import type { IKosDataModel } from \"../core/kosModel\";\n\n/**\n * Creates a property key string based on a given key from a Kos data model.\n *\n * Property keys are used by the KOS model framework to provide property expansion in model data.\n *\n * When create a model dependency or any model metadata that is derived from the existing model data,\n * a property key should be used to reference the data model key.\n *\n * For kos dependencies, propKeys can be used to resolve any dependency options that are derived from the data model.\n *\n * For topic handlers, the resolved topic can include propKey to allow for dynamic topic resolution based on the data model.\n *\n * @param key - The key from a Kos data model.\n * @returns A property key string enclosed in curly braces with a \"PROP_\" prefix.\n *\n * @example\n * // Create a property key for a data model key \"name\"\n * const propertyKey = createPropKey(\"name\");\n * // Result: \"{PROP_name}\"\n *\n * @example\n * // Create a property key for a data model key \"id\"\n * const propertyKey = createPropKey(\"id\");\n * // Result: \"{PROP_id}\"\n *\n * @example\n * The propKey can be used as part of dependency or topic listener to allow for models to\n * dynamically change the dependency or topic listener based on the data model.\n * ```typescript\n * @kosDependency({modelType: Ingredient.type, id: propertyKey})\n * ```\n */\nexport const createPropKey = <R extends IKosDataModel>(key: keyof R) =>\n `{PROP_${String(key)}}`;\n\nexport const createOptionKey = <R extends object>(key: keyof R) =>\n `{PROP_${String(key)}}`;\n","/* eslint-disable no-param-reassign */\nimport { createPropKey } from \"../../util/model-attribute-utils\";\nimport { IKosDataModel } from \"../kosModel\";\nimport { ParentModel } from \"./propKeys\";\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\nexport interface KosParentProps {\n parentId?: string;\n}\n\n/**\n * Decorator for declaring that a KOS model should be aware of it parent model.\n * This decorator will ensure that the parent model is available to the child model immediately after creation.\n * There is a slight performance overhead to this decorator, so it should only be used when necessary.\n *\n * @category KOS Model Decorator\n */\nconst DEFAULT_OPTION_KEY = createPropKey<any>(\"kosParentId\");\nexport const kosParentAware =\n <T extends IKosDataModel>(options?: KosParentProps) =>\n (constructor: DecoratedKosModel<T>): any => {\n constructor[ParentModel] = constructor[ParentModel] || {};\n const parentId = options?.parentId || DEFAULT_OPTION_KEY;\n constructor[ParentModel] = { parentId };\n };\n","/* eslint-disable no-param-reassign */\nimport type { IKosDataModel } from \"../kosModel\";\nimport { kosParentAware } from \"./kos-parent\";\nimport { CompanionParentModel } from \"./propKeys\";\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\n/**\n * Base interface for all companion models.\n * Provides the getCompanionParent() method available in both decorator and composition modes.\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 */\nexport interface KosCompanionComposition<\n TParent extends IKosDataModel = IKosDataModel\n> extends 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 */\nexport interface KosCompanionDecorator<\n TParent extends IKosDataModel = IKosDataModel\n> extends KosCompanionAware<TParent> {\n // Parent properties are dynamically proxied at runtime\n // TypeScript interface merging provides compile-time type safety\n}\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 *\n * @category KOS Model Decorator\n * @since 2.1.0\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\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 };\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 */\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).\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 * }\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 /**\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\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 */\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 * 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 */\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 * 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 */\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`) 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 * ## 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 */\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\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","/* eslint-disable no-param-reassign */\nimport type {\n FutureAwareContainer,\n IFutureModel,\n} from \"../../../models/models/future/future-types\";\nimport { FutureContainerSetup } from \"./propKeys\";\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 */\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 */\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 */\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\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 */\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 * Default future from the handler.\n * Returns the most recently added future or undefined if no futures are active.\n */\n future?: IFutureModel;\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\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 * // All Future Container properties and named futures are now available automatically\n * // Access: this.pourFuture, this.agitateFuture, this.gateFuture\n *\n * onFutureUpdate?(future: IFutureModel): void {\n * // Handle updates from any managed Future\n * }\n * }\n * ```\n */\nexport type KosMultipleFutureAwareFull<T extends string = string> =\n KosMultipleFutureAwareMinimal &\n MultipleFutureProperties<T> & {\n /**\n * Current operation progress as a percentage (0-100) for the default future.\n * Returns 0 when no default 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 for the default future.\n * Common values: \"IDLE\", \"IN_PROGRESS\", \"SUCCESS\", \"ERROR\", \"CANCELLED\".\n * Returns \"IDLE\" when no default Future is active.\n */\n status: string;\n\n /**\n * Whether the default operation is currently actively executing.\n * True when default 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 default 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 default Future operation.\n * Sends cancellation request to the backend service managing the Future.\n * No-op if no default 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 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 reactive getters for default future, progress, status, isRunning, isCancelled (in full mode)\n * - Adding dynamic named future getters based on @kosFuture aliases\n * - Adding cancelFuture method for canceling the default operation (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): void {\n * // Handle Future updates from any operation\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\n * interface BackgroundServiceModelImpl extends KosMultipleFutureAwareMinimal<\"task1\" | \"task2\"> {}\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 */\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","export enum DependencyLifecycle {\n INIT = \"init\",\n LOAD = \"load\",\n READY = \"ready\",\n ACTIVATE = \"activate\",\n ONLINE = \"online\",\n}\n\n/**\n * The parameters for the kosDependency decorator.\n * */\nexport interface KosDependencyParams<Options = unknown> {\n /** The type of the model to be injected. */\n modelType: string;\n /** The id of the model to be injected. */\n id?: string;\n /** The options to be passed to the model constructor. */\n options?: Options;\n /** The lifecycle at which the dependency should be injected. */\n lifecycle?: DependencyLifecycle;\n}\n","import type { KosMethodTypes, KosRequest, KosResponse } from \"../services/browser-router\";\nimport { DependencyModels } from \"./propKeys\";\nimport { DependencyLifecycle } from \"../../types/kos-dependency\";\n\n/**\n * Symbol to store HTTP route metadata on the model prototype\n */\nexport const HttpRouteHandlers = Symbol(\"HttpRouteHandlers\");\n\n/**\n * Internal property name for the auto-injected BrowserRouter dependency\n */\nconst BROWSER_ROUTER_DEPENDENCY_KEY = \"__httpBrowserRouter\";\n\n/**\n * Interface for HTTP route configuration\n */\nexport interface IHttpRouteConfig {\n method: KosMethodTypes;\n path: string;\n handler: string; // Method name\n middleware?: Array<(req: KosRequest, res: KosResponse, next: () => void) => void>;\n}\n\n/**\n * Base function for creating HTTP method decorators\n */\nfunction createHttpMethodDecorator(method: KosMethodTypes) {\n return function httpMethodDecorator(path: string) {\n return function (\n target: any,\n propertyKey: string,\n descriptor: PropertyDescriptor\n ) {\n // Ensure the HttpRouteHandlers property exists on the target object\n target[HttpRouteHandlers] = target[HttpRouteHandlers] || [];\n\n // Store the route configuration\n const routeConfig: IHttpRouteConfig = {\n method,\n path,\n handler: propertyKey,\n };\n\n target[HttpRouteHandlers].push(routeConfig);\n\n // Automatically add BrowserRouter as a dependency if not already present\n // This ensures the BrowserRouter is available when HTTP routes are registered\n target[DependencyModels] = target[DependencyModels] || {};\n \n // Only add if not already present (to avoid overwriting user-defined dependencies)\n if (!target[DependencyModels][BROWSER_ROUTER_DEPENDENCY_KEY]) {\n // We need to import BrowserRouter type here\n // Using a dynamic reference to avoid circular dependency\n target[DependencyModels][BROWSER_ROUTER_DEPENDENCY_KEY] = {\n modelType: \"browser-router-model\", // This is the MODEL_TYPE from BrowserRouter\n lifecycle: DependencyLifecycle.INIT,\n };\n }\n\n return descriptor;\n };\n };\n}\n\n/**\n * Decorator for GET endpoints\n * @param path - The route path (e.g., \"/api/users/:id\")\n * \n * Supports PropKeys for dynamic path segments:\n * - {MODEL_ID} - replaced with the model's ID\n * - {PROP_propertyName} - replaced with model.propertyName value\n * \n * @example Basic usage:\n * ```typescript\n * @get(\"/api/users/:id\")\n * async getUser(req: KosRequest<\"/api/users/:id\">, res: KosResponse) {\n * const userId = req.params.id;\n * const user = await this.userService.getUser(userId);\n * res.status(200).send(user);\n * }\n * ```\n * \n * @example With PropKeys:\n * ```typescript\n * class TenantApiModel {\n * tenantId = \"acme-corp\";\n * \n * @get(\"/api/tenants/{PROP_tenantId}/users\")\n * async getTenantUsers(req: KosRequest, res: KosResponse) {\n * // Route registered as: /api/tenants/acme-corp/users\n * }\n * \n * @get(\"/api/models/{MODEL_ID}/config\")\n * async getModelConfig(req: KosRequest, res: KosResponse) {\n * // Route registered as: /api/models/<actual-model-id>/config\n * }\n * }\n * ```\n */\nexport const get = createHttpMethodDecorator(\"GET\");\n\n/**\n * Decorator for POST endpoints\n * @param path - The route path\n * \n * @example\n * ```typescript\n * @post(\"/api/users\")\n * async createUser(req: KosRequest<\"/api/users\">, res: KosResponse) {\n * const userData = req.body;\n * const newUser = await this.userService.createUser(userData);\n * res.status(201).send(newUser);\n * }\n * ```\n */\nexport const post = createHttpMethodDecorator(\"POST\");\n\n/**\n * Decorator for PUT endpoints\n * @param path - The route path\n * \n * @example\n * ```typescript\n * @put(\"/api/users/:id\")\n * async updateUser(req: KosRequest<\"/api/users/:id\">, res: KosResponse) {\n * const userId = req.params.id;\n * const updates = req.body;\n * const updatedUser = await this.userService.updateUser(userId, updates);\n * res.status(200).send(updatedUser);\n * }\n * ```\n */\nexport const put = createHttpMethodDecorator(\"PUT\");\n\n/**\n * Decorator for DELETE endpoints\n * @param path - The route path\n * \n * @example\n * ```typescript\n * @del(\"/api/users/:id\")\n * async deleteUser(req: KosRequest<\"/api/users/:id\">, res: KosResponse) {\n * const userId = req.params.id;\n * await this.userService.deleteUser(userId);\n * res.status(204).send();\n * }\n * ```\n */\nexport const del = createHttpMethodDecorator(\"DELETE\");\n\n/**\n * Alias for del decorator\n */\nexport const httpDelete = del;\n\n/**\n * Check if a model has HTTP route handlers\n */\nexport function hasHttpRouteHandlers(model: any): boolean {\n return !!model?.[HttpRouteHandlers] && model[HttpRouteHandlers].length > 0;\n}\n\n/**\n * Get HTTP route handlers from a model\n */\nexport function getHttpRouteHandlers(model: any): IHttpRouteConfig[] {\n return model?.[HttpRouteHandlers] || [];\n}","/**\n * @internal\n */\nimport { IKosDataModel } from \"../kosModel\";\nimport { LogConfig } from \"./propKeys\";\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\ninterface LogConfigProps {\n group?: string;\n}\nexport const kosLogger =\n <T extends IKosDataModel>({ group }: LogConfigProps = { group: \"\" }) =>\n (constructor: DecoratedKosModel<T>): any => {\n constructor[LogConfig] = constructor[LogConfig] || {};\n constructor[LogConfig] = { group };\n };\n","import { KosLog } from \"../log\";\n\nexport interface LoggerOptions {\n modelId?: string;\n modelTypeName?: string;\n component?: string;\n}\n\nexport class KosLoggerFactory {\n static create({ modelId, modelTypeName, component }: LoggerOptions) {\n const nameParts = [component ?? \"kos\", modelTypeName, modelId]\n .filter(Boolean)\n .join(\".\");\n\n return KosLog.createLogger({ name: nameParts });\n }\n}\n","/* eslint-disable no-param-reassign */\nimport type { KosContextLogger } from \"../kosModel\";\nimport { KosLoggerFactory } from \"../model/kos-logger-factory\";\nimport { KosModelSymbol, LoggerSetup } from \"./propKeys\";\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 */\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 */\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 // Get the model type from the @kosModel decorator\n // This will be set when @kosModel is applied\n const getModelType = () => target.prototype[KosModelSymbol]?.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\ninterface KosModelEffectProps<T = any> {\n dependencies: (model: T) => any[];\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 */\nexport function kosModelEffect<T = any>(props?: KosModelEffectProps<T>) {\n return (target: T, _propertyKey: string, descriptor: PropertyDescriptor) => {\n target[ModelEffects] = target[ModelEffects] || {};\n\n target[ModelEffects][_propertyKey] = {\n dependencies: props?.dependencies,\n value: descriptor.value,\n };\n descriptor.value = function () {\n throw new Error(`Method ${_propertyKey} cannot be called directly.`);\n };\n };\n}\n","/**\n * @ignore\n * @deprecated\n */\nimport { ReferenceConfig } from \"./propKeys\";\n\ninterface ReferenceProps {\n modelType: string;\n}\n\nexport const kosReference =\n (props: ReferenceProps) =>\n (target: {} | any, name: PropertyKey): any => {\n target[ReferenceConfig] = target[ReferenceConfig] || {};\n target[ReferenceConfig][name] = props;\n };\n","/* eslint-disable no-param-reassign */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { TroubleAware } from \"../../../models/models/trouble/types\";\nimport { DependencyModels, TroubleAwareSetup } from \"./propKeys\";\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 */\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 at which the dependency should be injected.\n *\n * @category KOS Model Decorator\n * */\nexport const kosDependency =\n <Options = unknown>({\n /** The type of the model to be injected. */\n modelType,\n id,\n options,\n\n lifecycle,\n }: KosDependencyParams<Options>) =>\n (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType,\n id,\n options,\n lifecycle: lifecycle || DependencyLifecycle.INIT,\n };\n };\n","import {\n kosAutoEffect,\n KosLog,\n kosObservable,\n makeAutoObservable,\n} from \"../../../core\";\nimport {\n FutureAwareContainer,\n FutureContainer,\n IFutureModel,\n type MultiFutureAware,\n} from \"./future-types\";\n\n/**\n * Future handler for managing multiple concurrent long-running operations.\n *\n * Provides comprehensive lifecycle management for models that coordinate multiple\n * device operations simultaneously. Each Future is tracked with its own alias\n * and receives automatic progress updates and cleanup when operations complete.\n *\n * @example Managing Multiple Operations\n * ```typescript\n * @kosModel(\"device-maintenance-model\")\n * export class DeviceMaintenanceModel implements FutureContainer {\n * futureHandler: MultipleFutureHandler;\n *\n * constructor(modelId: string, options: any, context: KosCreationContext) {\n * this.id = modelId;\n * this.futureHandler = new MultipleFutureHandler(this);\n * }\n *\n * async startCalibration(deviceId: string): Promise<CalibrationResult> {\n * const future = await this.createFuture('/device/calibrate', { deviceId });\n * this.futureHandler.addFuture(future, `calibration-${deviceId}`);\n * return future;\n * }\n *\n * async startCleaning(deviceId: string): Promise<CleaningResult> {\n * const future = await this.createFuture('/device/clean', { deviceId });\n * this.futureHandler.addFuture(future, `cleaning-${deviceId}`);\n * return future;\n * }\n *\n * onFutureUpdate(future: IFutureModel): void {\n * // Handle progress updates from any managed Future\n * console.log(`${future.id}: ${future.progress}% complete`);\n * }\n * }\n * ```\n *\n * @group KOS Model\n * @category Asynchronous Operations\n */\nexport class MultipleFutureHandler<T extends {} = Record<string, unknown>>\n implements FutureAwareContainer<T>, MultiFutureAware<T>\n{\n private futures: Map<string, IFutureModel<T>>;\n private defaultContext: string;\n private context: string;\n private disposers = new Map<string, () => void>();\n private container?: FutureContainer<T>;\n constructor(container?: FutureContainer<T>, defaultContext?: string) {\n this.futures = kosObservable.map(new Map<string, IFutureModel<T>>());\n this.context = \"\";\n this.defaultContext = defaultContext || \"\";\n this.container = container;\n makeAutoObservable(this);\n }\n\n get allFutures() {\n return Array.from(this.futures.values());\n }\n\n get future() {\n return this.futures.get(this.defaultContext);\n }\n addFuture(future: IFutureModel<T>, alias?: string) {\n this.futures.set(alias || future.id, future);\n this.context = alias || future.id;\n const disposer = kosAutoEffect(() => {\n if (future.endState || future.progress) {\n this.container?.onFutureUpdate?.(future);\n }\n });\n this.disposers.set(alias || future.id, disposer);\n }\n\n removeFuture(alias?: string) {\n this.futures.delete(alias || this.context);\n this.disposers.get(alias || this.context)?.();\n this.disposers.delete(alias || this.context);\n }\n\n getFuture(alias?: string) {\n const future = this.futures.get(alias || this.context);\n return future;\n }\n\n get futureMap() {\n return this.futures;\n }\n}\n\n/**\n * Future handler for managing single long-running operations with simplified API.\n *\n * Provides streamlined lifecycle management for models that typically handle\n * one operation at a time. Automatically tracks progress and provides reactive\n * status information for UI integration.\n *\n * @example Single Operation Management\n * ```typescript\n * @kosModel(\"brewing-system-model\")\n * export class BrewingSystemModel implements FutureContainer {\n * futureHandler: FutureHandler;\n *\n * constructor(modelId: string, options: any, context: KosCreationContext) {\n * this.id = modelId;\n * this.futureHandler = new FutureHandler(this);\n * }\n *\n * async startBrewingCycle(recipe: Recipe): Promise<BrewingResult> {\n * const future = await this.createFuture('/brewing/start', { recipe });\n * this.futureHandler.addFuture(future);\n * return future;\n * }\n *\n * get isOperationActive(): boolean {\n * return this.futureHandler.status !== 'NOT_RESOLVED';\n * }\n *\n * get operationProgress(): number {\n * return this.futureHandler.progress;\n * }\n *\n * onFutureUpdate(future: IFutureModel): void {\n * // Handle progress updates from the active Future\n * console.log(`Brewing: ${future.progress}% complete`);\n * }\n * }\n * ```\n *\n * @group KOS Model\n * @category Asynchronous Operations\n */\nexport class FutureHandler<T extends object = Record<string, unknown>>\n implements FutureAwareContainer<T>\n{\n private disposer?: () => void;\n\n private _future?: IFutureModel<T>;\n private container?: FutureContainer<T>;\n constructor(container?: FutureContainer<T>) {\n this._future = undefined;\n this.container = container;\n makeAutoObservable(this);\n }\n removeFuture() {\n this._future = undefined;\n this.disposer?.();\n this.disposer = undefined;\n }\n\n get future() {\n return this._future;\n }\n getFuture(): IFutureModel<T> | undefined {\n return this._future;\n }\n\n addFuture(future: IFutureModel<T>) {\n this._future = future;\n\n const disposer = kosAutoEffect(() => {\n if (future.endState || future.progress) {\n this.container?.onFutureUpdate?.(future);\n }\n });\n this.disposer = disposer;\n }\n\n onFutureUpdate?: ((future: IFutureModel<T>) => void) | undefined;\n\n get allFutures() {\n return this._future ? [this._future] : [];\n }\n get timeRemaining() {\n return this._future?.timeRemaining || \"\";\n }\n\n get status() {\n return this._future?.status || \"NOT_RESOLVED\";\n }\n\n get progress() {\n return this._future?.progress || -1;\n }\n\n async cancel() {\n if (this._future) {\n try {\n await this._future.cancelFuture();\n } catch (e) {\n KosLog.error(e);\n throw e;\n }\n }\n }\n}\n","import type { TroubleModel } from \"../types\";\n\nexport const troubleByTypeReducer = (\n acc: Record<string, TroubleModel[]>,\n trouble: TroubleModel\n) => {\n const type = trouble.type;\n if (!acc[type]) {\n acc[type] = [];\n }\n acc[type].push(trouble);\n return acc;\n};\n","import { IAtom, action, createAtom, makeObservable, observable } from \"mobx\";\n\nexport const KosObservableData = Symbol(\"KosObservableData\");\nclass ObservableDataMap<T extends Record<string | number | symbol, any>> {\n private map: Map<keyof T, T[keyof T]>;\n _revision: number = 1;\n\n private atomMap: Map<keyof T, IAtom> = new Map();\n constructor() {\n this.map = observable.map(new Map<keyof T, T[keyof T]>());\n // Make _revision observable\n makeObservable(this, { _revision: observable });\n }\n\n // Set a value in the map\n setValue<K extends keyof T>(key: K, value: T[K]): void {\n const hadKey = this.map.has(key);\n this.map.set(key, value);\n if (!hadKey) {\n action(() => {\n this._revision++;\n })();\n }\n }\n\n // Get a value from the map\n getValue<K extends keyof T>(key: K): T[K] | undefined {\n return this.map.get(key);\n }\n\n has(key: keyof T): boolean {\n return this.map.has(key);\n }\n\n get entries(): [keyof T, T[keyof T]][] {\n return Array.from(this.map.entries());\n }\n\n // Getter for keys in the map\n get keys(): string[] {\n // Access revision to make this getter reactive to structural changes\n this._revision;\n return Array.from(this.map.keys()) as string[];\n }\n\n get values(): T[keyof T][] {\n return Array.from(this.map.values());\n }\n\n // Create a proxy handler to intercept property accesses\n private proxyHandler: ProxyHandler<ObservableDataMap<T>> = {\n get: (target, property: any) => {\n // Handle direct property access including _revision\n if (property === \"_revision\" || target[property] !== undefined) {\n return target[property];\n }\n if (this.atomMap.has(property)) {\n if (this.atomMap.get(property)?.reportObserved()) {\n return this.getValue(property);\n }\n }\n return this.getValue(property);\n }, // Retrieve value from the map // Retrieve value from the map\n set: (_target, property: keyof T, value: T[keyof T]) => {\n const hadKey = this.map.has(property);\n this.setValue(property, value); // Set value in the map\n if (!this.atomMap.has(property)) {\n this.atomMap.set(property, createAtom(property.toString()));\n }\n this.atomMap.get(property)?.reportChanged(); // Notify MobX that the value has changed\n if (!hadKey) {\n // Revision was already incremented in setValue, no need to increment again\n }\n return true;\n },\n ownKeys: () => [...(Array.from(this.map.keys()) as string[]), \"_revision\"],\n };\n\n setValues(initialData?: T) {\n if (initialData) {\n Object.keys(initialData).forEach((key) => {\n this.setValue(key as keyof T, initialData[key]);\n });\n }\n }\n // Create a proxy for the class instance\n get proxy(): T {\n return new Proxy(this, this.proxyHandler) as unknown as KosData<T>;\n }\n}\n\nObservableDataMap.prototype[KosObservableData] = true;\n\ntype Constructor<T> = new (...args: any[]) => T;\n\nfunction createObservableData<T extends Record<string, any>>(\n BaseClass: Constructor<ObservableDataMap<T>>,\n initialData?: T\n): Constructor<ObservableDataMap<T>> {\n return new Proxy(BaseClass, {\n construct: (_target, args) => {\n const instance = new BaseClass(...args);\n instance.setValues(initialData);\n return instance.proxy as unknown as T & {\n setValues: (initialData?: T) => void;\n };\n },\n });\n}\n\nexport type KosData<T extends Record<any, any>> = T & {\n setValues: (initialData?: T) => void;\n keys: (keyof T)[];\n entries: [keyof T, T[keyof T]][];\n values: T[keyof T][];\n has: (key: keyof T) => boolean;\n};\n\nexport const ObservableData = <T extends Record<string, any>>(\n initialData?: T\n): KosData<T> => {\n const od = createObservableData(ObservableDataMap<T>, initialData);\n return new od(initialData) as unknown as KosData<T>;\n};\n","import { autorun, makeAutoObservable, observable, runInAction } from \"mobx\";\nimport { KosLog } from \"../core/log\";\nimport { ObservableData, type KosData } from \"../util\";\nimport { IKosBaseContainer } from \"./kos-container-model\";\nimport type { IKosDataModel } from \"./kosModel\";\nimport { IKosIdentifiable } from \"./types/model\";\n\ninterface KosContainerIndexOptions<T extends IKosIdentifiable> {\n container: IKosBaseContainer<T>;\n key: keyof T | IndexMapper<T>;\n}\n\nexport interface IKosContainerIndex<T extends IKosIdentifiable> {\n index: Map<string, Set<T>>;\n keys: string[];\n data: KosData<Record<string, T[]>>;\n getByKey: (key: string) => T[];\n refresh: () => void;\n}\n\nexport interface IndexMapper<T extends IKosIdentifiable> {\n (model: T):\n | Promise<string | string[] | undefined>\n | string\n | string[]\n | undefined;\n}\n\nfunction arraysAreEqual<T extends IKosDataModel = IKosDataModel>(\n arr1: T[],\n arr2: T[]\n): boolean {\n // Check if both arrays have the same length\n if (arr1.length !== arr2.length) return false;\n\n return arr1.every((item1) => arr2.includes(item1));\n}\n\nexport class KosContainerIndex<T extends IKosIdentifiable>\n implements IKosContainerIndex<T>\n{\n private _container: IKosBaseContainer<T>;\n private _map: Map<string, Set<T>>;\n private _key: string | number | symbol | IndexMapper<T>;\n\n data: KosData<Record<string, T[]>>;\n constructor({ container, key }: KosContainerIndexOptions<T>) {\n this._container = container;\n this._map = observable.map(new Map());\n this._key = key;\n this.data = ObservableData();\n\n this.generateIndex();\n autorun(() => {\n if (this._container.revision) {\n this.generateIndex();\n }\n });\n makeAutoObservable(this);\n }\n\n refresh() {\n this.generateIndex();\n }\n\n private addItemToIndex(\n key: string,\n model: T,\n map = this._map,\n data: Record<string, T[]> = this.data\n ) {\n const currentValue = map.get(key) || new Set<T>();\n currentValue.add(model);\n map.set(key, currentValue);\n data[key] = Array.from(currentValue);\n }\n\n private resolveIndex(map, data: Record<string, T[]>) {\n const toRemove = this.data.keys.filter(\n (key) => !Object.keys(data).includes(key)\n );\n\n toRemove.forEach((key) => {\n delete this.data[key];\n this._map.delete(key);\n });\n Object.keys(data).forEach((key) => {\n const values = data[key];\n const existing = this.data[key] || [];\n if (!arraysAreEqual(values, existing)) {\n this.data[key] = values;\n const set = map.get(key) || new Set<T>();\n this._map.set(key, set);\n } else {\n KosLog.debug(`KosContainerIndex - Index ${key} is the same`);\n }\n });\n }\n private generateIndex() {\n runInAction(async () => {\n // this._map.clear();\n\n const tempMap = new Map<string, Set<T>>();\n const tempData: Record<string, T[]> = {};\n for (const model of this._container.data) {\n const value =\n typeof this._key === \"function\"\n ? await this._key(model)\n : model[this._key];\n if (Array.isArray(value)) {\n value.forEach((valueItem) => {\n this.addItemToIndex(valueItem, model, tempMap, tempData);\n });\n } else if (typeof value === \"string\" || typeof value === \"number\") {\n this.addItemToIndex(String(value), model, tempMap, tempData);\n } else if (typeof value === \"boolean\") {\n this.addItemToIndex(String(value), model, tempMap, tempData);\n }\n }\n\n this.resolveIndex(tempMap, tempData);\n });\n }\n\n get keys() {\n return Array.from(this._map.keys());\n }\n get index() {\n return this._map;\n }\n\n getByKey(key: string) {\n const models = this._map.get(key);\n if (models) {\n return Array.from(models);\n }\n return [];\n }\n}\n","import {\n isComputedProp,\n runInAction as kosAction,\n makeAutoObservable,\n observable,\n observe,\n reaction,\n} from \"mobx\";\n\nimport { destroyKosModel } from \"../util\";\nimport { ObservableData, type KosData } from \"../util/observable-proxy-map\";\nimport { KosContextManager } from \"./context/kos-context-manager\";\nimport { ExtensionManager } from \"./extension\";\nimport {\n IKosContainerIndex,\n IndexMapper,\n KosContainerIndex,\n} from \"./kos-container-index\";\nimport type { IKosDataModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\nimport { IKosIdentifiable } from \"./types/model\";\n\nexport interface IKosBaseContainer<T extends IKosIdentifiable> {\n revision: number;\n data: T[];\n idx: KosData<Record<string, Record<string, T[]>>>;\n index: Map<string, IKosContainerIndex<T>>;\n indexKeys: Record<string, string[] | undefined>;\n addModel: (model: T) => void;\n removeModel: (id: string) => void;\n addAll: (models: T[]) => void;\n removeAll: (ids: string[]) => void;\n getModel: (id: string) => T | undefined;\n increment: () => void;\n clear: () => Promise<void>;\n map: (typeof Array.prototype)[\"map\"];\n filter: (typeof Array.prototype)[\"filter\"];\n sort: (typeof Array.prototype)[\"sort\"];\n [Symbol.iterator](): IterableIterator<T>;\n}\n\nfunction observeComputedProperties(model, callback, keys: string[] = []) {\n // Get descriptors for all properties\n const descriptors = Object.getOwnPropertyDescriptors(model);\n\n // Filter to get only computed properties\n const computedProps = Object.keys(descriptors).filter((key) =>\n isComputedProp(model, key)\n );\n\n // Set up a reaction for each computed property\n const disposers = computedProps\n .filter((p) => keys.includes(p))\n .map((prop) =>\n reaction(\n () => model[prop], // Track the computed property\n (newValue, oldValue) => {\n // Call the callback with change details\n callback({ name: prop, newValue, oldValue });\n }\n )\n );\n\n // Return a function to dispose all reactions when needed\n return disposers;\n}\nexport interface IKosModelContainer<T extends IKosDataModel>\n extends IKosBaseContainer<T> {\n updateModel: (model: T) => void;\n getModel: (id: string) => T | undefined;\n getIndexByKey: (indexName: string, indexKey: string) => T[];\n getIndexKeys: (indexName: string) => string[];\n toJSON?: () => object;\n}\nconst log = KosLog.createLogger({ name: \"kos-container-model\" });\ntype PropType = string | number | symbol | undefined;\n\ninterface ContainerOptions<T extends IKosDataModel> {\n sortKey?: keyof T;\n indexMap?: Record<string, keyof T | IndexMapper<T>>;\n parentId?: string;\n extensionId?: string;\n}\nexport class KosModelContainer<T extends IKosDataModel>\n implements IKosModelContainer<T>\n{\n _data: Map<string, T>;\n private _sortKey?: PropType;\n private _revision: number;\n private _index: Map<string, IKosContainerIndex<T>>;\n private _optionsMap: ContainerOptions<T>[\"indexMap\"];\n private _disposerMap: Map<string, () => void> = new Map();\n private _parentId?: string;\n idx: KosData<Record<string, Record<string, T[]>>>;\n constructor(options?: ContainerOptions<T>) {\n this._data = observable.map(new Map());\n\n this._sortKey = options?.sortKey;\n this._revision = 1;\n const extensionOptions = options?.extensionId\n ? (ExtensionManager.indexExtension.loadIndexExtensions(\n options.extensionId\n ) as Record<string, keyof T | IndexMapper<T>>)\n : ({} as Record<string, keyof T | IndexMapper<T>>);\n const indexMap = options?.indexMap || {};\n this._optionsMap = { ...indexMap, ...extensionOptions };\n\n const tmp = options?.indexMap\n ? Object.keys(options.indexMap).reduce((acc, curr) => {\n acc[curr] = undefined;\n return acc;\n }, {})\n : {};\n this._index = observable.map(tmp);\n this.idx = ObservableData();\n this._parentId = options?.parentId;\n\n makeAutoObservable(this);\n this.init();\n }\n\n init() {\n Object.keys(this._optionsMap!).forEach((key) => {\n const modelKey = this._optionsMap![key];\n const idx = new KosContainerIndex<T>({\n container: this,\n key: modelKey,\n });\n this._index.set(key, idx);\n this.idx[key] = idx.data;\n });\n }\n [Symbol.iterator]() {\n return this.data[Symbol.iterator]();\n }\n\n get index() {\n return this._index;\n }\n get revision() {\n return this._revision;\n }\n\n get indexKeys() {\n return Array.from(this.index.keys()).reduce<\n Record<string, string[] | undefined>\n >((acc, curr) => {\n acc[curr] = this.index.get(curr)?.keys;\n return acc;\n }, {});\n }\n\n sortFn(a, b): number {\n const sortKey = this._sortKey;\n\n if (sortKey) {\n return String(a[sortKey]).localeCompare(String(b[sortKey]), undefined, {\n numeric: true,\n });\n }\n return 0;\n }\n\n get data() {\n const list = Array.from(this._data.values());\n\n if (this._sortKey) {\n list.sort(this.sortFn.bind(this));\n }\n return list;\n }\n\n increment() {\n kosAction(() => {\n this._revision = this._revision + 1;\n });\n }\n\n addAll(models: T[]) {\n kosAction(() => {\n models.forEach((model) => this.addModel(model, true));\n });\n this.increment();\n }\n\n removeAll(ids: string[]) {\n kosAction(() => {\n ids.forEach((id) => this.removeModel(id, true));\n this.increment();\n });\n }\n\n addModel(model: T, defer?: boolean) {\n this._data.set(model.id || \"\", model);\n if (model.id && this._parentId) {\n KosContextManager.setParentContext(model.id, this._parentId);\n }\n if (!defer) {\n this.increment();\n }\n const _disposer = this._disposerMap.get(model.id);\n if (_disposer) {\n _disposer();\n this._disposerMap.delete(model.id);\n }\n const _entries = Object.entries(this._optionsMap || {});\n const _values = Object.values(this._optionsMap || {});\n const _reverseMap = new Map(_entries.map(([k, v]) => [v, k]));\n const handler = (change) => {\n // if any of the index keys change refresh that specific index\n if (_values.includes(change.name as any)) {\n this.index.get(_reverseMap.get(change.name) as string)?.refresh();\n }\n // refresh all of the function based indexes.\n // could look to optimize this if needed but it would require a react hooks-like\n // dependency tracking system.\n const fnIndexs = _entries.filter(\n ([, value]) => typeof value === \"function\"\n );\n\n for (const [key] of fnIndexs) {\n this.index.get(key)?.refresh();\n }\n };\n const computedDisposers = observeComputedProperties(\n model,\n handler,\n _values.filter((v) => typeof v === \"string\") as string[]\n );\n const disposer = observe(model, handler);\n this._disposerMap.set(model.id || \"\", () =>\n [disposer, ...computedDisposers].forEach((d) => d())\n );\n }\n\n removeModel(id: string, defer?: boolean) {\n this._data.delete(id);\n if (!defer) {\n this.increment();\n }\n const disposer = this._disposerMap.get(id);\n if (disposer) {\n disposer();\n this._disposerMap.delete(id);\n }\n }\n\n updateModel(model: T) {\n this._data.set(model.id || \"\", model);\n this.increment();\n }\n\n getModel(id: string) {\n return this._data.get(id);\n }\n\n getIndexKeys(indexName: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n return idx.keys ?? [];\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n getIndexByKey(indexName: string, indexKey: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n if (idx.index.has(indexKey)) {\n return idx.getByKey(indexKey);\n } else {\n log.info(\n `key ${indexKey} not found in ${indexName} index: ${Array.from(\n idx.index.keys()\n )}`\n );\n return [];\n }\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n\n async clear() {\n this._data.forEach((model) => {\n const modelId = model.id;\n destroyKosModel(model)\n .then(() => {\n log.debug(`${modelId} destroyed, removing from map`);\n this.removeModel(modelId!, true);\n })\n .catch((e) => log.error(e));\n });\n this.increment();\n }\n\n filter<S extends any>(\n predicate: (value: any, index: number, array: any[]) => value is S,\n thisArg?: any\n ) {\n return this.data.filter(predicate, thisArg);\n }\n\n sort(compareFn?: ((a: any, b: any) => number) | undefined) {\n return this.data.sort(compareFn);\n }\n map<U>(\n callbackfn: (value: any, index: number, array: any[]) => U,\n thisArg?: any\n ) {\n return this.data.map(callbackfn, thisArg);\n }\n\n forEach(\n callbackfn: (value: any, index: number, array: any[]) => void,\n thisArg?: any\n ) {\n this.data.forEach(callbackfn, thisArg);\n }\n\n toJSON() {\n const indexes = this.indexKeys;\n return {\n indexes,\n data: this.data.map((model) => {\n return {\n id: model.id,\n type: model.constructor.name,\n };\n }),\n };\n }\n}\n","import { KosCore } from \"../core/kosCore\";\nimport { IKosDataModel } from \"../core/kosModel\";\n/**\n * Asynchronously waits for a Kos Data Model to become ready for use.\n *\n * This utility function is used to ensure that a Kos Data Model is fully\n * loaded and ready to be accessed before performing any operations on it.\n *\n * @category Utility\n * @name whenReady\n * @version 1.0.0\n * @param dataModel - The Kos Data Model to wait for readiness.\n * @throws {Error} If the specified data model is not found or if it has no ID.\n * @returns A promise that resolves to the same data model when it becomes ready.\n *\n * @example\n * // Wait for the 'dataModel' to become ready before using it.\n * const dataModel = await whenReady(dataModel);\n */\nexport const whenReady = async (dataModel: IKosDataModel) => {\n if (dataModel.id) {\n // Retrieve the model associated with the provided ID.\n const model = KosCore.getInstance().modelManager.getModelById(dataModel.id);\n\n // If the model is not found, throw an error.\n if (!model) {\n throw new Error(`Model with ID ${dataModel.id} not found`);\n }\n\n // Wait for the model to become ready before resolving the promise.\n await model?.whenReady();\n } else {\n // If the data model has no ID, throw an error.\n throw new Error(\"Data model must have a valid ID\");\n }\n\n // Return the same data model once it becomes ready.\n return dataModel;\n};\n","import { KosCore } from \"../core/kosCore\";\nimport { IKosDataModel, type IKosModel } from \"../core/kosModel\";\nimport { KosModelEvents, KosModelState } from \"../core/lifecycle\";\nimport { KosLog } from \"../core/log\";\nimport { whenReady } from \"./when-ready\";\n\n/**\n * Asynchronously destroys a KOS data model.\n *\n * @async\n * @param model - The KOS data model to destroy.\n * @throws An error if the model cannot be destroyed.\n */\nexport const destroyKosModel = async (model: IKosDataModel) => {\n await KosCore.getInstance().whenReady();\n await KosCore.getInstance().modelManager.initiateDestroyModel(model);\n};\n\nexport const unloadKosModel = async (dataModel: IKosDataModel) => {\n await KosCore.getInstance().whenReady();\n if (!dataModel.id) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(dataModel.id);\n if (model) {\n await model.fsm.transitionTo(KosModelEvents.UNLOAD, KosModelState.UNLOADED);\n }\n};\n/**\n * Asynchronously resets a KOS data model.\n *\n * @async\n * @param model - The KOS data model to reset.\n * @throws An error if the model cannot be reset.\n */\nexport const resetKosModel = async (model: IKosDataModel) => {\n await KosCore.getInstance().whenReady();\n\n await KosCore.getInstance().modelManager.reloadModel(model);\n KosLog.debug(\n `reload model initiated for model ${\n model.id\n }, model ready: ${isKosModelReady(model)} - ${Date.now()} `\n );\n await whenReady(model);\n KosLog.debug(\n `reload model complete for model ${\n model.id\n }, model ready: ${isKosModelReady(model)} - ${Date.now()} `\n );\n};\n\n/**\n * Asynchronously retrieves the type of a KOS data model.\n *\n * @async\n * @param modelId - The ID of the KOS data model.\n * @returns The type of the KOS data model.\n * @throws An error if the model ID is not provided or the model cannot be found.\n */\nexport const getKosModelType = async (modelId: string) => {\n await KosCore.getInstance().whenReady();\n if (!modelId) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n\n return model?.modelTypeName;\n};\n\n/**\n * Asynchronously retrieves a KOS data model and its type.\n *\n * @async\n * @param modelId - The ID of the KOS data model.\n * @returns An object containing the KOS data model and its type.\n * @throws An error if the model ID is not provided or the model cannot be found.\n */\nexport const getKosModel = async <T extends IKosDataModel = IKosDataModel>(\n modelId: string\n) => {\n await KosCore.getInstance().whenReady();\n if (!modelId) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n\n return { model: model?.modelData as T, type: model?.modelTypeName };\n};\n\n/**\n * Synchronously retrieves a KOS data model and its type.\n *\n * @param modelId - The ID of the KOS data model.\n * @returns An object containing the KOS data model and its type.\n * @throws An error if the model ID is not provided or the model cannot be found.\n */\nexport const getKosModelSync = <T extends IKosDataModel = IKosDataModel>(\n modelId: string\n) => {\n if (!modelId) {\n throw new Error(\"Model ID is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n\n return { model: model?.modelData as T, type: model?.modelTypeName };\n};\n\n/**\n * Finds and filters KOS data models of a specific type based on a predicate.\n *\n * @param modelType - The type of the KOS data models to search for.\n * @param predicate - An object representing filter conditions.\n * @returns An array of filtered KOS data models.\n * @throws An error if the model type is not provided.\n */\nexport const findModels = <T extends IKosDataModel>(\n modelType: string,\n predicate: { [k: string]: any }\n) => {\n if (!modelType) {\n throw new Error(\"Model type is required\");\n }\n const model = KosCore.getInstance().modelManager.getModelsByType(modelType);\n const filtered = model.filter((m) =>\n Object.keys(predicate).every((key) => m[key] === predicate[key])\n );\n return filtered as T[];\n};\n\n/**\n * Finds and retrieves the first KOS data model of a specific type based on a predicate.\n *\n * @param modelType - The type of the KOS data models to search for.\n * @param predicate - An object representing filter conditions.\n * @returns The first matching KOS data model, or undefined if none is found.\n * @throws An error if the model type is not provided.\n */\nexport const findModel = <T extends IKosDataModel>(\n modelType: string,\n predicate: { [k: string]: any }\n) => findModels<T>(modelType, predicate)[0];\n\n/**\n * Retrieves a companion KOS data model of a specific type associated with a given model.\n *\n * @param model - The KOS data model for which to retrieve a companion model.\n * @param type - The type of the companion model.\n * @returns The companion KOS data model of the specified type.\n * @throws An error if the model ID is not provided, the model cannot be found, or the companion model does not exist.\n */\nexport const getKosCompanionModel = <T extends IKosDataModel>(\n model: IKosDataModel,\n type: string\n) => {\n if (!model.id) {\n throw new Error(\"Model ID is required\");\n }\n const kosModel = KosCore.getInstance().modelManager.getModelById(model.id);\n if (!kosModel) {\n throw new Error(\"Model not found\");\n }\n\n const companionModel = kosModel.companionModels.get(type);\n return companionModel?.modelData as T;\n};\n\n/**\n * Retrieves all companion models for a given model.\n *\n * @param model - The KOS data model for which to retrieve a companion model.\n * @returns The list of companion KOS data models\n * @throws An error if the model ID is not provided, the model cannot be found, or the companion model does not exist.\n */\nexport const getAllKosCompanionModels = (model: IKosDataModel) => {\n if (!model.id) {\n throw new Error(\"Model ID is required\");\n }\n const kosModel = KosCore.getInstance().modelManager.getModelById(model.id);\n if (!kosModel) {\n throw new Error(\"Model not found\");\n }\n\n const companionModels = Array.from(kosModel.companionModels.all()).map(\n (m) => m.modelData\n );\n\n return companionModels;\n};\n\nexport const getObservableCompanions = (modelId: string) => {\n if (!modelId) {\n throw new Error(\"Model ID is required\");\n }\n const kosModel = KosCore.getInstance().modelManager.getModelById(modelId);\n if (!kosModel) {\n throw new Error(\"Model not found\");\n }\n\n const companionModels = kosModel.companionModels.data;\n\n return companionModels;\n};\n\nexport const resolveKosCompanion = <T extends IKosDataModel>(\n modelId: string,\n resolver: (model: T) => boolean\n): IKosModel | undefined => {\n const model = KosCore.getInstance().modelManager.getModelById(modelId);\n if (!model) {\n KosLog.info(`Model not found for id ${modelId}`);\n return undefined;\n }\n const companionModel = Array.from(model.companionModels.all()).find((m) =>\n resolver(m.modelData as T)\n );\n\n return companionModel;\n};\n\n/**\n * Checks if an object is an instance of a specific KOS data model type.\n *\n * @param type - The type of the KOS data model to check against.\n * @returns A type guard function that checks if an object is an instance of the specified KOS data model type.\n */\nexport const isKosModel =\n <T extends IKosDataModel>(type: string) =>\n (model: any): model is T =>\n Object.getPrototypeOf(model).modelTypeId === type;\n\nexport const isKosModelReady = (model: IKosDataModel) => {\n const kosModel = KosCore.getInstance().modelManager.getModelById(model.id);\n if (!kosModel) {\n throw new Error(\"Model not found\");\n }\n return kosModel.isReady();\n};\n","import { ModelFactory } from \"../types\";\nimport { KosContextManager } from \"./context/kos-context-manager\";\nimport { KosCore } from \"./kosCore\";\nimport { IKosDataModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-factory\" });\nexport const KosModelFactory = {\n byModelType: <T extends IKosDataModel, O extends {} = any>(\n modelType: string\n ) =>\n KosCore.getInstance().modelManager.getModelFactory<T>(\n modelType\n ) as ModelFactory<T, O>,\n getModelInstance: <T extends IKosDataModel, O extends {} = any>(\n id: string,\n modelType: string,\n options?: O\n ) => {\n const factory = KosModelFactory.byModelType<T, O>(modelType);\n if (!factory) {\n log.error(\n `No registered factory found for model type ${modelType}. Please register a factory for this model type. `\n );\n throw Error(`No factory found for model type ${modelType}`);\n }\n\n return factory.build(id, options);\n },\n};\n\nexport const Kos = {\n Factory: {\n create:\n <T extends IKosDataModel, O extends {} = any>(modelType: string) =>\n (id: string) =>\n (options?: O, parentId?: string) => {\n if (parentId) {\n KosContextManager.setParentContext(id, parentId);\n }\n const model = KosModelFactory.getModelInstance<T, O>(\n id,\n modelType,\n options\n );\n\n return model;\n },\n },\n\n Singleton: {\n create:\n <T extends IKosDataModel, O extends {} = any>(modelType: string) =>\n (options?: O, parentId?: string) => {\n if (parentId) {\n KosContextManager.setParentContext(modelType, parentId);\n }\n const model = KosModelFactory.getModelInstance<T, O>(\n modelType,\n modelType,\n options\n );\n\n return model;\n },\n },\n\n Model: {\n instance:\n <T extends IKosDataModel, O extends {} = any>(modelType: string) =>\n (id: string) =>\n KosModelFactory.getModelInstance<T, O>(id, modelType),\n },\n};\n","import type { BaseKosModelRegistrationBean } from \"../../types/model\";\nimport { KosCore } from \"../kosCore\";\nimport type {\n IKosModelRegistration,\n IKosRegistry,\n KosCompanionModelType,\n} from \"../types/registration\";\nimport {\n isKosModelRegistration,\n type KosModelRegistrationType,\n} from \"./model-registration\";\n\ndeclare global {\n interface Window {\n KosRegistry: {\n coreModels: Map<string, IKosModelRegistration>;\n preloadModels: string[];\n companionModels: Map<string, KosCompanionModelType<any>[]>;\n models: Map<string, BaseKosModelRegistrationBean<any, any>>;\n };\n }\n}\nwindow.KosRegistry =\n (window.KosRegistry as any) ||\n ({\n coreModels: new Map<string, IKosModelRegistration>(),\n preloadModels: [],\n companionModels: new Map<string, KosCompanionModelType<any>>(),\n models: new Map<string, BaseKosModelRegistrationBean<any, any>>(),\n } as any);\nconst coreModels = window.KosRegistry.coreModels;\nconst preloadModels: string[] = window.KosRegistry.preloadModels;\nconst companionModels = window.KosRegistry.companionModels;\nconst models = window.KosRegistry.models;\n\nexport interface RegistrationResult<R> {\n preload: (type: string) => RegistrationResult<R>;\n model: (\n registration:\n | BaseKosModelRegistrationBean<any, any>\n | KosModelRegistrationType<any, any>,\n preload?: boolean\n ) => RegistrationResult<R>;\n companion: (\n parentType: string,\n companion: KosCompanionModelType<any>\n ) => RegistrationResult<R>;\n legacy: <T extends IKosModelRegistration>(\n type: string,\n registration: T\n ) => RegistrationResult<R>;\n root: R;\n}\nexport const RegistrationManager = {\n model: {\n registerLegacyModel:\n <R>(root: R) =>\n <T extends IKosModelRegistration>(\n type: string,\n registration: T\n ): RegistrationResult<R> => {\n coreModels.set(type, registration);\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n preloadModel:\n <R>(root: R) =>\n (type: string): RegistrationResult<R> => {\n if (!preloadModels.includes(type)) {\n preloadModels.push(type);\n }\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n register:\n <R>(root: R) =>\n <\n T extends\n | BaseKosModelRegistrationBean<any, any>\n | KosModelRegistrationType<any, any>\n >(\n registration: T,\n preload?: boolean\n ): RegistrationResult<R> => {\n const register: BaseKosModelRegistrationBean<any, any> =\n isKosModelRegistration(registration)\n ? registration.registration()\n : registration;\n models.set(register.type, register as any);\n\n if (isKosModelRegistration(registration)) {\n registration.relatedModels.forEach((model) =>\n models.set(model.type, model.registration() as any)\n );\n }\n\n if (KosCore.getInstance().isReady) {\n if (\n !KosCore.getInstance().modelManager.registry.models[register.type]\n ) {\n console.info(\n `Model with type ${register.type} doesn't exist. Adding new registration`\n );\n KosCore.getInstance().modelManager.registry.models[register.type] =\n register.registration[register.type];\n if (isKosModelRegistration(registration)) {\n registration.relatedModels.forEach(\n (model) =>\n (KosCore.getInstance().modelManager.registry.models[\n model.type\n ] = model.registration().registration)\n );\n }\n }\n }\n if (preload) {\n RegistrationManager.model.preloadModel(root)(register.type);\n }\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n get: (type: string) => models.get(type),\n getAll: () => Array.from(models.entries()),\n getPreloadModels: () => preloadModels,\n getLegacyModels: () =>\n Array.from(coreModels.entries()).reduce((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {} as IKosRegistry[\"models\"]),\n },\n companion: {\n register:\n <R>(root: R) =>\n (\n parentType: string,\n companion: KosCompanionModelType<any>\n ): RegistrationResult<R> => {\n const companions = companionModels.get(parentType) || [];\n companions.push(companion);\n companionModels.set(parentType, companions);\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n root,\n };\n },\n getAll: () => Array.from(companionModels.entries()),\n },\n};\n\nexport const registerLegacyModel =\n RegistrationManager.model.registerLegacyModel;\nexport const registerKosModel = RegistrationManager.model.register;\nexport const registerCompanionModel = RegistrationManager.companion.register;\nexport const preloadKosModel = RegistrationManager.model.preloadModel;\n","import type { BaseKosModelRegistrationBean } from \"../../types/model\";\nimport { isKosModel } from \"../../util/kos-model-utils\";\nimport { Kos } from \"../kos-model-factory\";\nimport type {\n IKosDataModel,\n KosCreationContext,\n UpdateAware,\n} from \"../kosModel\";\nimport type { KosModelRegistrationFactory } from \"./base-kos-model-registration\";\nimport { RegistrationManager } from \"./registration-manager\";\nimport type { SingletonKosModelRegistrationFactory } from \"./singleton-kos-model-registration-factory\";\n\nexport const isUpdateable = (model: any): model is UpdateAware =>\n typeof model.updateModel === \"function\";\ninterface ModelRegistration<\n B extends boolean,\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n singleton: boolean;\n class: new (modelId: string, options: O, context: KosCreationContext) => T;\n type: string;\n factory: FactoryType<B, T, O>;\n}\n\ntype FactoryType<\n B extends boolean,\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = B extends true\n ? ReturnType<typeof Kos.Singleton.create<T, O>>\n : ReturnType<typeof Kos.Factory.create<T, O>>;\n\ntype KosOptionsFunction<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = (options: O) => { build: () => T };\nexport interface KosInstance<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n get: () => T;\n options: KosOptionsFunction<T, O>;\n forceUpdate: {\n options: KosOptionsFunction<T, O>;\n };\n}\n\nexport type KosModelRegistrationType<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> =\n | KosModelRegistrationFactory<T, O>\n | SingletonKosModelRegistrationFactory<T, O>;\n\nexport const isKosModelRegistration = (\n item: any\n): item is KosModelRegistrationType<any, any> =>\n item.registration !== undefined && typeof item.registration === \"function\";\nexport abstract class KosBaseModelRegistration<\n B extends boolean,\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n singleton: boolean;\n type: string;\n loader: string;\n class: new (modelId: string, options: O, context: KosCreationContext) => T;\n guard: ReturnType<typeof isKosModel<T>>;\n factory: FactoryType<B, T, O>;\n relatedModels: KosModelRegistrationType<any, any>[] = [];\n constructor(props: ModelRegistration<B, T, O>) {\n this.singleton = props.singleton;\n this.guard = isKosModel(props.type);\n this.type = props.type;\n this.loader = `kos.extension.model.loader.${props.type}`;\n this.factory = props.factory;\n this.class = props.class;\n }\n\n addRelatedModel(model: KosModelRegistrationType<any, any>) {\n this.relatedModels.push(model);\n }\n\n registerRelatedModels() {\n this.relatedModels.forEach((model) => model.register());\n }\n\n abstract registration(): BaseKosModelRegistrationBean<T, O>;\n\n register() {\n RegistrationManager.model.register({})(this.registration());\n this.registerRelatedModels();\n }\n\n abstract instance(id?: string): KosInstance<T, O>;\n}\n\nexport type KosModelRegistrationProps<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = Omit<ModelRegistration<false, T, O>, \"singleton\" | \"factory\">;\n","import type { BaseKosModelRegistrationBean } from \"../../types\";\nimport { getKosModelSync } from \"../../util/kos-model-utils\";\nimport { Kos } from \"../kos-model-factory\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport {\n KosBaseModelRegistration,\n isUpdateable,\n type KosInstance,\n type KosModelRegistrationProps,\n} from \"./model-registration\";\n\nexport class KosModelRegistrationFactory<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> extends KosBaseModelRegistration<false, T, O> {\n constructor(props: KosModelRegistrationProps<T, O>) {\n super({\n ...props,\n singleton: false,\n factory: Kos.Factory.create<T, O>(props.type),\n });\n }\n\n instance(id: string): KosInstance<T, O> {\n const optionsFactory = this.factory(id);\n return {\n get: () => {\n const model = getKosModelSync(id);\n if (!model) {\n throw new Error(\"Model not found with id \" + id);\n }\n if (this.guard(model)) {\n return model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n forceUpdate: {\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n if (isUpdateable(model)) {\n model.updateModel(options);\n } else {\n throw new Error(\n `Model ${this.type} is not updateable. Please implement UpdateAware interface`\n );\n }\n\n return model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n };\n },\n },\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n return model;\n } else {\n throw new Error(\"Model is not of type \" + this.type);\n }\n },\n };\n },\n };\n }\n registration(): BaseKosModelRegistrationBean<T, O> {\n return {\n type: this.type,\n predicate: this.guard,\n registration: {\n [this.type]: {\n class: this.class,\n singleton: false,\n },\n },\n\n factory: this.factory,\n };\n }\n}\n","import type { BaseKosModelRegistrationBean } from \"../../types\";\nimport { getKosModelSync } from \"../../util/kos-model-utils\";\nimport { Kos } from \"../kos-model-factory\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport {\n KosBaseModelRegistration,\n isUpdateable,\n type KosInstance,\n type KosModelRegistrationProps,\n} from \"./model-registration\";\n\nexport class SingletonKosModelRegistrationFactory<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> extends KosBaseModelRegistration<true, T, O> {\n constructor(props: KosModelRegistrationProps<T, O>) {\n super({\n ...props,\n singleton: true,\n factory: Kos.Singleton.create<T, O>(props.type),\n });\n }\n\n instance(): KosInstance<T, O> {\n const optionsFactory = this.factory;\n const result = {\n get: () => {\n const model = getKosModelSync(this.type);\n if (!model) {\n throw new Error(\"Model not found with id \" + this.type);\n }\n if (this.guard(model)) {\n return model;\n } else {\n throw new Error(\n `Model is not of type ${this.type}. Received type ${\n Object.getPrototypeOf(model).modelTypeId\n }`\n );\n }\n },\n forceUpdate: {\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n if (isUpdateable(model)) {\n model.updateModel(options);\n } else {\n throw new Error(\n `Model ${this.type} is not updateable. Please implement UpdateAware interface`\n );\n }\n\n return model;\n } else {\n throw new Error(\n `Model is not of type ${this.type}. Received type ${\n Object.getPrototypeOf(model).modelTypeId\n }`\n );\n }\n },\n };\n },\n },\n options: (options: O) => {\n return {\n build: () => {\n const model = optionsFactory(options);\n if (this.guard(model)) {\n return model;\n } else {\n throw new Error(\n `Model is not of type ${this.type}. Received type ${\n Object.getPrototypeOf(model).modelTypeId\n }`\n );\n }\n },\n };\n },\n };\n return result;\n }\n registration(): BaseKosModelRegistrationBean<T, O> {\n return {\n type: this.type,\n predicate: this.guard,\n registration: {\n [this.type]: {\n class: this.class,\n singleton: true,\n },\n },\n\n factory: this.factory,\n };\n }\n}\n","import { KOS_MODEL_ID } from \"../../../common\";\nimport { KosLog } from \"../log\";\n\nconst log = KosLog.createLogger({ name: \"resolve-parameters\" });\ninterface ResolveParameterOptions {\n value: string | object;\n modelId: string;\n modelData: any;\n}\nexport const resolveParameters = ({\n value,\n modelId,\n modelData,\n}: ResolveParameterOptions) => {\n let _value = value;\n if (Array.isArray(_value)) {\n return [...(value as any)];\n } else if (typeof _value !== \"string\" && typeof _value !== \"object\") {\n return _value;\n } else if (typeof _value === \"object\") {\n _value = Object.keys(_value).reduce((acc, curr) => {\n acc[curr] = resolveParameters({\n value: _value[curr],\n modelId,\n modelData,\n });\n\n return acc;\n }, {});\n } else if (typeof _value === \"string\") {\n const propRegex = new RegExp(\"{PROP_(.+?)}\", \"g\");\n let _depId: string | undefined = _value?.includes(KOS_MODEL_ID)\n ? _value.replace(KOS_MODEL_ID, modelId)\n : _value;\n\n if (modelData) {\n let hasUnresolvedProp = false;\n const isOnlyPropKey = /^{PROP_.+?}$/.test(_depId);\n\n _depId = _depId.replace(propRegex, (match, propName) => {\n if (\n Object.getOwnPropertyNames(modelData).includes(propName) ||\n Object.getOwnPropertyNames(Object.getPrototypeOf(modelData)).includes(\n propName\n )\n ) {\n const prop = modelData[propName];\n if (prop) {\n log.debug(`Resolved ${match} to ${prop}`);\n return prop;\n } else {\n const logLevel = isOnlyPropKey ? \"debug\" : \"warn\";\n log[logLevel](\n `Property ${propName} is falsy${\n isOnlyPropKey ? \"\" : \" in composite string\"\n }, marking for undefined return`\n );\n hasUnresolvedProp = true;\n return match;\n }\n }\n const logLevel = isOnlyPropKey ? \"debug\" : \"warn\";\n log[logLevel](\n `Property ${propName} not found in modelData${\n isOnlyPropKey ? \"\" : \" for composite string\"\n }`\n );\n return match;\n });\n\n if (hasUnresolvedProp) {\n return undefined;\n }\n }\n\n return _depId;\n } else {\n return _value;\n }\n\n return _value;\n};\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable max-len */\n/* eslint-disable no-param-reassign */\n/* eslint-disable max-classes-per-file */\nimport { makeAutoObservable } from \"mobx\";\nimport {\n FutureHandler,\n MultipleFutureHandler,\n} from \"../../../models/models/future/future-aware\";\nimport { troubleByTypeReducer } from \"../../../models/models/trouble/utils/trouble-reducer\";\nimport { KosContextManager } from \"../context/kos-context-manager\";\nimport { KosModelContainer } from \"../kos-container-model\";\nimport { KosCore } from \"../kosCore\";\nimport { IKosDataModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { KosModelRegistrationFactory } from \"../registration/base-kos-model-registration\";\nimport type { KosModelRegistrationType } from \"../registration/model-registration\";\nimport { SingletonKosModelRegistrationFactory } from \"../registration/singleton-kos-model-registration-factory\";\nimport {\n ChildModels,\n CompanionParentModel,\n ContainerAwareSetup,\n DependencyModels,\n FutureAliases,\n FutureContainerSetup,\n FutureService,\n KosModelSymbol,\n LogConfig,\n LoggerSetup,\n MultipleFutureContainerSetup,\n ParentModel,\n SubscriptionHandlers,\n TroubleAwareSetup,\n} from \"./propKeys\";\nimport { resolveParameters } from \"./resolve-parameters\";\n\nconst log = KosLog.createLogger({ group: \"decorators\", name: \"kos-model\" });\n\nfunction resolveParentContext(\n TargetClass: any,\n modelId: string,\n modelData: any\n) {\n const parentIdRaw = TargetClass[ParentModel]?.parentId;\n if (!parentIdRaw) return;\n\n const parentId = resolveParameters({\n value: parentIdRaw,\n modelData,\n modelId,\n });\n\n if (parentId && typeof parentId === \"string\") {\n KosContextManager.setParentContext(modelId, parentId);\n }\n}\n\nfunction injectFutureServices(modelInstance: any) {\n const future: Record<string, { handler: (args: any) => any }> =\n modelInstance[FutureService];\n if (!future) return;\n\n Object.entries(future).forEach(([key, { handler }]) => {\n modelInstance[key] = handler;\n });\n}\n\nfunction injectDependencies(modelInstance: any, modelId: string) {\n const dependencies = modelInstance[DependencyModels] || {};\n\n Object.entries(dependencies).forEach(([key, dependency]: [string, any]) => {\n const resolvedId = resolveParameters({\n value: dependency.id || dependency.modelType,\n modelData: modelInstance,\n modelId,\n });\n\n const options = Object.entries(dependency?.options || {}).reduce(\n (acc, [optKey, optVal]) => {\n acc[optKey] = resolveParameters({\n value: optVal as any,\n modelData: modelInstance,\n modelId,\n });\n return acc;\n },\n {} as Record<string, any>\n );\n\n if (typeof resolvedId === \"string\") {\n if (!dependency.lazy) {\n const model = KosCore.getInstance().modelManager.createModelInstance(\n dependency.modelType,\n resolvedId,\n options\n );\n modelInstance[key] = model.data;\n }\n\n KosCore.getInstance().modelManager.addDependency(modelId, resolvedId);\n }\n });\n}\n\nfunction injectFutureContainerSupport(modelInstance: any) {\n const futureSetup = modelInstance[FutureContainerSetup];\n if (!futureSetup) return;\n\n const { mode, handlerProperty } = futureSetup;\n\n // Create and add the futureHandler\n const futureHandler = new FutureHandler(modelInstance);\n modelInstance[handlerProperty] = futureHandler;\n\n // In full mode, add all the Future Container properties and methods\n if (mode === \"full\") {\n // Add future getter\n Object.defineProperty(modelInstance, \"future\", {\n get() {\n return futureHandler.future;\n },\n enumerable: true,\n configurable: true, // Allow MobX to make this observable\n });\n\n // Add progress getter\n Object.defineProperty(modelInstance, \"progress\", {\n get() {\n return futureHandler.future?.progress || 0;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add status getter\n Object.defineProperty(modelInstance, \"status\", {\n get() {\n return futureHandler.future?.status || \"IDLE\";\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add isRunning getter\n Object.defineProperty(modelInstance, \"isRunning\", {\n get() {\n return futureHandler.future ? !futureHandler.future.endState : false;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add isCancelled getter\n Object.defineProperty(modelInstance, \"isCancelled\", {\n get() {\n return futureHandler.future?.status === \"CANCELLED\" || false;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add cancelFuture method\n modelInstance.cancelFuture = async () => {\n if (futureHandler.future) {\n await futureHandler.future.cancelFuture();\n }\n };\n }\n}\n\nfunction injectMultipleFutureContainerSupport(modelInstance: any) {\n const setup = modelInstance[MultipleFutureContainerSetup];\n if (!setup) return;\n\n const { mode, handlerProperty } = setup;\n\n // Create and add the MultipleFutureHandler\n const futureHandler = new MultipleFutureHandler(modelInstance);\n modelInstance[handlerProperty] = futureHandler;\n\n // Add default future getter\n Object.defineProperty(modelInstance, \"future\", {\n get() {\n return futureHandler.future;\n },\n enumerable: true,\n configurable: true, // Allow MobX to make this observable\n });\n\n // Dynamically add named future getters based on aliases\n const aliases = modelInstance[FutureAliases];\n if (aliases instanceof Map) {\n aliases.forEach((alias) => {\n const futureGetterName = `${alias}Future`;\n\n // Add the main future getter for this alias\n Object.defineProperty(modelInstance, futureGetterName, {\n get() {\n return futureHandler.futureMap.get(alias);\n },\n enumerable: true,\n configurable: true,\n });\n\n // In full mode, add progress, status, isRunning, isCancelled for each aliased future\n if (mode === \"full\") {\n // Add progress getter for this alias\n Object.defineProperty(modelInstance, `${alias}Progress`, {\n get() {\n const future = futureHandler.futureMap.get(alias);\n return future?.progress || 0;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add status getter for this alias\n Object.defineProperty(modelInstance, `${alias}Status`, {\n get() {\n const future = futureHandler.futureMap.get(alias);\n return future?.status || \"IDLE\";\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add isRunning getter for this alias\n Object.defineProperty(modelInstance, `${alias}IsRunning`, {\n get() {\n const future = futureHandler.futureMap.get(alias);\n return future ? !future.endState : false;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add isCancelled getter for this alias\n Object.defineProperty(modelInstance, `${alias}IsCancelled`, {\n get() {\n const future = futureHandler.futureMap.get(alias);\n return future?.status === \"CANCELLED\" || false;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add cancel method for this alias\n modelInstance[\n `cancel${alias.charAt(0).toUpperCase()}${alias.slice(1)}`\n ] = async () => {\n const future = futureHandler.futureMap.get(alias);\n if (future) {\n await future.cancelFuture();\n }\n };\n }\n });\n }\n\n // In full mode, also add the default future properties and methods\n if (mode === \"full\") {\n // Add progress getter for default future\n Object.defineProperty(modelInstance, \"progress\", {\n get() {\n return futureHandler.future?.progress || 0;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add status getter for default future\n Object.defineProperty(modelInstance, \"status\", {\n get() {\n return futureHandler.future?.status || \"IDLE\";\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add isRunning getter for default future\n Object.defineProperty(modelInstance, \"isRunning\", {\n get() {\n return futureHandler.future ? !futureHandler.future.endState : false;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add isCancelled getter for default future\n Object.defineProperty(modelInstance, \"isCancelled\", {\n get() {\n return futureHandler.future?.status === \"CANCELLED\" || false;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add cancelFuture method for default future\n modelInstance.cancelFuture = async () => {\n if (futureHandler.future) {\n await futureHandler.future.cancelFuture();\n }\n };\n }\n}\n\nfunction injectTroubleAwareSupport(modelInstance: any) {\n const troubleSetup = modelInstance[TroubleAwareSetup];\n if (!troubleSetup) return;\n\n const { pathProperty } = troubleSetup;\n\n // troubleContainer dependency is already injected via DependencyModels\n // by the @kosTroubleAware decorator, so we just need to add the getters\n\n // Add troubles getter\n Object.defineProperty(modelInstance, \"troubles\", {\n get() {\n const pathValue = this[pathProperty];\n if (pathValue === undefined || pathValue === null) {\n const message = `@kosTroubleAware: Path property '${pathProperty}' is undefined on model ${\n this.id || \"unknown\"\n }. Returning empty troubles array.`;\n\n if (this.logger && typeof this.logger.warn === \"function\") {\n this.logger.warn(message);\n } else {\n console.warn(message);\n }\n\n return [];\n }\n\n return this.troubleContainer.troubles\n .getIndexByKey(\"byIface\", pathValue)\n .sort((a, b) => b.rank - a.rank);\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add troubleStatus getter (returns empty string by default - deprecated but required by interface)\n Object.defineProperty(modelInstance, \"troubleStatus\", {\n get() {\n return \"\";\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add troublesByType getter\n Object.defineProperty(modelInstance, \"troublesByType\", {\n get() {\n const troubles = this.troubles; // Will handle the undefined case\n return troubles.reduce(troubleByTypeReducer, {} as Record<string, any[]>);\n },\n enumerable: true,\n configurable: true,\n });\n}\n\nfunction injectContainerAwareSupport(modelInstance: any, modelId: string) {\n const containerSetup = modelInstance[ContainerAwareSetup];\n if (!containerSetup) return;\n\n const {\n containerProperty,\n includeMethods,\n includeGetters,\n modelsProperty,\n containerOptions,\n legacy,\n } = containerSetup;\n\n // Create container options with automatic parentId inference\n const finalContainerOptions = {\n ...containerOptions,\n // If parentId is not provided, use the modelId (first constructor parameter)\n parentId: containerOptions.parentId || modelId,\n };\n\n // Create and add the container\n const container = new KosModelContainer(finalContainerOptions);\n modelInstance[containerProperty] = container;\n\n // Register container as a kosChild for proper hierarchy management\n if (!modelInstance[ChildModels]) {\n modelInstance[ChildModels] = {};\n }\n modelInstance[ChildModels][containerProperty] = container;\n\n // Add convenience methods if requested\n if (includeMethods) {\n modelInstance.getModel = (id: string) => container.getModel(id);\n\n modelInstance.addModel = (model: any) => {\n container.addModel(model);\n };\n\n modelInstance.removeModel = (id: string) => {\n container.removeModel(id);\n };\n }\n\n // Add reactive getters if requested\n if (includeGetters) {\n // Add models getter - returns the container itself (compatible with IKosModelHolder)\n Object.defineProperty(modelInstance, modelsProperty, {\n get() {\n return container;\n },\n enumerable: true,\n configurable: true,\n });\n\n // Add data getter - returns the actual array (compatible with IKosModelHolder)\n Object.defineProperty(modelInstance, \"data\", {\n get() {\n return container.data;\n },\n enumerable: true,\n configurable: true,\n });\n }\n}\n\nfunction injectCompanionSupport(modelInstance: any, initialData: any) {\n const companionConfig =\n modelInstance.constructor.prototype[CompanionParentModel];\n if (!companionConfig) return;\n\n const { mode, parentProperty, excludeProperties } = companionConfig;\n\n // Get the parent model from initialData\n const parentModel = initialData[parentProperty];\n if (!parentModel) {\n log.warn(\n `Companion decorator configured but no parent model found at '${parentProperty}'`\n );\n return;\n }\n\n // Add getCompanionParent method (available in both modes)\n modelInstance.getCompanionParent = () => parentModel;\n\n // If composition mode, stop here - only getCompanionParent() is provided\n if (mode === \"composition\") {\n return;\n }\n\n // Lifecycle methods are never proxied (per-model type, parent executes first)\n const lifecycleMethods = [\n \"init\",\n \"load\",\n \"unload\",\n \"ready\",\n \"dispose\",\n \"destroy\",\n \"activate\",\n ];\n\n const internalMethods = [\n \"getDependencies\",\n \"getChildren\",\n \"update\",\n \"toJSON\",\n \"forceUpdate\",\n \"makeAutoObservable\",\n \"runInAction\",\n \"transaction\",\n \"observe\",\n \"unobserve\",\n \"intercept\",\n \"spy\",\n \"trace\",\n \"getCompanionParent\", // Don't override our own getCompanionParent\n ];\n\n // Check if a method is a topic handler by looking at the parent's SubscriptionHandlers\n const isTopicHandler = (name: string): boolean => {\n const subscriptionHandlers =\n parentModel.constructor.prototype[SubscriptionHandlers] || {};\n // Check if any registered handler function matches this method\n return Object.values(subscriptionHandlers).some((config: any) => {\n const handlerFunc = config?.handler;\n // Compare by function reference - the handler stored is the actual method\n return (\n handlerFunc === parentModel[name] ||\n handlerFunc === parentModel.constructor.prototype[name]\n );\n });\n };\n\n const shouldExclude = (name: string) =>\n name === \"constructor\" ||\n name.startsWith(\"_\") ||\n name.startsWith(\"__\") ||\n lifecycleMethods.includes(name) ||\n internalMethods.includes(name) ||\n excludeProperties.includes(name) ||\n isTopicHandler(name) || // Exclude topic handler methods in decorator mode\n name in modelInstance; // Don't override existing properties\n\n // Get all properties from parent and its prototype chain\n const properties = new Set<string>();\n\n // Get instance properties\n Object.getOwnPropertyNames(parentModel)\n .filter((name) => !shouldExclude(name))\n .forEach((name) => properties.add(name));\n\n // Get prototype properties\n let prototype = Object.getPrototypeOf(parentModel);\n while (prototype && prototype !== Object.prototype) {\n Object.getOwnPropertyNames(prototype)\n .filter((name) => !shouldExclude(name))\n .forEach((name) => properties.add(name));\n prototype = Object.getPrototypeOf(prototype);\n }\n\n // Create proxy properties on the companion\n for (const propertyName of properties) {\n try {\n const parentValue = (parentModel as any)[propertyName];\n\n if (typeof parentValue === \"function\") {\n // Create method proxy\n modelInstance[propertyName] = (...args: any[]) =>\n parentValue.apply(parentModel, args);\n } else {\n // Create property proxy with getter/setter\n // Since parent is already observable, these getters will automatically track parent changes\n Object.defineProperty(modelInstance, propertyName, {\n get: () => (parentModel as any)[propertyName],\n set: (value: any) => {\n (parentModel as any)[propertyName] = value;\n },\n enumerable: true,\n configurable: true, // Allow MobX to make this observable\n });\n }\n } catch (error) {\n // Skip properties that can't be accessed\n log.debug(\n `Skipping companion proxy for property ${propertyName}:`,\n error\n );\n }\n }\n}\n\nfunction makeSafeObservable(instance: any) {\n try {\n return makeAutoObservable(instance);\n } catch (e) {\n log.error(\"Failed to make observable:\", e);\n return instance;\n }\n}\n\nconst modelConstructorProxy: ProxyHandler<any> = {\n construct(TargetClass, args) {\n const [modelId, initialData = {}] = args;\n const kosContext = KosContextManager.createContext(modelId);\n\n resolveParentContext(TargetClass, modelId, initialData);\n\n // Check if @kosLoggerAware decorator is present - skip logger creation if so\n const hasLoggerAware = !!TargetClass.prototype[LoggerSetup];\n\n const logger = hasLoggerAware\n ? null // @kosLoggerAware will handle logger creation\n : KosLog.createLogger({\n name: TargetClass.prototype.modelTypeId,\n group: TargetClass[LogConfig]?.group ?? \"kos-model\",\n });\n\n const modelInstance = new TargetClass(modelId, initialData, {\n logger,\n kosContext,\n });\n\n injectFutureServices(modelInstance);\n injectFutureContainerSupport(modelInstance);\n injectMultipleFutureContainerSupport(modelInstance);\n injectTroubleAwareSupport(modelInstance);\n injectContainerAwareSupport(modelInstance, modelId);\n injectCompanionSupport(modelInstance, initialData);\n injectDependencies(modelInstance, modelId);\n\n return makeSafeObservable(modelInstance);\n },\n};\n\ninterface DecoratedKosModel<T extends IKosDataModel = IKosDataModel> {\n new (...args: any[]): T;\n}\n\ninterface KosModelConfig {\n modelTypeId: string;\n singleton?: boolean;\n autoRegister?: boolean;\n}\n\n/**\n * Decorator for defining a Kos Data Model class.\n *\n * @param config - The model configuration. Can be a string (backward compatibility) or configuration object.\n * @returns A decorator function that transforms the class into a KOS-compatible model.\n */\nexport function kosModel<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n>(config: string | KosModelConfig): ClassDecorator {\n return (constructor: any) => {\n const typedCtor = constructor as DecoratedKosModel<T>;\n\n // Parse configuration - support both string (backward compatibility) and object\n const modelConfig =\n typeof config === \"string\"\n ? { modelTypeId: config, autoRegister: false }\n : { autoRegister: false, ...config };\n\n typedCtor.prototype.modelTypeId = modelConfig.modelTypeId;\n typedCtor.prototype[KosModelSymbol] = true;\n typedCtor.prototype[SubscriptionHandlers] ??= {};\n typedCtor.prototype[DependencyModels] ??= {};\n\n KosLog.ifDebug(() => {\n KosLog.debug(`Registering model with id ${modelConfig.modelTypeId}`);\n });\n\n const proxiedCtor = new Proxy(typedCtor, modelConstructorProxy);\n\n // NEW: Transparently inject .Registration property if singleton flag is provided\n if (modelConfig.singleton !== undefined) {\n let registration: KosModelRegistrationType<T, O>;\n\n if (modelConfig.singleton) {\n registration = new SingletonKosModelRegistrationFactory<T, O>({\n class: proxiedCtor as any,\n type: modelConfig.modelTypeId,\n });\n } else {\n registration = new KosModelRegistrationFactory<T, O>({\n class: proxiedCtor as any,\n type: modelConfig.modelTypeId,\n });\n }\n\n // Inject as static property on the proxied constructor\n Object.defineProperty(proxiedCtor, \"Registration\", {\n value: registration,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n\n // Auto-register if requested (escape hatch for plugins)\n if (modelConfig.autoRegister) {\n registration.register();\n }\n }\n\n return proxiedCtor;\n };\n}\n","/**\n * @deprecated\n * @internal\n */\nimport { action } from \"mobx\";\nimport debounce from \"../../util/debounce\";\nimport { SubscriptionHandlers } from \"./propKeys\";\n\nexport interface IKosSubscriptionHandlerParams<T, M> {\n topic: string;\n condition?: (payload: T, model: M) => boolean;\n handler: Function;\n websocket?: boolean;\n skipParse?: boolean;\n}\n\nexport const kosSubscribe =\n <T = unknown, M = unknown>({\n topic,\n handler,\n websocket = false,\n condition = () => true,\n }: IKosSubscriptionHandlerParams<T, M>) =>\n (target: T) => {\n target[SubscriptionHandlers] = target[SubscriptionHandlers] || {};\n if (Array.isArray(topic)) {\n topic.forEach((t) => {\n target[SubscriptionHandlers][t] = {\n websocket,\n handler,\n condition,\n };\n });\n } else {\n target[SubscriptionHandlers][topic] = {\n websocket,\n handler: debounce(target, action(handler), 200),\n condition,\n };\n }\n };\n","/* eslint-disable no-param-reassign */\nimport type { ApiCallback } from \"../../../common/events\";\nimport { EventBusFunctional } from \"../../../common/events\";\nimport { DependencyLifecycle } from \"../../types\";\nimport { IKosDataModel } from \"../kosModel\";\nimport { SubscriptionHandlers } from \"./propKeys\";\nimport type { FlowControlOptions } from \"./kos-topic-handler-flow-control\";\n\n/**\n * Extended ApiCallback that includes wildcard capture data for handlers with trailing wildcards\n */\nexport interface ApiCallbackWithWildcard<T = string> extends ApiCallback<T> {\n wildcardCapture?: Record<string, string>;\n}\n\n/**\n * Utility function to extract trailing wildcard from a topic pattern and actual topic\n * @internal - exported for testing\n */\nexport function extractTrailingWildcard(\n pattern: string,\n actualTopic: string,\n wildcardName?: string\n): Record<string, string> {\n const result: Record<string, string> = {};\n\n if (!pattern.endsWith(\"/*\")) {\n return result;\n }\n\n // Remove the /* from the pattern to get the prefix\n const prefix = pattern.slice(0, -2);\n\n // Check if the actual topic starts with the prefix\n if (actualTopic.startsWith(prefix)) {\n const captured = actualTopic.slice(prefix.length + 1); // +1 to skip the /\n const name = wildcardName || \"path\";\n result[name] = captured;\n }\n\n return result;\n}\n\n/**\n * Check if a topic pattern has a trailing wildcard\n * @internal - exported for testing\n */\nexport function hasTrailingWildcard(pattern: string): boolean {\n return pattern.endsWith(\"/*\");\n}\n\n/**\n * Configuration parameters for defining a Kos topic handler function within a Kos Data Model class.\n *\n * @typeparam Response - The type of the raw response payload received from the topic.\n * @typeparam Model - The type of the Kos Data Model to which the topic handler belongs.\n * @typeparam TransformedResponse - The type of the transformed response payload after applying the transformation function.\n */\nexport interface IKosTopicHandlerParams<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n> {\n /**\n * The topic or array of topics to which the handler should respond.\n */\n topic: string | string[];\n\n /**\n * A conditional function that determines whether the handler should be invoked based on the received payload and the Kos Data Model instance.\n * If not provided, the handler will always be invoked when a matching topic is received.\n *\n * @param payload - The transformed payload received from the topic.\n * @param model - The Kos Data Model instance to which the topic handler belongs.\n * @returns `true` if the handler should be invoked, `false` otherwise.\n */\n condition?: (\n payload: TransformedResponse,\n model: Model,\n raw: Response\n ) => boolean;\n\n /**\n * A transformation function that converts the raw response payload into a desired format.\n * If not provided, the payload will be used as is.\n *\n * @param payload - The raw response payload received from the topic.\n * @returns The transformed payload in the desired format.\n */\n transform?: (payload: Response) => TransformedResponse;\n\n /**\n * Indicates whether the topic handler should listen for WebSocket messages.\n * If set to `true`, the handler will be invoked when WebSocket messages with matching topics are received.\n * Default is `false`.\n */\n websocket?: boolean;\n\n /**\n * @internal\n */\n fos?: boolean;\n\n /**\n * @internal\n */\n bridge?: boolean;\n\n lifecycle?: DependencyLifecycle;\n\n /**\n * @internal\n */\n skipParse?: boolean;\n\n destinationAddress?: string;\n\n // === FUNCTIONAL ENHANCEMENTS ===\n\n /**\n * Debounce events - only emit after a period of inactivity\n * @example debounce: 1000 // Wait 1 second after last event\n * @example debounce: { delay: 1000, discardIntermediate: true } // Only keep last value\n */\n debounce?:\n | number\n | {\n delay: number;\n /** If true, only keeps the last value. If false (default), accumulates all values */\n discardIntermediate?: boolean;\n };\n\n /**\n * Throttle events - limit emissions to once per interval\n * @example throttle: 500 // At most once every 500ms\n * @example throttle: { interval: 500, discardIntermediate: true } // Only keep first value in window\n */\n throttle?:\n | number\n | {\n interval: number;\n /** If true, only keeps the first value in window. If false (default), accumulates all values */\n discardIntermediate?: boolean;\n };\n\n /**\n * Buffer events and emit them as an array after time window or max size\n */\n buffer?: {\n /** Time window to collect events (ms) */\n time: number;\n /** Maximum number of events to buffer */\n maxSize?: number;\n };\n\n /**\n * Filter events based on a predicate function\n * Note: This operates on the raw payload before transformation\n */\n filter?: (payload: Response) => boolean;\n\n /**\n * Only handle the event once, then automatically unsubscribe\n */\n once?: boolean;\n\n /**\n * Replay the last N events to new handlers\n */\n replay?: {\n /** Number of events to remember and replay */\n bufferSize: number;\n };\n\n /**\n * Named wildcard capture for trailing /* patterns.\n * When enabled, the portion after the /* is parsed and passed to the handler.\n * You can optionally specify a name for the captured segment.\n *\n * @example\n * ```typescript\n * @kosTopicHandler({\n * topic: \"/config/system/*\",\n * websocket: true,\n * wildcardName: \"configPath\"\n * })\n * handleConfigUpdate(payload: ConfigData, raw: ApiCallbackWithWildcard<any>) {\n * // raw.wildcardCapture.configPath contains everything after \"/config/system/\"\n * }\n * ```\n */\n wildcardName?: string;\n\n /**\n * Advanced flow control options using async iterators internally.\n * Enables sophisticated event processing patterns like batching, backpressure,\n * on-the-fly transforms, and rate limiting.\n *\n * @example\n * ```typescript\n * @kosTopicHandler({\n * topic: 'sensor.data',\n * websocket: true,\n * flow: {\n * batch: { size: 50, window: 1000 },\n * transform: (events) => aggregateEvents(events),\n * backpressure: { maxConcurrent: 3 }\n * }\n * })\n * handleProcessedEvents(aggregatedData) {\n * // Receives transformed, batched data with backpressure control\n * }\n * ```\n */\n flow?: FlowControlOptions<Response, TransformedResponse>;\n}\n\n/**\n * Decorator for defining a Kos topic handler function within a Kos Data Model class.\n *\n * @param params - An object containing configuration parameters for the topic handler.\n * @returns A decorator function.\n *\n * @example Basic usage:\n * ```typescript\n * @kosTopicHandler({\n * topic: 'temperature/update',\n * websocket: true\n * })\n * handleTemperature(payload: TemperatureData) { }\n * ```\n *\n * @example Debounced handling:\n * ```typescript\n * @kosTopicHandler({\n * topic: 'rapid/updates',\n * websocket: true,\n * debounce: 1000 // Wait 1 second after last event\n * })\n * handleRapidUpdates(payload: UpdateData) { }\n * ```\n *\n * @example Buffered batch processing:\n * ```typescript\n * @kosTopicHandler({\n * topic: 'log/entry',\n * websocket: true,\n * buffer: { time: 5000, maxSize: 100 }\n * })\n * handleLogBatch(entries: LogEntry[]) { }\n * ```\n *\n * @example Trailing wildcard with custom name:\n * ```typescript\n * @kosTopicHandler({\n * topic: '/config/system/*',\n * websocket: true,\n * wildcardName: 'configPath'\n * })\n * handleConfigUpdate(payload: ConfigData, raw: ApiCallbackWithWildcard<any>) {\n * // raw.wildcardCapture.configPath = \"network/timeout\" (everything after \"/config/system/\")\n * }\n * ```\n *\n * @example Trailing wildcard with PropKeys:\n * ```typescript\n * const DEVICE_ID = createPropKey<DeviceModel>('deviceId');\n *\n * @kosTopicHandler({\n * topic: `/devices/${DEVICE_ID}/sensors/*`,\n * websocket: true,\n * wildcardName: 'sensorPath'\n * })\n * handleSensorEvent(payload: SensorData, raw: ApiCallbackWithWildcard<any>) {\n * // raw.wildcardCapture.sensorPath = \"temperature/reading\" (everything after device-specific prefix)\n * }\n * ```\n * @category KOS Model Decorator\n */\nexport function kosTopicHandler<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n>({\n topic,\n condition = (_payload, _model) => true,\n transform = (_payload) => _payload as any,\n websocket = false,\n fos = false,\n bridge = false,\n skipParse = false,\n lifecycle,\n destinationAddress,\n // Functional enhancements\n debounce,\n throttle,\n buffer,\n filter,\n once,\n replay,\n wildcardName,\n flow,\n}: IKosTopicHandlerParams<Response, Model, TransformedResponse>) {\n return (\n target: any,\n _propertyKey: string,\n descriptor: PropertyDescriptor\n ) => {\n // Ensure the SubscriptionHandlers property exists on the target object.\n target[SubscriptionHandlers] = target[SubscriptionHandlers] || {};\n\n const originalHandler = descriptor.value;\n\n // Create enhanced handler based on functional patterns\n let enhancedHandler = originalHandler;\n\n // Apply timing-based enhancements (these work on any payload type)\n const debounceDelay =\n typeof debounce === \"number\" ? debounce : debounce?.delay;\n const throttleInterval =\n typeof throttle === \"number\" ? throttle : throttle?.interval;\n\n if (debounceDelay && debounceDelay > 0) {\n enhancedHandler = createDebouncedHandler(enhancedHandler, debounce!);\n } else if (throttleInterval && throttleInterval > 0) {\n enhancedHandler = createThrottledHandler(enhancedHandler, throttle!);\n } else if (buffer) {\n enhancedHandler = createBufferedHandler(enhancedHandler, buffer);\n } else if (once) {\n enhancedHandler = createOnceHandler(enhancedHandler);\n }\n\n // Combine filter with existing condition function\n let enhancedCondition = condition;\n if (filter) {\n const originalCondition = condition;\n enhancedCondition = (\n payload: TransformedResponse,\n model: Model,\n raw: Response\n ) => {\n // First check the filter on raw payload\n if (!filter(raw)) {\n return false;\n }\n // Then check the original condition\n return originalCondition(payload, model, raw);\n };\n }\n\n // Wildcard processing is now handled in kos-subscription-manager.ts\n\n // Register handler(s) with their configurations.\n const handlerConfig = {\n websocket,\n fos,\n bridge,\n handler: enhancedHandler,\n condition: enhancedCondition,\n transform,\n lifecycle,\n skipParse,\n destinationAddress,\n wildcardName,\n flow,\n };\n\n if (Array.isArray(topic)) {\n topic.forEach((t) => {\n target[SubscriptionHandlers][t] = handlerConfig;\n });\n } else {\n target[SubscriptionHandlers][topic] = handlerConfig;\n }\n\n // Handle replay pattern\n if (replay) {\n setupReplayHandler(topic, replay.bufferSize);\n }\n };\n}\n\n// === HELPER FUNCTIONS FOR FUNCTIONAL PATTERNS ===\n\n// Type definitions for handler functions\ntype TopicHandler<T = any> = (this: any, payload: T) => void | Promise<void>;\ntype BufferedHandler<T = any> = (\n this: any,\n payloads: T[]\n) => void | Promise<void>;\n\nfunction createDebouncedHandler<T>(\n originalHandler: TopicHandler<T> | BufferedHandler<T>,\n config: number | { delay: number; discardIntermediate?: boolean }\n): TopicHandler<T> {\n const delay = typeof config === \"number\" ? config : config.delay;\n const discardIntermediate =\n typeof config === \"object\" ? config.discardIntermediate : false;\n\n let timeoutId: NodeJS.Timeout | null = null;\n let accumulated: T[] = [];\n\n return function (this: any, payload: T) {\n if (discardIntermediate) {\n // Original behavior - only keep last value\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n (originalHandler as TopicHandler<T>).call(this, payload);\n timeoutId = null;\n }, delay);\n } else {\n // New behavior - accumulate all values\n accumulated.push(payload);\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n timeoutId = setTimeout(() => {\n const batch = [...accumulated];\n accumulated = [];\n (originalHandler as BufferedHandler<T>).call(this, batch);\n timeoutId = null;\n }, delay);\n }\n };\n}\n\nfunction createThrottledHandler<T>(\n originalHandler: TopicHandler<T> | BufferedHandler<T>,\n config: number | { interval: number; discardIntermediate?: boolean }\n): TopicHandler<T> {\n const interval = typeof config === \"number\" ? config : config.interval;\n const discardIntermediate =\n typeof config === \"object\" ? config.discardIntermediate : false;\n\n let lastCall = 0;\n let timeoutId: NodeJS.Timeout | null = null;\n let accumulated: T[] = [];\n let pendingFlush = false;\n\n const flush = function (this: any) {\n if (accumulated.length > 0) {\n const batch = [...accumulated];\n accumulated = [];\n (originalHandler as BufferedHandler<T>).call(this, batch);\n }\n };\n\n return function (this: any, payload: T) {\n const now = Date.now();\n const timeSinceLastCall = now - lastCall;\n\n if (discardIntermediate) {\n // Original behavior - only process first value in window\n if (timeSinceLastCall >= interval) {\n lastCall = now;\n (originalHandler as TopicHandler<T>).call(this, payload);\n } else if (!timeoutId) {\n timeoutId = setTimeout(() => {\n lastCall = Date.now();\n (originalHandler as TopicHandler<T>).call(this, payload);\n timeoutId = null;\n }, interval - timeSinceLastCall);\n }\n } else {\n // New behavior - accumulate all values and emit batches at interval\n accumulated.push(payload);\n\n if (timeSinceLastCall >= interval) {\n lastCall = now;\n flush.call(this);\n } else if (!pendingFlush) {\n pendingFlush = true;\n timeoutId = setTimeout(() => {\n lastCall = Date.now();\n flush.call(this);\n timeoutId = null;\n pendingFlush = false;\n }, interval - timeSinceLastCall);\n }\n }\n };\n}\n\nfunction createBufferedHandler<T>(\n originalHandler: BufferedHandler<T>,\n bufferConfig: { time: number; maxSize?: number }\n): TopicHandler<T> {\n const buffer: T[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n const maxSize = bufferConfig.maxSize || 1000;\n\n const flush = (context: any) => {\n if (buffer.length > 0) {\n originalHandler.call(context, [...buffer]);\n buffer.length = 0;\n }\n };\n\n return function (this: any, payload: T) {\n buffer.push(payload);\n\n // Flush if buffer is full\n if (buffer.length >= maxSize) {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n flush(this);\n return;\n }\n\n // Set timeout if not already set\n if (!timeoutId) {\n timeoutId = setTimeout(() => {\n flush(this);\n timeoutId = null;\n }, bufferConfig.time);\n }\n };\n}\n\nfunction createOnceHandler<T>(\n originalHandler: TopicHandler<T>\n): TopicHandler<T> {\n let called = false;\n\n return function (this: any, payload: T) {\n if (!called) {\n called = true;\n originalHandler.call(this, payload);\n }\n };\n}\n\nfunction setupReplayHandler(topic: string | string[], bufferSize: number) {\n const topics = Array.isArray(topic) ? topic : [topic];\n\n topics.forEach((t) => {\n EventBusFunctional.replay(t, bufferSize);\n });\n}\n","import { EVENT_KOS_MODEL_READY } from \"../../common\";\n\nexport function modelEventTopicFactory(modelType: string, modelId?: string) {\n return `${EVENT_KOS_MODEL_READY}${modelType}${\n modelId ? `/${modelId}` : `/${modelType}`\n }`;\n}\n\nexport function modelTypeEventTopicFactory(modelType: string) {\n return `${EVENT_KOS_MODEL_READY}${modelType}`;\n}\n","import { when } from \"mobx\";\n\nexport function awaitFirstMatchingWhen(\n conditions: {\n condition: () => boolean;\n onMatch?: () => void;\n }[]\n): Promise<void> {\n const disposers: (() => void)[] = [];\n\n return new Promise<void>((resolve, reject) => {\n for (const { condition, onMatch } of conditions) {\n const disposer = when(condition, () => {\n // clean up all watchers\n disposers.forEach((d) => d());\n\n try {\n onMatch?.();\n resolve();\n } catch (e) {\n reject(e);\n }\n });\n disposers.push(disposer);\n }\n });\n}\n","import { ObservableMap } from \"mobx\";\nimport { DependencyModels } from \"../core/decorators\";\nimport { resolveParameters } from \"../core/decorators/resolve-parameters\";\nimport { IKosModelContainer } from \"../core/kos-container-model\";\nimport { KosCore } from \"../core/kosCore\";\nimport type { IKosDataModel, IKosModel } from \"../core/kosModel\";\nimport { KosModelEvents, KosModelState } from \"../core/lifecycle\";\nimport { KosLog } from \"../core/log\";\nimport {\n DependencyLifecycle,\n KosDependencyParams,\n} from \"../types/kos-dependency\";\n\nconst PROMISE_TIMEOUT = 5000;\nexport interface ModelPromise {\n promise?: Promise<void>;\n modelId?: string;\n model?: IKosModel;\n type?: string;\n status?: string;\n}\n\nclass ModelError extends Error {\n model: IKosModel;\n constructor(message: string | undefined, model) {\n super(message);\n this.model = model;\n }\n}\nexport type ModelPromiseResolver = (model: IKosModel) => Promise<void>;\n\nconst rejectAfterDelay = (\n ms: number,\n model: IKosModel,\n status: string\n): { promise: Promise<void>; cancel: () => void } => {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const promise = new Promise<void>((_, reject) => {\n timeoutId = setTimeout(() => {\n KosLog.error(\n `Model ${model.modelId} - ${model.modelTypeName} - ${status} timed out after ${ms}ms`\n );\n reject(\n new ModelError(\n `${model.modelId} - ${model.modelTypeName} - ${status}`,\n model\n )\n );\n }, ms);\n });\n\n const cancel = () => {\n if (timeoutId) clearTimeout(timeoutId);\n };\n\n return { promise, cancel };\n};\n\nexport const transitionToActive = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.GO_ACTIVE, KosModelState.ACTIVE);\n\nexport const transitionToReady = (model: IKosModel): Promise<void> =>\n model.whenReady();\n\nexport const transitionToLoad = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.LOAD, KosModelState.LOADED);\n\nexport const transitionToUnload = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.UNLOAD, KosModelState.UNLOADED);\n\nexport const transitionToInit = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.INITIALIZE, KosModelState.INITIALIZED);\n\nexport enum Transitions {\n ACTIVE = \"active\",\n READY = \"ready\",\n LOAD = \"load\",\n UNLOAD = \"unload\",\n INIT = \"init\",\n}\nexport const TransitionMap = {\n [Transitions.ACTIVE]: transitionToActive,\n [Transitions.READY]: transitionToReady,\n [Transitions.LOAD]: transitionToLoad,\n [Transitions.INIT]: transitionToInit,\n};\n\nexport const createModelDependency = (\n model: IKosModel,\n dependency: KosDependencyParams<any>\n) => {\n const _dataModelId = dependency.id || dependency.modelType;\n const dataModelId = resolveParameters({\n value: _dataModelId,\n modelData: model.modelData,\n modelId: model.modelId,\n }) as string;\n KosLog.debug(\n `activating dependent model ${dependency.modelType} with id ${dataModelId}`\n );\n const options = Object.keys(dependency?.options || {}).reduce((acc, curr) => {\n const value = dependency.options[curr];\n acc[curr] = resolveParameters({\n value: value,\n modelData: model.modelData,\n modelId: model.modelId,\n });\n return acc;\n }, {});\n const dependentModel = KosCore.getInstance().modelManager.createModelInstance(\n dependency.modelType,\n dataModelId,\n options\n );\n\n return { dependentModel, dataModelId };\n};\n\nexport const getDependenciesByLifecycle = (\n model: IKosModel,\n lifecycle: DependencyLifecycle = DependencyLifecycle.READY\n) => {\n const dependencies = model.modelData?.[DependencyModels] || {};\n if (Object.keys(dependencies).length === 0) {\n KosLog.debug(`${model.modelId} has no dependencies. Returning`);\n return [];\n }\n const dependenciesByLifecycle = Object.keys(dependencies)\n // find all the dependencies that match the lifecycle\n .filter((key) => dependencies[key].lifecycle === lifecycle)\n .map((key) => {\n const dependency = dependencies[key];\n const { dependentModel, dataModelId } = createModelDependency(\n model,\n dependency\n );\n model.modelData[key] = dependentModel.data;\n KosLog.debug(\n `waiting for dependent model ${dependency.modelType} with id ${dataModelId} - waiting for WHENREADY`\n );\n const readyFn = async (\n dependentModel: IKosModel,\n modelType: string,\n id: string\n ) => {\n await dependentModel.whenReady?.();\n KosLog.debug(`dependent model ${modelType} with id ${id} - READY`);\n };\n const { promise, cancel } = rejectAfterDelay(\n PROMISE_TIMEOUT,\n model,\n model.status\n );\n return Promise.race([\n readyFn(dependentModel.model, dependency.modelType, dataModelId)\n .then(() => {\n cancel();\n })\n .catch((err) => {\n console.error(\n `Error waiting for dependent model ${dependency.modelType} with id ${dataModelId}:`,\n err\n );\n cancel();\n }),\n promise,\n ]);\n })\n .filter((p) => !!p);\n\n return dependenciesByLifecycle;\n};\n\nexport const executeListLifecycle = async (\n sourceModel: IKosModel,\n models: (IKosModel | undefined)[],\n target: Transitions,\n sourceLifecycle: DependencyLifecycle\n) => {\n KosLog.debug(`Execute lifecycle with ${models.length} models`);\n if (models.length === 0) {\n KosLog.debug(`${sourceModel.modelId} has no children. Returning`);\n return;\n }\n if (!target) {\n KosLog.error(\n `${sourceModel.modelId} is not transitioning with a valid target ${target}`\n );\n return;\n }\n const childPromises = models\n .map<ModelPromise>((model) => {\n let p: Promise<void> | undefined;\n\n if (TransitionMap[target] && model) {\n p = TransitionMap[target](model);\n } else {\n if (!model) {\n KosLog.error(\"model is undefined. This shouldn't happen\");\n }\n\n if (!TransitionMap[target]) {\n KosLog.error(\n `There is no promise in the Transition Map for ${target}`\n );\n }\n }\n\n return {\n promise: p,\n modelId: model?.modelId,\n model,\n type: model?.modelTypeName,\n status: model?.status,\n };\n })\n .filter((modelPromise) => {\n if (!modelPromise.promise) {\n KosLog.error(`No promise found ${modelPromise.modelId}`);\n return false;\n }\n\n if (!modelPromise.model) {\n KosLog.error(`No model found ${modelPromise.modelId}`);\n return false;\n }\n return true;\n });\n\n const settledChildren = await Promise.allSettled(\n childPromises.map((promise) => {\n const { promise: timeoutPromise, cancel: timeoutCancel } =\n rejectAfterDelay(PROMISE_TIMEOUT, promise.model!, promise.status!);\n return Promise.race([\n promise.promise\n ?.then(() => {\n timeoutCancel();\n })\n .catch((err) => {\n KosLog.error(\n `Model ${promise.modelId} - ${promise.type} failed to transition to ${target}: ${err.message}`\n );\n timeoutCancel();\n }),\n timeoutPromise,\n ]);\n })\n );\n const failedChildren = settledChildren.filter((p) => p.status === \"rejected\");\n\n if (failedChildren.length > 0) {\n KosLog.error(\n `Model ${sourceModel.modelId} had ${failedChildren.length} failed child models on ${sourceLifecycle}`\n );\n }\n};\n\nexport const executeChildrenModelLifecycle = async (\n model: IKosModel,\n target: Transitions,\n sourceLifecycle: DependencyLifecycle\n) => {\n await executeListLifecycle(\n model,\n model.getChildren().filter((child) => !!child),\n target,\n sourceLifecycle\n );\n};\n\nexport const executeDependentModelLifecycle = async (\n model: IKosModel,\n lifecycle: DependencyLifecycle\n) => {\n // wait for all non-lazy dependencies to be ready\n const settled = await Promise.allSettled(\n getDependenciesByLifecycle(model, lifecycle)\n );\n const failed = settled.filter((p) => p.status === \"rejected\");\n if (failed.length) {\n KosLog.error(\n `There were ${failed.length} failed dependent models on ${lifecycle}`\n );\n KosLog.error(failed);\n }\n};\n\nexport const isPrintable = (model: any): model is { toJSON: () => object } =>\n typeof model.toJSON === \"function\";\n\nexport const isKosDataModel = (model: any): model is IKosDataModel =>\n model[DependencyModels] !== undefined;\n\nexport const isKosModelContainer = (\n model: any\n): model is IKosModelContainer<any> =>\n model.revision !== undefined && model.index !== undefined;\n\nexport const resolveChild = (attribute: any) => {\n if (!attribute) return undefined;\n if (isKosDataModel(attribute)) return attribute;\n if (isKosModelContainer(attribute)) return attribute.data;\n if (\n attribute instanceof Map ||\n attribute instanceof ObservableMap ||\n attribute instanceof Set\n ) {\n return Array.from(attribute.values()).filter(isKosDataModel);\n }\n if (Array.isArray(attribute)) {\n return attribute.filter(isKosDataModel);\n }\n return undefined;\n};\n","import { isKosDataModel, isKosModelContainer } from \"../../util\";\nimport { DependencyModels } from \"../decorators\";\n\n// kos-devtools-utils.ts\nexport function applyKosModelDevtoolsSupport(model: any) {\n const name = `KosModel(${model.modelTypeName}:${model.modelId})`;\n\n // Tag the model instance\n try {\n Object.defineProperty(model, Symbol.toStringTag, {\n value: name,\n configurable: true,\n });\n } catch {\n // Fallback for environments that don't support Symbol.toStringTag\n model.toString = () => name;\n }\n\n // Update constructor name for React DevTools\n try {\n Object.defineProperty(model.constructor, \"name\", {\n value: `KosModel_${model.modelTypeName}`,\n configurable: true,\n });\n } catch {\n // Fallback for environments that don't support changing constructor name\n model.constructor.name = `KosModel_${model.modelTypeName}`;\n }\n\n // Hide internal manager fields from console\n const hiddenFields = [\n \"fsm\",\n \"effectManager\",\n \"subscriptionManager\",\n \"onlineLifecycleManager\",\n \"companionManager\",\n \"childResolver\",\n \"_offlineQueue\",\n ];\n for (const key of hiddenFields) {\n if (key in model) {\n Object.defineProperty(model, key, { enumerable: false });\n }\n }\n\n // Add a non-enumerable debug snapshot\n Object.defineProperty(model, \"debugState\", {\n enumerable: false,\n configurable: true,\n get() {\n return {\n id: model.modelId,\n type: model.modelTypeName,\n initialized: model.initialized,\n loaded: model.loaded,\n status: model.status,\n onlineStatus: model.onlineStatus,\n activeStatus: model.activeStatus,\n companions: model.companionManager?.all()?.map((m) => m.modelTypeName),\n children: model.getChildren?.().map((m) => m.modelId),\n effects: !!model.effectManager,\n subs: !!model.subscriptionManager,\n };\n },\n });\n\n // Enhance modelData for DevTools\n enhanceModelDataForDevtools(\n model.modelData,\n model.modelTypeName,\n model.modelId,\n model\n );\n}\n\nfunction enhanceModelDataForDevtools(\n modelData: any,\n modelTypeName: string,\n modelId: string,\n model: any\n) {\n // Label in Chrome DevTools\n Object.defineProperty(modelData, Symbol.toStringTag, {\n value: `KosModelData(${modelTypeName}:${modelId})`,\n configurable: true,\n });\n\n // Optional: Update constructor name for React DevTools\n try {\n Object.defineProperty(modelData.constructor, \"name\", {\n value: `${modelTypeName}ModelData`,\n configurable: true,\n });\n } catch {\n // Fallback for environments that don't support changing constructor name\n modelData.constructor.name = `${modelTypeName}ModelData`;\n }\n\n Object.defineProperty(modelData, \"debugState\", {\n enumerable: false,\n configurable: true,\n get() {\n const children = model.getChildren?.() || [];\n const companions = model.companionManager?.all() || [];\n const dependencies: Record<string, any> =\n model.modelData[DependencyModels] || {};\n return {\n id: modelId,\n type: modelTypeName,\n companions: {\n count: companions.length,\n data: companions.map((m) => {\n return { type: m.modelTypeName, id: m.modelId };\n }),\n },\n dependencies: {\n count: Object.keys(dependencies).length,\n data: Object.values(dependencies).map((dependency) => {\n return {\n id: dependency.id || dependency.modelType,\n type: dependency.modelType,\n options: dependency.options,\n lifecycle: dependency.lifecycle,\n };\n }),\n },\n children: {\n count: children.length,\n data: children.map((m) => {\n return { id: m.modelId, type: m.modelTypeName };\n }),\n },\n data: modelData.toJSON?.() || {},\n subs: !!model.subscriptionManager,\n };\n },\n });\n\n Object.defineProperty(modelData, \"toJSON\", {\n configurable: true,\n enumerable: false,\n writable: true,\n value: () => {\n const json: Record<string, any> = {};\n\n for (const key of Object.keys(modelData)) {\n if (key.startsWith(\"_\") || typeof modelData[key] === \"function\")\n continue;\n\n try {\n const value = modelData[key];\n\n if (isKosDataModel(value)) {\n // Prefer that model’s toJSON, or fallback to id + type\n json[`[KOS Model] ${key}`] =\n typeof value.toJSON === \"function\"\n ? value.toJSON()\n : { id: value.id, type: value.constructor.name };\n } else if (isKosModelContainer(value)) {\n json[`[KOS Container] ${key}`] =\n typeof value.toJSON === \"function\"\n ? value.toJSON()\n : [\"Container\"];\n } else if (Array.isArray(value)) {\n json[key] = `[Array(${value.length})]`;\n } else if (typeof value === \"object\" && value !== null) {\n json[key] = JSON.parse(JSON.stringify(value));\n } else {\n json[key] = value;\n }\n } catch {\n json[key] = \"[unreadable]\";\n }\n }\n\n return json;\n },\n });\n}\n","import { resolveChild } from \"../../util/model-utils\";\nimport { KosContextManager } from \"../context/kos-context-manager\";\nimport { ChildModels } from \"../decorators\";\nimport { IKosDataModel, IKosModel } from \"../kosModel\";\nimport { KosModelState } from \"../lifecycle\";\nimport type { IKosIdentifiable } from \"../types\";\n\nexport class KosChildResolver {\n constructor(private readonly model: IKosModel) {}\n\n resolve(): IKosModel[] {\n const uniqueChildren = new Set<IKosIdentifiable>([\n ...this.getResolvedDecoratedChildren(),\n ...this.getAdditionalChildren(),\n ...this.model.companionModels.all(),\n ] as IKosIdentifiable[]);\n\n const resolvedModels = Array.from(uniqueChildren)\n .map((child) => this.model.modelManager.getModelById(child.id || \"\"))\n .filter((model) => model && model.status !== KosModelState.FAILED)\n .filter((model): model is IKosModel => !!model);\n\n resolvedModels.forEach((childModel) => {\n try {\n KosContextManager.setParentContext(\n childModel.modelId,\n this.model.modelId\n );\n } catch (e) {\n console.error(\n `Failed to set parent context for ${childModel.modelId} under ${this.model.modelId}`,\n e\n );\n }\n });\n\n return resolvedModels;\n }\n\n private getResolvedDecoratedChildren(): IKosDataModel[] {\n const rawChildren = this.model.modelData?.[ChildModels] || {};\n return Object.keys(rawChildren)\n .map((key) => resolveChild(this.model.modelData[key]))\n .filter((m) => !!m)\n .flat() as IKosDataModel[];\n }\n\n private getAdditionalChildren(): IKosDataModel[] {\n return this.model.modelData?.getChildren?.() || [];\n }\n}\n","// kos-companion-model-manager.ts\nimport { ObservableMap } from \"mobx\";\nimport type { IKosModel } from \"../kosModel\";\n\nexport class KosCompanionModelManager {\n private readonly companions = new ObservableMap<string, IKosModel>();\n\n constructor(private readonly hostModel: IKosModel) {}\n\n add(model: IKosModel): void {\n this.companions.set(model.modelTypeName, model);\n }\n\n clear(): void {\n this.companions.clear();\n }\n\n get(modelTypeName: string): IKosModel | undefined {\n return this.companions.get(modelTypeName);\n }\n\n all(): IKosModel[] {\n return [...this.companions.values()];\n }\n\n get data() {\n return this.companions;\n }\n}\n","import { autorun, reaction, runInAction } from \"mobx\";\nimport { ModelEffects } from \"../decorators/propKeys\"; // adjust path if needed\nimport type { KosOfflineQueueLogger } from \"./kos-offline-queue\";\n\nexport class KosEffectManager {\n private disposers: VoidFunction[] = [];\n\n constructor(\n private modelTypeName: string,\n private modelId: string,\n private modelData: any, // typically IKosDataModel\n private log: KosOfflineQueueLogger\n ) {}\n\n setup(): void {\n const modelEffects = this.modelData?.[ModelEffects] || {};\n\n for (const effectName of Object.keys(modelEffects)) {\n const { value, dependencies, options } = modelEffects[effectName];\n const handler = value.bind(this.modelData);\n\n const autoRunHandler = () => {\n this.log.info(\n `Running effect ${effectName} for ${this.modelTypeName} (${this.modelId})`\n );\n runInAction(() => handler());\n };\n\n const disposer = dependencies\n ? reaction(() => dependencies(this.modelData), autoRunHandler, {\n fireImmediately: !!options?.fireImmediately,\n })\n : autorun(autoRunHandler);\n\n this.disposers.push(disposer);\n }\n }\n\n disposeAll(): void {\n for (const dispose of this.disposers) {\n try {\n dispose();\n } catch (e) {\n this.log.info(`Failed to dispose effect for ${this.modelId}`, e);\n }\n }\n this.disposers = [];\n }\n}\n","import {\n action,\n createMachine,\n interpret,\n invoke,\n state,\n transition,\n} from \"robot3\";\nimport { IKosModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { KosModelEvents, KosModelState } from \"./constants\";\n\nconst log = KosLog.createLogger({ name: \"model-active-machine\" });\n\nexport const activeMachine = (model: IKosModel) => {\n const machine = createMachine(KosModelState.INACTIVE, {\n [KosModelState.FAILED]: state(\n transition(KosModelEvents.GO_ACTIVE, KosModelState.ACTIVATING)\n ),\n [KosModelState.INACTIVE]: state(\n transition(KosModelEvents.GO_ACTIVE, KosModelState.ACTIVATING)\n ),\n [KosModelState.ACTIVATING]: invoke(\n () => {\n model.activeStatus = KosModelState.ACTIVATING;\n return model.activate!();\n },\n transition(\n `done`,\n KosModelState.ACTIVE,\n action(() => {\n model.activeStatus = KosModelState.ACTIVE;\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.activeStatus = KosModelState.FAILED;\n })\n )\n ),\n [KosModelState.ACTIVE]: state(\n transition(KosModelEvents.GO_INACTIVE, KosModelState.DEACTIVATING)\n ),\n [KosModelState.DEACTIVATING]: invoke(\n () => {\n model.activeStatus = KosModelState.DEACTIVATING;\n return model.deactivate!();\n },\n transition(\n `done`,\n KosModelState.INACTIVE,\n action(() => {\n model.activeStatus = KosModelState.INACTIVE;\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.activeStatus = KosModelState.FAILED;\n })\n )\n ),\n });\n const service = interpret(machine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n return { service, machine };\n};\n","import { action, createMachine, interpret, state, transition } from \"robot3\";\nimport { IKosModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { KosModelEvents, KosModelState } from \"./constants\";\n\nconst log = KosLog.createLogger({ name: \"model-online-machine\" });\nexport const onlineMachine = (model: IKosModel) => {\n const machine = createMachine(KosModelState.OFFLINE, {\n [KosModelState.ONLINE]: state(\n transition(\n KosModelEvents.GO_OFFLINE,\n KosModelState.OFFLINE,\n action(async () => {\n await model.offline!();\n model.onlineStatus = KosModelState.OFFLINE;\n })\n )\n ),\n [KosModelState.OFFLINE]: state(\n transition(\n KosModelEvents.GO_ONLINE,\n KosModelState.ONLINE,\n action(async () => {\n log.debug(`Going online with model ${model.modelId}`);\n await model.online!();\n model.onlineStatus = KosModelState.ONLINE;\n await model.fsm.transitionTo(\n KosModelEvents.INITIALIZE,\n KosModelState.INITIALIZED\n );\n })\n )\n ),\n });\n\n const service = interpret(machine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n return { machine, service };\n};\n","import {\n action,\n createMachine,\n immediate,\n invoke,\n state,\n transition,\n} from \"robot3\";\nimport { kosAction, KosLog } from \"../..\";\nimport { IKosModel } from \"../kosModel\";\nimport { KosModelEvents, KosModelState } from \"./constants\";\nimport { activeMachine } from \"./model-active-machine\";\nimport { onlineMachine } from \"./model-online-machine\";\n\nexport const machine = (model: IKosModel) => {\n const active = activeMachine(model).service;\n const online = onlineMachine(model).service;\n return createMachine(KosModelState.CREATING, {\n [KosModelState.CREATING]: state(\n transition(KosModelEvents.CREATE, KosModelState.CREATED)\n ),\n [KosModelState.CREATED]: state(immediate(KosModelState.INITIALIZING)),\n [KosModelState.INITIALIZING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.INITIALIZING;\n });\n return model.init!();\n },\n transition(\n `done`,\n KosModelState.INITIALIZED,\n action(() => {\n model.status = KosModelState.INITIALIZED;\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n\n action(() => {\n KosLog.error(\n `Model ${model.modelId} - ${model.modelTypeName} failed to initialize. Transitioning to FAILED state.`\n );\n model.status = KosModelState.FAILED;\n })\n )\n ),\n [KosModelState.INITIALIZED]: state(immediate(KosModelState.LOADING)),\n [KosModelState.LOADING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.LOADING;\n });\n return model.load!();\n },\n transition(\n `done`,\n KosModelState.LOADED,\n action(() => {\n model.status = KosModelState.LOADED;\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.status = KosModelState.FAILED;\n })\n )\n ),\n [KosModelState.LOADED]: state(\n immediate(KosModelState.READYING),\n transition(KosModelEvents.UNLOAD, KosModelState.UNLOADING)\n ),\n [KosModelState.RESETTING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.RESETTING;\n });\n\n model.unload?.();\n return model.load!();\n },\n transition(\n `done`,\n KosModelState.LOADED,\n action(() => {\n model.status = KosModelState.LOADED;\n })\n )\n ),\n\n [KosModelState.READYING]: invoke(\n () => {\n kosAction(() => {\n model.status = KosModelState.READYING;\n });\n return model.ready!();\n },\n\n transition(\n `done`,\n KosModelState.READY,\n action(() => {\n kosAction(() => {\n model.status = KosModelState.READY;\n });\n online.send(KosModelEvents.GO_ONLINE);\n })\n ),\n transition(\n `error`,\n KosModelState.FAILED,\n action(() => {\n model.status = KosModelState.FAILED;\n })\n )\n ),\n\n [KosModelState.READY]: state(\n transition(\n KosModelEvents.UNLOAD,\n KosModelState.UNLOADED,\n action(model.unload?.bind(model))\n ),\n transition(KosModelEvents.RESET, KosModelState.RESETTING),\n transition(\n KosModelEvents.GO_ONLINE,\n KosModelState.READY,\n action(() => {\n online.send(KosModelEvents.GO_ONLINE);\n })\n ),\n transition(\n KosModelEvents.GO_OFFLINE,\n KosModelState.READY,\n action(() => {\n online.send(KosModelEvents.GO_OFFLINE);\n })\n ),\n transition(\n KosModelEvents.GO_ACTIVE,\n KosModelState.READY,\n action(() => {\n active.send(KosModelEvents.GO_ACTIVE);\n })\n ),\n transition(\n KosModelEvents.GO_INACTIVE,\n KosModelState.READY,\n action(() => {\n active.send(KosModelEvents.GO_INACTIVE);\n })\n )\n ),\n\n [KosModelState.UNLOADED]: state(),\n [KosModelState.FAILED]: state(),\n });\n};\n","/* eslint-disable max-classes-per-file */\n\nimport { interpret } from \"robot3\";\nimport type { IKosModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { machine } from \"./model-machine\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-lifecycle\" });\nexport interface KosOn {\n [k: string]: string;\n}\n\nexport interface KosInvoke<Context> {\n id: string;\n src: (context: Context) => Promise<any>;\n onDone: {\n target: string;\n };\n}\nexport interface KosLifecycleState {\n on: KosOn;\n}\nexport interface KosLifecycleStateContainer<Context> {\n [k: string]: {\n initial?: string;\n states?: KosLifecycleStateContainer<Context>;\n on?: KosOn;\n invoke?: KosInvoke<Context>;\n };\n}\n\nexport interface KosLifecycle<Context = any> {\n id: string;\n initial: string;\n states: KosLifecycleStateContainer<Context>;\n context: Context;\n}\n\nexport const fsm = (model: IKosModel) => {\n const service = interpret(machine(model), (_service) =>\n log.debug(\n `state machine for model ${model.modelId}: ${_service.machine.current});`\n )\n );\n\n return { service };\n};\n","import { IReactionDisposer, when } from \"mobx\";\nimport type { IKosModel } from \"../kosModel\";\nimport { KosModelEvents, KosModelState } from \"../lifecycle/constants\";\nimport { fsm } from \"../lifecycle/kosModelLifecycle\";\nimport type { KosOfflineQueueLogger } from \"./kos-offline-queue\";\n\nexport class KosFSMManager {\n private disposer?: IReactionDisposer;\n private readonly service: ReturnType<typeof fsm>[\"service\"];\n\n constructor(private model: IKosModel, private log: KosOfflineQueueLogger) {\n const machine = fsm(model);\n this.service = machine.service;\n this.service.send(KosModelEvents.CREATE);\n }\n\n /**\n * Returns the current raw state of the FSM\n */\n get current(): KosModelState {\n return this.service.machine.current;\n }\n\n /**\n * Waits for a transition to complete to the target state (or fails if error state reached)\n */\n async transitionTo(\n event: KosModelEvents,\n target: KosModelState,\n error: KosModelState = KosModelState.FAILED\n ): Promise<void> {\n const current = this.getTransitionStatusFor(target);\n\n if (current === target) {\n this.log.debug(\n `Model ${this.model.modelId} already in state ${target}, skipping transition`\n );\n return Promise.resolve();\n }\n\n this.log.debug(\n `Transitioning model ${this.model.modelId} with event ${event} toward target ${target}`\n );\n\n return new Promise<void>((resolve, reject) => {\n // Protect against multiple disposers being created\n this.disposer?.();\n\n this.disposer = when(\n () => {\n const status = this.getTransitionStatusFor(target);\n return status === target || status === error;\n },\n () => {\n const status = this.getTransitionStatusFor(target);\n if (status === error) {\n this.log.error(\n `Model ${this.model.modelId} entered error state ${error} during transition`\n );\n reject(\n new Error(\n `FSM transition failed for model ${this.model.modelId} with event ${event}`\n )\n );\n } else {\n this.log.debug(\n `Model ${this.model.modelId} reached target state ${target}`\n );\n resolve();\n }\n }\n );\n\n this.service.send(event);\n }).finally(() => {\n this.disposer?.();\n this.disposer = undefined;\n });\n }\n\n /**\n * Checks if a given target maps to status or activeStatus\n */\n private getTransitionStatusFor(target: KosModelState): KosModelState {\n return [KosModelState.ACTIVE, KosModelState.INACTIVE].includes(target)\n ? this.model.activeStatus\n : this.model.status;\n }\n}\n","// Avoiding direct import to prevent circular dependency\n// import type { KosBrowserRouter } from \"../../../models/models/browser-router\";\nimport { getKosModelSync } from \"../../util\";\nimport {\n getHttpRouteHandlers,\n hasHttpRouteHandlers,\n type IHttpRouteConfig,\n} from \"../decorators/kos-http-decorators\";\nimport type { IKosDataModel, KosContextLogger } from \"../kosModel\";\nimport type { KosRequest, KosResponse } from \"../services/browser-router\";\n\n// Browser router model type - using string to avoid circular dependency\nconst BROWSER_ROUTER_MODEL_TYPE = \"browser-router-model\";\n\n// Generic browser router interface to avoid importing the actual type\ninterface IBrowserRouter extends IKosDataModel {\n use(\n method: string,\n path: string,\n handler: (req: KosRequest, res: KosResponse) => Promise<void>\n ): void;\n remove(method: string, path: string): number;\n removeAllForPath(path: string): number;\n getRoutes(): Array<{ method: string; path: string }>;\n}\n\nexport interface KosHttpRouteLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n/**\n * Manager for registering HTTP route handlers from decorators with the browser router\n */\nexport class KosHttpRouteManager {\n private logger: KosHttpRouteLogger;\n private model: any;\n private router: IBrowserRouter | null = null;\n private registered = false;\n private registeredRoutes: Array<{ method: string; path: string }> = [];\n\n constructor(model: any, logger: KosHttpRouteLogger) {\n this.model = model;\n this.logger = logger;\n }\n\n /**\n * Register all HTTP routes during the load lifecycle\n * This is called automatically by the KOS model lifecycle\n */\n registerAll(): void {\n if (!hasHttpRouteHandlers(this.model)) {\n return;\n }\n\n // First try to get the auto-injected router from the model\n let router: IBrowserRouter | undefined = this.model.__httpBrowserRouter;\n\n // If not found via auto-injection, try to find any router property on the model\n if (!router) {\n // Check for any property that is a BrowserRouter\n for (const key of Object.keys(this.model)) {\n const prop = this.model[key];\n if (\n prop &&\n typeof prop === \"object\" &&\n \"use\" in prop &&\n typeof prop.use === \"function\"\n ) {\n router = prop as IBrowserRouter;\n break;\n }\n }\n }\n\n // Finally, fallback to global lookup\n if (!router) {\n router = getKosModelSync<IBrowserRouter>(\n BROWSER_ROUTER_MODEL_TYPE\n )?.model;\n }\n\n if (!router) {\n this.logger.error(\n `Cannot register HTTP routes: BrowserRouter not found. ` +\n `The HTTP decorators should have auto-injected it, but something went wrong.`\n );\n throw new Error(\n `BrowserRouter is required for HTTP route decorators but was not found. ` +\n `This should not happen as HTTP decorators auto-inject the dependency.`\n );\n }\n\n this.setRouter(router);\n }\n\n /**\n * Set the browser router instance\n */\n setRouter(router: IBrowserRouter): void {\n this.router = router;\n if (!this.registered) {\n this.registerRoutes();\n }\n }\n\n /**\n * Check if the model has HTTP route handlers\n */\n hasRoutes(): boolean {\n return hasHttpRouteHandlers(this.model);\n }\n\n /**\n * Register all HTTP route handlers with the browser router\n */\n private registerRoutes(): void {\n if (!this.router) {\n this.logger.warn(\"Cannot register routes: router not set\");\n return;\n }\n\n if (this.registered) {\n this.logger.debug(\"Routes already registered\");\n return;\n }\n\n const routes = getHttpRouteHandlers(this.model);\n\n if (routes.length === 0) {\n return;\n }\n\n this.logger.debug(`Registering ${routes.length} HTTP routes`);\n\n routes.forEach((route: IHttpRouteConfig) => {\n this.registerRoute(route);\n });\n\n this.registered = true;\n }\n\n /**\n * Resolve PropKeys in a path template\n * Supports:\n * - {MODEL_ID} - replaced with the model's ID\n * - {PROP_propertyName} - replaced with the value of model.propertyName\n *\n * @example\n * \"/api/models/{MODEL_ID}/data\" -> \"/api/models/my-model-123/data\"\n * \"/api/{PROP_tenantId}/users\" -> \"/api/tenant-456/users\"\n */\n private resolvePropKey(pathTemplate: string): string {\n const propRegex = /\\{PROP_([^}]+)\\}/g;\n let resolvedPath = pathTemplate;\n\n // Replace {MODEL_ID} with the actual model ID\n if (resolvedPath.includes(\"{MODEL_ID}\")) {\n const modelId = this.model.id || this.model._id || \"unknown\";\n resolvedPath = resolvedPath.replace(/\\{MODEL_ID\\}/g, modelId);\n }\n\n // Replace {PROP_xxx} with the actual property values\n let match: RegExpExecArray | null;\n while ((match = propRegex.exec(pathTemplate)) !== null) {\n const propName = match[1];\n if (propName in this.model) {\n const propValue = this.model[propName];\n resolvedPath = resolvedPath.replace(match[0], String(propValue));\n } else {\n this.logger.warn(\n `Property '${propName}' not found on model for PropKey resolution in path: ${pathTemplate}`\n );\n }\n }\n\n return resolvedPath;\n }\n\n /**\n * Register a single route with the browser router\n */\n private registerRoute(route: IHttpRouteConfig): void {\n if (!this.router) {\n return;\n }\n\n const handler = this.model[route.handler];\n\n if (!handler || typeof handler !== \"function\") {\n this.logger.error(`Handler method '${route.handler}' not found on model`);\n return;\n }\n\n // Resolve any PropKeys in the path\n const resolvedPath = this.resolvePropKey(route.path);\n\n this.logger.debug(\n `Registering ${route.method} ${resolvedPath} -> ${route.handler}` +\n (resolvedPath !== route.path ? ` (resolved from ${route.path})` : \"\")\n );\n\n // Create a wrapper that binds the handler to the model instance\n const boundHandler = async (req: KosRequest, res: KosResponse) => {\n try {\n await handler.call(this.model, req, res);\n } catch (error) {\n this.logger.error(\n `Error in route handler ${route.method} ${resolvedPath}:`,\n error\n );\n res.status?.(500).send({\n error: \"Internal server error\",\n message: error instanceof Error ? error.message : String(error),\n });\n }\n };\n\n // Check for duplicate routes before registering\n this.checkForDuplicateRoute(route.method, resolvedPath);\n\n // Register with the router using the resolved path\n this.router.use(route.method, resolvedPath, boundHandler);\n \n // Track the registered route for cleanup\n this.registeredRoutes.push({ method: route.method, path: resolvedPath });\n }\n\n /**\n * Check for duplicate routes and warn if found\n */\n private checkForDuplicateRoute(method: string, path: string): void {\n if (!this.router) {\n return;\n }\n\n // Get all currently registered routes from the router\n const existingRoutes = this.router.getRoutes();\n const duplicate = existingRoutes.find(\n route => route.method === method && route.path === path\n );\n\n if (duplicate) {\n this.logger.warn(\n `Duplicate route detected: ${method} ${path}. ` +\n `This route is already registered by another model. ` +\n `The new handler from model '${this.model.id || 'unknown'}' will override the existing one. ` +\n `Only the last registered handler will receive requests. ` +\n `Consider using different paths or namespacing to avoid conflicts.`\n );\n }\n }\n\n /**\n * Dispose of the route manager and cleanup all registered routes\n */\n dispose(): void {\n if (this.router && this.registeredRoutes.length > 0) {\n this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id || 'unknown'}`);\n \n let totalRemoved = 0;\n for (const route of this.registeredRoutes) {\n const removed = this.router.remove(route.method, route.path);\n totalRemoved += removed;\n \n if (removed > 0) {\n this.logger.debug(`Removed route: ${route.method} ${route.path}`);\n } else {\n this.logger.warn(`Failed to remove route: ${route.method} ${route.path} (not found)`);\n }\n }\n \n this.logger.debug(`Successfully removed ${totalRemoved} routes from browser router`);\n }\n\n // Clean up state\n this.registered = false;\n this.registeredRoutes = [];\n this.router = null;\n }\n\n /**\n * Get all routes registered by this manager (for debugging)\n */\n getRegisteredRoutes(): Array<{ method: string; path: string }> {\n return [...this.registeredRoutes];\n }\n}\n\n/**\n * Helper function to automatically register HTTP routes during model load\n * This is called automatically by the KOS model lifecycle if HTTP route handlers are detected\n *\n * @internal\n */\nexport function registerHttpRoutes(model: any, logger: KosContextLogger): void {\n if (!hasHttpRouteHandlers(model)) {\n return;\n }\n\n // Get the BrowserRouter instance automatically\n const router = getKosModelSync<IBrowserRouter>(BROWSER_ROUTER_MODEL_TYPE);\n\n if (!router?.model) {\n logger.error(\n `Cannot register HTTP routes: BrowserRouter not found. ` +\n `Make sure to include BrowserRouter in your model dependencies or create an instance.`\n );\n throw new Error(\n `BrowserRouter is required for HTTP route decorators but was not found. ` +\n `Add it as a dependency using @kosDependency or ensure an instance exists.`\n );\n }\n\n const manager = new KosHttpRouteManager(model, logger);\n manager.setRouter(router.model);\n}\n","export interface KosOfflineQueueLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\nexport class KosOfflineQueue {\n private queue: (() => void)[] = [];\n\n constructor(private log: KosOfflineQueueLogger) {}\n\n enqueue(handler: () => void): void {\n this.queue.push(handler);\n }\n\n flush(): void {\n if (this.queue.length === 0) return;\n\n this.log.warn(`Processing ${this.queue.length} offline message(s)`);\n for (const handler of this.queue) {\n try {\n handler();\n } catch (e) {\n this.log.error(\"Error while processing offline message:\", e);\n }\n }\n\n this.queue = [];\n this.log.info(\"Offline queue flushed\");\n }\n\n clear(): void {\n this.queue = [];\n }\n\n get length(): number {\n return this.queue.length;\n }\n\n get isEmpty(): boolean {\n return this.queue.length === 0;\n }\n}\n","import { EventBus } from \"../../../common\";\nimport type { IKosModel } from \"../kosModel\";\nimport { KosModelEvents, KosModelState } from \"../lifecycle\";\nimport type { KosOfflineQueueLogger } from \"./kos-offline-queue\";\n\nexport class KosOnlineLifecycleManager {\n private unsubscribers: VoidFunction[] = [];\n\n constructor(private model: IKosModel, private log: KosOfflineQueueLogger) {}\n\n register(): void {\n const modelId = this.model.modelId;\n\n const onlineUnsub = EventBus.subscribe(\"/kosCore/online\", async () => {\n this.log.debug(\n `Online event received for ${modelId}, waiting for readiness...`\n );\n await this.model.whenReady();\n this.log.debug(`${modelId} is ready — sending GO_ONLINE`);\n await this.model.fsm.transitionTo(\n KosModelEvents.GO_ONLINE,\n KosModelState.ONLINE\n );\n });\n\n const offlineUnsub = EventBus.subscribe(\"/kosCore/offline\", async () => {\n this.log.debug(\n `Offline event received for ${modelId} — sending GO_OFFLINE`\n );\n await this.model.fsm.transitionTo(\n KosModelEvents.GO_OFFLINE,\n KosModelState.OFFLINE\n );\n });\n\n this.unsubscribers.push(onlineUnsub.unsubscribe);\n this.unsubscribers.push(offlineUnsub.unsubscribe);\n }\n\n dispose(): void {\n this.unsubscribers.forEach((unsub) => unsub());\n this.unsubscribers = [];\n }\n}\n","import log from \"loglevel\";\nimport { \n subscribe as originalSubscribe,\n publish as originalPublish,\n once as originalOnce,\n waitFor as originalWaitFor,\n hasEventSubscriptions,\n reset,\n type EventCallback,\n type ApiCallback,\n type PublishResponse\n} from \"./eventBus\";\n\n/**\n * Re-export existing EventBus functionality\n */\nexport { \n hasEventSubscriptions, \n reset, \n type EventCallback, \n type ApiCallback,\n type PublishResponse \n};\n\n/**\n * Enhanced subscribe that maintains backward compatibility\n */\nexport const subscribe = originalSubscribe;\nexport const publish = originalPublish;\nexport const once = originalOnce;\nexport const waitFor = originalWaitFor;\n\n/**\n * AsyncIterator support for EventBus\n */\ninterface AsyncSubscription<T> {\n queue: T[];\n resolvers: Array<(value: T) => void>;\n closed: boolean;\n}\n\nclass AsyncEventIterator<T = ApiCallback> {\n private subscription: AsyncSubscription<T>;\n private unsubscribe: () => void;\n private eventType: string;\n\n constructor(eventType: string) {\n this.eventType = eventType;\n this.subscription = {\n queue: [],\n resolvers: [],\n closed: false,\n };\n\n // Subscribe to the event using the original EventBus\n const sub = originalSubscribe<T>(eventType, (msg?: T) => {\n if (this.subscription.closed) return;\n \n if (msg !== undefined) {\n // If there's a waiting resolver, resolve it immediately\n const resolver = this.subscription.resolvers.shift();\n if (resolver) {\n resolver(msg);\n } else {\n // Otherwise queue the message\n this.subscription.queue.push(msg);\n }\n }\n });\n\n this.unsubscribe = sub.unsubscribe;\n }\n\n async next(): Promise<IteratorResult<T>> {\n if (this.subscription.closed && this.subscription.queue.length === 0) {\n return { done: true, value: undefined };\n }\n\n // If there are queued messages, return the oldest one\n if (this.subscription.queue.length > 0) {\n return { \n done: false, \n value: this.subscription.queue.shift()! \n };\n }\n\n // Wait for the next message\n return new Promise<IteratorResult<T>>((resolve) => {\n if (this.subscription.closed) {\n resolve({ done: true, value: undefined });\n } else {\n this.subscription.resolvers.push((value: T) => {\n resolve({ done: false, value });\n });\n }\n });\n }\n\n async return(): Promise<IteratorResult<T>> {\n this.subscription.closed = true;\n this.unsubscribe();\n \n // Resolve any pending promises\n this.subscription.resolvers.forEach(resolver => {\n resolver(undefined as any);\n });\n this.subscription.resolvers = [];\n \n return { done: true, value: undefined };\n }\n\n async throw(error: Error): Promise<IteratorResult<T>> {\n this.subscription.closed = true;\n this.unsubscribe();\n throw error;\n }\n\n [Symbol.asyncIterator]() {\n return this;\n }\n}\n\n/**\n * Create an async iterator for an event type\n * \n * @example\n * ```typescript\n * for await (const message of iterate(\"user.events\")) {\n * console.log(\"Received:\", message);\n * }\n * ```\n */\nexport function iterate<T = ApiCallback>(eventType: string): AsyncEventIterator<T> {\n return new AsyncEventIterator<T>(eventType);\n}\n\n/**\n * Create an async generator that yields events\n * \n * @example\n * ```typescript\n * for await (const message of stream(\"user.events\")) {\n * console.log(\"Received:\", message);\n * }\n * ```\n */\nexport async function* stream<T = ApiCallback>(\n eventType: string,\n options?: {\n filter?: (msg: T) => boolean;\n transform?: (msg: T) => any;\n bufferSize?: number;\n }\n): AsyncGenerator<T, void, unknown> {\n const iterator = iterate<T>(eventType);\n const buffer: T[] = [];\n const maxBufferSize = options?.bufferSize ?? Infinity;\n\n try {\n for await (const message of iterator) {\n // Apply filter if provided\n if (options?.filter && !options.filter(message)) {\n continue;\n }\n\n // Apply transform if provided\n const output = options?.transform ? options.transform(message) : message;\n\n // Buffer management\n if (buffer.length >= maxBufferSize) {\n buffer.shift(); // Remove oldest if buffer is full\n }\n\n yield output;\n }\n } finally {\n await iterator.return();\n }\n}\n\n/**\n * Create a filtered stream of events\n */\nexport async function* filter<T = ApiCallback>(\n eventType: string,\n predicate: (msg: T) => boolean\n): AsyncGenerator<T, void, unknown> {\n for await (const message of iterate<T>(eventType)) {\n if (predicate(message)) {\n yield message;\n }\n }\n}\n\n/**\n * Map/transform events in a stream\n */\nexport async function* map<T = ApiCallback, R = any>(\n eventType: string,\n transform: (msg: T) => R\n): AsyncGenerator<R, void, unknown> {\n for await (const message of iterate<T>(eventType)) {\n yield transform(message);\n }\n}\n\n/**\n * Batch events with time window or count limit\n */\nexport async function* batch<T = ApiCallback>(\n eventType: string,\n options: {\n maxSize?: number;\n maxWait?: number;\n } = {}\n): AsyncGenerator<T[], void, unknown> {\n const maxSize = options.maxSize ?? 10;\n const maxWait = options.maxWait ?? 1000;\n \n const iterator = iterate<T>(eventType);\n let currentBatch: T[] = [];\n let batchTimer: NodeJS.Timeout | null = null;\n let batchPromise: Promise<void> | null = null;\n let resolveBatch: (() => void) | null = null;\n\n const startBatchTimer = () => {\n if (batchTimer) clearTimeout(batchTimer);\n \n batchPromise = new Promise<void>(resolve => {\n resolveBatch = resolve;\n batchTimer = setTimeout(() => {\n resolve();\n }, maxWait);\n });\n };\n\n try {\n startBatchTimer();\n\n while (true) {\n // Race between next message and batch timeout\n const result = await Promise.race([\n iterator.next(),\n batchPromise!.then(() => ({ done: false, timeout: true } as any))\n ]);\n\n if (result.done) {\n // Iterator finished, yield remaining batch if any\n if (currentBatch.length > 0) {\n yield currentBatch;\n }\n break;\n }\n\n if (result.timeout) {\n // Timeout reached, yield current batch\n if (currentBatch.length > 0) {\n yield currentBatch;\n currentBatch = [];\n }\n startBatchTimer();\n } else {\n // New message received\n currentBatch.push(result.value);\n \n if (currentBatch.length >= maxSize) {\n // Batch size reached\n yield currentBatch;\n currentBatch = [];\n startBatchTimer();\n }\n }\n }\n } finally {\n if (batchTimer) clearTimeout(batchTimer);\n await iterator.return();\n }\n}\n\n/**\n * Merge multiple event streams\n */\nexport async function* merge<T = ApiCallback>(\n ...eventTypes: string[]\n): AsyncGenerator<{ eventType: string; message: T }, void, unknown> {\n const iterators = eventTypes.map(type => ({\n type,\n iterator: iterate<T>(type),\n done: false,\n }));\n\n const pendingPromises = new Map<string, Promise<IteratorResult<T>>>();\n\n try {\n // Start all iterators\n for (const item of iterators) {\n if (!item.done) {\n pendingPromises.set(\n item.type,\n item.iterator.next()\n );\n }\n }\n\n while (pendingPromises.size > 0) {\n // Wait for any iterator to produce a value\n const [eventType, result] = await Promise.race(\n Array.from(pendingPromises.entries()).map(\n async ([type, promise]) => [type, await promise] as [string, IteratorResult<T>]\n )\n );\n\n pendingPromises.delete(eventType);\n\n const iterator = iterators.find(it => it.type === eventType)!;\n\n if (result.done) {\n iterator.done = true;\n } else {\n yield { eventType, message: result.value };\n \n // Queue next value from this iterator\n if (!iterator.done) {\n pendingPromises.set(\n eventType,\n iterator.iterator.next()\n );\n }\n }\n }\n } finally {\n // Clean up all iterators\n await Promise.all(\n iterators.map(item => item.iterator.return())\n );\n }\n}\n\n/**\n * Process events with backpressure control\n */\nexport async function processWithBackpressure<T = ApiCallback>(\n eventType: string,\n processor: (msg: T) => Promise<void>,\n maxConcurrent: number = 5\n): Promise<void> {\n const processing = new Set<Promise<void>>();\n\n for await (const message of iterate<T>(eventType)) {\n // Wait if at max concurrent\n if (processing.size >= maxConcurrent) {\n await Promise.race(processing);\n }\n\n // Start processing\n const processPromise = processor(message)\n .catch(err => {\n log.error(`Error processing ${eventType}:`, err);\n })\n .finally(() => {\n processing.delete(processPromise);\n });\n\n processing.add(processPromise);\n }\n\n // Wait for remaining processing\n await Promise.all(processing);\n}\n\n/**\n * Take only the first N events\n */\nexport async function* take<T = ApiCallback>(\n eventType: string,\n count: number\n): AsyncGenerator<T, void, unknown> {\n let taken = 0;\n for await (const message of iterate<T>(eventType)) {\n if (taken >= count) break;\n yield message;\n taken++;\n }\n}\n\n/**\n * Skip the first N events\n */\nexport async function* skip<T = ApiCallback>(\n eventType: string,\n count: number\n): AsyncGenerator<T, void, unknown> {\n let skipped = 0;\n for await (const message of iterate<T>(eventType)) {\n if (skipped < count) {\n skipped++;\n continue;\n }\n yield message;\n }\n}\n\n/**\n * Debounce events (only emit after a period of inactivity)\n */\nexport async function* debounce<T = ApiCallback>(\n eventType: string,\n delay: number\n): AsyncGenerator<T, void, unknown> {\n const iterator = iterate<T>(eventType);\n let lastValue: T | undefined;\n let timer: NodeJS.Timeout | null = null;\n let timerPromise: Promise<void> | null = null;\n let resolveTimer: (() => void) | null = null;\n\n try {\n while (true) {\n if (timerPromise) {\n // Wait for either next message or timer\n const result = await Promise.race([\n iterator.next(),\n timerPromise.then(() => ({ done: false, timeout: true } as any))\n ]);\n\n if (result.done) {\n // Iterator finished\n if (lastValue !== undefined) {\n yield lastValue;\n }\n break;\n }\n\n if (result.timeout) {\n // Timer expired, emit last value\n if (lastValue !== undefined) {\n yield lastValue;\n lastValue = undefined;\n }\n timerPromise = null;\n } else {\n // New message, reset timer\n lastValue = result.value;\n if (timer) clearTimeout(timer);\n \n timerPromise = new Promise<void>(resolve => {\n resolveTimer = resolve;\n timer = setTimeout(() => resolve(), delay);\n });\n }\n } else {\n // First message\n const result = await iterator.next();\n if (result.done) break;\n \n lastValue = result.value;\n timerPromise = new Promise<void>(resolve => {\n resolveTimer = resolve;\n timer = setTimeout(() => resolve(), delay);\n });\n }\n }\n } finally {\n if (timer) clearTimeout(timer);\n await iterator.return();\n }\n}\n\n/**\n * Throttle events (limit emission rate)\n */\nexport async function* throttle<T = ApiCallback>(\n eventType: string,\n interval: number\n): AsyncGenerator<T, void, unknown> {\n let lastEmit = 0;\n \n for await (const message of iterate<T>(eventType)) {\n const now = Date.now();\n const timeSinceLastEmit = now - lastEmit;\n \n if (timeSinceLastEmit < interval) {\n // Wait for remaining interval\n await new Promise(resolve => \n setTimeout(resolve, interval - timeSinceLastEmit)\n );\n }\n \n lastEmit = Date.now();\n yield message;\n }\n}\n\n/**\n * Combine latest values from multiple event streams\n */\nexport async function* combineLatest<T = ApiCallback>(\n ...eventTypes: string[]\n): AsyncGenerator<Record<string, T | undefined>, void, unknown> {\n const latest: Record<string, T | undefined> = {};\n const hasEmitted: Set<string> = new Set();\n\n // Initialize with undefined\n eventTypes.forEach(type => {\n latest[type] = undefined;\n });\n\n for await (const { eventType, message } of merge<T>(...eventTypes)) {\n latest[eventType] = message;\n hasEmitted.add(eventType);\n\n // Only emit once all streams have emitted at least once\n if (hasEmitted.size === eventTypes.length) {\n yield { ...latest };\n }\n }\n}","export enum KosFetchMethods {\n GET = `GET`,\n PUT = `PUT`,\n POST = `POST`,\n DELETE = `DELETE`,\n}\n\ntype FetchMethodStrings = keyof typeof KosFetchMethods;\n\nexport interface Headers {\n append(name: string, value: string): void;\n delete(name: string): void;\n get(name: string): string | null;\n has(name: string): boolean;\n set(name: string, value: string): void;\n forEach(\n callbackfn: (value: string, key: string, parent: Headers) => void,\n thisArg?: any\n ): void;\n}\n\ninterface Body {\n readonly body: ReadableStream<Uint8Array> | null;\n readonly bodyUsed: boolean;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n formData(): Promise<FormData>;\n json<T = any>(): Promise<T | null>;\n text(): Promise<string>;\n}\n\nexport interface Response extends Body {\n readonly headers: Headers;\n readonly ok: boolean;\n readonly redirected: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly type: ResponseType;\n readonly url: string;\n clone(): Response;\n}\n\n/**\n * Represents the configuration options for performing a Kos WebSocket fetch operation.\n */\nexport interface KosFetchOptions {\n /**\n * The HTTP method for the request (e.g., 'GET', 'POST', 'PUT', 'DELETE', etc.).\n */\n method: FetchMethodStrings;\n\n /**\n * The request body - 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 timeout?: number;\n\n headers?: Record<string, string>;\n\n /**\n * Enable streaming mode for large responses\n */\n stream?: boolean;\n\n /**\n * Response type hint for binary data handling\n */\n responseType?: \"text\" | \"json\" | \"arraybuffer\" | \"blob\";\n}\n\nexport interface KosFetchResponse {\n headers: Headers;\n status: string | number | boolean;\n ok: boolean;\n json: <\n T = Record<string | number | symbol, string | number | symbol>\n >() => Promise<T>;\n body: ReadableStream<Uint8Array> | null;\n}\n\nexport interface KosFetchReqeust {\n path: string;\n requestId: string;\n method: FetchMethodStrings;\n destinationAddress?: string;\n ordered?: boolean;\n tracker?: string;\n bridge?: boolean;\n headers?: Record<string, string | number | boolean>;\n}\n\nexport interface KosMessageRequest\n extends Omit<KosFetchReqeust, \"method\" | \"path\" | \"requestId\"> {\n requestType: string;\n requestId?: string;\n headers?: Record<string, string>;\n}\nexport interface KosBroadcastRequest {\n topic: string;\n}\n\nexport interface KosMessageOptions extends KosBroadcastRequest {\n destinationAddress?: string;\n responseId?: string;\n type?: string;\n}\n\nexport interface KosHttpMessageOptions {\n destinationAddress: string;\n sourceAddress: string;\n responseId: string;\n status: number;\n type: string;\n contentType?: string;\n}\n\nexport interface KosFetchResponseParams {\n path: string;\n responseId?: string;\n destinationAddress: string;\n status: string | number | boolean;\n}\n\nexport interface KosFetchPostReqeust extends KosFetchReqeust {\n body?: string;\n}\n","import {\n HEADER_CACHE_CONTROL,\n HEADER_CONTENT_TYPE,\n HEADER_DESTINATION_ADDR,\n HEADER_FOS_REQUEST_ID,\n HEADER_METHOD,\n HEADER_ORDERED,\n HEADER_REQUEST_ID,\n HEADER_REQUEST_TYPE,\n HEADER_RESPONSE_ID,\n HEADER_SOURCE_ADDR,\n HEADER_TOPIC,\n HEADER_URL,\n HEADER_WORK_TRACKER,\n STATUS,\n} from \"../../common\";\nimport { KosCore } from \"../core/kosCore\";\nimport { KosLog } from \"../core/log\";\nimport {\n KosBroadcastRequest,\n KosFetchReqeust,\n KosFetchResponseParams,\n KosMessageOptions,\n type KosHttpMessageOptions,\n type KosMessageRequest,\n} from \"../types\";\n\nexport const createStudioMessage = ({\n path,\n requestId,\n method,\n destinationAddress,\n}: KosFetchReqeust) => {\n let msg = `${HEADER_METHOD}:${method}\\n`;\n msg += `topic:${path}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_REQUEST_ID}:${requestId}\\n`;\n if (destinationAddress) {\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n }\n\n msg += `${HEADER_REQUEST_TYPE}:kos.studio.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const createFosBaseMessage = ({\n path,\n requestId,\n method,\n destinationAddress,\n ordered,\n tracker,\n}: KosFetchReqeust) => {\n let msg = `${HEADER_TOPIC}:/http${path}\\n`;\n msg += `${HEADER_METHOD}:${method}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_FOS_REQUEST_ID}:${requestId}\\n`;\n if (destinationAddress) {\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n }\n if (ordered) {\n msg += `${HEADER_ORDERED}:true\\n`;\n }\n if (tracker) {\n msg += `${HEADER_WORK_TRACKER}:${tracker}\\n`;\n }\n msg += `${HEADER_REQUEST_TYPE}:fos.http.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const createBaseMessage = ({\n path,\n requestId,\n method,\n destinationAddress,\n ordered,\n tracker,\n bridge,\n headers,\n}: KosFetchReqeust) => {\n let msg = `${HEADER_METHOD}:${method}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_REQUEST_ID}:${requestId}\\n`;\n if (destinationAddress) {\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n }\n if (ordered) {\n msg += `${HEADER_ORDERED}:true\\n`;\n }\n if (tracker) {\n msg += `${HEADER_WORK_TRACKER}:${tracker}\\n`;\n }\n\n if (headers) {\n Object.keys(headers).forEach((key) => {\n msg += `${key}:${headers[key]}\\n`;\n });\n }\n msg += `${HEADER_REQUEST_TYPE}:${bridge ? \"fos\" : \"kos\"}.http.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const createMessageBody = (msg: string, body?: string) => {\n let _msg = msg;\n if (body) {\n _msg += body;\n }\n return _msg;\n};\n\nexport function createHeaders(headers: Record<string, string>): Headers {\n const _headers = { ...headers };\n return {\n append(name: string, value: string) {\n _headers[name] = value;\n },\n delete(name: string) {\n delete _headers[name];\n },\n get(name: string) {\n return _headers[name];\n },\n forEach(callbackFn) {\n Object.keys(_headers).forEach((key) =>\n callbackFn(_headers[key], key, this)\n );\n },\n has(name) {\n return Object.hasOwn(_headers, name);\n },\n set(name: string, value: string) {\n _headers[name] = value;\n },\n keys() {\n return Object.keys(_headers);\n },\n values() {\n return Object.values(_headers);\n },\n entries() {\n return Object.entries(_headers);\n },\n } as unknown as Headers;\n}\n\nexport function createReadableStream(\n msg: string\n): ReadableStream<Uint8Array> | null {\n let sent = false;\n if (window.ReadableStream) {\n const stream = new ReadableStream({\n start(controller) {\n // The following function handles each data chunk\n function push() {\n // \"done\" is a Boolean and value a \"Uint8Array\"\n return Promise.resolve({ done: sent, value: msg }).then(\n ({ done, value }) => {\n // Is there no more data to read?\n if (done) {\n // Tell the browser that we have finished sending data\n controller.close();\n return;\n }\n\n // Get the data and send it to the browser via the controller\n controller.enqueue(value);\n sent = true;\n push();\n }\n );\n }\n\n push();\n },\n });\n return stream;\n }\n return msg as any;\n}\n\nexport const createStudioMessageRequest = ({\n path,\n requestId,\n destinationAddress,\n}: KosFetchReqeust) => {\n let msg = `topic:${path}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n msg += `${HEADER_REQUEST_ID}:${requestId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:kos.studio.request\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const createKosMessage = ({\n requestId,\n destinationAddress,\n requestType,\n headers,\n}: KosMessageRequest) => {\n let msg = `${HEADER_REQUEST_ID}:${requestId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:${requestType}\\n`;\n if (headers) {\n Object.keys(headers).forEach((key) => {\n msg += `${key}:${headers[key]}\\n`;\n });\n }\n msg += `\\n`;\n return msg;\n};\n\nexport const sendKosMessage = <T extends object>(\n msg: T,\n options: KosMessageRequest\n) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createKosMessage(options),\n typeof wrappedMsg === \"string\" ? wrappedMsg : JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n KosLog.debug(\"Sending message\", _msg);\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\nexport const createStudioMessageResponse = ({\n path,\n responseId,\n status,\n destinationAddress,\n}: KosFetchResponseParams) => {\n let msg = `topic:${path}\\n`;\n msg += `${HEADER_URL}:${path}\\n`;\n if (responseId) msg += `${HEADER_RESPONSE_ID}:${responseId}\\n`;\n msg += `${STATUS}:${status}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n\n msg += `${HEADER_REQUEST_TYPE}:kos.studio.response\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const sendStudioMessageRequest = <T extends object>(\n msg: T,\n options: KosFetchReqeust\n) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createStudioMessageRequest(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\nexport const sendStudioMessage = <T extends object>(\n msg: T,\n options: KosFetchResponseParams\n) => {\n const wrappedMsg = options.responseId\n ? { status: options.status, data: msg }\n : msg;\n\n const _msg = createMessageBody(\n createStudioMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\nexport const createBroadcastMessageResponse = ({\n topic,\n}: KosBroadcastRequest) => {\n let msg = `topic:${topic}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:kos.broker.send\\n`;\n msg += `\\n`;\n return msg;\n};\nexport const createKosHtpMessageResponse = ({\n responseId,\n destinationAddress,\n type,\n sourceAddress,\n status,\n}: KosHttpMessageOptions) => {\n let msg = `${HEADER_RESPONSE_ID}:${responseId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_SOURCE_ADDR}:${sourceAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:${type ?? \"kos.message.request\"}\\n`;\n msg += `${STATUS}:${status}\\n`;\n msg += `${HEADER_CONTENT_TYPE}:application/json\\n`;\n msg += `${HEADER_CACHE_CONTROL}:no-cache\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport const createKosMessageResponse = ({\n topic,\n responseId,\n destinationAddress,\n type,\n}: KosMessageOptions) => {\n let msg = `topic:${topic}\\n`;\n if (responseId) msg += `${HEADER_RESPONSE_ID}:${responseId}\\n`;\n msg += `${HEADER_DESTINATION_ADDR}:${destinationAddress}\\n`;\n msg += `${HEADER_REQUEST_TYPE}:${type ?? \"kos.message.request\"}\\n`;\n msg += `\\n`;\n return msg;\n};\n\nexport interface KosBroadcastRequestParams<T extends object> {\n msg: T;\n options: KosBroadcastRequest;\n}\nexport const sendBroadcastMessage = <T extends object>({\n msg,\n options,\n}: KosBroadcastRequestParams<T>) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createBroadcastMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\nexport interface KosMessageResponseParams<T extends object> {\n msg: T;\n options: KosMessageOptions;\n}\n\nexport interface KosHttpMessageResponseParams<T extends object> {\n msg: T;\n options: KosHttpMessageOptions;\n}\nexport const sendKosMessageResponse = <T extends object>({\n msg,\n options,\n}: KosMessageResponseParams<T>) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createKosMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\nexport const sendKosHttpMessageResponse = <T extends object>({\n msg,\n options,\n}: KosHttpMessageResponseParams<T>) => {\n const wrappedMsg = msg;\n\n const _msg = createMessageBody(\n createKosHtpMessageResponse(options),\n JSON.stringify(wrappedMsg)\n );\n\n const socketTransport = KosCore.getInstance().transport.socket;\n if (socketTransport) {\n socketTransport.socket.send(_msg);\n } else {\n KosLog.error(\"socket transport is not initialized\");\n }\n};\n\nexport const getMessageBody = (payload, skipParse) => {\n try {\n return skipParse ? payload.body ?? payload : JSON.parse(payload.body);\n } catch {\n return payload.body || payload;\n }\n};\n","import type { Transport } from \"./transport\";\n\nexport class WebSocketBridgeTransport extends WebSocket implements Transport {\n constructor(address: string) {\n super(address);\n }\n}\n","import { makeObservable, observable, runInAction } from \"mobx\";\nimport { EventBus, KosWsEvents } from \"../../../common\";\nimport { KosLog } from \"../log\";\nimport { Transport } from \"./transport\";\nimport { WebSocketBridgeTransport } from \"./web-socket-transport-adapter\";\n\nexport enum WebSocketEvents {\n CONNECTED = `websocket.connected`,\n DISCONNECTED = `websocket.disconnected`,\n}\nexport interface TransportParams {\n host: string;\n port: number;\n protocol: string;\n alias?: string;\n onConnectionEstablished?: () => void;\n onConnectionLost?: () => void;\n Transport?: new (url: string) => Transport;\n}\nexport interface MessageTransport {\n socket: Transport;\n send: (data: string | ArrayBufferLike | Blob | ArrayBufferView) => void;\n connectionEstablished: boolean;\n addOfflineMessage: (msg: string) => void;\n}\n\nexport interface KosInternalEvent {\n headers: Record<string | `topic` | `http-request-id`, string>;\n body: string;\n}\n\ninterface OfflineMessage {\n msg: string;\n fos?: boolean;\n}\n\nexport function processKosMessage(data: string): KosInternalEvent {\n const MESSAGE_SEPARATOR = `\\n\\n`;\n const SEPARATOR = `\\n`;\n const HEADER_SEPARATOR = /:(.*)/s;\n\n const [headerText, body] = data\n .split(MESSAGE_SEPARATOR)\n .map((line: string) => line.trim());\n const headers = headerText\n .split(SEPARATOR)\n .reduce((acc: any, curr: string) => {\n const [header, value] = curr\n .split(HEADER_SEPARATOR)\n .map((raw: string) => raw.trim());\n if (header && value) {\n acc[header] = value;\n }\n return acc;\n }, {});\n\n return {\n headers,\n body: body,\n };\n}\nexport function processKosSnifferMessage(data: string): KosInternalEvent {\n const MESSAGE_SEPARATOR = `\\n\\n`;\n const SEPARATOR = `\\n`;\n const HEADER_SEPARATOR = /:(.*)/s;\n\n const [, headerText, body] = data\n .split(MESSAGE_SEPARATOR)\n .map((line: string) => line.trim());\n const headers = headerText\n .split(SEPARATOR)\n .reduce((acc: any, curr: string) => {\n const [header, value] = curr\n .split(HEADER_SEPARATOR)\n .map((raw: string) => raw.trim());\n if (header && value) {\n acc[header] = value;\n }\n return acc;\n }, {});\n\n return {\n headers,\n body: body,\n };\n}\n\nexport abstract class BaseTransport implements MessageTransport {\n protected host: string;\n protected port: number;\n protected protocol: string;\n public socket: Transport;\n public connectionEstablished: boolean;\n private alias?: string;\n private onConnectionEstablished?: () => void;\n private onConnectionLost?: () => void;\n protected offlineMessages: OfflineMessage[] = [];\n protected abstract RESPONSE_ID_HEADER: string;\n private oldSend: (\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n ) => void;\n constructor({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n Transport = WebSocketBridgeTransport,\n }: TransportParams) {\n this.host = host;\n this.port = port;\n this.protocol = protocol;\n this.onConnectionEstablished = onConnectionEstablished;\n this.onConnectionLost = onConnectionLost;\n this.alias = alias;\n this.socket = new Transport(\n `${this.protocol}${this.host}:${this.port}/events`\n );\n this.socket.onmessage = this.onMessage.bind(this);\n this.socket.onopen = this.onOpen.bind(this);\n this.socket.onclose = this.onClose.bind(this);\n this.oldSend = this.socket.send;\n this.connectionEstablished = false;\n EventBus.subscribe(\"/mock/msg/receive\", (data) => {\n if (data?.body) {\n KosLog.wsReceive(data?.body);\n const msg: MessageEvent = {\n data: data.body,\n } as unknown as MessageEvent;\n this.socket?.onmessage?.(msg);\n }\n });\n\n makeObservable(this, {\n connectionEstablished: observable,\n });\n }\n\n addOfflineMessage(msg: string) {\n this.offlineMessages.push({ msg });\n }\n processMessageEvent(msg: MessageEvent): KosInternalEvent {\n const { data } = msg;\n return processKosMessage(data);\n }\n\n onMessage(event: Event) {\n try {\n // parsing the message payload\n KosLog.debug(\"webSocketTransport: onMessage received\");\n\n const { headers, body } = this.processMessageEvent(event as MessageEvent);\n KosLog.wsReceive((event as MessageEvent).data);\n const subscriptionTopic =\n headers[\"subscription\"] ||\n headers[this.RESPONSE_ID_HEADER] ||\n headers[\"topic\"] ||\n headers[\"type\"];\n if (subscriptionTopic) {\n let msgBody = body;\n let msgHeaders = headers;\n\n if (subscriptionTopic === \"kos.sniffer.msg\") {\n const { headers: snifferHeaders, body: snifferBody } =\n processKosSnifferMessage((event as MessageEvent).data);\n msgBody = snifferBody;\n msgHeaders = {\n ...headers,\n ...snifferHeaders,\n };\n }\n\n EventBus.publish(subscriptionTopic, msgBody, msgHeaders);\n }\n } catch (ex: any) {\n KosLog.error(`onMessage exception`, ex.message, ex.stack);\n }\n }\n\n onOpen(event: Event) {\n KosLog.info(`websocket connection opened`);\n\n this.socket = event.currentTarget as Transport;\n runInAction(() => {\n this.connectionEstablished = true;\n if (this.alias) {\n this.socket.send(`type:kos.addr.alias\\nalias:${this.alias}\\n\\n`);\n }\n KosLog.debug(\n `sending ${this.offlineMessages.length} offline FOS messages`\n );\n this.offlineMessages.forEach((msg) => {\n KosLog.debug(`sending offline message ${msg.msg}`);\n this.socket?.send(msg.msg);\n });\n\n this.offlineMessages = [];\n this.onConnectionEstablished?.();\n });\n }\n\n onClose() {\n if (this.socket) {\n this.socket.close();\n }\n\n runInAction(() => {\n this.connectionEstablished = false;\n });\n\n KosLog.debug(`websocket disconnected. Attempting calling callback`);\n if (this.onConnectionLost) {\n setTimeout(this.onConnectionLost, 2500);\n }\n }\n\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {\n KosLog.wsSend(data);\n if (window.kosLogEvents) {\n const { headers, body } = processKosMessage(String(data));\n EventBus.publish(KosWsEvents.SEND, { headers, body });\n }\n if (window.kosTopicIntercept && window.kosEnableMocks) {\n const { handler, requestId } = window.kosTopicIntercept(data);\n if (handler) {\n data = `mocked:true\\n${data}`;\n\n const msg = handler(requestId);\n const returnData: MessageEvent = {\n data: `mocked:true\\n${msg}`,\n } as unknown as MessageEvent;\n this.socket?.onmessage?.(returnData);\n } else {\n this.oldSend.call(this.socket, data);\n }\n } else {\n this.oldSend.call(this.socket, data);\n }\n }\n}\n","import log from \"loglevel\";\nimport type { Transport } from \"./transport\";\n\ntype MessageType = string | ArrayBufferLike | Blob | ArrayBufferView;\nexport class BridgeTransport implements Transport {\n addEventListener!: () => any;\n dispatchEvent!: () => any;\n removeEventListener!: () => any;\n private _onclose!: ((ev: CloseEvent) => any) | null;\n private _onerror!: ((ev: Event) => any) | null;\n private _onmessage!: ((ev: MessageEvent) => any) | null;\n private _onopen!: ((ev: Event) => any) | null;\n private messageQueue: MessageType[] = [];\n private isSending = false;\n\n constructor(addr: string) {\n log.debug(`called Bridge Transport with addr ${addr}`);\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this;\n globalThis.kosWindowWebsocketRecv = (msg: string) => {\n if (that.onmessage) {\n const data: MessageEvent = { data: msg } as unknown as MessageEvent;\n that.onmessage(data);\n }\n };\n // initalize the transport\n log.debug(\"Opening bridge transport\");\n globalThis.kosWindowWebsocketOpen();\n log.debug(\"Opened bridge transport\");\n\n this._onclose = null;\n this._onerror = null;\n this._onmessage = null;\n this._onopen = null;\n this.addEventListener = () => log.debug(\"not implemented\");\n this.dispatchEvent = () => log.debug(\"not implemented\");\n this.removeEventListener = () => log.debug(\"not implemented\");\n }\n\n close() {\n log.debug(\"closing\");\n }\n\n private sendNextMessage() {\n if (this.messageQueue.length > 0) {\n const message = this.messageQueue.shift();\n globalThis.kosWindowWebsocketSend(message);\n setTimeout(() => this.sendNextMessage(), 1);\n } else {\n this.isSending = false;\n }\n }\n enqueueMessage(message: MessageType) {\n this.messageQueue.push(message);\n if (!this.isSending) {\n this.isSending = true;\n this.sendNextMessage();\n }\n }\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {\n globalThis.kosWindowWebsocketSend(data);\n }\n\n get onmessage() {\n return this._onmessage;\n }\n set onmessage(fn: ((ev: MessageEvent) => any) | null) {\n this._onmessage = fn;\n }\n\n get onopen() {\n return this._onopen;\n }\n set onopen(fn: ((ev: Event) => any) | null) {\n this._onopen = fn;\n }\n\n get onclose() {\n return this._onclose;\n }\n set onclose(fn: ((ev: CloseEvent) => any) | null) {\n this._onclose = fn;\n }\n\n get onerror() {\n return this._onerror;\n }\n set onerror(fn: ((ev: Event) => any) | null) {\n this._onopen = fn;\n }\n}\n","import { BaseTransport, TransportParams } from \"./base-message-transport\";\nimport { BridgeTransport } from \"./bridge-transport\";\n\nexport class BridgeMessageTransport extends BaseTransport {\n protected RESPONSE_ID_HEADER: string;\n constructor({ host, port, alias }: TransportParams) {\n super({\n host,\n port,\n Transport: BridgeTransport,\n alias,\n protocol: \"kos://\",\n });\n this.RESPONSE_ID_HEADER = `response-id`;\n }\n}\n","import { BaseTransport, TransportParams } from \"./base-message-transport\";\n\nexport class FosTransport extends BaseTransport {\n protected RESPONSE_ID_HEADER: string;\n constructor({ host, port }: TransportParams) {\n super({ host, port, protocol: `ws://` });\n this.RESPONSE_ID_HEADER = `requestId`;\n }\n}\n","import { BaseTransport, TransportParams } from \"./base-message-transport\";\n\nexport class KosTransport extends BaseTransport {\n protected RESPONSE_ID_HEADER: string;\n constructor({\n host,\n port,\n protocol,\n onConnectionEstablished,\n onConnectionLost,\n alias,\n }: TransportParams) {\n super({\n host,\n port,\n onConnectionEstablished,\n onConnectionLost,\n alias,\n protocol,\n });\n this.RESPONSE_ID_HEADER = `response-id`;\n }\n}\n","// eslint-disable-next-line spaced-comment, @typescript-eslint/triple-slash-reference\n/// <reference path=\"../../types/global.d.ts\" />\nimport { KosLog } from \"../log\";\nimport { BridgeMessageTransport } from \"./bridge-message-transport\";\nimport { FosTransport } from \"./fos-message-transport\";\nimport { KosTransport } from \"./kos-message-transport\";\n\nwindow.kosEnableMocks = process.env.KOS_MOCK_WS === \"true\";\nwindow.kosLogEvents = process.env.KOS_LOG_WS === \"true\";\n\ninterface FactoryParams {\n host: string;\n port: number;\n protocol: string;\n fos?: boolean;\n alias?: string;\n onConnectionEstablished?: () => void;\n onConnectionLost?: () => void;\n}\n\n/**\n *\n * @description\n * Extend event to get access to the data property.\n */\nexport interface KosInternalEvent {\n headers: Record<string | `topic` | `http-request-id`, string>;\n body: string;\n}\n\nexport class TransportFactory {\n static build({\n host,\n port,\n protocol,\n fos,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n }: FactoryParams) {\n KosLog.debug(`initializing websocket connection`);\n KosLog.warn(\n `kosWindowWebsocketOpen: ${\n globalThis.kosWindowWebsocketOpen ? `true` : `false`\n }`\n );\n KosLog.warn(`fos: ${fos ? `true` : `false`}`);\n if (window.kosMockWs || (globalThis.kosWindowWebsocketOpen && !fos)) {\n KosLog.warn(`Using bridged message transport`);\n const transport = new BridgeMessageTransport({\n host,\n port,\n protocol,\n onConnectionEstablished,\n onConnectionLost,\n alias,\n });\n return transport;\n }\n if (fos) {\n const transport = new FosTransport({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n });\n return transport;\n } else {\n const transport = new KosTransport({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n });\n return transport;\n }\n }\n}\n","import Logger from \"loglevel\";\nimport {\n action,\n computed,\n makeObservable,\n observable,\n reaction,\n when,\n} from \"mobx\";\nimport { EventBus, EventCallback } from \"../../../common\";\n\nimport { getQueryParams } from \"../../util/get-query-params\";\nimport { KosLog } from \"../log\";\nimport { MessageTransport } from \"./base-message-transport\";\nimport { TransportFactory } from \"./transport-factory\";\n\nconst params = getQueryParams();\nif ((params as any).fos) {\n window.kosUseFos = true;\n}\nconst fosPort = process.env.KOS_FOS_PORT;\nwindow.kosUseFos = !!(window.kosUseFos || process.env.KOS_USE_FOS === \"true\");\nwindow.kosFosPort = fosPort ? parseInt(fosPort) : 0;\n\nconst log = Logger.getLogger(\"web-socket-transport\");\nexport enum KosWSTransportStatus {\n NOT_INITIALIZED = \"not_initialized\",\n INITIALIZED = \"initialized\",\n OFFLINE = \"OFFLINE\",\n ONLINE = \"ONLINE\",\n}\nexport interface IKosMessage {\n [k: string]: string | number | boolean;\n}\n\nexport interface IKosConnectionStatus {\n status: string;\n message?: string;\n}\n\nexport interface KosSubscriptionParams {\n topic: string;\n callback: EventCallback;\n fos?: boolean;\n bridge?: boolean;\n destinationAddress?: string | null;\n}\nexport interface IKosServiceTransport {\n host: string;\n port: number;\n protocol: string;\n token?: string;\n alias?: string;\n connectionEstablished: boolean;\n authorized: boolean;\n socket?: MessageTransport;\n init(): IKosServiceTransport;\n subscribeTopic(params: KosSubscriptionParams): VoidFunction;\n whenReady(): Promise<IKosConnectionStatus>;\n fosSocket?: MessageTransport;\n}\n\nexport type KosCallback = (msg: IKosMessage) => void;\n\nexport enum WebSocketEvents {\n CONNECTED = `websocket.connected`,\n DISCONNECTED = `websocket.disconnected`,\n RELOAD = `websocket.reload`,\n}\n\ninterface WebSocketTransportParams {\n host?: string;\n port?: number;\n protocol?: string;\n token?: string;\n initialize?: boolean;\n alias?: string;\n fos?: {\n port: number;\n };\n}\n\nexport class WebSocketTransport implements IKosServiceTransport {\n private static _instance: IKosServiceTransport;\n\n host: string;\n\n port: number;\n\n protocol: string;\n\n private _token?: string;\n\n private webSocketSupported = !!globalThis.WebSocket;\n\n authorized: boolean;\n\n alias?: string;\n\n socket?: MessageTransport;\n\n fosSocket?: MessageTransport;\n\n fosPort?: number;\n\n useFosTransport: boolean;\n\n constructor({\n host = `localhost`,\n port = 8080,\n protocol = \"ws://\",\n token,\n initialize,\n alias,\n fos,\n }: WebSocketTransportParams) {\n this.host = host;\n this.port = port;\n this.protocol = protocol;\n this._token = token;\n this.alias = alias;\n this.authorized = process.env.KOS_ALLOW_ANONYMOUS === \"true\" ? true : false;\n\n this.useFosTransport = !!fos;\n this.fosPort = fos?.port;\n this.socket = undefined;\n this.fosSocket = undefined;\n\n let initialized = false;\n makeObservable(this, {\n authorized: observable,\n socket: observable,\n fosSocket: observable,\n init: action,\n connectionEstablished: computed,\n });\n\n reaction(\n () => this.connectionEstablished,\n (connectionEstablished) => {\n if (connectionEstablished) {\n log.warn(\"Connection Established\");\n\n EventBus.publish(\n WebSocketEvents.CONNECTED,\n WebSocketEvents.CONNECTED\n );\n if (initialized) {\n // reload only if the websocket has been initialized once\n EventBus.publish(WebSocketEvents.RELOAD, WebSocketEvents.RELOAD);\n }\n initialized = true;\n }\n }\n );\n\n if (initialize) {\n this.init();\n }\n }\n\n get connectionEstablished() {\n if (!this.webSocketSupported) {\n return false;\n }\n if (!this.socket) {\n return false;\n }\n\n if (this.useFosTransport && !this.fosSocket) {\n return false;\n }\n\n if (this.useFosTransport && this.fosSocket) {\n return (\n this.socket.connectionEstablished &&\n this.fosSocket.connectionEstablished\n );\n }\n if (!this.useFosTransport && this.socket) {\n return this.socket.connectionEstablished;\n }\n return false;\n }\n\n init() {\n KosLog.warn(`Initializing WebSocketTransport on ${this.host}:${this.port}`);\n if (this.useFosTransport) {\n this.fosSocket = TransportFactory.build({\n host: this.host,\n port: this.fosPort || 9854,\n protocol: this.protocol,\n fos: true,\n });\n }\n this.socket = TransportFactory.build({\n host: this.host,\n port: this.port,\n protocol: this.protocol,\n alias: this.alias,\n onConnectionLost: () => {\n log.error(`Connection Lost`);\n EventBus.publish(\n WebSocketEvents.DISCONNECTED,\n WebSocketEvents.DISCONNECTED\n );\n this.init();\n },\n });\n\n if (globalThis.kosWindowWebsocketOpen) {\n const ev: Event = {\n currentTarget: this.socket.socket,\n } as unknown as Event;\n this.socket.socket?.onopen?.(ev);\n }\n return this;\n }\n\n private _sendSubscriptionMessage(\n topic: string,\n type: \"subscribe\" | \"unsubscribe\",\n fos = false,\n bridge = false,\n connectionId?: string | null\n ) {\n log.debug(`${type} to topic ${topic}`);\n const params = getQueryParams();\n const connectionParam = (params as any)?.connId;\n const connId =\n connectionId ?? connectionParam ?? (window as any)?.kosBridge?.(\"connId\");\n log.debug(`subscribing with connId ${connId}`);\n\n const dstAddr = connId ? `dst-addr:${connId}\\n` : \"\";\n const msg = fos\n ? `subscribe:${topic}`\n : bridge\n ? `type:fos.broker\\ncmd:${type}\\n${dstAddr}topics:${topic}\\n`\n : `${dstAddr}type:kos.broker.${type}\\n\\n[\"${topic}\"]`;\n const established = fos\n ? this.fosSocket?.connectionEstablished\n : this.socket?.connectionEstablished;\n if (established) {\n const socket = fos ? this.fosSocket : this.socket;\n socket?.socket?.send(msg);\n } else {\n log.debug(`no connection adding to offline messages`);\n const socket = fos ? this.fosSocket : this.socket;\n socket?.addOfflineMessage(msg);\n }\n }\n\n subscribeTopic({\n topic,\n callback,\n fos,\n bridge,\n destinationAddress,\n }: KosSubscriptionParams) {\n const { unsubscribe, count } = EventBus.subscribe(topic, callback);\n log.debug(`Topic ${topic} currently has ${count} subscribers`);\n this._sendSubscriptionMessage(\n topic,\n \"subscribe\",\n fos,\n bridge,\n destinationAddress\n );\n\n return () => {\n const { count } = unsubscribe();\n log.debug(`Topic ${topic} currently has ${count} subscribers`);\n if (count === 0) {\n this._sendSubscriptionMessage(\n topic,\n \"unsubscribe\",\n fos,\n bridge,\n destinationAddress\n );\n }\n };\n }\n\n async whenReady() {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const that = this;\n if (!this.webSocketSupported) {\n return {\n status: `not supported`,\n };\n }\n await when(\n () =>\n !!that.socket?.connectionEstablished &&\n (!that.useFosTransport || !!that.fosSocket?.connectionEstablished) &&\n that.authorized\n );\n return {\n status: `success`,\n };\n }\n\n get token() {\n return this._token!;\n }\n set token(token: string) {\n this._token = token;\n this.init();\n }\n public static host(host = `localhost`) {\n this.getInstance().host = host;\n return this;\n }\n\n public static port(port = 8080) {\n this.getInstance().port = port;\n return this;\n }\n\n public static alias(alias: string) {\n this.getInstance().alias = alias;\n }\n\n public static getInstance(port = 8080, token?: string) {\n if (!this._instance) {\n const fos = window.kosUseFos\n ? { port: window.kosFosPort || 8081 }\n : undefined;\n this._instance = new this({ port, token, fos });\n }\n return this._instance;\n }\n}\n","import type { IKosTopicHandlerParams } from \"./kosTopicHandler\";\nimport type { IKosDataModel } from \"../kosModel\";\n\n/**\n * Advanced flow control options for kosTopicHandler\n */\nexport interface FlowControlOptions<T = any, R = T> {\n /**\n * Batching configuration\n */\n batch?: {\n /** Maximum number of events in a batch */\n size?: number;\n /** Maximum time window to collect events (ms) */\n window?: number;\n };\n\n /**\n * Transform function to apply to batched events\n * @param events - Array of events in the batch\n * @returns Transformed data to pass to handler\n */\n transform?: (events: T[]) => R;\n\n /**\n * Backpressure control to prevent overwhelming slow handlers\n */\n backpressure?: {\n /** Maximum concurrent handler executions */\n maxConcurrent?: number;\n /** Queue size limit before dropping events */\n maxQueue?: number;\n /** Policy for dropping events when queue is full */\n dropPolicy?: \"oldest\" | \"newest\" | \"none\";\n /** Callback when events are dropped due to queue overflow */\n onQueueFull?: (droppedEvents: T[]) => void;\n };\n\n /**\n * Advanced filtering with state awareness\n */\n filter?: {\n /** Predicate function for filtering events */\n predicate: (event: T, context: FilterContext) => boolean;\n /** Remember last N events for stateful filtering */\n historySize?: number;\n };\n\n /**\n * Rate limiting options\n */\n rateLimit?: {\n /** Maximum events to process per time window */\n maxEvents: number;\n /** Time window in milliseconds */\n windowMs: number;\n /** What to do when rate limit is exceeded */\n onExceeded?: \"drop\" | \"delay\" | \"error\";\n };\n\n /**\n * Error handling strategy for the flow\n */\n errorHandling?: {\n /** Retry failed events */\n retry?: {\n attempts: number;\n backoffMs: number;\n };\n /** Continue processing other events if one fails */\n continueOnError?: boolean;\n };\n}\n\nexport interface FilterContext {\n /** Previous events in the filter history */\n history: any[];\n /** Current batch being processed */\n currentBatch: any[];\n /** Timestamp when filtering started */\n startTime: number;\n}\n\n/**\n * Enhanced kosTopicHandler params with flow control\n */\nexport interface IKosTopicHandlerFlowParams<\n T = any, \n Model extends IKosDataModel = any, \n R = T\n> extends IKosTopicHandlerParams<T, Model, R> {\n /**\n * Advanced flow control options using async iterators internally\n */\n flow?: FlowControlOptions<T, R>;\n}\n\n/**\n * Statistics for monitoring flow control performance\n */\nexport interface FlowControlStats {\n /** Total events received */\n eventsReceived: number;\n /** Total batches processed */\n batchesProcessed: number;\n /** Events dropped due to backpressure */\n eventsDropped: number;\n /** Current queue size */\n currentQueueSize: number;\n /** Average batch size */\n averageBatchSize: number;\n /** Processing rate (events/second) */\n processingRate: number;\n /** Last processing timestamp */\n lastProcessedAt: number;\n}\n\n/**\n * Internal flow control manager\n */\nexport class FlowControlManager<T = any, R = T> {\n private config: FlowControlOptions<T, R>;\n private stats: FlowControlStats;\n private filterHistory: T[] = [];\n private activePromises = new Set<Promise<any>>();\n private eventQueue: T[] = [];\n private rateLimitWindow = new Map<number, number>();\n\n constructor(config: FlowControlOptions<T, R>) {\n this.config = config;\n this.stats = {\n eventsReceived: 0,\n batchesProcessed: 0,\n eventsDropped: 0,\n currentQueueSize: 0,\n averageBatchSize: 0,\n processingRate: 0,\n lastProcessedAt: Date.now(),\n };\n }\n\n async *processEvents(\n eventStream: AsyncIterable<T>\n ): AsyncGenerator<R, void, unknown> {\n const batchConfig = this.config.batch || { size: 1, window: 0 };\n\n if (batchConfig.size === 1 && !batchConfig.window) {\n // Single event processing with flow control\n for await (const event of eventStream) {\n yield* this.processSingleEvent(event);\n }\n } else {\n // Batch processing\n yield* this.processBatchedEvents(eventStream, batchConfig);\n }\n }\n\n private async *processSingleEvent(\n event: T\n ): AsyncGenerator<R, void, unknown> {\n this.stats.eventsReceived++;\n\n // Apply filtering\n if (this.config.filter && !this.shouldProcessEvent(event)) {\n return;\n }\n\n // Check rate limiting\n if (this.config.rateLimit && !this.checkRateLimit()) {\n if (this.config.rateLimit.onExceeded === \"drop\") {\n this.stats.eventsDropped++;\n return;\n } else if (this.config.rateLimit.onExceeded === \"delay\") {\n await this.waitForRateLimit();\n }\n }\n\n // Use queue system for backpressure management\n if (this.config.backpressure) {\n this.enqueueEvent(event);\n await this.waitForCapacity();\n \n // Process from queue\n const queuedEvent = this.dequeueEvent();\n if (queuedEvent) {\n const transformed = this.config.transform\n ? this.config.transform([queuedEvent])\n : ([queuedEvent] as unknown as R);\n\n yield transformed;\n this.updateProcessingStats([queuedEvent]);\n }\n } else {\n // Direct processing without queue\n const transformed = this.config.transform\n ? this.config.transform([event])\n : ([event] as unknown as R);\n\n yield transformed;\n this.updateProcessingStats([event]);\n }\n }\n\n private async *processBatchedEvents(\n eventStream: AsyncIterable<T>,\n batchConfig: { size?: number; window?: number }\n ): AsyncGenerator<R, void, unknown> {\n const maxSize = batchConfig.size || 100;\n const maxWait = batchConfig.window || 1000;\n\n let batch: T[] = [];\n let lastFlush = Date.now();\n\n const flushBatch = async (): Promise<R | undefined> => {\n if (batch.length === 0) return undefined;\n\n const currentBatch = [...batch];\n batch = [];\n lastFlush = Date.now();\n\n // Apply batch-level filtering\n const filteredBatch = this.config.filter\n ? currentBatch.filter((event) => this.shouldProcessEvent(event))\n : currentBatch;\n\n if (filteredBatch.length === 0) return undefined;\n\n // Check backpressure\n if (this.config.backpressure) {\n await this.waitForCapacity();\n }\n\n // Transform batch\n const transformed = this.config.transform\n ? this.config.transform(filteredBatch)\n : (filteredBatch as unknown as R);\n\n this.stats.batchesProcessed++;\n this.updateProcessingStats(filteredBatch);\n\n return transformed;\n };\n\n try {\n for await (const event of eventStream) {\n this.stats.eventsReceived++;\n \n // Use queue system for backpressure management\n if (this.config.backpressure) {\n this.enqueueEvent(event);\n \n // Process from queue instead of directly\n while (this.eventQueue.length > 0) {\n const queuedEvent = this.dequeueEvent();\n if (queuedEvent) {\n batch.push(queuedEvent);\n }\n \n const now = Date.now();\n const timeSinceLastFlush = now - lastFlush;\n\n // Flush if batch is full OR time window exceeded\n if (batch.length >= maxSize || timeSinceLastFlush >= maxWait) {\n const flushed = await flushBatch();\n if (flushed !== undefined) {\n yield flushed;\n }\n break; // Break to get next event from stream\n }\n }\n } else {\n // Direct processing without queue when no backpressure config\n batch.push(event);\n\n const now = Date.now();\n const timeSinceLastFlush = now - lastFlush;\n\n // Flush if batch is full OR time window exceeded\n if (batch.length >= maxSize || timeSinceLastFlush >= maxWait) {\n const flushed = await flushBatch();\n if (flushed !== undefined) {\n yield flushed;\n }\n }\n }\n }\n\n // Flush remaining events\n const flushed = await flushBatch();\n if (flushed !== undefined) {\n yield flushed;\n }\n } finally {\n // No cleanup needed with this simpler approach\n }\n }\n\n private shouldProcessEvent(event: T): boolean {\n if (!this.config.filter) return true;\n\n const context: FilterContext = {\n history: [...this.filterHistory],\n currentBatch: [],\n startTime: Date.now(),\n };\n\n const shouldProcess = this.config.filter.predicate(event, context);\n\n // Update filter history\n if (this.config.filter.historySize) {\n this.filterHistory.push(event);\n if (this.filterHistory.length > this.config.filter.historySize) {\n this.filterHistory.shift();\n }\n }\n\n return shouldProcess;\n }\n\n private checkRateLimit(): boolean {\n if (!this.config.rateLimit) return true;\n\n const now = Date.now();\n const windowStart = Math.floor(now / this.config.rateLimit.windowMs);\n const currentCount = this.rateLimitWindow.get(windowStart) || 0;\n\n if (currentCount >= this.config.rateLimit.maxEvents) {\n return false;\n }\n\n this.rateLimitWindow.set(windowStart, currentCount + 1);\n\n // Clean up old windows\n for (const [window] of this.rateLimitWindow) {\n if (window < windowStart - 1) {\n this.rateLimitWindow.delete(window);\n }\n }\n\n return true;\n }\n\n private async waitForRateLimit(): Promise<void> {\n if (!this.config.rateLimit) return;\n\n const now = Date.now();\n const windowStart = Math.floor(now / this.config.rateLimit.windowMs);\n const nextWindow = (windowStart + 1) * this.config.rateLimit.windowMs;\n const waitTime = nextWindow - now;\n\n if (waitTime > 0) {\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n }\n }\n\n private async waitForCapacity(): Promise<void> {\n if (!this.config.backpressure) return;\n\n const maxConcurrent = this.config.backpressure.maxConcurrent || 5;\n const maxQueue = this.config.backpressure.maxQueue || 1000;\n\n // Wait for available execution slots\n while (this.activePromises.size >= maxConcurrent) {\n await Promise.race(this.activePromises);\n }\n\n // Check if queue is full and handle overflow\n if (this.eventQueue.length >= maxQueue) {\n this.handleQueueOverflow();\n }\n }\n\n private handleQueueOverflow(): void {\n if (!this.config.backpressure) return;\n\n const maxQueue = this.config.backpressure.maxQueue || 1000;\n const dropPolicy = this.config.backpressure.dropPolicy || \"oldest\";\n const onQueueFull = this.config.backpressure.onQueueFull;\n\n if (dropPolicy === \"none\") {\n // Don't drop anything, let queue grow (risky but sometimes needed)\n return;\n }\n\n const overflow = this.eventQueue.length - maxQueue;\n if (overflow <= 0) return;\n\n let droppedEvents: T[] = [];\n\n if (dropPolicy === \"oldest\") {\n // Drop oldest events (from beginning of queue)\n droppedEvents = this.eventQueue.splice(0, overflow);\n } else if (dropPolicy === \"newest\") {\n // Drop newest events (from end of queue)\n droppedEvents = this.eventQueue.splice(-overflow);\n }\n\n // Update stats\n this.stats.eventsDropped += droppedEvents.length;\n this.stats.currentQueueSize = this.eventQueue.length;\n\n // Notify about dropped events\n if (onQueueFull && droppedEvents.length > 0) {\n try {\n onQueueFull(droppedEvents);\n } catch (error) {\n // Don't let callback errors break the flow control\n console.warn(\"Error in onQueueFull callback:\", error);\n }\n }\n }\n\n private enqueueEvent(event: T): void {\n this.eventQueue.push(event);\n this.stats.currentQueueSize = this.eventQueue.length;\n \n // Check for queue overflow after adding\n if (this.config.backpressure) {\n const maxQueue = this.config.backpressure.maxQueue || 1000;\n if (this.eventQueue.length > maxQueue) {\n this.handleQueueOverflow();\n }\n }\n }\n\n private dequeueEvent(): T | undefined {\n const event = this.eventQueue.shift();\n this.stats.currentQueueSize = this.eventQueue.length;\n return event;\n }\n\n private updateProcessingStats(batch: T[]): void {\n const now = Date.now();\n const timeSinceLastProcessed = now - this.stats.lastProcessedAt;\n\n this.stats.averageBatchSize =\n (this.stats.averageBatchSize * this.stats.batchesProcessed +\n batch.length) /\n (this.stats.batchesProcessed + 1);\n\n this.stats.processingRate =\n timeSinceLastProcessed > 0\n ? batch.length / (timeSinceLastProcessed / 1000)\n : this.stats.processingRate;\n\n this.stats.lastProcessedAt = now;\n this.stats.currentQueueSize = this.eventQueue.length;\n }\n\n trackPromise<U>(promise: Promise<U>): Promise<U> {\n this.activePromises.add(promise);\n promise.finally(() => this.activePromises.delete(promise));\n return promise;\n }\n\n getStats(): FlowControlStats {\n return { ...this.stats };\n }\n}\n","import { EventBus } from \"../../../common\";\nimport * as AsyncEventBus from \"../../../common/events/async-event-bus\";\nimport { DependencyLifecycle } from \"../../types\";\n\nimport { getMessageBody } from \"../../util/kos-message-utils\";\nimport {\n extractTrailingWildcard,\n hasTrailingWildcard,\n} from \"../decorators/kosTopicHandler\";\nimport { SubscriptionHandlers } from \"../decorators/propKeys\";\nimport { IKosDataModel, IKosModel } from \"../kosModel\";\nimport { WebSocketTransport } from \"../transport\";\nimport type {\n KosOfflineQueue,\n KosOfflineQueueLogger,\n} from \"./kos-offline-queue\";\nimport { FlowControlManager, type FlowControlOptions } from \"../decorators/kos-topic-handler-flow-control\";\n\nexport class KosSubscriptionManager {\n private disposers: VoidFunction[] = [];\n private activatableDisposers: VoidFunction[] = [];\n private flowControllers = new Map<string, FlowControlManager>();\n\n constructor(\n private model: IKosModel,\n private modelData: IKosDataModel,\n private modelId: string,\n private offlineQueue: KosOfflineQueue,\n private log: KosOfflineQueueLogger\n ) {}\n\n registerAll(lifecycle?: string): void {\n const subscriptions = this.modelData?.[SubscriptionHandlers] || {};\n const keys = Object.keys(subscriptions);\n\n this.log.debug(\n `Found ${keys.length} subscriptions in ${this.modelId} (lifecycle: ${\n lifecycle ?? \"any\"\n })`\n );\n\n keys.forEach((topic) => {\n const config = subscriptions[topic];\n const topicLifecycle = config.lifecycle;\n\n if (lifecycle && lifecycle !== topicLifecycle) return;\n\n const resolvedTopic = this.resolvePropKey(topic);\n this.log.debug(`Resolved topic: ${topic} → ${resolvedTopic}`);\n\n // Check if this subscription uses flow control\n if (config.flow) {\n this.subscribeWithFlowControl(config, resolvedTopic, topicLifecycle);\n } else {\n // Standard subscription path\n const handler = this.createHandler(resolvedTopic, config);\n this.subscribe(\n config,\n resolvedTopic,\n handler,\n topicLifecycle === DependencyLifecycle.ACTIVATE\n );\n }\n });\n }\n\n deactivate(): void {\n this.log.debug(`Deactivating subscriptions for ${this.modelId}`);\n\n for (const dispose of this.activatableDisposers) {\n try {\n dispose();\n } catch (e) {\n this.log.error(\"Error during subscription disposal\", e);\n }\n }\n this.activatableDisposers = [];\n }\n\n disposeAll(): void {\n const allDisposers = [...this.disposers, ...this.activatableDisposers];\n this.log.debug(\n `Disposing ${allDisposers.length} subscriptions for ${this.modelId}`\n );\n \n // Dispose flow controllers\n for (const [topic, controller] of this.flowControllers) {\n this.log.debug(`Disposing flow controller for ${topic}`);\n }\n this.flowControllers.clear();\n\n for (const dispose of allDisposers) {\n try {\n dispose();\n } catch (e) {\n this.log.error(\"Error during subscription disposal\", e);\n }\n }\n this.disposers = [];\n this.activatableDisposers = [];\n }\n\n private subscribe(\n subscription: any,\n topic: string,\n handler: (payload: any) => void,\n activatable: boolean\n ): void {\n const destinationAddress = subscription.destinationAddress\n ? this.resolvePropKey(subscription.destinationAddress)\n : null;\n if (subscription.websocket) {\n this.log.debug(`Subscribing to WebSocket topic: ${topic}`);\n const socketSub = WebSocketTransport.getInstance().subscribeTopic({\n topic,\n callback: handler,\n fos: subscription.fos,\n bridge: subscription.bridge,\n destinationAddress: destinationAddress,\n });\n this.disposers.push(socketSub); // socketSub is assumed to be a function\n } else {\n this.log.debug(`Subscribing to EventBus topic: ${topic}`);\n const { unsubscribe } = EventBus.subscribe(topic, handler);\n if (activatable) {\n this.activatableDisposers.push(unsubscribe);\n } else {\n this.disposers.push(unsubscribe);\n }\n }\n }\n\n private createHandler(\n resolvedTopic: string,\n subscription: any\n ): (payload: any) => void {\n return async (payload: any) => {\n try {\n const sourceAddress = payload?.headers?.[\"src-addr\"];\n const subscribedDestinationAddress =\n subscription.destinationAddress &&\n this.resolvePropKey(subscription.destinationAddress);\n const matchedDestinationAddress = subscribedDestinationAddress\n ? !!(sourceAddress === subscribedDestinationAddress)\n : true;\n\n // Extract wildcard capture if applicable\n const wildcardCapture = this.extractWildcardCapture(\n resolvedTopic,\n payload,\n subscription\n );\n\n if (!this.model.isReady()) {\n this.log.warn(\n `Model ${this.modelId} not ready. Queuing message for ${resolvedTopic}`\n );\n\n const offlineHandler = () => {\n const body = getMessageBody(payload, subscription.skipParse);\n const data = subscription.transform(body);\n if (\n matchedDestinationAddress &&\n subscription.condition(data, this.modelData, payload)\n ) {\n return this.callHandlerWithWildcard(\n subscription,\n data,\n wildcardCapture,\n payload\n );\n }\n };\n this.offlineQueue.enqueue(offlineHandler);\n } else {\n const body = getMessageBody(payload, subscription.skipParse);\n const data = subscription.transform(body);\n if (\n matchedDestinationAddress &&\n subscription.condition(data, this.modelData, payload)\n ) {\n return this.callHandlerWithWildcard(\n subscription,\n data,\n wildcardCapture,\n payload\n );\n }\n }\n } catch (e) {\n this.log.error(`Error handling subscription for ${resolvedTopic}`, e);\n }\n };\n }\n\n private extractWildcardCapture(\n resolvedTopic: string,\n payload: any,\n subscription: any\n ): Record<string, string> | null {\n // Check if subscription has wildcardName parameter and topic has trailing wildcard\n if (!subscription.wildcardName || !hasTrailingWildcard(resolvedTopic)) {\n return null;\n }\n\n const actualTopic = payload?.headers?.topic || \"\";\n return extractTrailingWildcard(\n resolvedTopic,\n actualTopic,\n subscription.wildcardName\n );\n }\n\n private callHandlerWithWildcard(\n subscription: any,\n data: any,\n wildcardCapture: Record<string, string> | null,\n payload: any\n ): any {\n // Extend payload with wildcard capture if available\n if (wildcardCapture && Object.keys(wildcardCapture).length > 0) {\n const extendedPayload = {\n ...payload,\n wildcardCapture,\n };\n return subscription.handler.call(\n this.modelData,\n data,\n extendedPayload,\n this.modelData\n );\n } else {\n // Call without wildcard capture (original behavior)\n return subscription.handler.call(\n this.modelData,\n data,\n payload,\n this.modelData\n );\n }\n }\n\n private resolvePropKey(template: string): string {\n const propRegex = /.*({PROP_(.+)})/;\n let topic = template.includes(\"{MODEL_ID}\")\n ? template.replace(\"{MODEL_ID}\", this.modelId)\n : template;\n\n const match = topic.match(propRegex);\n if (match && match[2] in this.modelData) {\n topic = topic.replace(match[1], this.modelData[match[2]]);\n }\n\n return topic;\n }\n\n // ===== FLOW CONTROL METHODS =====\n\n private async subscribeWithFlowControl(\n config: any,\n resolvedTopic: string,\n lifecycle: string\n ): Promise<void> {\n this.log.debug(`Setting up flow control for topic: ${resolvedTopic}`);\n\n // Create flow control manager\n const flowManager = new FlowControlManager(config.flow);\n this.flowControllers.set(resolvedTopic, flowManager);\n\n // Create the enhanced handler\n const enhancedHandler = this.createFlowControlHandler(resolvedTopic, config);\n\n // Start the async flow processing\n const flowProcessor = this.startFlowProcessing(\n config,\n resolvedTopic,\n enhancedHandler,\n flowManager\n );\n\n // Track the processor for cleanup\n const cleanup = () => {\n this.flowControllers.delete(resolvedTopic);\n flowProcessor.then(controller => controller?.abort());\n };\n\n if (lifecycle === DependencyLifecycle.ACTIVATE) {\n this.activatableDisposers.push(cleanup);\n } else {\n this.disposers.push(cleanup);\n }\n }\n\n private async startFlowProcessing(\n config: any,\n resolvedTopic: string,\n handler: Function,\n flowManager: FlowControlManager\n ): Promise<AbortController | null> {\n const controller = new AbortController();\n\n try {\n // Create event source based on subscription type\n let eventSource: AsyncIterable<any>;\n\n if (config.websocket) {\n // Subscribe to WebSocket and get async iterator\n const destinationAddress = config.destinationAddress\n ? this.resolvePropKey(config.destinationAddress)\n : null;\n\n WebSocketTransport.getInstance().subscribeTopic({\n topic: resolvedTopic,\n callback: () => {}, // Empty callback, we'll use async iteration\n fos: config.fos,\n bridge: config.bridge,\n destinationAddress: destinationAddress,\n });\n\n eventSource = AsyncEventBus.iterate(resolvedTopic);\n } else {\n // Use EventBus async iterator\n eventSource = AsyncEventBus.iterate(resolvedTopic);\n }\n\n // Process events through flow control\n (async () => {\n try {\n for await (const processedData of flowManager.processEvents(eventSource)) {\n if (controller.signal.aborted) break;\n\n // Execute handler with processed data\n const handlerPromise = handler(processedData);\n \n // Track promise for backpressure if it's async\n if (handlerPromise instanceof Promise) {\n await flowManager.trackPromise(handlerPromise);\n }\n }\n } catch (error) {\n this.log.error(`Flow control error for ${resolvedTopic}:`, error);\n }\n })();\n\n return controller;\n } catch (error) {\n this.log.error(`Failed to start flow processing for ${resolvedTopic}:`, error);\n return null;\n }\n }\n\n private createFlowControlHandler(\n resolvedTopic: string,\n config: any\n ): (processedData: any) => void | Promise<void> {\n return async (processedData: any) => {\n try {\n // Apply additional filtering and conditions\n if (config.condition && !config.condition(processedData, this.modelData, processedData)) {\n return;\n }\n\n if (!this.model.isReady()) {\n this.log.warn(\n `Model ${this.modelId} not ready. Queuing flow-controlled message for ${resolvedTopic}`\n );\n \n const offlineHandler = () => {\n return config.handler.call(this.modelData, processedData, processedData, this.modelData);\n };\n this.offlineQueue.enqueue(offlineHandler);\n } else {\n // Execute the handler with flow-controlled data\n return config.handler.call(this.modelData, processedData, processedData, this.modelData);\n }\n } catch (error) {\n this.log.error(`Error in flow control handler for ${resolvedTopic}:`, error);\n \n // Apply retry logic if configured\n if (config.flow?.errorHandling?.retry) {\n await this.retryHandler(config, processedData, error);\n } else if (!config.flow?.errorHandling?.continueOnError) {\n throw error;\n }\n }\n };\n }\n\n private async retryHandler(config: any, data: any, originalError: any): Promise<void> {\n const retryConfig = config.flow.errorHandling.retry;\n let lastError = originalError;\n\n for (let attempt = 1; attempt <= retryConfig.attempts; attempt++) {\n try {\n this.log.debug(`Retry attempt ${attempt}/${retryConfig.attempts} for handler`);\n await new Promise(resolve => setTimeout(resolve, retryConfig.backoffMs * attempt));\n \n return config.handler.call(this.modelData, data, data, this.modelData);\n } catch (error) {\n lastError = error;\n this.log.warn(`Retry attempt ${attempt} failed:`, error);\n }\n }\n\n this.log.error(`All retry attempts failed, throwing last error:`, lastError);\n throw lastError;\n }\n\n /**\n * Get flow control statistics for monitoring\n */\n public getFlowControlStats(): Record<string, any> {\n const stats: Record<string, any> = {};\n \n for (const [topic, manager] of this.flowControllers) {\n stats[topic] = manager.getStats();\n }\n \n return stats;\n }\n}\n","type Logger = {\n debug: (...args: any[]) => void;\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n};\n\nexport function createTaggedLogger(base: Logger, tag: string): Logger {\n const prefix = `[Model:${tag}]`;\n\n return {\n debug: (...args) => base.debug(prefix, ...args),\n info: (...args) => base.info(prefix, ...args),\n warn: (...args) => base.warn(prefix, ...args),\n error: (...args) => base.error(prefix, ...args),\n };\n}\n","import { ModelEffects, SubscriptionHandlers } from \"../decorators/propKeys\";\nimport { HttpRouteHandlers } from \"../decorators/kos-http-decorators\";\nimport type { IKosDataModel } from \"../kosModel\";\n\nexport function hasModelEffects(modelData: IKosDataModel): boolean {\n return (\n !!modelData?.[ModelEffects] &&\n Object.keys(modelData[ModelEffects]).length > 0\n );\n}\n\nexport function hasSubscriptionHandlers(modelData: IKosDataModel): boolean {\n return (\n !!modelData?.[SubscriptionHandlers] &&\n Object.keys(modelData[SubscriptionHandlers]).length > 0\n );\n}\n\nexport function hasHttpRouteHandlers(modelData: IKosDataModel): boolean {\n return (\n !!modelData?.[HttpRouteHandlers] &&\n modelData[HttpRouteHandlers].length > 0\n );\n}\n","// kos-model-component-factory.ts\nimport type { IKosDataModel, IKosModel } from \"../kosModel\";\nimport { KosChildResolver } from \"./kos-child-resolver\";\nimport { KosCompanionModelManager } from \"./kos-companion-model-manager\";\nimport { KosEffectManager } from \"./kos-effects-manager\";\nimport { KosFSMManager } from \"./kos-fsm-manager\";\nimport { KosHttpRouteManager } from \"./kos-http-route-manager\";\nimport { KosLoggerFactory } from \"./kos-logger-factory\";\nimport { KosOfflineQueue } from \"./kos-offline-queue\";\nimport { KosOnlineLifecycleManager } from \"./kos-online-lifecycle-manager\";\nimport { KosSubscriptionManager } from \"./kos-subscription-manager\";\nimport { createTaggedLogger } from \"./logger-utils\";\nimport {\n hasHttpRouteHandlers,\n hasModelEffects,\n hasSubscriptionHandlers,\n} from \"./model-introspection-utils\";\n\ninterface KosModelComponents {\n fsm: KosFSMManager;\n offlineQueue: KosOfflineQueue;\n subscriptionManager?: KosSubscriptionManager;\n effectManager?: KosEffectManager;\n onlineLifecycleManager?: KosOnlineLifecycleManager;\n httpRouteManager?: KosHttpRouteManager;\n companionManager: KosCompanionModelManager;\n childResolver: KosChildResolver;\n}\n\nexport class KosModelComponentFactory {\n static createAll<T extends IKosDataModel>(\n model: IKosModel<T>\n ): KosModelComponents {\n const { modelId, modelTypeName, modelData } = model;\n\n // Single shared logger\n const log = KosLoggerFactory.create({\n modelId,\n modelTypeName,\n });\n\n const fsm = new KosFSMManager(model, createTaggedLogger(log, \"fsm\"));\n const offlineQueue = new KosOfflineQueue(\n createTaggedLogger(log, \"offline-queue\")\n );\n const companionManager = new KosCompanionModelManager(model);\n const childResolver = new KosChildResolver(model);\n\n const components: KosModelComponents = {\n fsm,\n offlineQueue,\n companionManager,\n childResolver,\n };\n\n if (hasModelEffects(modelData)) {\n components.effectManager = new KosEffectManager(\n modelTypeName,\n modelId,\n modelData,\n createTaggedLogger(log, \"effect\")\n );\n }\n\n if (hasSubscriptionHandlers(modelData)) {\n const subLogger = createTaggedLogger(log, \"subscription\");\n\n components.subscriptionManager = new KosSubscriptionManager(\n model,\n modelData,\n modelId,\n offlineQueue,\n subLogger\n );\n\n components.onlineLifecycleManager = new KosOnlineLifecycleManager(\n model,\n createTaggedLogger(log, \"online\")\n );\n }\n\n if (hasHttpRouteHandlers(modelData)) {\n components.httpRouteManager = new KosHttpRouteManager(\n modelData,\n createTaggedLogger(log, \"http-routes\")\n );\n }\n\n return components;\n }\n}\n","/* eslint-disable max-len */\nimport logger from \"loglevel\";\nimport { makeAutoObservable } from \"mobx\";\n\nimport { KosOfflineQueue } from \"./model/kos-offline-queue\";\n\nimport { EventBus } from \"../../common\";\n\n// import { KosModelManager } from \"./kosModelManager\";\n\nimport { ExtensionManager } from \"../core/extension/extension-manager\";\n\nimport { kosAction } from \"..\";\nimport {\n modelEventTopicFactory,\n modelTypeEventTopicFactory,\n} from \"../../models/utils/model-event-utils\";\nimport { DependencyLifecycle } from \"../types/kos-dependency\";\nimport { awaitFirstMatchingWhen } from \"../util/await-first-matching-when\";\nimport {\n Transitions,\n executeChildrenModelLifecycle,\n executeDependentModelLifecycle,\n} from \"../util/model-utils\";\nimport {\n KosContext,\n KosContextBean,\n KosContextManager,\n} from \"./context/kos-context-manager\";\nimport { CompanionParentModel } from \"./decorators\";\nimport type { KosModelManager } from \"./kosModelManager\";\nimport { KosModelState } from \"./lifecycle/constants\";\nimport { KosLog } from \"./log\";\nimport { applyKosModelDevtoolsSupport } from \"./model/apply-kos-dev-tool-support\";\nimport { KosChildResolver } from \"./model/kos-child-resolver\";\nimport { KosCompanionModelManager } from \"./model/kos-companion-model-manager\";\nimport { KosEffectManager } from \"./model/kos-effects-manager\";\nimport { KosFSMManager } from \"./model/kos-fsm-manager\";\nimport { KosHttpRouteManager } from \"./model/kos-http-route-manager\";\nimport { KosModelComponentFactory } from \"./model/kos-model-component-factory\";\nimport { KosOnlineLifecycleManager } from \"./model/kos-online-lifecycle-manager\";\nimport { KosSubscriptionManager } from \"./model/kos-subscription-manager\";\nimport type { KosParentAware } from \"./types\";\n\nconst log = logger.getLogger(\"kos-model\");\n\nconst MODEL_LOADER = \"kos.extension.model.loader\";\nexport interface IKosModelLifecycle {\n init?(context?: KosContext): Promise<void>;\n load?(context?: KosContext): Promise<void>;\n ready?(context?: KosContext): Promise<void>;\n online?(context?: KosContext): Promise<void>;\n offline?(context?: KosContext): Promise<void>;\n unload?(context?: KosContext): void;\n activate?(context?: KosContext): Promise<void>;\n deactivate?(context?: KosContext): Promise<void>;\n}\n\nexport interface IKosVisitor<T extends IKosDataModel | IKosModel> {\n visit: (model: T) => void;\n}\n\nexport interface IKosVisitorHost<T extends IKosDataModel | IKosModel> {\n accept?: (visitor: IKosVisitor<T>) => void;\n}\n\nexport type KosContextLogger = ReturnType<typeof KosLog.getLogger>;\nexport interface IKosModelLogger {\n logger: KosContextLogger;\n}\n\nexport interface KosCreationContext extends IKosModelLogger {\n kosContext: KosContextBean;\n [key: string]: any;\n}\n\nexport interface IKosDataModel\n extends IKosModelLifecycle,\n IKosVisitorHost<IKosDataModel> {\n id: string;\n getDependencies?(): void;\n getChildren?: () => IKosDataModel[];\n update?: (values) => Promise<void>;\n toJSON?: () => object;\n}\n\nexport interface IKosCompanionOptions<\n T extends IKosDataModel = IKosDataModel,\n O extends object = object\n> extends KosParentAware {\n companionParent: T;\n data?: O;\n}\n\nexport interface IKosContainerModel<\n T extends IKosDataModel,\n R extends object = Record<string, unknown>\n> {\n models: T[];\n createModel?: (request: R) => Promise<unknown>;\n deleteModel?: (id: string) => Promise<void>;\n getModel?: (id: string) => T | undefined;\n}\n\nexport interface ReloadAware {\n reload: () => Promise<void>;\n}\n\nexport interface UnloadAware {\n unload: () => Promise<void>;\n}\n\nexport interface UpdateAware<O extends object = Record<string, any>> {\n updateModel: (options: O) => void;\n}\n\nexport interface IKosModel<DataDef extends IKosDataModel = IKosDataModel>\n extends IKosCompanionModelContainer,\n IKosModelLifecycle,\n IKosVisitorHost<IKosModel> {\n modelId: string;\n status: KosModelState;\n onlineStatus: KosModelState;\n activeStatus: KosModelState;\n modelTypeName: string;\n loaded: boolean;\n fsm: KosFSMManager;\n isReady(): boolean;\n isActive(): boolean;\n isOnline(): boolean;\n whenReady(): Promise<void>;\n whenInitialized(): Promise<void>;\n whenLoaded(): Promise<void>;\n registerSubscribers(): Promise<void>;\n getChildren(): IKosModel[];\n modelData: DataDef;\n modelManager: KosModelManager;\n}\n\ninterface KosModelParameters<DataType extends IKosDataModel> {\n modelTypeName: string;\n id?: string | number;\n modelData: DataType;\n}\n\ninterface IKosCreateParam<Options extends object = Record<string, any>> {\n id?: string;\n modelTypeId: string;\n options?: Options;\n}\n\nexport type IKosDataModelBuilder<D, M extends IKosDataModel> = (data: D) => M;\n\nexport type IKosDataModelCreator<\n M extends IKosDataModel = IKosDataModel,\n O extends object = Record<string, any>\n> = (params: IKosCreateParam<O>) => M;\n\nexport interface IKosDataModelFactory<D, M extends IKosDataModel> {\n build?: IKosDataModelBuilder<D, M>;\n create?: IKosDataModelCreator<M>;\n}\n\ninterface IKosCompanionModelContainer {\n clearCompanionModels: () => void;\n addCompanionModel: (model: IKosModel) => void;\n companionModels: KosCompanionModelManager;\n}\nexport class KosModel<DataDef extends IKosDataModel = IKosDataModel>\n implements IKosModel<DataDef>, IKosCompanionModelContainer\n{\n private _id: string;\n\n private _status: KosModelState;\n\n private _activeStatus: KosModelState;\n private _onlineStatus: KosModelState;\n\n modelData: DataDef;\n\n modelTypeName: string;\n\n initialized: boolean;\n\n loaded: boolean;\n offlineQueue: KosOfflineQueue;\n subscriptionManager?: KosSubscriptionManager;\n effectManager?: KosEffectManager;\n httpRouteManager?: KosHttpRouteManager;\n onlineLifecycleManager?: KosOnlineLifecycleManager;\n companionManager: KosCompanionModelManager;\n childResolver: KosChildResolver;\n fsm: KosFSMManager;\n\n constructor({ modelTypeName, id, modelData }: KosModelParameters<DataDef>) {\n this._id = typeof id !== \"undefined\" ? `${id}` : modelTypeName;\n this.modelTypeName = modelTypeName;\n this.initialized = false;\n this.loaded = false;\n this.modelData = modelData;\n this._status = KosModelState.CREATED;\n this._activeStatus = KosModelState.INACTIVE;\n this._onlineStatus = KosModelState.OFFLINE;\n const components = KosModelComponentFactory.createAll(this);\n\n this.fsm = components.fsm;\n this.offlineQueue = components.offlineQueue;\n this.companionManager = components.companionManager;\n this.childResolver = components.childResolver;\n\n if (components.effectManager) {\n this.effectManager = components.effectManager;\n }\n if (components.subscriptionManager) {\n this.subscriptionManager = components.subscriptionManager;\n }\n if (components.httpRouteManager) {\n this.httpRouteManager = components.httpRouteManager;\n }\n if (components.onlineLifecycleManager) {\n this.onlineLifecycleManager = components.onlineLifecycleManager;\n }\n makeAutoObservable(this, {\n fsm: false,\n effectManager: false,\n subscriptionManager: false,\n onlineLifecycleManager: false,\n companionManager: false,\n childResolver: false,\n offlineQueue: false,\n });\n\n applyKosModelDevtoolsSupport(this);\n }\n\n get companionModels() {\n return this.companionManager;\n }\n\n set status(status: KosModelState) {\n this._status = status;\n }\n\n get status() {\n return this._status;\n }\n get modelId() {\n return this._id;\n }\n\n get id() {\n return this._id;\n }\n get activeStatus() {\n return this._activeStatus;\n }\n set activeStatus(activeStatus: KosModelState) {\n this._activeStatus = activeStatus;\n }\n\n get onlineStatus() {\n return this._onlineStatus;\n }\n set onlineStatus(onlineStatus: KosModelState) {\n this._onlineStatus = onlineStatus;\n }\n\n get modelManager() {\n return globalThis.kos.modelManager;\n }\n\n isActive() {\n return this._status === KosModelState.ACTIVE;\n }\n\n isOnline() {\n return this._onlineStatus === KosModelState.ONLINE;\n }\n\n isReady() {\n return this._status === KosModelState.READY;\n }\n\n async deactivate(): Promise<void> {\n log.debug(\n `deactivating model ${this.modelTypeName} with id ${this.modelId}`\n );\n try {\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.deactivate?.(context);\n log.debug(\n `Model ${this.modelTypeName} with id ${this.modelId} deactivated`\n );\n this.subscriptionManager?.deactivate();\n } catch (e) {\n log.debug(`Model ${this.modelId} failed to deactivated`);\n throw e;\n }\n }\n\n async activate(): Promise<void> {\n log.debug(`activating model ${this.modelTypeName} with id ${this.modelId}`);\n await executeDependentModelLifecycle(this, DependencyLifecycle.ACTIVATE);\n\n try {\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.activate?.(context);\n\n log.debug(\n `Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`\n );\n this.subscriptionManager?.registerAll(DependencyLifecycle.ACTIVATE);\n log.debug(\n `Model ${this.modelTypeName} with id ${this.modelId} activated`\n );\n } catch (e) {\n log.debug(`Model ${this.modelId} failed to activate`);\n throw e;\n }\n\n return;\n }\n\n async whenLoaded(): Promise<void> {\n await awaitFirstMatchingWhen([\n {\n condition: () => this.status === KosModelState.FAILED,\n onMatch: () => {\n throw new Error(`Failed to initialize model ${this.modelId}`);\n },\n },\n {\n condition: () => this.loaded,\n onMatch: () => {\n log.debug(`Model ${this.modelId} is loaded`);\n },\n },\n ]);\n }\n\n async whenInitialized(): Promise<void> {\n await awaitFirstMatchingWhen([\n {\n condition: () => this.status === KosModelState.FAILED,\n onMatch: () => {\n throw new Error(`Failed to initialize model ${this.modelId}`);\n },\n },\n {\n condition: () => this.initialized,\n onMatch: () => {\n log.debug(`Model ${this.modelId} is initialized`);\n },\n },\n ]);\n }\n async whenReady(): Promise<void> {\n await awaitFirstMatchingWhen([\n {\n condition: () => this.status === KosModelState.FAILED,\n onMatch: () => {\n throw new Error(`Failed to ready model ${this.modelId}`);\n },\n },\n {\n condition: () => this.status === KosModelState.READY,\n onMatch: () => {\n log.debug(`Model ${this.modelId} is ready`);\n },\n },\n ]);\n }\n\n async ready() {\n if (this.fsm.current === KosModelState.READY) {\n log.debug(\n `already readying model ${this.modelTypeName} with id ${this.modelId} returning`\n );\n return;\n }\n\n try {\n log.debug(`readying model ${this.modelTypeName} with id ${this.modelId}`);\n // wait for all non-lazy dependencies to be ready\n await executeDependentModelLifecycle(this, DependencyLifecycle.READY);\n\n await executeChildrenModelLifecycle(\n this,\n Transitions.READY,\n DependencyLifecycle.READY\n );\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.ready?.(context);\n\n this.offlineQueue.flush();\n\n this.subscriptionManager?.registerAll(DependencyLifecycle.READY);\n log.debug(`Model ${this.modelId} is ready`);\n\n const payload = {\n modelId: this.modelId,\n modelType: this.modelTypeName,\n };\n EventBus.publish(\n modelEventTopicFactory(this.modelTypeName, this.modelId),\n payload\n );\n\n EventBus.publish(modelTypeEventTopicFactory(this.modelTypeName), payload);\n } catch (e) {\n log.error(e);\n throw Error(e as any);\n }\n }\n\n async load(): Promise<void> {\n const companionParent = this[CompanionParentModel];\n if (companionParent) {\n await companionParent.whenLoaded();\n }\n const { modelTypeName, modelId } = this;\n\n if (\n this.fsm.current === KosModelState.LOADED ||\n this.fsm.current === KosModelState.LOADING\n ) {\n log.debug(\n `Model ${modelTypeName} with id ${modelId} already loaded or loading`\n );\n return;\n }\n\n log.debug(`Loading model ${modelTypeName} with id ${modelId}`);\n\n await executeDependentModelLifecycle(this, DependencyLifecycle.LOAD);\n\n try {\n const context = KosContextManager.getContext(modelId);\n const MODEL_LOADER_TYPE = `${MODEL_LOADER}.${modelTypeName}`;\n const loadedContext = await ExtensionManager.loader.executeLoader(\n MODEL_LOADER_TYPE,\n {}\n );\n if (loadedContext) {\n log.info(\n `Setting loaded context for ${modelId}, type: ${modelTypeName}`\n );\n context?.set(MODEL_LOADER_TYPE, loadedContext);\n }\n\n await this.modelData?.load?.(context);\n\n kosAction(() => {\n this.loaded = true;\n });\n log.debug(\n `Model ${modelTypeName} with id ${modelId} successfully loaded`\n );\n\n this.subscriptionManager?.registerAll(DependencyLifecycle.LOAD);\n this.httpRouteManager?.registerAll();\n this.effectManager?.setup();\n } catch (e) {\n log.error(`Model ${modelId} failed to load`, e);\n throw e;\n }\n }\n\n async unload(): Promise<void> {\n log.debug(`unloading model ${this.modelTypeName} with id ${this.modelId}`);\n try {\n const childrenUnload = this.getChildren()\n .map((child) => child.unload?.())\n .filter((p) => !!p);\n await Promise.allSettled(childrenUnload);\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.unload?.(context);\n this.loaded = false;\n this.onlineLifecycleManager?.dispose();\n log.debug(`Model ${this.modelTypeName} with id ${this.modelId} unloaded`);\n this.effectManager?.disposeAll();\n this.subscriptionManager?.disposeAll();\n this.httpRouteManager?.dispose();\n } catch (e) {\n log.debug(`Model ${this.modelId} failed to unload`);\n throw e;\n }\n }\n async init(): Promise<void> {\n const companionParent = this[CompanionParentModel];\n if (companionParent) {\n await companionParent.whenInitialized();\n }\n const { modelId, modelTypeName } = this;\n const context = KosContextManager.getContext(modelId);\n\n log.debug(`Initializing model ${modelTypeName} with id ${modelId}`);\n await executeDependentModelLifecycle(this, DependencyLifecycle.INIT);\n\n try {\n await this.modelData?.init?.(context);\n this.initialized = true;\n log.debug(`Model ${modelTypeName} with id ${modelId} initialized`);\n\n this.onlineLifecycleManager?.register();\n\n this.registerSubscribers(DependencyLifecycle.INIT);\n } catch (e) {\n log.error(`Model ${modelId} failed to initialize`, e);\n throw e;\n }\n }\n\n async registerSubscribers(lifecycle?: DependencyLifecycle) {\n log.debug(\n `registering subscribers in ${this.modelTypeName} with id ${this.modelId}`\n );\n\n this.subscriptionManager?.registerAll(lifecycle);\n }\n\n async online() {\n log.debug(`online model ${this.modelTypeName} with id ${this.modelId}`);\n this.registerSubscribers();\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.online?.(context);\n }\n\n async offline() {\n log.debug(`offline model ${this.modelTypeName} with id ${this.modelId}`);\n this.subscriptionManager?.disposeAll();\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.offline?.(context);\n }\n\n accept(visitor: IKosVisitor<IKosModel>) {\n visitor.visit(this);\n }\n getChildren(): IKosModel[] {\n return this.childResolver.resolve();\n }\n\n addCompanionModel(model: IKosModel<IKosDataModel>) {\n this.companionManager.add(model);\n }\n\n clearCompanionModels() {\n this.companionManager.clear();\n }\n}\n","import { DataLoader, DataMapper, PropertyMapper } from \"../extension\";\nimport type {\n IKosDataModel,\n IKosDataModelBuilder,\n IKosDataModelCreator,\n IKosModel,\n} from \"../kosModel\";\n\nexport interface IKosSubscriptionSpecification {\n webSocket: boolean;\n handler: (payload: any, model: IKosModel) => void;\n}\n\nexport interface TroubleHandlerContext {\n title: string;\n subtitle: string;\n steps?: Record<string, { title: string; subtitle: string }>;\n canDismiss?: boolean;\n showTimeRemaining?: boolean;\n}\nexport interface TroubleHandler extends TroubleHandlerContext {\n type: string;\n context?: Record<string, TroubleHandlerContext>;\n}\n\nexport interface IKosModelRegistration {\n builder?: IKosDataModelBuilder<any, any>;\n create?: IKosDataModelCreator<any, any>;\n class?: new (...args) => IKosDataModel;\n\n singleton?: boolean;\n preload?: boolean;\n subscriptions?: Record<string, IKosSubscriptionSpecification>;\n}\n\nexport interface ExtensionRegistration {\n dataMapper?: Record<string, DataMapper | DataMapper[]>;\n propertyMapper?: Record<string, PropertyMapper>;\n contextLoader?: Record<string, DataLoader>;\n}\n\nexport type KosCompanionTypeFactory<T extends IKosDataModel = IKosDataModel> = (\n model: T,\n options: any\n) => string | undefined;\nexport type KosCompanionModelType<T extends IKosDataModel = IKosDataModel> =\n | string\n | KosCompanionTypeFactory<T>;\n\nexport const isKosCompanionTypeFactory = (\n obj: any\n): obj is KosCompanionTypeFactory => typeof obj === \"function\";\nexport interface IKosCompanionRegistration {\n type: KosCompanionModelType<any>;\n}\n\nexport type Preloaded =\n | string\n | { modelType: string; modelId: string; options?: any };\nexport interface IKosRegistry {\n alias?: string;\n models: Record<string, IKosModelRegistration>;\n companionModels?: Record<string, IKosCompanionRegistration[]>;\n troubleHandlers?: Record<string, TroubleHandler>;\n\n // eslint-disable-next-line no-use-before-define\n preloadModels: Preloaded[];\n\n extensions?: ExtensionRegistration;\n}\n","// model-instantiator.ts\n\nimport { CompanionParentModel } from \"./decorators\";\nimport { KosModel, type IKosDataModel, type IKosModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\nimport type { KosModelCacheHandler } from \"./model-cache\";\nimport { isKosCompanionTypeFactory, type IKosRegistry } from \"./types\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-instantiator\" });\n\ninterface CreateOptions {\n modelTypeId: string;\n id?: string;\n options?: Record<string, any>;\n}\n\nexport class KosModelInstantiator {\n constructor(\n private registry: IKosRegistry,\n private cache: KosModelCacheHandler\n ) {}\n\n createModelInstance<DataDef extends IKosDataModel>(\n typeId: string,\n id?: string,\n options: Record<string, any> = {}\n ): { model: IKosModel<DataDef>; data: DataDef } {\n const modelRegistry = this.registry.models[typeId];\n if (!modelRegistry)\n throw new Error(`No model registered for type ${typeId}`);\n\n const modelId = modelRegistry.singleton ? typeId : id;\n this.cache.restoreFromDeleteCache(modelId);\n\n if (!this.cache.hasModel(modelId)) {\n log.debug(`Creating model instance: ${typeId} [${modelId}]`);\n\n const dataInstance = modelRegistry.create\n ? modelRegistry.create({ modelTypeId: typeId, id: modelId, options })\n : new modelRegistry.class!(modelId, options);\n\n const model = new KosModel<DataDef>({\n modelTypeName: typeId,\n id: modelId,\n modelData: dataInstance,\n });\n\n this.cache.addModel(model);\n this._createCompanionModels(model, options);\n }\n\n const activeModel = this.cache.getModelById<DataDef>(modelId!);\n\n if (!activeModel) {\n log.error(`Model ${typeId} [${modelId}] not found in cache`);\n throw new Error(`Model ${typeId} [${modelId}] not found in cache`);\n }\n return { model: activeModel, data: activeModel.modelData };\n }\n\n private _createCompanionModels(\n model: IKosModel,\n options: Record<string, any>\n ) {\n const typeId = model.modelTypeName;\n const companionDefs = this.registry.companionModels?.[typeId] || [];\n\n for (const { type } of companionDefs) {\n const companionType = isKosCompanionTypeFactory(type)\n ? type(model.modelData, options)\n : type;\n if (!companionType) continue;\n\n const companionId = `${companionType}-${model.modelId}`;\n const result = this.createModelInstance(companionType, companionId, {\n data: options,\n companionParent: model.modelData,\n kosParentId: model.modelId,\n });\n\n if (result?.model) {\n result.model[CompanionParentModel] = model;\n model.addCompanionModel(result.model);\n }\n }\n }\n}\n","// model-registry.ts\n\nimport type { BaseKosModelRegistrationBean, ModelFactory } from \"../types\";\nimport { modelFactory } from \"../util\";\nimport type { IKosDataModel, IKosDataModelBuilder } from \"./kosModel\";\nimport { IKosRegistry, KosCompanionModelType } from \"./types/registration\";\n\nexport class KosModelRegistry {\n constructor(private _registry: IKosRegistry) {}\n\n get registry(): IKosRegistry {\n return this._registry;\n }\n getModelTypeRegistry(typeId: string) {\n const modelRegistry = this.registry.models[typeId];\n if (!modelRegistry)\n throw new Error(`No registration for model type ${typeId}`);\n return modelRegistry;\n }\n\n registerModel<T extends BaseKosModelRegistrationBean<any, any>>(reg: T) {\n const typeId = reg.type;\n if (!this.registry.models[typeId]) {\n this.registry.models = { ...this.registry.models, ...reg.registration };\n }\n }\n\n registerCompanionModel(\n typeId: string,\n companion: KosCompanionModelType<any>\n ) {\n this.registry.companionModels ??= {};\n this.registry.companionModels[typeId] ??= [];\n if (\n !this.registry.companionModels[typeId].some((c) => c.type === companion)\n ) {\n this.registry.companionModels[typeId].push({ type: companion });\n }\n }\n\n getModelSubscriptions(typeId: string) {\n return this.getModelTypeRegistry(typeId)?.subscriptions || {};\n }\n\n getDataModelBuilder<D, M extends IKosDataModel>(\n typeId: string\n ): IKosDataModelBuilder<D, M> {\n const builder = this.getModelTypeRegistry(typeId)?.builder;\n if (!builder) {\n throw new Error(`No builder found for model type ${typeId}`);\n }\n return builder;\n }\n\n getModelFactory<T extends IKosDataModel>(modelType: string): ModelFactory<T> {\n return modelFactory<T>(modelType);\n }\n}\n","/* eslint-disable max-len */\n\nimport { type BaseKosModelRegistrationBean } from \"../types\";\nimport { modelFactory } from \"../util\";\nimport { KosDependencyManager } from \"./dependency-manager\";\nimport { KosDeletionManager } from \"./kos-deletion-manager\";\nimport { IKosDataModel, IKosDataModelBuilder, IKosModel } from \"./kosModel\";\nimport { KosModelEvents, KosModelState } from \"./lifecycle\";\nimport { KosLog } from \"./log\";\nimport { KosModelCache } from \"./model-cache\";\nimport { KosModelInstantiator } from \"./model-instantiator\";\nimport { KosModelRegistry } from \"./model-registry\";\nimport { IKosModelManager } from \"./types/kos-model-manager-types\";\nimport { IKosRegistry, type KosCompanionModelType } from \"./types/registration\";\n\nexport const MODEL_DELETION_DELAY = 10;\n\nconst log = KosLog.createLogger({ name: \"kos-model-manager\" });\n\nexport class KosModelManager implements IKosModelManager {\n private cache!: KosModelCache;\n private instantiator!: KosModelInstantiator;\n private dependencies: KosDependencyManager;\n private _registry!: KosModelRegistry;\n private constructor() {\n globalThis.kos = globalThis.kos || {};\n this.dependencies = new KosDependencyManager();\n globalThis.kos.modelManager = this;\n globalThis.kos.resolveKosModel = (modelId: string) => {\n const model = this.getModelById(modelId);\n if (model) {\n return model.modelData || {};\n }\n return undefined;\n };\n globalThis.kos.kosModelJson = (modelId: string) => {\n const model = this.getModelById(modelId);\n if (model) {\n return model.modelData.toJSON?.() || {};\n }\n return undefined;\n };\n\n globalThis.kos.kosModelDebug = (modelId: string) => {\n const model = this.getModelById(modelId);\n if (model) {\n return (model.modelData as any)?.debugState || {};\n }\n return undefined;\n };\n\n globalThis.kos.kmd = globalThis.kos.kosModelDebug;\n globalThis.kos.kmj = globalThis.kos.kosModelJson;\n }\n\n static create(registry: IKosRegistry, reset?: boolean) {\n const instance = this.getInstance(reset);\n instance._registry = new KosModelRegistry(registry);\n instance.cache = new KosModelCache(registry.preloadModels);\n instance.instantiator = new KosModelInstantiator(registry, instance.cache);\n return instance;\n }\n\n static getInstance(reset?: boolean): KosModelManager {\n if (!globalThis.kos?.modelManager || reset) {\n log.debug(\"Creating new instance of KosModelManager\");\n new this();\n }\n return globalThis.kos?.modelManager;\n }\n\n get registry() {\n return this._registry.registry;\n }\n\n /**\n * Retrieves the preloaded models from the registry. If the models have already been\n * preloaded, it returns the cached preloaded models. Otherwise, it initializes and\n * preloads the models based on the registry's `preloadModels` configuration.\n *\n * @returns An array of preloaded model instances.\n *\n * @remarks\n * - Logs debug information during the preloading process.\n * - Logs an error if returning cached preloaded models.\n * - Supports both string-based model keys and object-based model configurations.\n */\n get preloadedModels() {\n return this.cache.preload((modelKey) => {\n log.debug(`preloading ${modelKey}`);\n if (typeof modelKey === \"string\") {\n return this.createModelInstance(modelKey).model;\n } else {\n return this.createModelInstance(\n modelKey.modelType,\n modelKey.modelId,\n modelKey.options\n ).model;\n }\n });\n }\n\n get models() {\n return this.cache.models;\n }\n\n /**\n * Retrieves a model by its unique identifier.\n *\n * @template T - The type of the data model extending `IKosDataModel`.\n * @param id - The unique identifier of the model to retrieve.\n * @returns The model associated with the given ID as `IKosModel<T>`, or `undefined` if the model is marked for deletion.\n */\n getModelById<T extends IKosDataModel>(id: string): IKosModel<T> {\n return this.cache.getModelById(id) as IKosModel<T>;\n }\n\n /**\n * Adds a model to the manager. If a model with the same ID already exists,\n * it returns the existing model instead of adding the new one.\n *\n * @template T - The type of the data model extending `IKosDataModel`.\n * @param model - The model to be added, implementing `IKosModel<T>`.\n * @returns The active model, either the existing one with the same ID or the newly added model.\n */\n addModel<T extends IKosDataModel>(model: IKosModel<T>): IKosModel<T> {\n return this.cache.addModel(model) as IKosModel<T>;\n }\n\n /**\n * Removes a model from the manager and performs cleanup operations.\n *\n * This method traverses the model hierarchy, invoking the `accept` method\n * on each child model to allow for recursive processing. During traversal,\n * it performs the following actions:\n * - Calls the `offline` method on the model, if defined.\n * - Clears any companion models associated with the model.\n * - Deletes the model's context from the `KosContextManager`.\n * - Removes the model from the internal `_modelsById` and `_toDelete` maps.\n *\n * @param model - The model to be removed. Must implement the `IKosModel` interface.\n */\n removeModel(model: IKosModel): void {\n this.cache.removeModel(model.modelId);\n }\n\n /**\n * Checks if a model with the specified ID exists.\n *\n * @param modelId - The unique identifier of the model to check. Optional.\n * @returns `true` if the model ID is provided and a model with the given ID exists; otherwise, `false`.\n */\n hasModel(modelId?: string) {\n return this.cache.hasModel(modelId);\n }\n\n /**\n * Retrieves a list of models of a specific type that satisfy the provided filter criteria.\n *\n * @template T - The type of the data model extending `IKosDataModel`.\n * @param typeId - The identifier of the model type to filter by.\n * @param modelFilter - A callback function used to filter models. It receives a model of type `T` and should return `true` if the model passes the filter, or `false` otherwise.\n * @returns An array of models of type `T` that match the specified type and filter criteria.\n */\n getModelsByType<T extends IKosDataModel>(\n typeId: string,\n modelFilter: (model: T) => boolean\n ) {\n return Array.from(this.models)\n .filter((model) => model.modelTypeName === typeId)\n .filter((model) =>\n modelFilter ? modelFilter(model.modelData as T) : true\n )\n .map((model) => model.modelData as T);\n }\n\n /**\n * Retrieves the subscriptions associated with a specific model type.\n *\n * @param typeId - The unique identifier of the model type.\n * @returns An object containing the subscriptions for the specified model type,\n * or an empty object if the model type is not registered.\n */\n getModelSubscriptions(typeId: string) {\n return this._registry.getModelSubscriptions(typeId);\n }\n\n /**\n * Retrieves the data model builder for a specified model type.\n *\n * @template D - The type of the data used by the model.\n * @template M - The type of the data model that extends `IKosDataModel`.\n * @param typeId - The unique identifier for the model type.\n * @returns An instance of `IKosDataModelBuilder` for the specified model type,\n * or `undefined` if the model type is not registered.\n */\n getDataModelBuilder<D, M extends IKosDataModel>(\n typeId: string\n ): IKosDataModelBuilder<D, M> {\n return this._registry.getDataModelBuilder(typeId);\n }\n\n /**\n * Retrieves a model factory function for the specified model type.\n *\n * @template T - The type of the data model that extends `IKosDataModel`.\n * @param modelType - A string representing the type of the model.\n * @returns A factory function for creating instances of the specified model type.\n */\n getModelFactory<T extends IKosDataModel>(modelType: string) {\n return modelFactory<T>(modelType);\n }\n\n /**\n * Adds a dependency relationship between two models.\n *\n * This method establishes a \"uses\" relationship where the model identified\n * by `modelId` depends on the model identified by `dependencyId`. It ensures\n * that the dependency is not marked for deletion and restores it from the\n * delete cache if necessary. The relationship is then recorded in both the\n * `_usedByCache` and `_usesCache` for efficient lookup.\n *\n * @param modelId - The identifier of the model that depends on the dependency.\n * @param dependencyId - The identifier of the model being depended upon.\n */\n addDependency(modelId: string, dependencyId: string) {\n this.cache.restoreFromDeleteCache(dependencyId);\n this.dependencies.add(modelId, dependencyId);\n }\n\n /**\n * Removes a dependency relationship between two models.\n *\n * This method updates the internal caches to reflect that the specified\n * `modelId` no longer depends on the `dependencyId`. It removes the\n * `modelId` from the list of models that use the `dependencyId` and\n * removes the `dependencyId` from the list of dependencies used by the\n * `modelId`.\n *\n * @param modelId - The ID of the model that has the dependency.\n * @param dependencyId - The ID of the dependency to be removed.\n */\n removeDependency(modelId: string, dependencyId: string) {\n this.dependencies.remove(modelId, dependencyId);\n }\n\n /**\n * Reloads the specified model by its ID. If the model exists and is found\n * by its ID, it transitions the model to the RESETTING state using the\n * RESET event.\n *\n * @param model - The data model to be reloaded. Must implement the `IKosDataModel` interface.\n * The `id` property of the model is used to locate the corresponding model.\n *\n * @returns A promise that resolves once the model has been transitioned, or does nothing\n * if the model ID is not provided or the model is not found.\n */\n async reloadModel(model: IKosDataModel) {\n if (model.id) {\n const kosModel = this.getModelById(model.id);\n if (kosModel) {\n await kosModel.fsm.transitionTo(\n KosModelEvents.RESET,\n KosModelState.RESETTING\n );\n }\n }\n }\n\n /**\n * Initiates the destruction process for a given model.\n *\n * This method checks if the model can be destroyed and, if so, schedules it for deletion.\n * The model is removed from the internal `_modelsById` map and added to the `_toDelete` map.\n * A deletion task is then queued with a delay, during which the model will be destroyed.\n *\n * @param model - The model to be destroyed. Must implement the `IKosDataModel` interface.\n * @throws {Error} If the model does not have a valid `id`.\n */\n async initiateDestroyModel(model: IKosDataModel) {\n if (!model.id) throw new Error(\"Model ID is required\");\n if (!this.dependencies.canDestroy(model.id)) return;\n\n const kosModel = this.getModelById(model.id);\n if (kosModel) {\n this.cache.markForDeletion(kosModel);\n KosDeletionManager.addToDeletionQueue(\n model.id,\n setTimeout(() => this.destroyModel(kosModel), MODEL_DELETION_DELAY)\n );\n }\n }\n\n /**\n * Destroys the specified model if it meets the criteria for destruction.\n *\n * @param model - The model to be destroyed, implementing the `IKosModel` interface.\n *\n * @remarks\n * This method checks if the model has a valid `modelId` and if it can be destroyed\n * by invoking the `canDestroyModel` method. If the conditions are met, it performs\n * the following actions:\n * 1. Calls the `unload` method on the model, if it exists.\n * 2. Removes the model from the manager using the `removeModel` method.\n *\n * @throws This method does not explicitly throw errors, but any errors occurring\n * during the `unload` or `removeModel` operations will propagate to the caller.\n */\n async destroyModel(model: IKosModel) {\n if (model?.modelId && this.dependencies.canDestroy(model.modelId)) {\n await model.unload?.();\n this.removeModel(model);\n }\n }\n\n /**\n * Creates an instance of a model based on the specified type ID and optional model ID.\n * If the model already exists, it retrieves the existing instance; otherwise, it creates a new one.\n *\n * @template DataDef - The type of the data model, extending `IKosDataModel`.\n * @param typeId - The unique identifier for the type of model to create.\n * @param id - An optional unique identifier for the specific model instance. If not provided,\n * the `typeId` is used for singleton models.\n * @param options - An optional record of additional options to pass to the model creation process.\n * @returns An object containing the created or retrieved model instance and its associated data.\n */\n createModelInstance<DataDef extends IKosDataModel>(\n typeId: string,\n id?: string,\n options: Record<string, any> = {}\n ) {\n return this.instantiator.createModelInstance<DataDef>(typeId, id, options);\n }\n\n /**\n * Registers a companion model for a specific type identifier.\n *\n * This method ensures that the companion model is added to the registry\n * for the given `typeId`. If a companion model of the same type already\n * exists for the `typeId`, it will not be added again.\n *\n * @param typeId - The unique identifier for the type to which the companion model belongs.\n * @param companionRegistration - The companion model type to register.\n */\n registerCompanionModel(\n typeId: string,\n companionRegistration: KosCompanionModelType<any>\n ) {\n this._registry.registerCompanionModel(typeId, companionRegistration);\n }\n\n /**\n * Registers a new model type in the model manager if it is not already registered.\n *\n * @template T - A type that extends `BaseKosModelRegistrationBean` with specific type and registration details.\n * @param reg - The registration object containing the type identifier and registration details for the model.\n *\n * @remarks\n * - If the model type is not already present in the registry, it logs the registration\n * and updates the registry with the new model type.\n * - The `type` property of the registration object is used as the unique identifier for the model type.\n */\n registerModel<T extends BaseKosModelRegistrationBean<any, any>>(reg: T) {\n this._registry.registerModel(reg);\n }\n}\n","import log from \"loglevel\";\nimport { runInAction } from \"mobx\";\nimport {\n action,\n createMachine,\n immediate,\n interpret,\n invoke,\n state,\n transition,\n} from \"robot3\";\nimport type { IKosCoreManager } from \"../kosCore\";\n\nexport enum KosCoreState {\n CREATING = `creating`,\n CREATED = `created`,\n INITIALIZING = `initializing`,\n INITIALIZED = `initialized`,\n LOADING = `loading`,\n LOADED = `loaded`,\n ONLINE = `online`,\n READYING = `readying`,\n READY = `ready`,\n OFFLINE = `offline`,\n UNLOADING = `unloading`,\n UNLOADED = `unloaded`,\n RELOADING = `reloading`,\n}\n\nexport enum KosCoreEvents {\n CREATE = `create`,\n INITIALIZE = `init`,\n READY = `ready`,\n GO_ONLINE = `go_online`,\n GO_OFFLINE = `go_offline`,\n UNLOAD = `unload`,\n RELOAD = `reload`,\n}\n\nexport interface KosOn {\n [k: string]: string;\n}\n\nexport interface KosInvoke<Context> {\n id: string;\n src: (context: Context) => Promise<any>;\n onDone: {\n target: string;\n };\n}\nexport interface KosLifecycleState {\n on: KosOn;\n}\nexport interface KosLifecycleStateContainer<Context> {\n [k: string]: {\n initial?: string;\n states?: KosLifecycleStateContainer<Context>;\n on?: KosOn;\n invoke?: KosInvoke<Context>;\n };\n}\n\nexport interface KosLifecycle<Context = any> {\n id: string;\n initial: string;\n states: KosLifecycleStateContainer<Context>;\n context: Context;\n}\n\nexport const coreFsm = (core: IKosCoreManager) => {\n const onlineMachine = createMachine(KosCoreState.OFFLINE, {\n [KosCoreState.ONLINE]: state(\n transition(\n KosCoreEvents.GO_OFFLINE,\n KosCoreState.OFFLINE,\n action(() => {\n core.offline!();\n runInAction(() => {\n core.isOnline = false;\n });\n })\n )\n ),\n [KosCoreState.OFFLINE]: state(\n transition(\n KosCoreEvents.GO_ONLINE,\n KosCoreState.ONLINE,\n action(() => {\n core.online!();\n runInAction(() => {\n core.isOnline = true;\n });\n })\n )\n ),\n });\n const online = interpret(onlineMachine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n const machine = createMachine({\n [KosCoreState.CREATING]: state(\n transition(KosCoreEvents.CREATE, KosCoreState.CREATED)\n ),\n [KosCoreState.CREATED]: state(immediate(KosCoreState.INITIALIZING)),\n [KosCoreState.INITIALIZING]: invoke(\n () => core.init!(),\n transition(`done`, KosCoreState.INITIALIZED)\n ),\n [KosCoreState.INITIALIZED]: state(immediate(KosCoreState.LOADING)),\n [KosCoreState.LOADING]: invoke(\n () => core.load!(),\n transition(`done`, KosCoreState.LOADED)\n ),\n [KosCoreState.LOADED]: state(\n immediate(KosCoreState.READYING),\n transition(KosCoreEvents.UNLOAD, KosCoreState.UNLOADING)\n ),\n\n [KosCoreState.READYING]: invoke(\n () => core.ready!(),\n transition(\n `done`,\n KosCoreState.READY,\n action(() => {\n runInAction(() => {\n core.status = KosCoreState.READY;\n });\n })\n )\n ),\n [KosCoreState.RELOADING]: invoke(\n () => core.reload!(),\n transition(`done`, KosCoreState.LOADING)\n ),\n [KosCoreState.READY]: state(\n transition(KosCoreEvents.RELOAD, KosCoreState.RELOADING),\n transition(\n KosCoreEvents.UNLOAD,\n KosCoreState.UNLOADED,\n action(core.unload.bind(core))\n ),\n transition(\n KosCoreEvents.GO_ONLINE,\n KosCoreState.READY,\n action(() => {\n online.send(KosCoreEvents.GO_ONLINE);\n })\n ),\n transition(\n KosCoreEvents.GO_OFFLINE,\n KosCoreState.READY,\n action(() => {\n online.send(KosCoreEvents.GO_OFFLINE);\n })\n )\n ),\n\n [KosCoreState.UNLOADED]: state(),\n });\n\n const service = interpret(machine, (_service) =>\n log.debug(_service.machine.current)\n );\n\n return { service, online };\n};\n","import { makeAutoObservable, when } from \"mobx\";\nimport { KosModelManager } from \"./kosModelManager\";\nimport {\n IKosServiceTransport,\n WebSocketEvents,\n WebSocketTransport,\n} from \"./transport/webSocketTransport\";\nimport { IKosRegistry } from \"./types/registration\";\n\nimport { runInAction as kosAction } from \"mobx\";\nimport { EventBus } from \"../../common\";\nimport { getQueryParams } from \"../util/get-query-params\";\nimport \"../util/kos-config-init\";\nimport { ExtensionManager } from \"./extension\";\nimport { IKosModel, ReloadAware, UnloadAware } from \"./kosModel\";\nimport {\n KosCoreEvents,\n KosCoreState,\n coreFsm,\n} from \"./lifecycle/kosCoreLifecycle\";\nimport { KosLog } from \"./log\";\nimport { RegistrationManager } from \"./registration\";\nimport { IKosModelManager } from \"./types/kos-model-manager-types\";\n\nconst log = KosLog.createLogger({ name: \"kos-core\" });\n\ndeclare global {\n interface Window {\n KosCore: IKosCoreManager;\n }\n}\n\nconst getConnectionAlias = () => {\n const params = getQueryParams();\n const alias = (params as any)?.alias;\n const envAlias = process.env.KOS_CONNECTION_ALIAS;\n return alias || envAlias || undefined;\n};\n\nconst getDefaultProtocol = () => {\n const defaultProtocol = window.location.protocol;\n\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n let protocol;\n try {\n const _url = new URL(hostUrl);\n protocol = _url.protocol === \"https:\" ? \"wss://\" : \"ws://\";\n } catch {\n // ignore errors\n }\n\n const result = protocol\n ? protocol\n : defaultProtocol === \"https:\"\n ? \"wss://\"\n : \"ws://\";\n return result;\n};\n\nconst getDefaultHost = () => {\n const defaultHost = window.location.hostname;\n const envHost = process.env.KOS_HOST;\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n let host;\n try {\n const _url = new URL(hostUrl);\n host = _url.hostname;\n } catch {\n // ignore errors\n }\n\n const result = host ?? envHost ?? defaultHost;\n return result;\n};\n\nconst getDefaultPort = () => {\n const defaultPort = window.location.port;\n const envPort = process.env.KOS_PORT;\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n let port;\n try {\n const _url = new URL(hostUrl);\n port = _url.port;\n } catch {\n // ignore errors\n }\n\n const result = port ?? envPort ?? defaultPort;\n return result;\n};\n\nconst rejectAfterDelay = (\n ms: number,\n model: IKosModel\n): { promise: Promise<void>; cancel: () => void } => {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const promise = new Promise<void>((_, reject) => {\n timeoutId = setTimeout(() => {\n if (model) {\n KosLog.error(\n `Model ${model.modelId} - ${model.modelTypeName} preloading - timed out after ${ms}ms`\n );\n } else {\n KosLog.error(`KOS Core preloading timed out after ${ms}ms`);\n }\n reject(\n new Error(\n `Model ${model?.modelId} - ${model?.modelTypeName} - timed out after ${ms}ms`\n )\n );\n }, ms);\n });\n\n const cancel = () => {\n if (timeoutId) clearTimeout(timeoutId);\n };\n\n return { promise, cancel };\n};\nconst isReloadable = (model: any): model is ReloadAware =>\n typeof model.reload === \"function\";\n\nconst isUnloadable = (model: any): model is UnloadAware =>\n typeof model.unload === \"function\";\nexport interface IKosCoreLifecycle {\n /**\n * lifecycle function to initialize the core and provide initial values that\n * will be used by the system. For example, loading the logger, setting up\n * internationialization or performing any capability validation would occur here\n */\n init(): Promise<void>;\n\n load(): Promise<void>;\n\n unload(): Promise<void>;\n\n ready(): Promise<void>;\n\n online(): Promise<void>;\n\n offline(): Promise<void>;\n\n whenReady(): Promise<void>;\n\n reload(): Promise<void>;\n\n isReady: boolean;\n}\nexport interface IKosWebSocketTransportContainer {\n transport: IKosServiceTransport;\n connectionAlias?: string;\n}\nexport interface IKosModelManagerContainer {\n status: KosCoreState;\n isOnline: boolean;\n onlineStatus: boolean;\n modelManager: IKosModelManager;\n}\n\nexport type IKosCoreManager = IKosCoreLifecycle &\n IKosModelManagerContainer &\n IKosWebSocketTransportContainer & { reloading: boolean };\n\nexport enum AuthState {\n LOGGED_IN = \"logged_in\",\n LOGGED_OUT = \"logged_out\",\n}\nexport class KosCore implements IKosCoreManager {\n fsmService: ReturnType<typeof coreFsm>;\n\n private static _instance: IKosCoreManager;\n\n status: KosCoreState;\n\n private initialized: boolean;\n\n private loaded: boolean;\n\n private _transport: IKosServiceTransport;\n\n public modelManager!: IKosModelManager;\n\n public authState: AuthState;\n public isOnline: boolean;\n\n private _reloading: boolean;\n private _unloading: boolean;\n connectionAlias?: string;\n\n private constructor(connectionAlias?: string) {\n this.initialized = false;\n this.connectionAlias = connectionAlias;\n this.loaded = false;\n this.isOnline = false;\n this.status = KosCoreState.CREATED;\n this.authState = AuthState.LOGGED_OUT;\n this._reloading = false;\n this._unloading = false;\n makeAutoObservable(this);\n\n EventBus.subscribe(\"token\", (data) => {\n if (data) {\n this.transport.token = data.body;\n }\n });\n\n EventBus.subscribe(WebSocketEvents.CONNECTED, async () => {\n await this.whenReady();\n this.fsmService.service.send(KosCoreEvents.GO_ONLINE);\n });\n\n EventBus.subscribe(WebSocketEvents.DISCONNECTED, async () => {\n this.fsmService.service.send(KosCoreEvents.GO_OFFLINE);\n });\n EventBus.subscribe(\"/studioServer/auth/LOGGED_IN\", () => {\n this.authState = AuthState.LOGGED_IN;\n this.transport.authorized = true;\n // this.fsmService.service.send(KosCoreEvents.RELOAD);\n });\n EventBus.subscribe(\"/studioServer/auth/LOGIN_REQUIRED\", () => {\n this.authState = AuthState.LOGGED_OUT;\n this.transport.authorized = false;\n });\n\n EventBus.subscribe(WebSocketEvents.RELOAD, () => {\n log.warn(\"WebSocket requested reload\");\n this.fsmService.service.send(KosCoreEvents.RELOAD);\n });\n\n EventBus.subscribe(\"/studio/project/reload\", () => {\n log.warn(\"Project requested reload\");\n this.fsmService.service.send(KosCoreEvents.RELOAD);\n });\n\n // EventBus.subscribe(\"/studioServer/auth/LOGGED_OUT\", () => {\n // this.fsmService.service.send(KosCoreEvents.UNLOAD);\n // });\n const ws = WebSocketTransport.getInstance();\n\n const host = getDefaultHost();\n const port = getDefaultPort();\n const protocol = getDefaultProtocol();\n ws.host = host;\n\n ws.port = Number.parseInt(port);\n\n ws.protocol = protocol;\n if (process.env.KOS_ALLOW_ANONYMOUS === \"true\") {\n ws.authorized = true;\n }\n\n const alias = getConnectionAlias() ?? connectionAlias;\n if (alias) {\n ws.alias = alias.replace(\"{{TIMESTAMP}}\", Date.now().toString());\n }\n\n this._transport = ws.init();\n this.fsmService = coreFsm(this);\n this.fsmService.service.send(KosCoreEvents.CREATE);\n }\n\n get onlineStatus() {\n return this.isOnline && !this._reloading && !this._unloading;\n }\n get reloading() {\n return this._reloading;\n }\n\n get unloading() {\n return this._unloading;\n }\n async reload(): Promise<void> {\n const currentTime = Date.now();\n if (this._reloading) {\n log.info(\"reload already in progress\");\n return;\n }\n this._reloading = true;\n log.warn(\"reloading KOS Core\");\n log.warn(\"reloading preloaded models\");\n const modelManager = this.modelManager;\n for (const model of modelManager.preloadedModels) {\n if (isReloadable(model.modelData)) {\n log.info(`reloading model ${model.modelId}`);\n model.unload?.();\n await model.modelData.reload();\n model.registerSubscribers?.();\n log.info(`reloading model ${model.modelId} complete`);\n }\n }\n\n for (const model of modelManager.models) {\n // only reload models that are not preloaded\n if (\n !modelManager.preloadedModels.includes(model) &&\n isReloadable(model.modelData)\n ) {\n model.unload?.();\n await model.modelData.reload();\n model.registerSubscribers?.();\n }\n }\n const elapsed = Date.now() - currentTime;\n setTimeout(() => {\n kosAction(() => {\n log.warn(\"reloading KOS Core complete\");\n this._reloading = false;\n });\n }, 1000 - elapsed);\n }\n\n async online(): Promise<void> {\n log.debug(\"KOS Core going online\");\n await this._transport.whenReady();\n log.debug(\"KOS Transport Ready. Calling online() for models\");\n EventBus.publish(\"/kosCore/online\", \"/kosCore/online\");\n console.timeEnd(\"kosCore:startup\");\n }\n async offline(): Promise<void> {\n log.debug(\"KOS Core going offline\");\n EventBus.publish(\"/kosCore/offline\", \"/kosCore/offline\");\n }\n\n async unload(): Promise<void> {\n log.debug(\"Unloading KOS Core\");\n const currentTime = Date.now();\n this._unloading = true;\n log.debug(\"unloading KOS Core\");\n const modelManager = this.modelManager;\n for (const model of modelManager.models) {\n if (isUnloadable(model.modelData)) {\n model.unload?.();\n }\n }\n const elapsed = Date.now() - currentTime;\n setTimeout(() => {\n kosAction(() => {\n this._unloading = false;\n });\n }, 1000 - elapsed);\n }\n\n async whenReady() {\n await when(() => this.status === KosCoreState.READY);\n }\n async ready(): Promise<void> {\n log.debug(\"Readying KOS Core\");\n await this._transport.whenReady();\n\n const promises = this.modelManager!.preloadedModels.map((model) => {\n return {\n modelId: model.modelId,\n model,\n promise: model.whenReady!(),\n };\n });\n\n const settled = await Promise.allSettled(\n promises.map((promise) => {\n const { promise: timeoutPromise, cancel: timeoutCancel } =\n rejectAfterDelay(5000, promise.model);\n Promise.race([\n promise.promise.then(() => {\n timeoutCancel();\n }),\n timeoutPromise,\n ]);\n })\n );\n const failed = settled.filter((p) => p.status === \"rejected\");\n if (failed.length) {\n log.error(\n `There were ${failed.length} failed models on model preloading`\n );\n\n throw Error(\n `There were ${failed.length} failed models on model preloading`\n );\n }\n\n log.debug(`leaving kos-core ready() `);\n }\n\n get isReady() {\n return this.status === KosCoreState.READY;\n }\n set transport(transport: IKosServiceTransport) {\n this._transport = transport;\n }\n get transport() {\n return this._transport;\n }\n\n get coreInitialized() {\n return this.initialized;\n }\n\n get modelsLoaded() {\n return this.loaded;\n }\n\n async init(): Promise<void> {\n log.debug(\"entering kos-core init()\");\n\n console.time(\"kosCore:startup\");\n console.time(\"kosCore:init\");\n await this._transport.whenReady();\n\n this.initialized = true;\n log.debug(\"initialized - leaving kos-core init()\");\n console.timeEnd(\"kosCore:init\");\n }\n\n async load(): Promise<void> {\n log.debug(\"entering kos-core load()\");\n console.time(\"kosCore:load\");\n\n this.loaded = true;\n log.debug(\"loaded - leaving kos-core load()\");\n console.timeEnd(\"kosCore:load\");\n }\n\n public static create(\n registry: IKosRegistry,\n reset?: boolean,\n connectionAlias?: string\n ) {\n const instance = this.getInstance({ reset, connectionAlias });\n\n if (registry.extensions?.dataMapper) {\n Object.keys(registry.extensions.dataMapper).forEach((key) => {\n const dataMapper = registry.extensions?.dataMapper?.[key];\n if (dataMapper) {\n if (Array.isArray(dataMapper)) {\n dataMapper.forEach((mapper) => {\n ExtensionManager.dataMapper.registerDataMapper(key, mapper);\n });\n } else {\n ExtensionManager.dataMapper.registerDataMapper(key, dataMapper);\n }\n }\n });\n }\n\n if (registry.extensions?.propertyMapper) {\n Object.keys(registry.extensions.propertyMapper).forEach((key) => {\n const propertyMapper = registry.extensions?.propertyMapper?.[key];\n if (propertyMapper) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n key,\n propertyMapper\n );\n }\n });\n }\n\n if (registry.extensions?.contextLoader) {\n Object.keys(registry.extensions.contextLoader).forEach((key) => {\n const loader = registry.extensions?.contextLoader?.[key];\n if (loader) {\n ExtensionManager.loader.registerLoader(key, loader);\n }\n });\n }\n\n RegistrationManager.model.getAll().forEach(([, value]) => {\n registry.models = { ...registry.models, ...value.registration };\n });\n\n registry.models = {\n ...registry.models,\n ...RegistrationManager.model.getLegacyModels(),\n };\n\n RegistrationManager.companion.getAll().forEach(([key, value]) => {\n registry.companionModels = { ...registry.companionModels };\n registry.companionModels[key] = registry.companionModels[key] || [];\n for (const companion of value) {\n registry.companionModels[key].push({ type: companion });\n }\n });\n\n RegistrationManager.model.getPreloadModels().forEach((preload) => {\n if (registry.preloadModels.includes(preload)) {\n return;\n }\n registry.preloadModels.push(preload);\n });\n const modelManager = KosModelManager.create(registry, reset);\n instance.modelManager = modelManager;\n return instance;\n }\n\n public static getInstance(data?: {\n reset?: boolean;\n connectionAlias?: string;\n }): IKosCoreManager {\n this._instance = window.KosCore as any;\n // Do you need arguments? Make it a regular static method instead.\n if (!this._instance || data?.reset) {\n window.KosCore = new this(data?.connectionAlias) as any;\n this._instance = window.KosCore as any;\n }\n return this._instance;\n }\n}\n","/**\n * Utility functions for handling binary data in KOS WebSocket transport\n */\n\n/**\n * Convert ArrayBuffer to base64 string for WebSocket transport\n */\nexport function arrayBufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n let binary = \"\";\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n/**\n * Convert base64 string back to ArrayBuffer\n */\nexport function base64ToArrayBuffer(base64: string): ArrayBuffer {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes.buffer;\n}\n\n/**\n * Convert Blob to ArrayBuffer\n */\nexport async function blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {\n return await blob.arrayBuffer();\n}\n\n/**\n * Convert ArrayBuffer to Blob\n */\nexport function arrayBufferToBlob(buffer: ArrayBuffer, type?: string): Blob {\n return new Blob([buffer], { type: type || \"application/octet-stream\" });\n}\n\n/**\n * Convert FormData to a serializable format\n */\nexport async function serializeFormData(formData: FormData): Promise<{\n fields: Record<string, string>;\n files: Array<{ name: string; filename: string; type: string; data: string }>;\n}> {\n const fields: Record<string, string> = {};\n const files: Array<{\n name: string;\n filename: string;\n type: string;\n data: string;\n }> = [];\n\n // Use forEach if entries() is not available\n const entries: Array<[string, FormDataEntryValue]> = [];\n formData.forEach((value, key) => {\n entries.push([key, value]);\n });\n\n for (const [key, value] of entries) {\n if (value instanceof File) {\n const buffer = await value.arrayBuffer();\n files.push({\n name: key,\n filename: value.name,\n type: value.type,\n data: arrayBufferToBase64(buffer),\n });\n } else {\n fields[key] = value.toString();\n }\n }\n\n return { fields, files };\n}\n\n/**\n * Create a ReadableStream from chunks\n */\nexport function createChunkedStream(\n onPull: (\n controller: ReadableStreamDefaultController<Uint8Array>\n ) => Promise<void>\n): ReadableStream<Uint8Array> {\n return new ReadableStream({\n async start() {\n // Initial setup\n },\n async pull(controller) {\n await onPull(controller);\n },\n cancel() {\n // Cleanup on stream cancellation\n },\n });\n}\n\n/**\n * Process body for WebSocket transport\n */\nexport async function processRequestBody(\n body: string | ArrayBuffer | Blob | FormData | Uint8Array | undefined\n): Promise<{ data: string; contentType: string; encoding?: string }> {\n if (!body) {\n return { data: \"\", contentType: \"text/plain\" };\n }\n\n if (typeof body === \"string\") {\n return { data: body, contentType: \"text/plain\" };\n }\n\n if (body instanceof ArrayBuffer || body instanceof Uint8Array) {\n let buffer: ArrayBuffer;\n if (body instanceof Uint8Array) {\n // Create a new ArrayBuffer with just the Uint8Array's data\n buffer = new ArrayBuffer(body.byteLength);\n new Uint8Array(buffer).set(body);\n } else {\n buffer = body;\n }\n return {\n data: arrayBufferToBase64(buffer),\n contentType: \"application/octet-stream\",\n encoding: \"base64\",\n };\n }\n\n if (body instanceof Blob) {\n const buffer = await blobToArrayBuffer(body);\n return {\n data: arrayBufferToBase64(buffer),\n contentType: body.type || \"application/octet-stream\",\n encoding: \"base64\",\n };\n }\n\n if (body instanceof FormData) {\n const serialized = await serializeFormData(body);\n return {\n data: JSON.stringify(serialized),\n contentType: \"multipart/form-data\",\n encoding: \"json\",\n };\n }\n\n throw new Error(\"Unsupported body type\");\n}\n","import { EventBus } from \"../../common\";\nimport { KosCore } from \"../core/kosCore\";\nimport { KosLog } from \"../core/log\";\nimport { KosFetchOptions, Response } from \"../types/utils/kos-fetch\";\nimport { uuid } from \"./api-request-id\";\nimport {\n arrayBufferToBlob,\n base64ToArrayBuffer,\n createChunkedStream,\n processRequestBody,\n} from \"./binary-utils\";\nimport {\n createBaseMessage,\n createFosBaseMessage,\n createHeaders,\n createMessageBody,\n createReadableStream,\n createStudioMessage,\n} from \"./kos-message-utils\";\n\nconst log = KosLog.createLogger({ name: \"kos-fetch\" });\n\n/**\n * Represents the response data received from a Kos service.\n *\n * @typeparam T - The type of data in the response.\n */\nexport interface KosServiceResponse<T> {\n data: T;\n status: number;\n}\n\n/**\n * The WebSocket timeout duration in milliseconds.\n */\nconst WS_TIMEOUT = process.env.KOS_WS_TIMEOUT\n ? parseInt(process.env.KOS_WS_TIMEOUT)\n : 30000;\n\n/**\n * A delay function used to resolve promises with a delay.\n *\n * @returns A promise that resolves after a minimal delay.\n */\nconst delay = () =>\n new Promise((resolve) => {\n setTimeout(() => {\n resolve(true);\n }, 0);\n });\n\n/**\n * Determines the appropriate message factory function based on the provided options.\n *\n * @param options - The Kos fetch options.\n * @returns A message factory function.\n */\nconst fetchMessageFactory = (options?: KosFetchOptions) => {\n if (options?.studio) {\n return createStudioMessage;\n } else if (options?.fos) {\n return createFosBaseMessage;\n } else {\n return createBaseMessage;\n }\n};\n\n/**\n * Performs a Kos WebSocket fetch operation, providing fetch-like behavior over a WebSocket transport.\n *\n * @async\n * @param url - The URL to fetch from.\n * @param options - The Kos fetch options.\n * @returns A promise that resolves to the response from the server.\n */\nconst kosFetchWs = async (\n url: string,\n options?: KosFetchOptions\n): Promise<Response> => {\n const transport = KosCore.getInstance().transport;\n await transport.whenReady();\n const requestId = uuid();\n const urlObj = new URL(url);\n const path = `${urlObj.pathname}${urlObj.search}`;\n log.debug(`path: ${path}`);\n const TIMEOUT = options?.timeout || WS_TIMEOUT;\n const messageFactory = fetchMessageFactory(options);\n\n // Process body and get content type\n const processedBody = await processRequestBody(options?.body);\n const additionalHeaders: Record<string, string> = {};\n\n if (processedBody.contentType) {\n additionalHeaders[\"content-type\"] = processedBody.contentType;\n }\n if (processedBody.encoding) {\n additionalHeaders[\"content-encoding\"] = processedBody.encoding;\n }\n\n const msg = createMessageBody(\n messageFactory({\n path,\n requestId,\n method: options?.method || `GET`,\n destinationAddress: options?.destinationAddress || \"\",\n ordered: options?.ordered,\n tracker: options?.tracker,\n bridge: options?.bridge,\n headers: { ...options?.headers, ...additionalHeaders },\n }),\n processedBody.data\n );\n\n return new Promise((resolve) => {\n let unsubscribe: (() => void) | null = null;\n let timeoutId: NodeJS.Timeout | null = null;\n\n // Handle user-provided abort signal\n if (options?.signal) {\n if (options.signal.aborted) {\n // Already aborted\n resolve({\n headers: createHeaders({}),\n status: 0,\n ok: false,\n json: async <T>(): Promise<T | null> => null,\n body: createReadableStream(``),\n redirected: false,\n statusText: `Request aborted`,\n type: `basic`,\n url: ``,\n clone: function (): Response {\n throw new Error(`Function not implemented.`);\n },\n bodyUsed: false,\n arrayBuffer: function (): Promise<ArrayBuffer> {\n throw new Error(`Function not implemented.`);\n },\n blob: function (): Promise<Blob> {\n throw new Error(`Function not implemented.`);\n },\n formData: function (): Promise<FormData> {\n throw new Error(`Function not implemented.`);\n },\n text: function (): Promise<string> {\n throw new Error(`Function not implemented.`);\n },\n });\n return;\n }\n\n options.signal.addEventListener(\"abort\", () => {\n // Clean up on abort\n if (timeoutId) clearTimeout(timeoutId);\n if (unsubscribe) unsubscribe();\n\n resolve({\n headers: createHeaders({}),\n status: 0,\n ok: false,\n json: async <T>(): Promise<T | null> => null,\n body: createReadableStream(``),\n redirected: false,\n statusText: `Request aborted`,\n type: `basic`,\n url: ``,\n clone: function (): Response {\n throw new Error(`Function not implemented.`);\n },\n bodyUsed: false,\n arrayBuffer: function (): Promise<ArrayBuffer> {\n throw new Error(`Function not implemented.`);\n },\n blob: function (): Promise<Blob> {\n throw new Error(`Function not implemented.`);\n },\n formData: function (): Promise<FormData> {\n throw new Error(`Function not implemented.`);\n },\n text: function (): Promise<string> {\n throw new Error(`Function not implemented.`);\n },\n });\n });\n }\n\n timeoutId = setTimeout(() => {\n log.error(`Timeout occurred - url: ${url}`);\n if (unsubscribe) unsubscribe();\n resolve({\n headers: createHeaders({}),\n status: 404,\n ok: false,\n json: async <T>(): Promise<T | null> => null,\n body: createReadableStream(``),\n redirected: false,\n statusText: ``,\n type: `basic`,\n url: ``,\n clone: function (): Response {\n throw new Error(`Function not implemented.`);\n },\n bodyUsed: false,\n arrayBuffer: function (): Promise<ArrayBuffer> {\n throw new Error(`Function not implemented.`);\n },\n blob: function (): Promise<Blob> {\n throw new Error(`Function not implemented.`);\n },\n formData: function (): Promise<FormData> {\n throw new Error(`Function not implemented.`);\n },\n text: function (): Promise<string> {\n throw new Error(`Function not implemented.`);\n },\n });\n }, TIMEOUT);\n\n const subscription = EventBus.subscribe(requestId, (responseMsg) => {\n if (timeoutId) clearTimeout(timeoutId);\n\n const responseHeaders = responseMsg?.headers || {};\n const contentType = responseHeaders[\"content-type\"] || \"text/plain\";\n const encoding = responseHeaders[\"content-encoding\"];\n const responseBody = responseMsg?.body || \"\";\n\n // Handle binary data based on encoding\n let bodyData: string | ArrayBuffer = responseBody;\n if (encoding === \"base64\" && responseBody) {\n try {\n bodyData = base64ToArrayBuffer(responseBody);\n } catch (e) {\n log.error(\"Failed to decode base64 response\", e);\n }\n }\n\n const response: Response = {\n headers: createHeaders(responseHeaders),\n status:\n (responseHeaders[`status`] && parseInt(responseHeaders[`status`])) ||\n 200,\n ok: responseHeaders[`status`] === `200`,\n\n json: async <T>(): Promise<T | null> => {\n try {\n if (typeof bodyData === \"string\") {\n return bodyData.length ? (JSON.parse(bodyData) as T) : null;\n } else {\n // Convert ArrayBuffer to string for JSON parsing\n const decoder = new TextDecoder();\n const text = decoder.decode(bodyData);\n return text.length ? (JSON.parse(text) as T) : null;\n }\n } catch (e) {\n throw Error(`Not a JSON response`);\n }\n },\n\n text: async (): Promise<string> => {\n if (typeof bodyData === \"string\") {\n return bodyData;\n } else {\n const decoder = new TextDecoder();\n return decoder.decode(bodyData);\n }\n },\n\n arrayBuffer: async (): Promise<ArrayBuffer> => {\n if (bodyData instanceof ArrayBuffer) {\n return bodyData;\n } else {\n const encoder = new TextEncoder();\n return encoder.encode(bodyData).buffer;\n }\n },\n\n blob: async (): Promise<Blob> => {\n if (bodyData instanceof ArrayBuffer) {\n return arrayBufferToBlob(bodyData, contentType);\n } else {\n return new Blob([bodyData], { type: contentType });\n }\n },\n\n formData: async (): Promise<FormData> => {\n // This is a simplified implementation\n // In a real scenario, you'd need to parse multipart/form-data\n const formData = new FormData();\n if (\n contentType === \"multipart/form-data\" &&\n typeof bodyData === \"string\"\n ) {\n try {\n const parsed = JSON.parse(bodyData);\n if (parsed.fields) {\n Object.entries(parsed.fields).forEach(([key, value]) => {\n formData.append(key, value as string);\n });\n }\n if (parsed.files) {\n // Files would need special handling\n log.warn(\n \"File reconstruction in FormData not fully implemented\"\n );\n }\n } catch (e) {\n throw new Error(\"Failed to parse FormData\");\n }\n }\n return formData;\n },\n\n body: options?.stream\n ? createChunkedStream(async (controller) => {\n // For streaming support, you'd need to handle chunked messages\n // This is a placeholder for future implementation\n if (bodyData instanceof ArrayBuffer) {\n controller.enqueue(new Uint8Array(bodyData));\n } else {\n const encoder = new TextEncoder();\n controller.enqueue(encoder.encode(bodyData));\n }\n controller.close();\n })\n : createReadableStream(typeof bodyData === \"string\" ? bodyData : \"\"),\n\n redirected: false,\n statusText: ``,\n type: `basic`,\n url: ``,\n clone: function (): Response {\n // Implement a basic clone\n return { ...this };\n },\n bodyUsed: false,\n };\n\n // Clean up the subscription\n subscription.unsubscribe();\n delay().then(() => resolve(response));\n });\n\n // Store unsubscribe function for cleanup\n unsubscribe = subscription.unsubscribe;\n\n const socket = options?.fos ? transport.fosSocket : transport.socket;\n if (!socket) {\n throw Error(`No web socket transport available: ${options}`);\n }\n socket?.send(msg);\n });\n};\n\n/**\n * Represents the base URL for Kos fetch requests.\n */\nlet BASE_URL = `kos:`;\nlet kosFetch = kosFetchWs;\n// Check if mocking of fetch requests is enabled\nif (process.env.KOS_MOCK_FETCH === `true`) {\n const PORT = process.env.KOS_PORT || \"9999\";\n kosFetch = fetch; // Use the standard fetch for mocking\n BASE_URL = `http://localhost:${PORT}`;\n}\n\n// Export the kosFetch function and BASE_URL for use in other modules\nexport { BASE_URL, kosFetch };\n","import { KosCore } from \"../core/kosCore\";\nimport { IKosDataModel, IKosModel, IKosVisitor } from \"../core/kosModel\";\nimport { KosLog } from \"../core/log\";\n\nconst log = KosLog.createLogger({\n name: \"kos-model-visitor\",\n group: \"kos-ui-core\",\n});\n\n/**\n * Represents a base class for visiting and processing Kos data models.\n *\n * @abstract\n * @implements IKosVisitor<IKosModel>\n * @category Core\n */\nexport abstract class KosModelVisitor implements IKosVisitor<IKosModel> {\n /**\n * A set to keep track of visited model IDs to prevent redundant visits.\n */\n visitedModels: Set<string> = new Set();\n\n /**\n * Initializes a new instance of the KosModelVisitor class.\n */\n constructor() {\n this.visitedModels = new Set();\n }\n\n /**\n * Starts the visiting process from a root Kos data model.\n *\n * @param rootModel - The root Kos data model to start visiting from.\n * @throws An error if the rootModel does not have an ID or if it cannot be found.\n */\n start(rootModel: IKosDataModel): void {\n if (rootModel.id === undefined) {\n throw new Error(\"rootModel must have an id\");\n }\n\n const kosModel = KosCore.getInstance().modelManager.getModelById(\n rootModel.id\n );\n\n if (!kosModel) {\n throw new Error(`Could not find rootModel with id: ${rootModel.id}`);\n }\n\n this.visitedModels.clear();\n kosModel.accept?.(this);\n }\n\n /**\n * Visits and processes a Kos model.\n *\n * @param model - The Kos model to visit and process.\n */\n visit(model: IKosModel): void {\n if (this.visitedModels.has(model.modelId)) {\n log.info(`model ${model.modelId} already visited`);\n return;\n }\n\n // Call the visitModel method to allow custom processing of the model.\n const stopVisiting = !!this.visitModel(model.modelData, this);\n\n this.visitedModels.add(model.modelId);\n\n if (stopVisiting) {\n return;\n }\n\n // Visit and process the children of the current model.\n model.getChildren?.().forEach((child) => {\n child.accept?.(this);\n });\n }\n\n /**\n * Abstract method to visit and process a Kos data model.\n *\n * @param model - The Kos data model to visit and process.\n * @param context - The KosModelVisitor instance for context.\n * @returns `true` to stop visiting further models, or `false` or `undefined` to continue visiting.\n */\n abstract visitModel<T extends IKosDataModel = IKosDataModel>(\n model: T,\n context: KosModelVisitor\n ): boolean | void;\n}\n","import { KosLog } from \"../core/log\";\nimport type { KosFetchOptions } from \"../types\";\nimport { BASE_URL, kosFetch } from \"./kos-fetch\";\n\n/**\n * Resolves the service URL configuration.\n * @param _service - The optional service name (not used).\n * @returns An object with `isMock` and `URL` properties.\n */\nexport const resolveBaseUrl = () => {\n const MOCK = false;\n const URL = BASE_URL;\n return { isMock: MOCK, URL };\n};\n\nconst log = KosLog.createLogger({ name: \"kos-service-request\" });\nconst ERROR_UNKNOWN = \"errUnknown\";\ntype NonNeverKeys<T> = {\n [K in keyof T]-?: T[K] extends never | undefined ? never : K;\n}[keyof T];\n\nexport type AvailableMethods<T> = Exclude<\n NonNeverKeys<T>,\n \"parameters\" | \"requestBody\"\n>;\n\nexport type PathsByMethod<T> = {\n [Method in \"get\" | \"put\" | \"post\" | \"delete\"]: {\n [K in keyof T]: Method extends AvailableMethods<T[K]> ? K : never;\n }[keyof T & keyof { [K in keyof T]: Method extends keyof T[K] ? K : never }];\n};\n\ntype ClientGetParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"get\"] extends { parameters: infer P } ? P : never;\n\ntype ClientPostParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"post\"] extends { parameters: infer P } ? P : never;\n\ntype ClientPutParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"put\"] extends { parameters: infer P } ? P : never;\n\ntype ClientDeleteParams<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"delete\"] extends { parameters: infer P } ? P : never;\n\ntype ClientGetBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"get\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\ntype ClientPostBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"post\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\ntype ClientPutBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"put\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\ntype ClientDeleteBody<\n Paths extends Record<string, any>,\n K extends keyof Paths\n> = Paths[K][\"delete\"] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\nexport type ClientResponse<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n> = Paths[K][M] extends { responses: { 200: { content: infer R } } }\n ? R[keyof R]\n : unknown;\n\ntype ClientParams<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n> = Paths[K][M] extends { parameters: infer P } ? P : never;\n\ntype ClientBody<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n> = Paths[K][M] extends { requestBody: { content: infer B } }\n ? B[keyof B]\n : never;\n\nexport type ServiceResponse<T> = [string, null] | [null, T];\n\nexport type DeepRequired<T> = {\n [K in keyof T]-?: T[K] extends object ? DeepRequired<T[K]> : T[K];\n};\nexport type ElementType<T> = T extends (infer U)[] ? U : never;\n\n// Define a generic request function using your custom transport layer\nasync function clientRequest<\n Paths extends Record<string, any>,\n K extends keyof Paths,\n M extends AvailableMethods<Paths[K]> | string\n>(\n endpoint: K,\n method: M,\n options?: RequestOptions,\n params?: ClientParams<Paths, K, M>,\n body?: ClientBody<Paths, K, M>\n): Promise<ServiceResponse<ClientResponse<Paths, K, M>>> {\n const url = (params as any)?.path\n ? Object.keys((params as any).path).reduce<string>(\n (acc, key) =>\n String(acc).replace(`{${key}}`, (params as any)?.path[key]),\n String(endpoint)\n )\n : String(endpoint);\n\n const query = (params as any)?.query\n ? Object.keys((params as any).query)\n .map((key) => `${key}=${(params as any).query[key]}`)\n .join(\"&\")\n : \"\";\n\n const fullUrl = `${resolveBaseUrl().URL}${url}${\n query ? `?${encodeURIComponent(query)}` : \"\"\n }`;\n\n log.debug(`fullUrl: ${fullUrl}`);\n const fetchOptions = {\n method: String(method).toUpperCase() as any,\n body: null as any,\n ...options,\n };\n if (body) {\n fetchOptions.body = JSON.stringify(body);\n }\n const response = await kosFetch(fullUrl, fetchOptions);\n\n if (response.status < 200 || response.status >= 400) {\n return [`${response.statusText || ERROR_UNKNOWN}`, null];\n }\n\n const payload = await response.json();\n return [null, payload.data];\n}\n\ntype RequestOptions = Omit<KosFetchOptions, \"method\" | \"body\">;\nexport function createClient<Paths extends Record<string, any>>() {\n // Extract valid paths for each method\n type ValidPaths = PathsByMethod<Paths>;\n\n return {\n get: <K extends ValidPaths[\"get\"]>(\n endpoint: K,\n params?: ClientGetParams<Paths, K>,\n options?: RequestOptions\n ) => clientRequest<Paths, K, \"get\">(endpoint, \"get\", options, params),\n\n post: <K extends ValidPaths[\"post\"]>(\n endpoint: K,\n params?: ClientPostParams<Paths, K>,\n body?: ClientPostBody<Paths, K>,\n options?: RequestOptions\n ) =>\n clientRequest<Paths, K, \"post\">(endpoint, \"post\", options, params, body),\n\n put: <K extends ValidPaths[\"put\"]>(\n endpoint: K,\n params?: ClientPutParams<Paths, K>,\n body?: ClientPutBody<Paths, K>,\n options?: RequestOptions\n ) => clientRequest<Paths, K, \"put\">(endpoint, \"put\", options, params, body),\n\n delete: <K extends ValidPaths[\"delete\"]>(\n endpoint: K,\n params?: ClientDeleteParams<Paths, K>,\n body?: ClientPutBody<Paths, K>,\n options?: RequestOptions\n ) =>\n clientRequest<Paths, K, \"delete\">(\n endpoint,\n \"delete\",\n options,\n params,\n body\n ),\n };\n}\n","export type Middleware<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n> = (context: Context<D, R>, next: () => Promise<void>) => Promise<void>;\n\nexport interface Context<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n> {\n data: D;\n result: Partial<R>;\n}\n\ntype ScalarValue = string | number | boolean | null | undefined;\nexport class MiddlewareChain<\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>,\n T extends Context<D, R> = Context<D, R>\n> {\n private middlewares: Middleware<D, R>[] = [];\n\n use(middleware: Middleware<D, R>): void {\n this.middlewares.push(middleware);\n }\n\n async execute(context: T): Promise<void> {\n let index = 0;\n\n const next = async (): Promise<void> => {\n index++;\n if (index < this.middlewares.length) {\n await this.middlewares[index](context, next);\n }\n };\n\n await this.middlewares[index](context, next);\n }\n}\n\nexport const processMiddleware = async <\n D extends object = Record<string, ScalarValue>,\n R extends object = Record<string, ScalarValue>\n>(\n data: D,\n middleware: Middleware<D, R>[]\n) => {\n const chain = new MiddlewareChain<D, R>();\n middleware.forEach((m) => chain.use(m));\n\n const context: Context<D, R> = { data, result: {} as R };\n await chain.execute(context);\n return context.result as R;\n};\n","import { IKosDataModel } from \"../core/kosModel\";\nimport { KosCore } from \"../core/kosCore\";\nimport { ModelFactory } from \"../types/model\";\n\nexport const modelFactory = <T extends IKosDataModel, O extends Object = {}>(\n typeId: string\n): ModelFactory<T, O> => {\n return {\n type: typeId,\n build: (modelId?: string, options?: O) =>\n KosCore.getInstance().modelManager.createModelInstance<T, O>(\n typeId,\n modelId,\n options\n ).data,\n\n buildAsync: async (modelId?: string, options?: O) => {\n const response = KosCore.getInstance().modelManager.createModelInstance<\n T,\n O\n >(typeId, modelId, options);\n await response.model.whenInitialized();\n return response.data;\n },\n };\n};\n","import { KosCore } from \"../core/kosCore\";\nimport type { KosCompanionModelType } from \"../core/types/registration\";\nimport type { BaseKosModelRegistrationBean } from \"../types/model\";\n\nexport const updateModelRegistration = <\n T extends BaseKosModelRegistrationBean<any, any>\n>(\n modelRegistration: T\n): void => {\n KosCore.getInstance().modelManager.registerModel(modelRegistration);\n};\n\nexport const updateCompanionModelRegistration = (\n typeId: string,\n companionRegistration: KosCompanionModelType<any>\n): void => {\n KosCore.getInstance().modelManager.registerCompanionModel(\n typeId,\n companionRegistration\n );\n};\n","import { KosCore } from \"../core/kosCore\";\nimport { sendKosMessageResponse } from \"./kos-message-utils\";\n\nconst TOPIC = \"/kos/ui/internal/heartbeat/\";\n\ninterface HeartbeatOptions {\n // An ID to identify the pairing between the two clients.\n relationshipId: string;\n // The websocket client ID that the active one should pair with.\n destinationAddress: string;\n // A function called if the pairing is aborted.\n onAbort?: () => void;\n // By default the utlity will emit a beat every 2000 miliseconds. Use this\n // to change that.\n beatTime?: number;\n // By default the utlity will wait 3 seconds without a beat from the paired client\n // before aborting. Use this to change that.\n waitTime?: number;\n}\n\n/**\n * Sets up a connection between two clients such that\n * if one is closed, the other is notified of its closure.\n *\n * @category Utility\n */\nexport const pairedClientHeartbeat = ({\n relationshipId,\n destinationAddress,\n onAbort,\n waitTime,\n beatTime,\n}: HeartbeatOptions) => {\n const transport = KosCore.getInstance().transport;\n\n // Create an abort controller so we can cancel any requests that depend\n // on both clients being open (e.g in the case where one client is waiting for a response from another)\n const controller = new AbortController();\n\n let lastHeartBeat: number = performance.now();\n\n // Subscribe to the client heartbeat topic using the intent reponse id.\n const unsubscribe = transport.subscribeTopic({\n topic: `${TOPIC}${relationshipId}`,\n callback: () => {\n lastHeartBeat = performance.now();\n },\n });\n\n const _waitTime = waitTime ?? 3000;\n\n // If the last heartbeat was more than 5 seconds ago, abort the operation.\n const waitInterval = window.setInterval(() => {\n let timeDiff = performance.now() - lastHeartBeat;\n timeDiff = timeDiff / 1000;\n\n if (timeDiff > _waitTime / 1000) {\n controller.abort();\n }\n // Check that the last pulse was within the last 3 seconds.\n }, _waitTime);\n\n const _beatTime = beatTime ?? 2000;\n\n const beatInterval = window.setInterval(() => {\n sendKosMessageResponse({\n msg: {},\n options: {\n topic: `${TOPIC}${relationshipId}`,\n destinationAddress,\n },\n });\n }, _beatTime);\n\n const cleanUpHeartbeat = () => {\n window.clearInterval(beatInterval);\n window.clearInterval(waitInterval);\n unsubscribe();\n };\n\n const handleAbort = () => {\n cleanUpHeartbeat();\n if (onAbort) {\n onAbort();\n }\n controller.signal.removeEventListener(\"abort\", handleAbort);\n };\n\n controller.signal.addEventListener(\"abort\", handleAbort);\n\n return { cleanUpHeartbeat };\n};\n","type PipeFn = (arg: any) => any;\nexport const pipe =\n (...fns: PipeFn[]) =>\n (x: any) =>\n fns.reduce((v, f) => f(v), x);\n","import { KosLog } from \"../core/log\";\n\ninterface BackoffOptions {\n /** the maximum number of attempts to make */\n maxAttempts: number;\n\n /** the base delay (in ms) between attempts */\n baseDelayMs: number;\n\n /** the factor by which to increase the delay with each attempt */\n backoffFactor: number;\n}\n/**\n * Default backoff options.\n */\nconst BASE_OPTIONS: BackoffOptions = {\n maxAttempts: 5,\n baseDelayMs: 100,\n backoffFactor: 1.5,\n};\n\n/**\n * Provides exponential backoff for a given operation.\n * @param operation - the async operation to perform\n * @param options - optional backoff options\n * @returns - the result of the operation if successful\n * @throws - the last error if all attempts fail\n */\nexport async function retryWithExponentialBackoff<T>(\n operation: () => Promise<T>,\n options?: Partial<BackoffOptions>\n): Promise<T> {\n let attempt = 1;\n const _options = { ...BASE_OPTIONS, ...options };\n const { maxAttempts, baseDelayMs, backoffFactor } = _options;\n let delayMs = baseDelayMs;\n\n while (attempt <= maxAttempts) {\n try {\n const result = await operation();\n return result; // If the operation succeeds, return the result\n } catch (error) {\n KosLog.error(`Attempt ${attempt} failed: ${error}`);\n\n if (attempt < maxAttempts) {\n // Exponential backoff: increase the delay exponentially with each attempt\n delayMs = baseDelayMs * Math.pow(backoffFactor, attempt);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n attempt++;\n } else {\n throw error; // If all attempts fail, re-throw the error\n }\n }\n }\n\n // If we reach this point, all attempts have failed, so reject with the last error\n throw new Error(\"All attempts failed\");\n}\n","/**\n * @module ServiceFactory\n * @description\n * The ServiceFactory module provides functions for interacting with Kos services, such as retrieving, modifying, and deleting entities.\n * These functions communicate with the server and handle various service operations.\n *\n * @example\n * // Create a Kos service instance for managing entities.\n * const entityService = ServiceFactory.build({\n * basePath: \"/api/entities\",\n * getAllPath: \"/list\",\n * getOnePath: \"/get\",\n * deleteModelPath: \"/delete\",\n * addModelPath: \"/add\",\n * modifyModelPath: \"/modify\",\n * });\n *\n * // Fetch a list of entities.\n * const entities = await entityService.getAll({ ordered: true });\n *\n * // Get details of a specific entity by ID.\n * const entityDetails = await entityService.getModelById({ id: \"entity123\" });\n *\n * // Add a new entity to the server.\n * const newEntity = { name: \"New Entity\" };\n * await entityService.addModel({ model: newEntity });\n *\n * // Modify an existing entity.\n * const updatedEntity = { id: \"entity123\", name: \"Updated Entity\" };\n * await entityService.modifyModel({ model: updatedEntity });\n */\n\nimport { KosLog } from \"../core/log\";\nimport type { KosFetchOptions } from \"../types/utils/kos-fetch\";\nimport type { KosServiceResponse } from \"./kos-fetch\";\nimport { BASE_URL, kosFetch } from \"./kos-fetch\";\n\nconst log = KosLog.createLogger({ name: \"kos-service-request\" });\n/**\n * Resolves the service URL configuration.\n * @param _service - The optional service name (not used).\n * @returns An object with `isMock` and `URL` properties.\n */\nexport const resolveServiceUrl = (_service?: string) => {\n const MOCK = false;\n const URL = BASE_URL;\n return { isMock: MOCK, URL };\n};\n\n/**\n * Represents a function that can be used for fetching data.\n */\ntype FetchType = typeof kosFetch | typeof fetch;\n\n/**\n * Represents parameters for deleting an entity from the server.\n */\ninterface DeleteModelParams extends CommonParams {\n id: string;\n urlOverride?: string;\n tracker?: string;\n}\n\n/**\n * Removes an entity from the server based on its ID.\n * @param destinationAddress - The destination address for the request.\n * @param url - The base URL for the service.\n * @param _fetch - The fetch function to use.\n * @returns An empty response with status 200.\n */\nconst deleteModel =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <ResponseType = unknown>({\n id,\n tracker,\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n }: DeleteModelParams) => {\n const options: KosFetchOptions = {\n method: `DELETE`,\n };\n\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n if (tracker) {\n options.tracker = tracker;\n }\n\n addCommonParams(options, {\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const response = await _fetch(urlOverride || `${url}/${id}`, options);\n\n if (!response.ok) {\n throw Error(\n `There was a problem deleting the model; returned status ${response.status}`\n );\n }\n\n const configResponse: KosServiceResponse<ResponseType> | undefined =\n await response.json();\n\n return configResponse;\n };\n\n/**\n * Represents common parameters shared across different service operations.\n */\ntype CommonParams = Partial<Orderable> &\n Partial<StudioRequest> &\n Partial<FosRequest> &\n Partial<RoutableRequest> &\n Partial<TimeoutAware>;\n\n/**\n * Represents parameters for fetching a list of entities.\n */\ninterface GetAllParams extends CommonParams {\n urlOverride?: string;\n tracker?: string;\n}\n\n/**\n * Represents parameters for fetching a single entity by ID.\n */\ninterface GetModelByIdParams extends GetAllParams {\n id: string;\n}\n\n/**\n * Adds common parameters to a KosFetchOptions object.\n * @param options - The KosFetchOptions object to modify.\n * @param param1 - The common parameters to add.\n * @returns The modified KosFetchOptions object.\n */\nconst addCommonParams = (\n options: KosFetchOptions,\n { ordered, studio, fos, destinationAddress, bridge, timeout }: CommonParams\n) => {\n if (timeout) {\n options.timeout = timeout;\n }\n if (ordered) {\n options.ordered = ordered;\n }\n\n if (studio) {\n options.studio = studio;\n }\n\n if (fos) {\n options.fos = fos;\n }\n\n if (bridge) {\n options.bridge = bridge;\n }\n\n if (destinationAddress || destinationAddress === \"\") {\n options.destinationAddress = destinationAddress;\n }\n\n return options;\n};\n\n/**\n * Retrieves a list of entities managed by the KOS Server.\n * @param destinationAddress - The destination address for the request.\n * @param url - The base URL for the service.\n * @param _fetch - The fetch function to use.\n * @returns The list of entities.\n */\nconst getAll =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Response>({\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n timeout,\n destinationAddress: destinationAddressOverride,\n }: GetAllParams) => {\n const options: KosFetchOptions = {\n method: `GET`,\n };\n\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || url;\n\n const response = await _fetch(resolvedUrl, options);\n\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem retrieving the model; returned status ${response.status}`,\n payload\n );\n }\n\n const configResponse: KosServiceResponse<Response[]> | undefined =\n await response.json();\n\n return configResponse;\n };\n\n/**\n * Represents parameters for fetching a single entity.\n */\nconst getOne =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Response>({\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n tracker,\n timeout,\n destinationAddress: destinationAddressOverride,\n }: GetAllParams) => {\n const options: KosFetchOptions = {\n method: `GET`,\n };\n\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n if (tracker) {\n options.tracker = tracker;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || url;\n log.debug(`resolvedUrl: ${resolvedUrl}`);\n const response = await _fetch(resolvedUrl, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem retrieving the model; returned status ${response.status}`,\n payload\n );\n }\n const configResponse: KosServiceResponse<Response> | undefined =\n await response.json();\n return configResponse;\n };\n\nconst getModelById =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Response>({\n urlOverride,\n id,\n ordered,\n studio,\n fos,\n bridge,\n timeout,\n destinationAddress: destinationAddressOverride,\n }: GetModelByIdParams) => {\n const options: KosFetchOptions = {\n method: `GET`,\n };\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || `${url}/${id}`;\n const response = await _fetch(resolvedUrl, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem retrieving the model; returned status ${response.status}`,\n payload\n );\n }\n const configResponse: KosServiceResponse<Response> | undefined =\n await response.json();\n return configResponse;\n };\n\ninterface Orderable {\n ordered: boolean;\n}\n\ninterface TimeoutAware {\n timeout: number;\n}\n\ninterface FosRequest {\n fos: boolean;\n bridge: boolean;\n}\n\ninterface StudioRequest {\n studio: boolean;\n}\n\ninterface RoutableRequest {\n destinationAddress: string;\n}\ninterface AddModelParams<Request>\n extends Partial<Orderable>,\n Partial<StudioRequest>,\n Partial<FosRequest>,\n Partial<RoutableRequest>,\n Partial<TimeoutAware> {\n model: Request;\n urlOverride?: string;\n tracker?: string;\n}\n\ninterface ModifyModelParams<Request>\n extends Partial<Orderable>,\n Partial<StudioRequest>,\n Partial<FosRequest>,\n Partial<RoutableRequest>,\n Partial<TimeoutAware> {\n model?: Request;\n id: string;\n urlOverride?: string;\n}\n\nexport class FetchError<\n T extends Record<string, any> | string = { error: string }\n> extends Error {\n payload?: T;\n constructor(message: string, payload?: T) {\n super(message);\n this.name = \"FetchException\";\n this.payload = payload;\n }\n}\n/**\n * Adds a new Entity to the server.\n *\n * Only members of the `kos.freestyle` org have permissions to invoke this operation.\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the corresponding event channel.\n *\n * @param model - the model to be added\n * @returns an empty response with status 200.\n */\nconst add =\n (destinationAddress: string, url: string, _fetch: FetchType) =>\n async <Request>({\n model,\n urlOverride,\n ordered,\n tracker,\n studio,\n fos,\n bridge,\n timeout,\n destinationAddress: destinationAddressOverride,\n }: AddModelParams<Request>) => {\n const options: KosFetchOptions = {\n method: `POST`,\n body: typeof model === \"string\" ? model : JSON.stringify(model),\n };\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n if (tracker) {\n options.tracker = tracker;\n }\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const response = await _fetch(urlOverride || url, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem sending the POST data; returned status ${response.status}`,\n payload\n );\n }\n const configResponse: KosServiceResponse<any> | undefined =\n await response.json();\n return configResponse;\n };\n\n/**\n * Modifies an existing model on the server.\n * @param method - The HTTP method to use for the modification operation (default is \"POST\").\n * @param destinationAddress - The destination address for the request.\n * @param url - The base URL for the service.\n * @param _fetch - The fetch function to use.\n * @returns An empty response with status 200.\n */\nconst modifyModel =\n (\n method: \"PUT\" | \"POST\" = \"POST\",\n destinationAddress: string,\n url: string,\n _fetch: FetchType\n ) =>\n async <Request>({\n // Reqeust should be Request = unknown...\n model,\n id,\n urlOverride,\n ordered,\n studio,\n fos,\n bridge,\n timeout,\n destinationAddress: destinationAddressOverride,\n }: ModifyModelParams<Request>) => {\n const options: KosFetchOptions = {\n method,\n };\n if (model) {\n options.body = JSON.stringify(model);\n }\n if (destinationAddress) {\n options.destinationAddress = destinationAddress;\n }\n\n addCommonParams(options, {\n timeout,\n ordered,\n studio,\n fos,\n bridge,\n destinationAddress: destinationAddressOverride,\n });\n\n const response = await _fetch(urlOverride || `${url}/${id}`, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined;\n try {\n payload = await response.json();\n } catch (error) {\n // silently ignore parsing error\n }\n throw new FetchError(\n `There was a problem modifying the model; returned status ${response.status}`,\n payload\n );\n }\n const configResponse: KosServiceResponse<any> | undefined = // <--- KosServiceResponse<any> should be KosServiceResponse<Request>...\n await response.json();\n return configResponse;\n };\n/**\n * Represents parameters for creating a service instance.\n */\ninterface ServiceFactoryParams {\n destinationAddress?: string;\n basePath: string;\n getAllPath?: string;\n getOnePath?: string;\n deleteModelPath?: string;\n addModelPath?: string;\n modifyModelPath?: string;\n mock?: boolean;\n}\n\n/**\n * A factory for creating service instances with common configurations.\n */\nexport const ServiceFactory = {\n /**\n * Builds a service instance with the specified configuration.\n *\n * @param params - The configuration parameters for the service instance.\n * @returns An object with service methods for interacting with the server.\n *\n * @example\n * // Create a Kos service instance for managing entities.\n * const entityService = ServiceFactory.build({\n * basePath: \"/api/entities\",\n * getAllPath: \"/list\",\n * getOnePath: \"/get\",\n * deleteModelPath: \"/delete\",\n * addModelPath: \"/add\",\n * modifyModelPath: \"/modify\",\n * });\n *\n * // Fetch a list of entities.\n * const entities = await entityService.getAll({ ordered: true });\n *\n * // Get details of a specific entity by ID.\n * const entityDetails = await entityService.getModelById({ id: \"entity123\" });\n *\n * // Add a new entity to the server.\n * const newEntity = { name: \"New Entity\" };\n * await entityService.addModel({ model: newEntity });\n *\n * // Modify an existing entity.\n * const updatedEntity = { id: \"entity123\", name: \"Updated Entity\" };\n * await entityService.modifyModel({ model: updatedEntity });\n */\n build: ({\n destinationAddress = \"\",\n basePath,\n getAllPath,\n getOnePath,\n deleteModelPath,\n addModelPath,\n modifyModelPath,\n mock = false,\n }: ServiceFactoryParams) => {\n const _fetch = mock ? fetch : kosFetch;\n return {\n /**\n * Retrieves a list of entities managed by the KOS Server.\n *\n * @param params - The parameters for the request, including common options.\n * @returns The list of entities.\n */\n getAll: getAll(destinationAddress, getAllPath || basePath, _fetch),\n\n /**\n * Retrieves details of a specific entity by its ID.\n *\n * @param params - The parameters for the request, including common options and the entity ID.\n * @returns Details of the requested entity.\n */\n getModelById: getModelById(\n destinationAddress,\n getOnePath || basePath,\n _fetch\n ),\n\n /**\n * Retrieves details of a single entity.\n *\n * @param params - The parameters for the request, including common options.\n * @returns Details of the requested entity.\n */\n getOne: getOne(destinationAddress, getOnePath || basePath, _fetch),\n\n /**\n * Adds a new entity to the server.\n *\n * @param params - The parameters for the request, including common options and the new entity model.\n * @returns An empty response with status 200.\n */\n addModel: add(destinationAddress, addModelPath || basePath, _fetch),\n\n /**\n * Deletes an entity from the server based on its ID.\n *\n * @param params - The parameters for the request, including common options and the entity ID.\n * @returns An empty response with status 200.\n */\n deleteModel: deleteModel(\n destinationAddress,\n deleteModelPath || basePath,\n _fetch\n ),\n\n /**\n * Modifies an existing entity on the server.\n *\n * @param params - The parameters for the request, including common options and the entity model.\n * @returns An empty response with status 200.\n */\n modifyModel: modifyModel(\n \"POST\",\n destinationAddress,\n modifyModelPath || basePath,\n _fetch\n ),\n\n /**\n * Modifies an existing entity on the server using the HTTP PUT method.\n *\n * @param params - The parameters for the request, including common options and the entity model.\n * @returns An empty response with status 200.\n */\n putModel: modifyModel(\n \"PUT\",\n destinationAddress,\n modifyModelPath || basePath,\n _fetch\n ),\n\n /**\n * Adds a new entity to the server using the HTTP POST method.\n *\n * @param params - The parameters for the request, including common options and the new entity model.\n * @returns An empty response with status 200.\n */\n postModel: add(destinationAddress, addModelPath || basePath, _fetch),\n };\n },\n};\n","import { uuid } from \"./api-request-id\";\n\nconst _sessionKey = uuid();\n\nexport const getKosSessionKey = (): string => `kos-${_sessionKey}`;\n\nexport const isLocalRefId = (id?: string): boolean =>\n !!id && !id.includes(\"VM_SERVICE\") && id.startsWith(getKosSessionKey());\n","import log from \"loglevel\";\nimport { EventBus } from \"../../common\";\n\nimport { uuid } from \"./api-request-id\";\nimport { KosServiceResponse } from \"./kos-fetch\";\n\nexport interface ErrorResponse {\n error?: string;\n}\n\nexport const waitForRequest = async <ResponseType extends ErrorResponse>(\n requestId: string,\n timeout = 60000\n) =>\n new Promise<ResponseType>((resolve, reject) => {\n const { unsubscribe } = EventBus.subscribe(requestId, (op) => {\n log.debug(`recieved response for refId ${requestId}: ${op}`);\n unsubscribe();\n clearTimeout(cancel);\n try {\n const body: ResponseType = op?.body ? JSON.parse(op.body) : {};\n resolve(body);\n } catch {\n const body = (op?.body as unknown) || {};\n resolve(body as ResponseType);\n }\n });\n\n const cancel = setTimeout(() => {\n unsubscribe();\n reject(Error(`Request with ID ${requestId} timed out. Cancelling.`));\n }, timeout);\n });\n\nexport const sendRequest = async <R, T extends KosServiceResponse<any>>(\n requestPromise: (param: R) => Promise<T | undefined>,\n params: R,\n refId: string\n) => {\n const op = waitForRequest(refId);\n const result = await Promise.allSettled([requestPromise(params), op]);\n\n if (result[0].status === \"fulfilled\") {\n if (result[1].status === \"rejected\") {\n throw Error(result[1].reason);\n } else {\n if (result[0].value) {\n if (result[1].value.error) {\n throw Error(result[1].value.error);\n }\n result[0].value.data = result[1].value;\n return result[0].value;\n }\n }\n } else {\n throw Error(result[0].reason);\n }\n return undefined;\n};\n\ninterface SyncPublishParams<T> {\n topic: string;\n msg: T;\n requestId?: string;\n}\nexport const syncPublish = async <T, R extends ErrorResponse>({\n topic,\n msg,\n requestId,\n}: SyncPublishParams<T>) => {\n const _requestId = requestId ?? uuid();\n const responsePromise = waitForRequest<R>(_requestId);\n EventBus.publish(topic, msg, { sync: _requestId });\n const response = await responsePromise;\n if (response.error) {\n throw Error(response.error);\n }\n return response;\n};\n","import { ObservableMap, makeAutoObservable } from \"mobx\";\nimport { kosAction } from \"../..\";\nimport { getAllKosCompanionModels, getKosModelSync } from \"../../util\";\nimport { IKosDataModel } from \"../kosModel\";\nconst contextMap = new Map<string, KosContextBean>();\n\nexport interface KosContext {\n get(key: string): any;\n set(key: string, value: any): void;\n}\nexport class KosContextBean implements KosContext {\n private _context: ObservableMap<string, any>;\n private _parent?: string | undefined;\n private _id: string;\n constructor(id: string) {\n this._id = id;\n this._context = new ObservableMap({});\n this._parent = \"\";\n makeAutoObservable(this);\n }\n\n setParent(parent: string) {\n kosAction(() => {\n this._parent = parent;\n });\n }\n get id() {\n return this._id;\n }\n\n get context() {\n return this._context;\n }\n\n get parentModel() {\n if (!this._parent) {\n return undefined;\n }\n return getKosModelSync(this._parent)?.model;\n }\n\n get companionModels() {\n const model = getKosModelSync(this._id);\n if (!model?.model) {\n return [];\n }\n return getAllKosCompanionModels(model.model);\n }\n\n get(key: string) {\n if (this._context.has(key)) {\n return this._context.get(key);\n }\n\n if (this.companionModels.length > 0) {\n const value = this.companionModels.find((companion: IKosDataModel) => {\n if (!companion.id) {\n return false;\n }\n if (!contextMap.has(companion.id)) {\n return false;\n }\n return contextMap.get(companion.id)?.context.has(key);\n });\n if (value) {\n return contextMap.get(value.id)?.get(key);\n }\n }\n\n if (this._parent) {\n return contextMap.get(this._parent)?.get(key);\n }\n return undefined;\n }\n set(key: string, value: any) {\n this._context.set(key, value);\n }\n remove(key: string) {\n this._context.delete(key);\n }\n clear() {\n this._context.clear();\n }\n}\n\nexport const KosContextManager = {\n createContext: (id: string, parentId?: string) => {\n const context = contextMap.get(id) ?? new KosContextBean(id);\n if (parentId) {\n if (!contextMap.has(parentId)) {\n throw new Error(`Parent context ${parentId} does not exist`);\n }\n context.setParent(parentId);\n } else if (id !== \"root\") {\n context.setParent(\"root\");\n }\n contextMap.set(id, context);\n return context;\n },\n getContext: (id: string) => contextMap.get(id),\n deleteContext: (id: string) => {\n contextMap.delete(id);\n },\n setParentContext: (id: string, parentId: string) => {\n if (!contextMap.has(parentId)) {\n throw new Error(`Parent context ${parentId} does not exist`);\n }\n contextMap.get(id)?.setParent(parentId);\n },\n rootContext: () => contextMap.get(\"root\"),\n};\n\nKosContextManager.createContext(\"root\");\n\nexport const resolveKosContext = (model: IKosDataModel) =>\n KosContextManager.getContext(model.id);\n","import {\n isObservable,\n runInAction as kosAction,\n makeAutoObservable,\n observable,\n observe,\n} from \"mobx\";\n\nimport { ObservableData, type KosData } from \"../util/observable-proxy-map\";\nimport {\n IKosContainerIndex,\n IndexMapper,\n KosContainerIndex,\n} from \"./kos-container-index\";\nimport { IKosBaseContainer } from \"./kos-container-model\";\nimport { KosLog } from \"./log\";\nimport { IKosIdentifiable } from \"./types/model\";\n\nexport interface IKosDataContainer<T extends IKosIdentifiable>\n extends IKosBaseContainer<T> {\n updateModel: (model: T) => void;\n getModel: (id: string) => T | undefined;\n getIndexByKey: (indexName: string, indexKey: string) => T[];\n getIndexKeys: (indexName: string) => string[];\n}\nconst log = KosLog.createLogger({ name: \"kos-data-container\" });\ntype PropType = string | number | symbol | undefined;\n\ninterface ContainerOptions<T extends IKosIdentifiable> {\n sortKey?: keyof T;\n indexMap?: Record<string, keyof T | IndexMapper<T>>;\n}\nexport class KosDataContainer<T extends IKosIdentifiable>\n implements IKosDataContainer<T>\n{\n _data: Map<string, T>;\n private _sortKey?: PropType;\n private _revision: number;\n private _index: Map<string, IKosContainerIndex<T>>;\n private _optionsMap: ContainerOptions<T>[\"indexMap\"];\n private _disposerMap: Map<string, () => void> = new Map();\n idx: KosData<Record<string, Record<string, T[]>>>;\n constructor(options?: ContainerOptions<T>) {\n this._data = observable.map(new Map());\n this._sortKey = options?.sortKey;\n this._revision = 1;\n this._optionsMap = options?.indexMap || {};\n const tmp = options?.indexMap\n ? Object.keys(options.indexMap).reduce((acc, curr) => {\n acc[curr] = undefined;\n return acc;\n }, {})\n : {};\n this._index = observable.map(tmp);\n this.idx = ObservableData();\n makeAutoObservable(this, {});\n this.init();\n }\n\n init() {\n Object.keys(this._optionsMap!).forEach((key) => {\n const modelKey = this._optionsMap![key];\n const idx = new KosContainerIndex<T>({\n container: this,\n key: modelKey,\n });\n this._index.set(key, idx);\n this.idx[key] = idx.data;\n });\n }\n\n [Symbol.iterator]() {\n return this.data[Symbol.iterator]();\n }\n\n get index() {\n return this._index;\n }\n\n get indexKeys() {\n return Array.from(this.index.keys()).reduce<\n Record<string, string[] | undefined>\n >((acc, curr) => {\n acc[curr] = this.index.get(curr)?.keys;\n return acc;\n }, {});\n }\n\n get revision() {\n return this._revision;\n }\n\n addAll(models: T[]) {\n kosAction(() => {\n models.forEach((model) => this.addModel(model));\n });\n }\n\n removeAll(ids: string[]) {\n kosAction(() => {\n ids.forEach((id) => this.removeModel(id));\n });\n }\n\n sortFn(a, b): number {\n const sortKey = this._sortKey;\n\n if (sortKey) {\n return String(a[sortKey]).localeCompare(String(b[sortKey]), undefined, {\n numeric: true,\n });\n }\n return 0;\n }\n\n get data() {\n const list = Array.from(this._data.values());\n\n if (this._sortKey) {\n list.sort(this.sortFn.bind(this));\n }\n return list;\n }\n\n increment() {\n kosAction(() => {\n this._revision = this._revision + 1;\n });\n }\n addModel(model: T, defer?: boolean) {\n const observableData = isObservable(model)\n ? model\n : observable.object(model);\n const _disposer = this._disposerMap.get(model.id);\n if (_disposer) {\n _disposer();\n this._disposerMap.delete(model.id);\n }\n this._data.set(observableData.id || \"\", observableData);\n if (!defer) {\n this.increment();\n }\n\n const disposer = observe(observableData, (change) => {\n if (Object.values(this._optionsMap || {}).includes(change.name as any)) {\n this.increment();\n }\n });\n this._disposerMap.set(observableData.id || \"\", disposer);\n }\n\n removeModel(id: string) {\n this._data.delete(id);\n this.increment();\n const disposer = this._disposerMap.get(id);\n if (disposer) {\n disposer();\n this._disposerMap.delete(id);\n }\n }\n\n updateModel(model: T) {\n const observableData = observable.object(model);\n this._data.set(observableData.id || \"\", observableData);\n this.increment();\n }\n\n getModel(id: string) {\n return this._data.get(id);\n }\n\n getIndexKeys(indexName: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n return idx.keys ?? [];\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n\n getIndexByKey(indexName: string, indexKey: string) {\n if (this.index.has(indexName)) {\n const idx = this.index.get(indexName)!;\n if (idx.index.has(indexKey)) {\n return idx.getByKey(indexKey);\n } else {\n log.info(\n `key ${indexKey} not found in ${indexName} index: ${Array.from(\n idx.index.keys()\n )}`\n );\n return [];\n }\n } else {\n log.info(\n `index ${indexName} not found in ${Array.from(this.index.keys())}`\n );\n return [];\n }\n }\n\n async clear() {\n this._data.clear();\n this.increment();\n }\n\n filter<S extends any>(\n predicate: (value: any, index: number, array: any[]) => value is S,\n thisArg?: any\n ) {\n return this.data.filter(predicate, thisArg);\n }\n\n sort(compareFn?: ((a: any, b: any) => number) | undefined) {\n return this.data.sort(compareFn);\n }\n map<U>(\n callbackfn: (value: any, index: number, array: any[]) => U,\n thisArg?: any\n ) {\n return this.data.map(callbackfn, thisArg);\n }\n\n forEach(\n callbackfn: (value: any, index: number, array: any[]) => void,\n thisArg?: any\n ) {\n this.data.forEach(callbackfn, thisArg);\n }\n\n toJSON() {\n const indexes = this.indexKeys;\n return {\n indexes,\n data: this.data.map((model) => {\n return {\n id: model.id,\n };\n }),\n };\n }\n}\n","import {\n IdentifiableModelFactory,\n KosIdentifiableModelRegistration,\n KosModelClassRegistration,\n KosSingletonModelClassRegistration,\n SingletonFactory,\n} from \"../types\";\nimport { isKosModel } from \"../util\";\nimport { Kos } from \"./kos-model-factory\";\nimport { IKosDataModel, KosCreationContext } from \"./kosModel\";\n\ntype IdentifiableChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosModelClassRegistration<T, O> & {\n singleton: false;\n factory: IdentifiableModelFactory<T, O>;\n};\n\ntype SingletonChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n singleton: true;\n factory: SingletonFactory<T, O>;\n};\n\ntype ChildRegistration<\n T extends IKosDataModel = any,\n O extends object = Record<string, any>\n> = IdentifiableChildRegistration<T, O> | SingletonChildRegistration<T, O>;\n\ntype Reg<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosIdentifiableModelRegistration<T, O> & {\n singleton: false;\n factory: IdentifiableModelFactory<T, O>;\n};\ninterface ModelRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n [k: string]: Reg<T, O>;\n}\ninterface RegistrationProps<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n}\nexport class KosRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n childRegistration?: any;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n constructor({ type, model, childRegistration }: RegistrationProps<T, O>) {\n this.type = type;\n this.model = model;\n this.childRegistration = childRegistration;\n }\n\n get factory() {\n return Kos.Factory.create<T, O>(this.type);\n }\n\n get registration(): ModelRegistration<T, O> {\n return {\n [this.type]: {\n class: this.model,\n singleton: false,\n factory: this.factory,\n },\n ...this.childRegistration,\n } as ModelRegistration<T, O>;\n }\n\n get predicate() {\n return isKosModel<T>(this.type);\n }\n}\n","import {\n IdentifiableModelFactory,\n KosIdentifiableModelRegistration,\n KosSingletonModelClassRegistration,\n SingletonFactory,\n} from \"../types\";\nimport { isKosModel } from \"../util\";\nimport { Kos } from \"./kos-model-factory\";\nimport { IKosDataModel, KosCreationContext } from \"./kosModel\";\n\ntype IdentifiableChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosIdentifiableModelRegistration<T, O> & {\n factory: IdentifiableModelFactory<T, O>;\n};\n\ntype SingletonChildRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n factory: SingletonFactory<T, O>;\n};\n\ntype ChildRegistration<\n T extends IKosDataModel = any,\n O extends object = Record<string, any>\n> = IdentifiableChildRegistration<T, O> | SingletonChildRegistration<T, O>;\n\ntype Reg<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> = KosSingletonModelClassRegistration<T, O> & {\n factory: SingletonFactory<T, O>;\n};\ninterface Singleton<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n [k: string]: Reg<T, O>;\n}\n\ninterface RegistrationProps<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n}\nexport class KosSingletonRegistration<\n T extends IKosDataModel,\n O extends object = Record<string, any>\n> {\n type: string;\n model: new (modelId: string, options: O, context: KosCreationContext) => T;\n childRegistration?: any;\n constructor({ type, model, childRegistration }: RegistrationProps<T, O>) {\n this.type = type;\n this.model = model;\n this.childRegistration = childRegistration;\n }\n\n get factory() {\n return Kos.Singleton.create<T, O>(this.type);\n }\n\n get registration(): Singleton<T, O> {\n return {\n [this.type]: {\n class: this.model,\n singleton: true,\n factory: this.factory,\n },\n ...this.childRegistration,\n } as Singleton<T, O>;\n }\n\n get predicate() {\n return isKosModel<T>(this.type);\n }\n}\n","import { makeAutoObservable } from \"mobx\";\nimport { EventBus } from \"../../../../common\";\n\nexport interface IKosToken {\n token?: string;\n}\nclass KosToken implements IKosToken {\n private _token?: string;\n constructor() {\n makeAutoObservable(this);\n EventBus.subscribe(\"token\", (token) => {\n this.token = token?.body;\n });\n }\n\n get token() {\n return this._token;\n }\n\n set token(token) {\n this._token = token;\n }\n}\n\nexport default KosToken;\n","// Extracts route parameter names from a path like \"/user/:id/profile/:section\"\ntype ExtractParams<T extends string> =\n T extends `${infer _Start}/:${infer Param}/${infer Rest}`\n ? { [K in Param | keyof ExtractParams<`/${Rest}`>]: string }\n : T extends `${infer _Start}/:${infer Param}`\n ? { [K in Param]: string }\n : {};\n\nexport type KosMethodTypes = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\nexport type KosRequest<TPath extends string = string> = {\n id: string;\n method: string;\n path: TPath;\n params: ExtractParams<TPath>;\n query?: Record<string, string>;\n body?: any;\n};\n\nexport type KosResponse = {\n send: (data: any) => void;\n status?: (code: number) => KosResponse;\n};\n\nexport type RouteMetadata = {\n method: string;\n path: string;\n description?: string;\n parameters?: any[]; // OpenAPI-compliant parameter definitions\n};\n\nexport type KosMiddleware<TPath extends string = string> = (\n req: KosRequest<TPath>,\n res: KosResponse,\n next: () => Promise<void> | void\n) => Promise<void> | void;\n\nexport class BrowserKosRouter {\n private routes: {\n method: string;\n path: string;\n middlewares: KosMiddleware<any>[];\n }[] = [];\n private openApiRoutes: RouteMetadata[] = [];\n\n use<TPath extends string = string>(\n method: string,\n path: TPath,\n ...middlewares: KosMiddleware<TPath>[]\n ) {\n this.routes.push({ method, path, middlewares });\n\n // Extract route parameters for OpenAPI\n const params = this.extractOpenApiParams(path);\n\n this.openApiRoutes.push({\n method,\n path,\n parameters: params,\n });\n }\n\n /**\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(route => route.path !== path);\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 method: route.method,\n path: route.path\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","/**\n * @file intent-service.ts\n * @description\n * Provides a simple API for sending and handling \"intents\"—structured messages that allow decoupled communication between different parts of your application.\n * Utilizes the EventBus to publish and subscribe to intent events, supporting both fire-and-forget and request/response (async) patterns.\n *\n * Example usage:\n *\n * // Listening for an intent in a model:\n * @kosTopicHandler({\n * topic: `/kos/intent/studio.start.vm`,\n * })\n * async handleIntent(payload: any) {\n * this.logger.warn(payload);\n * return { test: \"foo\" };\n * }\n *\n * // Sending an intent:\n * sendIntent({\n * type: \"studio.start.vm\",\n * options: { imageId: id },\n * });\n *\n * // Sending an async intent and handling the response:\n * sendAsyncIntent({\n * type: \"studio.start.vm\",\n * options: { imageId: id },\n * }).then(([error, data]) => {\n * if (error) {\n * log.error(`Error starting VM: ${error}`);\n * } else if (data) {\n * log.warn(`result: ${JSON.stringify(data, null, 2)}`);\n * }\n * });\n */\n\nimport { EventBus, type ApiCallback } from \"../../../common/events\";\nimport { uuid, type ServiceResponse } from \"../../util\";\nimport { KosLog } from \"../log\";\n\nconst log = KosLog.createLogger({ name: \"intent-service\" });\n\n/**\n * Represents an intent message.\n * @template T - The payload/options type for the intent.\n * @property {string} type - The intent type (e.g., \"studio.start.vm\").\n * @property {T} options - The payload/options for the intent.\n */\nexport interface Intent<T extends Record<string, any> = Record<string, any>> {\n type: string;\n options: T;\n}\n\n/**\n * Sends an intent as a fire-and-forget event.\n * If there are subscribers for the intent type, the event is published; otherwise, a log message is emitted.\n *\n * @param {Intent} intent - The intent to send.\n * @returns {void}\n *\n * @example\n * sendIntent({\n * type: \"studio.start.vm\",\n * options: { imageId: id },\n * });\n */\nconst sendIntent = (intent: Intent): void => {\n if (EventBus.hasEventSubscriptions(`/kos/intent/${intent.type}`)) {\n EventBus.publish(`/kos/intent/${intent.type}`, intent.options, {\n \"kos.intent.type\": intent.type,\n });\n } else {\n log.info(`No subscribers for intent ${intent.type}. Intent not sent.`);\n }\n};\n\n/**\n * Sends an intent and waits for a response. Returns a promise that resolves with the response or a timeout error after 1 second.\n *\n * - If there are subscribers, a unique request ID is generated and used for the response channel.\n * - If no subscribers, resolves with `body: undefined`.\n *\n * @template R - The expected response body type.\n * @param {Intent} intent - The intent to send.\n * @returns {Promise<ServiceResponse<{ body: R | undefined; payload: ApiCallback<R> | undefined }>>}\n *\n * @example\n * sendAsyncIntent({\n * type: \"studio.start.vm\",\n * options: { imageId: id },\n * }).then(([error, data]) => {\n * if (error) {\n * log.error(`Error starting VM: ${error}`);\n * } else if (data) {\n * log.warn(`result: ${JSON.stringify(data, null, 2)}`);\n * }\n * });\n */\nconst sendAsyncIntent = async <R = any>(\n intent: Intent\n): Promise<\n ServiceResponse<{ body: R | undefined; payload: ApiCallback<R> | undefined }>\n> =>\n new Promise((resolve) => {\n const { type, options: payload } = intent;\n if (EventBus.hasEventSubscriptions(`/kos/intent/${intent.type}`)) {\n const requestId = uuid();\n\n const { unsubscribe } = EventBus.subscribe(\n requestId,\n (response: ApiCallback<R> | undefined) => {\n clearTimeout(timeout);\n unsubscribe();\n if (response) {\n response.headers = response.headers || {};\n response.headers[\"kos.intent.type\"] = type;\n response.headers[\"responseId\"] = requestId;\n }\n\n resolve([null, { body: response?.body, payload: response }]);\n }\n );\n const timeout = setTimeout(() => {\n unsubscribe();\n resolve([`Intent ${type} timed out after 1 second`, null]);\n console.warn(`Intent ${type} timed out after 1 second`);\n }, 1000);\n EventBus.publish(`/kos/intent/${type}`, payload, {\n \"kos.intent.type\": type,\n sync: requestId,\n });\n } else {\n log.info(`No subscribers for intent ${intent.type}. Intent not sent.`);\n resolve([null, { body: undefined, payload: undefined }]);\n }\n });\n\nexport { sendAsyncIntent, sendIntent };\n","/**\n * Service for waiting for KOS applications to start\n * Provides utilities to wait for specific apps before proceeding with initialization\n */\n\nimport { EventBusState } from \"../../../common/events\";\n\nimport { kosFetch, type KosServiceResponse } from \"../../util/kos-fetch\";\nimport { KosLog } from \"../log\";\n\nconst log = KosLog.createLogger({ name: \"app-startup-service\" });\n\n/**\n * Interface representing a started KOS application\n */\nexport interface KosStartedApp {\n stopped: boolean;\n appId: string;\n started: boolean;\n sectionName: string;\n postStarted: boolean;\n parentAppId: string;\n}\n\n/**\n * Options for waiting for app startup\n */\nexport interface WaitForAppsOptions {\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Whether to throw error if apps don't start (default: true) */\n throwOnTimeout?: boolean;\n /** Whether apps must be fully post-started (default: false) */\n requirePostStarted?: boolean;\n}\n\n/**\n * Wait for specific KOS applications to be started\n *\n * @param appIds - Array of application IDs to wait for\n * @param options - Configuration options\n * @returns Promise that resolves when all apps are started\n *\n * @example\n * ```typescript\n * // Wait for single app\n * await waitForAppsToStart(['kosdev.ddk']);\n *\n * // Wait for multiple apps with custom timeout\n * await waitForAppsToStart([\n * 'kosdev.ddk',\n * 'com.kondra.summer.2025.controlledPourPlugin'\n * ], { timeout: 60000 });\n *\n * // Wait without throwing on timeout\n * const success = await waitForAppsToStart(['kosdev.ddk'], {\n * throwOnTimeout: false\n * });\n * ```\n */\nexport async function waitForAppsToStart(\n appIds: string[],\n options: WaitForAppsOptions = {}\n): Promise<boolean> {\n const {\n timeout = 30000,\n throwOnTimeout = true,\n requirePostStarted = false,\n } = options;\n\n if (appIds.length === 0) {\n log.warn(\"No app IDs provided to waitForAppsToStart\");\n return true;\n }\n\n log.debug(`Waiting for apps to start: ${appIds.join(\", \")}`);\n\n try {\n // Generate event topics for each app\n const eventTopics = appIds.map((appId) => `/kos/app/started/${appId}`);\n\n const startedApps = await EventBusState.waitForAllWithState<\n KosStartedApp[]\n >(eventTopics, {\n getCurrentState: async () => {\n try {\n const { default: api } = await import(\n \"../../../models/utils/service\"\n );\n\n const [error, data] = await api.get(\"/api/kos/apps/started\");\n if (error) {\n log.error(\"Error fetching started apps:\", error);\n return [];\n }\n return data as KosStartedApp[];\n\n // const response = await kosFetch(\"kos:///api/kos/apps/started\");\n // if (response.ok) {\n // const result: KosServiceResponse<KosStartedApp[]> | null =\n // await response.json();\n // return result?.data ?? [];\n // }\n } catch (error) {\n log.error(\"Failed to fetch app startup status:\", error);\n }\n return [];\n },\n shouldUseFetchedState: (apps) =>\n appIds.every((appId) => {\n const app = apps.find((a) => a.appId === appId);\n if (!app) return false;\n\n // Check if app is started\n if (!app.started) return false;\n\n // Check post-started if required\n if (requirePostStarted && !app.postStarted) return false;\n\n return true;\n }),\n timeout,\n });\n\n // Verify all apps are properly started\n const notStartedApps = appIds.filter((appId) => {\n const app = startedApps.find((a) => a.appId === appId);\n if (!app) return true;\n if (!app.started) return true;\n if (requirePostStarted && !app.postStarted) return true;\n return false;\n });\n\n if (notStartedApps.length > 0) {\n const message = `Apps not started: ${notStartedApps.join(\", \")}`;\n log.error(message);\n\n if (throwOnTimeout) {\n throw new Error(`App startup timeout: ${message}`);\n }\n return false;\n }\n\n log.info(`All apps started successfully: ${appIds.join(\", \")}`);\n return true;\n } catch (error) {\n const message = `Failed to wait for apps to start: ${appIds.join(\", \")}`;\n log.error(message, error);\n\n if (throwOnTimeout) {\n throw new Error(\n `${message} - ${error instanceof Error ? error.message : String(error)}`\n );\n }\n return false;\n }\n}\n\n/**\n * Wait for a single KOS application to start (convenience function)\n *\n * @param appId - Application ID to wait for\n * @param options - Configuration options\n * @returns Promise that resolves when app is started\n */\nexport async function waitForAppToStart(\n appId: string,\n options: WaitForAppsOptions = {}\n): Promise<boolean> {\n return waitForAppsToStart([appId], options);\n}\n\n/**\n * Check if specific apps are currently started (no waiting)\n *\n * @param appIds - Array of application IDs to check\n * @param requirePostStarted - Whether to require post-started status\n * @returns Promise resolving to status of each app\n */\nexport async function checkAppsStarted(\n appIds: string[],\n requirePostStarted = false\n): Promise<Record<string, boolean>> {\n const result: Record<string, boolean> = {};\n\n try {\n const response = await kosFetch(\"kos:///api/kos/apps/started\");\n if (!response.ok) {\n appIds.forEach((appId) => (result[appId] = false));\n return result;\n }\n\n const serviceResponse: KosServiceResponse<KosStartedApp[]> | null =\n await response.json();\n const apps = serviceResponse?.data ?? [];\n\n appIds.forEach((appId) => {\n const app = apps.find((a) => a.appId === appId);\n result[appId] =\n app?.started === true &&\n (!requirePostStarted || app?.postStarted === true);\n });\n } catch (error) {\n log.error(\"Failed to check app startup status:\", error);\n appIds.forEach((appId) => (result[appId] = false));\n }\n\n return result;\n}\n\n/**\n * Get all currently started apps\n *\n * @returns Promise resolving to array of started apps\n */\nexport async function getStartedApps(): Promise<KosStartedApp[]> {\n try {\n const response = await kosFetch(\"kos:///api/kos/apps/started\");\n if (!response.ok) {\n return [];\n }\n\n const result: KosServiceResponse<KosStartedApp[]> | null =\n await response.json();\n return result?.data ?? [];\n } catch (error) {\n log.error(\"Failed to fetch started apps:\", error);\n return [];\n }\n}\n","import {\n autorun,\n computed,\n makeAutoObservable,\n makeObservable,\n observable,\n reaction,\n runInAction,\n when,\n} from \"mobx\";\nexport * from \"./core/api\";\nexport * from \"./core/context\";\nexport * from \"./core/decorators\";\nexport * from \"./core/extension\";\nexport * from \"./core/kos-container-index\";\nexport * from \"./core/kos-container-model\";\nexport * from \"./core/kos-data-container\";\nexport * from \"./core/kos-model-factory\";\nexport * from \"./core/kos-registration\";\nexport * from \"./core/kos-singleton-registration\";\nexport * from \"./core/kosCore\";\nexport * from \"./core/kosModel\";\nexport * from \"./core/kosModelManager\";\nexport { KosModelEvents, KosModelState } from \"./core/lifecycle\";\nexport * from \"./core/log\";\nexport * from \"./core/models\";\nexport { default as KosToken } from \"./core/models/kos-token\";\nexport {\n KosModelRegistrationFactory,\n preloadKosModel,\n registerCompanionModel,\n registerKosModel,\n registerLegacyModel,\n RegistrationManager,\n SingletonKosModelRegistrationFactory,\n type KosModelRegistrationType,\n type RegistrationResult,\n} from \"./core/registration\";\nexport * from \"./core/services\";\nexport * from \"./core/transport\";\nexport * from \"./core/types\";\nexport * from \"./types\";\nexport * from \"./util\";\nexport {\n kosAction,\n kosAutoEffect,\n kosComputed,\n kosEffect,\n kosObservable,\n kosWhen,\n makeAutoObservable,\n makeObservable,\n};\n\n/**\n * {@inheritDoc when}\n * @category Utility\n */\nconst kosWhen = when;\n\n/**\n * {@inheritDoc computed}\n * @category Utility\n */\nconst kosComputed = computed;\n/**\n * {@inheritDoc runInAction}\n * @category Utility\n */\nconst kosAction = runInAction;\n\n/**\n * Creates a named reactive view and keeps it alive, so that the view is always updated if one of the dependencies changes, even when the view is not further used by something else.\n *\n * @param view — The reactive view\n *\n * @returns — disposer function, which can be used to stop the view from being updated in the future.\n * @category Utility\n */\nconst kosAutoEffect = autorun;\n\n/**\n * {@inheritDoc reaction}\n * @category Utility\n */\nconst kosEffect = reaction;\n\n/**\n * {@inheritDoc observable}\n * @category Utility\n */\nconst kosObservable = observable;\n","export {};\n\nexport const FUTURE_NOT_ASSIGNED = \"Not Assigned\";\nexport const EVENT_TROUBLE_ADDED = \"kos.trouble.added\";\nexport const EVENT_TROUBLE_REMOVED = \"kos.trouble.removed\";\nexport enum KosCoreModelPropertyMapper {\n TroubleRank = \"kos.trouble.rank.mapper\",\n TroubleColor = \"kos.trouble.color.mapper\",\n TroubleRole = \"kos.trouble.role.mapper\",\n}\n\n/**\n * Enum for the different message bus topics that are used in the KOS system.\n */\nexport enum Topics {\n TIME_CHANGE = \"/kos/internal/time/time\",\n DAY_CHANGE = \"/kos/internal/time/day\",\n TIMEZONE_CHANGE = \"/kos/internal/time/timezone\",\n}\n","import { BASE_URL, KosLog, ServiceFactory } from \"../../../core\";\nimport { ConfigPropertyTypes } from \"../../models\";\n\nconst log = KosLog.createLogger({\n name: \"config-bean-service\",\n group: \"Services\",\n});\n\nconst URL = BASE_URL;\n\n/**\n * @category Service Module\n * @name /services/config-bean\n * @version 1.0.0\n * @author Mark Pomerant <mpomerant@coca-cola.com>\n *\n * Services that can be invoked to perform operations on Config Beans\n */\n\n/**\n * The response from the server when an organization is\n * created or updated\n */\nexport interface ConfigBeanResponse {\n scopes: string[];\n details: ConfigBeanDetailsResponse[];\n}\n\nexport interface ConfigScope {\n scope: string;\n overrides?: Record<string, ConfigPropertyTypes>;\n}\n\nexport interface ConfigBeanDetailsResponse {\n bean: {\n [key: string]: ConfigPropertyTypes;\n };\n scopes: ConfigScope[];\n schema: SchemaResponse;\n}\n\nexport interface ConfigBeanRequest {\n [k: string]: ConfigPropertyTypes;\n}\n\nexport interface DecimalOption {\n decimals: number;\n}\n\nexport const hasDecimals = (option?: any): option is DecimalOption =>\n (option as DecimalOption)?.decimals !== undefined;\nexport type SchemaNodeType = \"String\" | \"int\" | \"boolean\" | \"double\";\nexport interface UnitSystemKeypadOptions {\n unitSystems: {\n [k: string]: {\n min: number;\n max: number;\n decimals: number;\n };\n };\n type: \"unitSystemKeypad\";\n}\n\nexport interface UnitSystemListOptions {\n type: \"unitSystemList\";\n unitSystems: {\n [k: string]: {\n list: string[];\n };\n };\n}\n\nexport interface UnitSystemRangeCountOptions {\n type: \"unitSystemRangeCount\";\n unitSystems: {\n [k: string]: {\n start: number;\n end: number;\n count: number;\n decimals: number;\n };\n };\n}\n\nexport interface UnitSystemRangeIntervalOptions {\n type: \"unitSystemRangeInterval\";\n unitSystems: {\n [k: string]: {\n start: number;\n end: number;\n interval: number;\n decimals: number;\n };\n };\n}\nexport interface KeypadOptions {\n min: number;\n max: number;\n decimals: number;\n type: \"keypad\";\n}\n\nexport interface RangeCountOptions {\n type: \"rangeCount\";\n start: number;\n end: number;\n count: number;\n decimals: number;\n}\n\nexport interface RangeIntervalOptions {\n type: \"rangeInterval\";\n start: number;\n end: number;\n interval: number;\n decimals: number;\n}\nexport interface ListOptions {\n type: \"list\";\n list: string[];\n}\n\nexport type SchemaOptionsType =\n | KeypadOptions\n | RangeCountOptions\n | RangeIntervalOptions\n | ListOptions\n | UnitSystemKeypadOptions\n | UnitSystemListOptions\n | UnitSystemRangeCountOptions\n | UnitSystemRangeIntervalOptions;\n\nexport interface SchemaNode {\n type: SchemaNodeType;\n format?: string;\n options: SchemaOptionsType;\n}\n\nexport interface EnumSchemaNode {\n type: \"enum\";\n format?: string;\n values: string[];\n}\n\nexport type SchemaNodeDef = SchemaNode | EnumSchemaNode;\nexport interface SchemaResponse {\n paths: string[];\n schema: {\n [key: string]: SchemaNodeDef;\n };\n}\n\nconst { postModel, getOne } = ServiceFactory.build({\n destinationAddress: \"\",\n basePath: `${URL}/kos/config/`,\n});\n\ninterface ConfigBeanUpdateRecord {\n attr: string;\n currentValue: string;\n previousValue: string;\n}\n\nexport interface ConfigBeanUpdateResponse {\n changes: ConfigBeanUpdateRecord[];\n errors: string[];\n}\n/**\n * Modifies an ConfigBean from the server based on the id.\n *\n * @param id - the id of the ConfigBean to be modified\n * @returns an empty response with status 200.\n */\nexport const modifyConfigBean = async (\n id: string,\n model: ConfigBeanRequest,\n path = `/api/kos/config`\n) => {\n log.debug(`sending modify request for ConfigBean: ${id}`);\n const response = postModel({\n model,\n urlOverride: `${URL}${path}/${id}`,\n });\n return response;\n};\n\n/**\n * Modifies an ConfigBean from the server based on the id.\n *\n * @param id - the id of the ConfigBean to be modified\n * @returns an empty response with status 200.\n */\nexport const getConfigBean = async (id: string, path = `/api/kos/config`) => {\n log.debug(`sending get request for ConfigBean: ${id}`);\n const response = await getOne<ConfigBeanResponse>({\n urlOverride: `${URL}${path}/details/${id}/15`,\n });\n return response;\n};\n","export const isBoolean = (val: string) =>\n val.toLowerCase() === \"true\" || val.toLowerCase() === \"false\";\n\nexport const isNumber = (val: string) => {\n try {\n const result = Number(val);\n return !isNaN(result);\n } catch (e) {\n return false;\n }\n};\n","import { runInAction } from \"mobx\";\nimport { ModelFactory } from \"../../../core\";\nimport {\n ConfigBeanRequest,\n ConfigBeanResponse,\n ConfigBeanUpdateResponse,\n type ConfigScope,\n} from \"../../services/config-bean\";\nimport { isBoolean, isNumber } from \"../../utils/prop-utils\";\nimport { ConfigPropertyTypes } from \"../types\";\nimport type { IConfigBeanModel } from \"./config-bean-model\";\nimport type { IConfigBeanModelOptions } from \"./config-bean-types\";\n\nexport function evaluateScopes(scopes: ConfigScope[] = []) {\n return scopes.reverse().reduce((acc, curr) => {\n const { overrides } = curr;\n if (overrides) {\n acc = { ...acc, ...overrides };\n }\n return acc;\n }, {});\n}\nfunction flattenObject(obj: any, parentKey = \"\", result = {}) {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n // Construct new key for the flattened object\n const newKey = parentKey ? `${parentKey}.${key}` : key;\n\n if (\n typeof obj[key] === \"object\" &&\n obj[key] !== null &&\n !Array.isArray(obj[key])\n ) {\n // Recursively flatten for nested objects\n flattenObject(obj[key], newKey, result);\n } else {\n // Assign value to the new key in the flattened object\n result[newKey] = obj[key];\n }\n }\n }\n return result;\n}\n/**\n * Maps a `ConfigBeanResponse` DTO to an `IConfigBeanModel` object.\n *\n * @remarks\n * This function will run as a mobx action ensuring that all observers are notified\n * if any changes are made.\n *\n * @params dto - the Data Transfer Object received from the backend\n * @params model - the IModel to be update\n *\n * @internal\n * @category Config Bean\n */\nexport const mapDtoToConfigBeanModel = (\n dto: ConfigBeanResponse,\n model: IConfigBeanModel\n) => {\n const bean = dto.details[0].bean || evaluateScopes(dto.details[0].scopes);\n const flattened = flattenObject(bean);\n runInAction(() => {\n const values = {\n ...flattened,\n };\n\n model.props.setValues(values);\n });\n};\n\nexport const mapUpdateDtoToConfigBeanModel = (\n dto: ConfigBeanUpdateResponse,\n model: IConfigBeanModel\n) => {\n runInAction(() => {\n dto.changes.forEach((change) => {\n const key = change.attr;\n let val: ConfigPropertyTypes = change.currentValue;\n let previousValue: ConfigPropertyTypes = change.previousValue;\n\n if (typeof val === \"string\" && isBoolean(val)) {\n val = val.toLowerCase() == \"true\";\n previousValue = (previousValue as string)?.toLowerCase() == \"true\";\n }\n\n if (typeof val === \"string\" && isNumber(val)) {\n val = Number(val);\n previousValue = Number(previousValue);\n }\n\n model.props[key] = val;\n model.prevProps[key] = previousValue;\n });\n });\n};\n\n/**\n * Maps a `IConfigBeanModel` to a `ConfigBeanRequest` DTO that can be sent to the\n * server as part of a service request.\n *\n * @remarks\n * This function will perform any type conversion or data mapping required\n * by the `ConfigBeanRequest`.\n *\n * @params model - instance of the `IConfigBeanModel`\n * @returns - a valid `ConfigBeanRequest` that can be used to\n * instantiate a new model.\n *\n * @internal\n * @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 kosAction,\n kosModel,\n KosModelRegistrationFactory,\n kosTopicHandler,\n ObservableData,\n} from \"../../../core\";\nimport type {\n ConfigBeanKeys,\n IConfigBeanModelOptions,\n} from \"./config-bean-types\";\n\nimport { KosLog as Logger } from \"../../../core\";\nimport {\n getConfigBean as getConfigBeanService,\n modifyConfigBean as modifyConfigBeanService,\n type ConfigBeanUpdateResponse,\n type SchemaResponse,\n} from \"../../services/config-bean\";\nimport { ConfigPropertyTypes } from \"../types\";\nimport {\n mapConfigBeanModelToDto,\n mapDtoToConfigBeanModel,\n mapUpdateDtoToConfigBeanModel,\n} from \"./config-bean-model-builder\";\n\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\");\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 /**\n * @category Constructor\n *\n * @param modelId - the unique modelId for this Config Bean\n * @param options - any options that should be merged into the Config Bean\n * @params options.id - the unique id of the Config Bean\n * @params options.name - the name of the Config Bean\n *\n */\n constructor(modelId: string, options: IConfigBeanModelOptions) {\n Object.assign(this, options);\n\n // assign the id from the passed in model id\n this.id = modelId;\n this.path = options.path;\n this.serviceBasePath = options.serviceBasePath;\n // assign private methods from options\n const {\n modifyConfigBean = modifyConfigBeanService,\n getConfigBean = getConfigBeanService,\n } = options;\n this._modifyConfigBean = modifyConfigBean;\n this._getConfigBean = getConfigBean;\n\n this.props =\n ObservableData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>();\n this.prevProps =\n ObservableData<Record<ConfigBeanKeys<T>, ConfigPropertyTypes>>();\n }\n\n /**\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(this.path, this.serviceBasePath);\n if (response?.data) {\n const data = response.data;\n mapDtoToConfigBeanModel(data, this as IConfigBeanModel<T>);\n log.debug(this.values);\n const schemaResponse = response?.data.details[0].schema;\n kosAction(() => {\n if (schemaResponse) {\n this._schema = schemaResponse;\n }\n });\n }\n }\n\n /**\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(this.path, request, this.serviceBasePath);\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 })\n handleConfigBeanUpdated(configBean: ConfigBeanUpdateResponse) {\n mapUpdateDtoToConfigBeanModel(configBean, this as IConfigBeanModel<T>);\n }\n}\n\nexport const ConfigBean = new KosModelRegistrationFactory<\n IConfigBeanModel,\n IConfigBeanModelOptions\n>({\n class: ConfigBeanModelImpl<any>,\n type: CONFIG_BEAN_MODEL_TYPE,\n});\n","/* eslint-disable no-param-reassign */\nimport { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { ConfigBean } from \"../models/config-bean\";\n\ninterface KosConfigParams {\n path: string;\n lazy?: boolean;\n serviceBasePath?: string;\n}\n\nexport const kosConfigBean =\n ({ path, lazy, serviceBasePath }: KosConfigParams) =>\n (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: ConfigBean.type,\n id: `${ConfigBean.type}-${path}`,\n options: {\n path,\n serviceBasePath,\n },\n lifecycle: DependencyLifecycle.INIT,\n lazy,\n };\n };\n","/**\n * @internal\n */\nimport { ServiceFactory, resolveServiceUrl } from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"REGION_INFO_SERVICE\");\nconst { getOne, getAll } = ServiceFactory.build({\n basePath: `${URL}/api/kos/regions/info`,\n});\n\nexport interface DateFormat {\n id: string;\n format: string;\n order: string;\n}\nexport interface TimeFormat {\n id: string;\n format: string;\n ampm: boolean;\n}\nexport interface Unit {\n measure: string;\n name: string;\n scale: number;\n offset: number;\n decimals: number;\n alias: string;\n def: boolean;\n}\nexport interface UnitSystem {\n id: string;\n units: Unit[];\n}\nexport interface RegionInfoResponse {\n unitSystems: UnitSystem[];\n timeFormats: TimeFormat[];\n dateFormats: DateFormat[];\n}\n\nexport interface BaseRegionResponse {\n id: string;\n country: string;\n timeFormatId: string;\n dateFormatId: string;\n unitSystemId: string;\n timeZones: string[];\n hidden: boolean;\n}\nexport type RegionsResponse<\n AdditionalData extends BaseRegionResponse = BaseRegionResponse\n> = BaseRegionResponse & {\n [key in keyof AdditionalData]: AdditionalData[key];\n};\n/**\n * @category Service\n * @internal\n * Retrieves the initial Region Info data.\n */\nexport const getRegionInfo = async () => {\n try {\n const response = await getOne<RegionInfoResponse>({});\n return response;\n } catch (error) {\n return undefined;\n }\n};\n\nexport const getRegions = async () => {\n try {\n const response = await getAll<RegionsResponse>({\n urlOverride: `${URL}/api/kos/regions`,\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 * @group KOS Model\n * @category Region Info\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// Can be a string or the literal 'default'.\nexport type MeasureMapKeys = string | \"default\";\n\n// Record mapping MeasureMapKeys to Unit, defining units for each measurement system.\nexport type SystemMeasureMap = Record<MeasureMapKeys, Unit>;\n\n// Record mapping measurement types to their respective SystemMeasureMap.\nexport type MeasureMap = Record<string, SystemMeasureMap>;\n\n// Record mapping strings, typically used for default settings.\nexport type SystemDefaultMap = Record<string, string>;\n\n// Record mapping unit systems to their default settings.\nexport type DefaultMeasureMap = Record<string, SystemDefaultMap>;\n\n/**\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 * @group KOS Model\n * @category Region Info\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface RegionInfoOptions {}\n\n// Base interface for options requiring an id.\ninterface BaseOptions {\n id: string; // Unique identifier\n}\n\n// Interface extending BaseOptions with a format property.\ninterface FormatOptions extends BaseOptions {\n format: string; // Format specifier (e.g., date or time format)\n}\n\n/**\n * 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 * @group KOS Model\n * @category Region Info\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 * @group KOS Model\n * @category Region Info\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 * @group KOS Model\n * @category Region Info\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 * @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 */\nexport interface RegionInfoModel<\n AdditionalData extends BaseRegionResponse = BaseRegionResponse\n> extends RegionInfoOptions,\n IKosDataModel {\n /** Unique identifier for the region model instance. */\n readonly id: string;\n\n /** The default unit system (e.g., metric or imperial) for the region. */\n readonly defaultUnitSystem: string;\n\n /** The currently selected unit system. */\n readonly selectedUnitSystem: string;\n\n /** The currently selected time format as a string. */\n readonly selectedTimeFormat: string;\n\n /** The currently selected date format as a string. */\n readonly selectedDateFormat: string;\n\n /** The order of date elements (e.g., day/month/year) for the selected format. */\n readonly selectedDateOrder: string;\n\n /** The currently selected country. */\n readonly selectedCountry: string;\n\n /** The currently selected time zone. */\n readonly selectedTimeZone: string;\n\n /**\n * The detailed information of the selected region, extended with additional data.\n * The type of additional data is determined by the generic parameter `AdditionalData`.\n */\n selectedRegion: RegionsResponse<AdditionalData>;\n\n /** Flag indicating if the 12-hour time format (AM/PM) is used. */\n is12HourTimeFormat: boolean;\n\n /** An array of available regions as strings. */\n availableRegions: string[];\n\n /** Identifier of the region. */\n regionId: string;\n\n readonly dateFormatId: string;\n readonly timeFormatId: string;\n readonly unitSystemId: string;\n\n /** An array of available time zones as strings. */\n timeZones: string[];\n\n /** An array of all available time zones as strings. */\n allTimeZones: string[];\n\n /** Time format options available for selection. */\n readonly timeFormatOptions: TimeFormatOptions[];\n\n /** Date format options available for selection. */\n readonly dateFormatOptions: DateFormatOptions[];\n\n /** Unit system options available for selection. */\n readonly unitSystemOptions: UnitSystemOptions[];\n\n /**\n * Converts a value from one unit to another.\n *\n * @param value - The numerical value to convert.\n * @param from - The unit source to convert from.\n * @param to - The unit source to convert to.\n * @returns The converted value as a string.\n * @internal\n */\n convert(value: number, from: UnitSource, to: UnitSource): string;\n\n /**\n * Sets the selected time format.\n *\n * @param id - The identifier of the time format to select.\n */\n setSelectedTimeFormat(id: string): void;\n\n /**\n * Sets the selected date format.\n *\n * @param id - The identifier of the date format to select.\n */\n setSelectedDateFormat(id: string): void;\n\n /**\n * Sets the selected unit system.\n *\n * @param id - The identifier of the unit system to select.\n */\n setSelectedUnitSystem(id: string): void;\n\n /**\n * Retrieves the default unit for a given measure in a specified unit system.\n *\n * @param measure - The measure for which to get the default unit.\n * @param unitSystem - The unit system in which to find the default unit.\n * @returns The default unit for the specified measure and system.\n */\n getDefaultUnitForMeasure(measure: string, unitSystem: string): string;\n\n /**\n * Retrieves the measure associated with a given unit.\n *\n * @param unit - The unit for which to get the measure.\n * @returns The measure associated with the specified unit.\n *\n * @internal\n */\n getUnitMeasure: (unit: string) => string;\n\n /**\n *\n * @internal\n */\n getUnitSystem: (unit?: string) => string;\n\n /**\n * Retrieves the default number of decimal places for a unit in a given measure and system.\n *\n * @param measure - The measure to consider.\n * @param unitSystem - The unit system in which the unit is defined.\n * @param unit - Optional specific unit to consider.\n * @returns The number of decimal places for the unit.\n */\n getDefaultUnitDecimalPlaces(\n measure: string,\n unitSystem: string,\n unit?: string\n ): number;\n}\n\n// Enum for keys used in UnitTuple.\nexport enum UnitTupleKeys {\n family,\n scale,\n offset,\n decimals,\n alias,\n system,\n}\n\n// Tuple type for unit properties: family, scale, offset, decimals, alias.\nexport type UnitTuple = [\n family: string, // Unit family (e.g., length, volume)\n scale: number, // Scale factor for unit conversion\n offset: number, // Offset for unit conversion\n decimals: number, // Number of decimal places for precision\n alias: string, // Alternative name or alias for the unit\n system: string // Measurement system (e.g., metric, imperial)\n];\n","import { UnitTuple } from \"../types\";\nconst timeTuples = {\n s: [\"time\", 1, 0, 0],\n second: [\"time\", 1, 0, 0],\n m: [\"time\", 1 / 60, 0, 0],\n minute: [\"time\", 1 / 60, 0, 0],\n h: [\"time\", 1 / 3600, 0, 0],\n hour: [\"time\", 1 / 3600, 0, 0],\n day: [\"time\", 1 / 86400, 0, 0],\n week: [\"time\", 1 / 604800, 0, 0],\n month: [\"time\", 1 / 2628000, 0, 0],\n year: [\"time\", 1 / 31536000, 0, 0],\n default: [\"time\", 1 / 0.001, 0, 0],\n ms: [\"time\", 1 / 0.001, 0, 0],\n millisecond: [\"time\", 1 / 0.001, 0, 0],\n microsecond: [\"time\", 1 / 0.000001, 0, 0],\n nanosecond: [\"time\", 1 / 0.000000001, 0, 0],\n picosecond: [\"time\", 1 / 0.000000000001, 0, 0],\n};\nexport function unitSystemMapReducer(acc, unitSystem) {\n const system = unitSystem.id;\n const units = unitSystem.units.reduce(\n (acc, unit) => {\n const unitTuple: UnitTuple = [\n unit.measure,\n unit.scale,\n unit.offset,\n unit.decimals,\n unit.alias,\n system,\n ];\n acc[unit.name] = unitTuple;\n if (unit.alias) {\n acc[unit.alias] = unitTuple;\n }\n return acc;\n },\n {\n ...timeTuples,\n }\n );\n\n return { ...acc, ...units };\n}\n\nexport function measureMapReducer(systemAcc, unitSystem) {\n const system = unitSystem.id;\n\n const measures = unitSystem.units.reduce(\n (acc, unit) => {\n const measure = acc[unit.measure] || {};\n\n const systemMeasure = measure[system] || {};\n measure[system] = systemMeasure;\n\n const unitTuple: UnitTuple = [\n unit.measure,\n unit.scale,\n unit.offset,\n unit.decimals,\n unit.alias,\n system,\n ];\n systemMeasure[unit.name] = unitTuple;\n if (Object.hasOwn(unit, \"default\")) {\n Object.defineProperty(systemMeasure, \"default\", {\n value: unitTuple,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n acc[unit.measure] = measure;\n if (unit.alias) {\n acc[unit.alias] = measure;\n }\n return acc;\n },\n {\n time: {\n [system]: {\n ...timeTuples,\n },\n },\n }\n );\n Object.keys(measures).forEach((measure) => {\n systemAcc[measure] = {\n ...systemAcc[measure],\n ...measures[measure],\n };\n });\n\n return systemAcc;\n}\n\nexport function defaultMeasureMapReducer(systemAcc, unitSystem) {\n const system = unitSystem.id;\n\n const measures = unitSystem.units.reduce(\n (acc, unit) => {\n const measure = acc[unit.measure] || {};\n\n if (Object.hasOwn(unit, \"default\")) {\n measure[system] = unit.name;\n }\n acc[unit.measure] = measure;\n return acc;\n },\n {\n time: {\n [system]: \"millisecond\",\n },\n }\n );\n Object.keys(measures).forEach((measure) => {\n systemAcc[measure] = {\n ...systemAcc[measure],\n ...measures[measure],\n };\n });\n\n return systemAcc;\n}\n","import { Kos, KosLog, kosModel } from \"../../../core\";\nimport { kosConfigBean } from \"../../decorators/kos-config-bean\";\n\nimport type { IConfigBeanModel } from \"../config-bean/config-bean-model\";\nimport {\n BaseRegionResponse,\n DateFormat,\n getRegionInfo,\n getRegions,\n RegionsResponse,\n TimeFormat,\n} from \"./services\";\nimport {\n DateFormatOptions,\n DefaultMeasureMap,\n MeasureMap,\n RegionInfoModel,\n RegionInfoOptions,\n TimeFormatOptions,\n UnitSource,\n UnitSystemOptions,\n UnitTuple,\n UnitTupleKeys,\n} from \"./types\";\nimport {\n defaultMeasureMapReducer,\n measureMapReducer,\n unitSystemMapReducer,\n} from \"./utils/unit-system-utils\";\n\ninterface RegionSettingsService {\n unitSystemId: string;\n timeFormatId: string;\n dateFormatId: string;\n country: string;\n timeZone: string;\n}\n\ninterface RegionService {\n regionId: string;\n}\n\ntype RegionSettingsConfigBean = IConfigBeanModel<RegionSettingsService>;\n\ntype RegionConfigBean = IConfigBeanModel<RegionService>;\n\nconst MODEL_TYPE = \"region-info-model\";\n\nconst log = KosLog.createLogger({ name: \"region-info-model\" });\n\n/**\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 private regionMap: Record<string, RegionsResponse<AdditionalData>>;\n private timeFormats: Record<string, TimeFormat>;\n private dateFormats: Record<string, DateFormat>;\n private unitSystems: Record<string, UnitSystemOptions>;\n @kosConfigBean({ path: \"kos:service:region:settings\" })\n regionSource!: RegionSettingsConfigBean;\n\n @kosConfigBean({ path: \"kos:service:region\" })\n private region!: RegionConfigBean;\n\n private regions: string[] = [];\n private timeZoneMap: Record<string, string[]> = {};\n\n constructor(modelId: string) {\n this.id = modelId;\n\n this.unitSystems = {};\n this.unitSystemMap = {};\n this.measureMap = {};\n this.defaultMeasureMap = {};\n\n this.timeFormats = {};\n this.regions = [];\n this.dateFormats = {};\n this.timeZoneMap = {};\n this.regionMap = {};\n }\n\n get availableRegions() {\n return this.regions;\n }\n get defaultUnitSystem() {\n return String(this.regionSource.props[\"unitSystemId\"]).toLowerCase() || \"\";\n }\n\n get unitSystemId() {\n return this.defaultUnitSystem;\n }\n\n get timeFormatId() {\n const _timeFormatId = this.regionSource.props[\"timeFormatId\"];\n if (!_timeFormatId) {\n return \"\";\n }\n const selectedTimeFormatId = String(_timeFormatId);\n\n const resolvedTimeFormatId = this.timeFormats[selectedTimeFormatId];\n return resolvedTimeFormatId ? String(resolvedTimeFormatId.id) : \"\";\n }\n\n get selectedTimeFormat() {\n const selectedTimeFormatId = this.timeFormatId;\n return selectedTimeFormatId\n ? String(this.timeFormats[selectedTimeFormatId].format)\n : \"HH:mm:ss\";\n }\n\n get is12HourTimeFormat() {\n const selectedTimeFormatId = this.timeFormatId;\n return selectedTimeFormatId\n ? this.timeFormats[selectedTimeFormatId].ampm\n : true;\n }\n\n get dateFormatId() {\n const _dateFormatId = this.regionSource.props[\"dateFormatId\"];\n if (!_dateFormatId) {\n return \"\";\n }\n const selectedDateFormatId = String(_dateFormatId);\n return selectedDateFormatId\n ? this.dateFormats[selectedDateFormatId].id\n : \"\";\n }\n\n get selectedDateFormat() {\n const selectedDateFormatId = this.dateFormatId;\n return selectedDateFormatId\n ? this.dateFormats[selectedDateFormatId].format\n : \"\";\n }\n\n get selectedDateOrder() {\n const selectedDateFormatId = this.dateFormatId;\n\n return selectedDateFormatId\n ? this.dateFormats[selectedDateFormatId].order.toLowerCase()\n : \"dmy\";\n }\n\n get selectedCountry() {\n return (this.regionSource.props[\"country\"] as string) || \"en\";\n }\n\n get selectedTimeZone() {\n return (this.regionSource.props[\"timeZone\"] as string) || \"\";\n }\n\n get timeZones() {\n return this.regionId ? this.timeZoneMap[this.regionId] || [] : [];\n }\n\n get allTimeZones() {\n // const allTimeZones = Object.values(this.timeZoneMap).flat();\n const allTimeZones = Intl.supportedValuesOf(\"timeZone\");\n\n return allTimeZones;\n }\n\n get regionId() {\n return (this.region.props[\"regionId\"] as string) || \"\";\n }\n\n get selectedRegion() {\n return this.regionMap[this.regionId];\n }\n\n get selectedUnitSystem() {\n return String(this.regionSource.props[\"unitSystemId\"]) || \"\";\n }\n\n get timeFormatOptions() {\n return Object.keys(this.timeFormats).map<TimeFormatOptions>((key) => {\n return {\n id: key,\n format: this.timeFormats[key].format,\n ampm: this.timeFormats[key].ampm,\n };\n });\n }\n\n get dateFormatOptions() {\n return Object.keys(this.dateFormats).map<DateFormatOptions>((key) => {\n return {\n id: key,\n format: this.dateFormats[key].format,\n order: this.dateFormats[key].order,\n };\n });\n }\n\n get unitSystemOptions() {\n return Object.keys(this.unitSystems).map<UnitSystemOptions>((key) => {\n return {\n id: key,\n name: key,\n };\n });\n }\n\n setSelectedTimeFormat(timeFormatId: string) {\n if (!this.timeFormatOptions.find((option) => option.id === timeFormatId)) {\n throw Error(\n `Invalid time format id. Must be one of ${this.timeFormatOptions\n .map((option) => option.id)\n .join(\", \")}`\n );\n }\n this.regionSource.updateProperty(\"timeFormatId\", timeFormatId);\n }\n\n setSelectedDateFormat(dateFormatId: string) {\n if (!this.dateFormatOptions.find((option) => option.id === dateFormatId)) {\n throw Error(\n `Invalid date format id. Must be one of ${this.dateFormatOptions\n .map((option) => option.id)\n .join(\", \")}`\n );\n }\n this.regionSource.updateProperty(\"dateFormatId\", dateFormatId);\n }\n\n setSelectedUnitSystem(unitSystemId: string) {\n if (!this.unitSystemOptions.find((option) => option.id === unitSystemId)) {\n throw Error(\n `Invalid date format id. Must be one of ${this.unitSystemOptions\n .map((option) => option.id)\n .join(\", \")}`\n );\n }\n this.regionSource.updateProperty(\"unitSystemId\", unitSystemId);\n }\n\n getUnitSystem(_unit?: string) {\n if (!_unit) {\n return this.defaultUnitSystem;\n }\n const unit = _unit === \"drt\" ? \"second\" : _unit;\n const unitTuple = this.unitSystemMap[unit];\n if (!unitTuple) {\n throw Error(\n `No unit found with name: ${unit}. Unit should be one of ${Object.keys(\n this.unitSystemMap\n ).join(\", \")}`\n );\n }\n return unitTuple[UnitTupleKeys.system];\n }\n getUnitMeasure(_unit: string) {\n const unit = _unit === \"drt\" ? \"second\" : _unit;\n const unitTuple = this.unitSystemMap[unit];\n if (!unitTuple) {\n throw Error(\n `No unit found with name: ${unit}. Unit should be one of ${Object.keys(\n this.unitSystemMap\n ).join(\", \")}`\n );\n }\n return unitTuple[UnitTupleKeys.family];\n }\n\n /**\n *@internal\n */\n getDefaultUnitDecimalPlaces(\n measure: string,\n unitSystem: string,\n _unit?: string\n ) {\n if (!measure || !unitSystem) {\n throw Error(\"Measure and unit system are required\");\n }\n const unit = _unit === \"drt\" ? \"second\" : _unit;\n const measureUnitSystems = this.measureMap[measure];\n if (!measureUnitSystems) {\n throw Error(\n `No unit systems found for measure: ${measure}. Measure should come from list of measures: ${Object.keys(\n this.measureMap\n ).join(\", \")}`\n );\n }\n\n const unitSystemUnits = measureUnitSystems[unitSystem.toLowerCase()];\n if (!unitSystemUnits) {\n throw Error(\n `No unit system found for measure: ${measure} and unit system: ${unitSystem}. Unit system should come form list of unit systems: ${Object.keys(\n measureUnitSystems\n ).join(\", \")}`\n );\n }\n\n const defaultUnit = unitSystemUnits[unit || \"default\"];\n if (!defaultUnit) {\n throw Error(\n `No unit \"${\n unit || \"default\"\n }\" found for measure: ${measure} and unit system: ${unitSystem}. Unit should come from list of units: ${Object.keys(\n unitSystemUnits\n ).join(\", \")}`\n );\n }\n return defaultUnit[UnitTupleKeys.decimals];\n }\n\n /**\n *@internal\n */\n getDefaultUnitForMeasure(measure: string, unitSystem: string) {\n if (!measure || !unitSystem) {\n throw Error(\"Measure and unit system are required\");\n }\n\n const measureUnitSystems = this.defaultMeasureMap[measure];\n if (!measureUnitSystems) {\n throw Error(\n `No unit systems found for measure: ${measure}. Measure should come from list of measures: ${Object.keys(\n this.measureMap\n ).join(\", \")}`\n );\n }\n\n const unitSystemUnits = measureUnitSystems[unitSystem.toLowerCase()];\n if (!unitSystemUnits) {\n throw Error(\n `No unit system found for measure: ${measure} and unit system: ${unitSystem}. Unit system should come form list of unit systems: ${Object.keys(\n measureUnitSystems\n ).join(\", \")}`\n );\n }\n return unitSystemUnits;\n }\n\n /**\n *@internal\n */\n\n convertByUnit(value: number, fromUnit: UnitTuple, toUnit: UnitTuple) {\n if (fromUnit[UnitTupleKeys.family] !== toUnit[UnitTupleKeys.family]) {\n throw new Error(\n `Cannot convert between units of different families: ${\n fromUnit[UnitTupleKeys.family]\n } and ${toUnit[UnitTupleKeys.family]}`\n );\n }\n\n const fromOffset = fromUnit[UnitTupleKeys.offset] as number;\n const fromScale = fromUnit[UnitTupleKeys.scale] as number;\n const toScale = toUnit[UnitTupleKeys.scale] as number;\n const toOffset = toUnit[UnitTupleKeys.offset] as number;\n const decimals = toUnit[UnitTupleKeys.decimals] as number;\n const convertedValue =\n (value - fromOffset) / (fromScale / toScale) + toOffset;\n\n return convertedValue.toFixed(decimals);\n }\n\n /**\n *@internal\n */\n convertByUnitName(value: number, from: string, to: string) {\n const fromUnit = this.unitSystemMap[from];\n const toUnit = this.unitSystemMap[to];\n if (!fromUnit || !toUnit) {\n throw new Error(\n `No unit found with name: ${from} or ${to}. Unit should be one of ${Object.keys(\n this.unitSystemMap\n ).join(\", \")}`\n );\n }\n return this.convertByUnit(value, fromUnit, toUnit);\n }\n\n /**\n * @internal\n */\n convert(value: number, from: UnitSource, to: UnitSource) {\n if (from.unit && to.unit) {\n return this.convertByUnitName(value, from.unit, to.unit);\n }\n\n const fromName = from.unit || \"\";\n const toName = to.unit || \"\";\n let fromUnit = this.unitSystemMap[fromName];\n let toUnit = this.unitSystemMap[toName];\n if (!toUnit && to.measure && to.system) {\n const measureSystems = this.measureMap[to.measure];\n if (!measureSystems) {\n throw Error(\n `Could not find measure ${\n to.measure\n }. Measure should be one of ${Object.keys(this.measureMap).join(\n \", \"\n )}`\n );\n }\n toUnit = measureSystems[to.system]?.[\"default\"];\n if (!toUnit) {\n log.info(\"Could not find default unit for measure\", to.measure);\n }\n }\n\n if (!fromUnit && from.measure && from.system) {\n const measureSystems = this.measureMap[from.measure];\n if (!measureSystems) {\n throw Error(\n `Could not find measure ${\n to.measure\n }. Measure should be one of ${Object.keys(this.measureMap).join(\n \", \"\n )}`\n );\n }\n fromUnit = measureSystems[from.system]?.[\"default\"];\n if (!fromUnit) {\n log.info(\"Could not find default unit for measure\", from.measure);\n }\n }\n\n if (!fromUnit || !toUnit) {\n log.warn(\"Could not find unit to convert to or from. Return value as is\");\n return String(value);\n }\n\n return this.convertByUnit(value, fromUnit, toUnit);\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * @internal\n */\n async init(): Promise<void> {\n log.debug(\"initializing region info\");\n }\n\n /**\n * @internal\n */\n async load(): Promise<void> {\n log.debug(\"loading region info\");\n\n const regions = await getRegions();\n if (regions) {\n this.regions = regions.data.map((region) => region.id);\n this.timeZoneMap = regions.data.reduce((acc, region) => {\n return { ...acc, [region.id]: region.timeZones };\n }, this.timeZoneMap);\n this.regionMap = regions.data.reduce((acc, region) => {\n return { ...acc, [region.id]: region };\n }, {});\n }\n\n const regionInfo = await getRegionInfo();\n if (regionInfo) {\n this.unitSystems = regionInfo.data.unitSystems.reduce((acc, curr) => {\n const unitSystem = {\n id: curr.id,\n name: curr.id,\n };\n acc[curr.id] = unitSystem;\n return acc;\n }, this.unitSystems);\n this.unitSystemMap = regionInfo.data.unitSystems.reduce(\n unitSystemMapReducer,\n {}\n );\n\n this.measureMap = regionInfo.data.unitSystems.reduce(\n measureMapReducer,\n {}\n );\n\n this.defaultMeasureMap = regionInfo.data.unitSystems.reduce(\n defaultMeasureMapReducer,\n {}\n );\n\n this.timeFormats = regionInfo.data.timeFormats.reduce(\n (acc, timeFormat) => {\n return { ...acc, [timeFormat.id]: timeFormat };\n },\n {}\n );\n\n this.dateFormats = regionInfo.data.dateFormats.reduce(\n (acc, dateFormat) => {\n return { ...acc, [dateFormat.id]: dateFormat };\n },\n {}\n );\n }\n }\n\n /**\n * @internal\n */\n async ready(): Promise<void> {\n await this.regionSource.ready?.();\n }\n}\n\nconst Registration = {\n registration: {\n [MODEL_TYPE]: {\n class: RegionInfoModelImpl,\n singleton: true,\n },\n },\n type: MODEL_TYPE,\n factory: Kos.Singleton.create<RegionInfoModel, RegionInfoOptions>(MODEL_TYPE),\n};\nexport default Registration;\n","import { getKosModelSync, isKosModelReady } from \"../../core\";\nimport { RegionInfo } from \"../models/region-info\";\nimport { RegionInfoModel, UnitSource } from \"../models/region-info/types\";\n\nexport type UnitConversionSource = string | UnitSource;\n\ninterface CreateUnitSourceProps {\n source: UnitConversionSource;\n defaultSystem?: string;\n defaultMeasure?: string;\n}\nconst createUnitSource = ({\n source,\n defaultSystem = \"si\",\n defaultMeasure,\n}: CreateUnitSourceProps) => {\n let unit: UnitSource = { system: defaultSystem, measure: defaultMeasure };\n if (typeof source === \"string\") {\n unit = { ...unit, unit: source };\n } else {\n unit = { ...unit, ...source };\n }\n\n return unit;\n};\n\n/**\n * Region-aware unit conversion utility that can be used to convert between units of measure.\n *\n * When converting between units of measure, the source and target unit can be specified as a string or as a {@see UnitSource} object.\n * @example\n * in the simplest case, the source and target units can be specified as strings so long as they belong to the same measure (volume, length etc):\n *\n * ```typescript\n * import { convert } from \"@kosdev-code/kos-ui-sdk\";\n *\n * const value = convert(1000, \"milliliter\", \"fluid-ounce\");\n * ```\n *\n * The to unit can be omitted in which case the value will be converted to the default unit for the selected region measure:\n * @example\n * ```typescript\n * import { convert } from \"@kosdev-code/kos-ui-sdk\";\n *\n * // convert 1000 milliliters to the default unit for the region. If the region is set to US, the value will be converted to fluid ounces.\n * const value = convert(1000, \"milliliter\");\n * ```\n *\n * The source and target units can also be specified as {@see UnitSource} objects:\n * @example\n * ```typescript\n * import { convert } from \"@kosdev-code/kos-ui-sdk\";\n *\n * const value = convert(1000, {name: \"milliliter\", measure: \"volume\", system: \"si\"}, {name: \"fluid-ounce\", measure: \"volume\", system: \"us\"});\n * ```\n * In this case properties on the source and target are all optional so long as either the name or measure is specified.\n *\n * @param value - the value to convert\n * @param from - the source unit\n * @param to - the target unit. If omitted, the value will be converted to the default unit for the region measure.\n * @returns the converted value\n */\nexport const convert = (\n value: number,\n from: UnitConversionSource,\n to?: UnitConversionSource\n) => {\n const { model: regionInfo } = getKosModelSync<RegionInfoModel>(\n RegionInfo.type\n );\n if (!regionInfo) {\n throw new Error(\"RegionInfo model not found\");\n }\n\n if (!isKosModelReady(regionInfo)) {\n throw new Error(\"RegionInfo model not ready\");\n }\n const defaultToSource = { system: regionInfo.defaultUnitSystem };\n const fromUnit: UnitSource = createUnitSource({ source: from });\n\n const toUnit: UnitSource = createUnitSource({\n source: to || defaultToSource,\n defaultMeasure: regionInfo.getUnitMeasure(fromUnit.unit || \"\"),\n });\n\n return regionInfo.convert(value, fromUnit, toUnit);\n};\n\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 * @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 { kosConfigBean } from \"../../decorators/kos-config-bean\";\nimport type { UnitConverter } from \"../../decorators/kos-config-bean-prop\";\n\nimport { format } from \"date-fns\";\nimport {\n hasDecimals,\n type EnumSchemaNode,\n type SchemaNodeDef,\n} from \"../../services/config-bean\";\n\nimport type { IConfigBeanModel } from \"../config-bean/config-bean-model\";\nimport { RegionInfo, type RegionInfoModel } from \"../region-info\";\nimport type { UnitSource } from \"../region-info/types\";\nimport type { ConfigPropertyTypes } from \"../types\";\nimport {\n configOptionsFactory,\n displayOptionsFactory,\n} from \"./config-options-factory\";\nimport type {\n ConfigBeanPropOptions,\n ConfigPropConverter,\n FormatOptions,\n KosConfigProperty,\n OptionsExpander,\n OptionsType,\n} from \"./types\";\n\nfunction isEnum(schema?: SchemaNodeDef): schema is EnumSchemaNode {\n return schema?.type === \"enum\";\n}\n\nfunction convertFormats(format: string) {\n switch (format) {\n case \"s\":\n return \"second\";\n case \"ms\":\n return \"millisecond\";\n case \"min\":\n return \"minute\";\n case \"h\":\n return \"hour\";\n case \"d\":\n return \"day\";\n case \"w\":\n return \"week\";\n case \"m\":\n return \"month\";\n case \"y\":\n return \"year\";\n case \"ml\":\n return \"milliliter\";\n default:\n return format;\n }\n}\n\nfunction secondsToFormattedTime(\n secondsSinceMidnight: number,\n formatString: string\n): string {\n // Create a reference to the start of the day (midnight)\n const midnight = new Date();\n midnight.setHours(0, 0, 0, 0);\n\n // Add the seconds to the midnight time\n const time = new Date(midnight.getTime() + secondsSinceMidnight * 1000);\n\n return format(time, formatString);\n}\n\nconst MODEL_TYPE = \"config-bean-prop-model\";\nconst log = KosLog.createLogger({ name: \"config-bean-prop-model\" });\nconst PATH_PROP = createPropKey<KosConfigProperty>(\"path\");\n\nconst SERVICE_PATH_PROP = createPropKey<KosConfigProperty>(\"serviceBasePath\");\n\n/**\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 @kosDependency({ modelType: RegionInfo.type })\n regionInfo!: RegionInfoModel;\n\n @kosConfigBean({ path: PATH_PROP, serviceBasePath: SERVICE_PATH_PROP })\n bean!: IConfigBeanModel;\n\n constructor(modelId: string, options: ConfigBeanPropOptions) {\n this.id = modelId;\n this.path = options.path;\n this.attribute = options.attribute;\n this.converter = options.converter;\n this.formatter = options.formatter;\n this.serviceBasePath = options.serviceBasePath;\n this.optionsExpander = options.optionsExpander;\n }\n\n // -------------------LIFECYCLE----------------------------\n\n /**\n * For cases where the default unit system is used, this method will return\n * the number of decimal places to use for the given measure.\n * @param measure the measure to get the default decimal places for\n * @param unitSystem the unit system to use\n * @returns the number of decimal places to use for the given measure\n * @throws Error if measure is not provided\n **/\n getDefaultUnitDecimalPlaces(\n measure: string,\n unitSystem: string,\n unit?: string\n ) {\n if (!measure) {\n throw new Error(\"measure is required\");\n }\n\n if (!unitSystem) {\n throw new Error(\"unitSystem is required\");\n }\n\n const displayDecimals = hasDecimals(this.displayOptions)\n ? this.displayOptions.decimals\n : this.regionInfo.getDefaultUnitDecimalPlaces(measure, unitSystem, unit);\n return displayDecimals;\n }\n\n /**\n * For cases where the default unit system is used, this method will return\n * the default unit for the given measure.\n * @param measure the measure to get the default unit for\n * @param unitSystem the unit system to use\n * @returns the default unit for the given measure\n * @throws Error if measure is not provided\n * @throws Error if unitSystem is not provided\n * @throws Error if the default unit for the given measure is not found\n **/\n getDefaultUnitForMeasure(measure: string, unitSystem: string) {\n if (!measure) {\n throw new Error(\"measure is required\");\n }\n\n if (!unitSystem) {\n throw new Error(\"unitSystem is required\");\n }\n return this.regionInfo.getDefaultUnitForMeasure(measure, unitSystem);\n }\n\n /**\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 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 const unit = _unit === \"drt\" ? \"second\" : _unit;\n if (this.converter) {\n const globalMeasure = this.converter?.measure;\n const toMeasure = this.converter?.to?.measure;\n const fromMeasure = this.converter?.from?.measure;\n const _measure = globalMeasure || toMeasure || fromMeasure || measure;\n\n const toUnit =\n this.converter?.to?.unit ||\n this.regionInfo.getDefaultUnitForMeasure(\n _measure!,\n this.converter?.to?.system ?? this.regionInfo.defaultUnitSystem\n );\n const toSystem =\n this.converter?.to?.system ?? this.regionInfo.getUnitSystem(toUnit);\n\n const fromUnit =\n this.schemaFormat === \"drt\" ? \"second\" : this.schemaFormat || unit;\n return {\n ...this.converter,\n from: {\n unit: fromUnit,\n ...this.converter.from,\n },\n\n to: {\n ...this.converter.to,\n unit: toUnit,\n system: toSystem,\n },\n measure: _measure,\n };\n }\n\n if (unit && measure) {\n const toUnit = this.regionInfo.getDefaultUnitForMeasure(\n measure,\n this.regionInfo.defaultUnitSystem\n );\n const fromSystem = this.regionInfo.getUnitSystem(unit);\n const toSystem = this.regionInfo.getUnitSystem(toUnit);\n\n const isSameSystem = fromSystem === toSystem;\n return {\n measure,\n to: {\n unit: isSameSystem ? unit : toUnit,\n },\n };\n }\n return undefined;\n }\n /**\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 converter?: {\n measure?: string;\n from?: UnitConverter | string;\n to?: UnitConverter | string;\n };\n}\n\nexport function kosConfigProperty(params: KosConfigParams) {\n const {\n path,\n attribute,\n converter,\n formatter,\n lazy,\n optionsExpander,\n serviceBasePath,\n } = params;\n const _converter = converter;\n if (_converter) {\n if (\n typeof _converter !== \"function\" &&\n typeof _converter.from === \"string\"\n ) {\n _converter.from = { unit: _converter.from };\n }\n\n if (typeof _converter !== \"function\" && typeof _converter.to === \"string\") {\n _converter.to = { unit: _converter.to };\n }\n }\n return (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: KosConfigPropertySpec.type,\n id: `${path}-${attribute}`,\n options: {\n path,\n attribute,\n serviceBasePath,\n converter: _converter,\n formatter,\n optionsExpander,\n },\n\n lifecycle: DependencyLifecycle.INIT,\n lazy,\n };\n };\n}\n","import { modelFactory } from \"../../../core\";\n\nimport type { IFutureModel, IFutureModelOptions } from \"./future-types\";\n\nexport const FUTURE_MODEL_TYPE = \"future-model\";\nexport const FutureFactory = modelFactory<IFutureModel, IFutureModelOptions>(\n FUTURE_MODEL_TYPE\n);\n","import { KosLog, resolveServiceUrl, ServiceFactory } from \"../../../core\";\n\nconst log = KosLog.createLogger({ name: \"future-service\", group: \"Services\" });\n\nconst { isMock, URL } = resolveServiceUrl(\"FUTURE_SERVICE\");\n\n/**\n * @category Service Module\n * @name /services/future\n * @version 1.0.0\n * @author Matthew Holman <maholman@coca-cola.com>\n *\n * Services that can be invoked to perform operations on Futures\n */\n\n/**\n * The possible endState codes returned by a Future\n */\nexport enum FutureEndState {\n Success = \"SUCCESS\",\n Fail = \"FAIL\",\n Aborted = \"ABORT\",\n Canceled = \"CANCEL\",\n}\n\n/**\n * The response from the server when an organization is\n * created or updated\n */\nexport interface FutureResponse {\n tracker?: string;\n /** the id of the Future */\n id: string;\n /** the remaining time of the Future */\n remainingTimeMs?: number;\n /** the progress of the Future */\n progress?: number;\n /** the end state of the Future */\n endState?: FutureEndState;\n /** the reason for a failure */\n reason?: string;\n /** object containing client data */\n clientData?: Record<string, unknown>;\n /** object containing reason data */\n reasonData?:\n | {\n name: string;\n version: string;\n }\n | {\n vmId: string;\n target: string;\n }\n | {\n vmId: string;\n target: string;\n }[];\n /** object containing client data */\n note?: string;\n}\n\nexport interface FutureRequest {\n /** the id of the Future to create */\n id: string;\n}\n\nconst { getAll, modifyModel, addModel, deleteModel, postModel } =\n ServiceFactory.build({\n destinationAddress: \"\",\n basePath: `${URL}/api/future`,\n mock: isMock,\n });\n\n// ------------------SERVICES----------------------\n\n/**\n * @category Service\n * Retrieves the list of Futures.\n */\nexport const getFutures = async () => {\n const response = await getAll<FutureResponse>({});\n return response;\n};\n\n/**\n * Removes an Future based on the id.\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the `/future/delete` event channel.\n *\n * @param futureId - the id of the future to be deleted\n * @returns an empty response with status 200.\n */\nexport const deleteFuture = async (id: string, path = \"/api/kos/future\") => {\n log.info(`sending delete request for Future: ${id}`);\n const response = await deleteModel({\n id,\n urlOverride: `${URL}${path}/${id}`,\n });\n return response;\n};\n\n/**\n * Adds a new Future.\n *\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the `/future/add` event channel.\n *\n * @param organization - the organization to be added\n * @returns an empty response with status 200.\n * @internal\n */\nexport const addFuture = async (\n future: FutureRequest,\n path = \"/api/kos/future\"\n) => {\n log.info(`sending add request for Future`);\n const response = await addModel({\n model: future,\n urlOverride: `${URL}${path}`,\n });\n return response;\n};\n\n/**\n * Modifies an Future from the server based on the id.\n *\n * While the immediate response to the request is empty, and additions will be broadcast\n * to all interested listeners on the `/future/update` event channel.\n *\n * @param id - the id of the Future to be modified\n * @returns an empty response with status 200.\n */\nexport const modifyFuture = async (\n id: string,\n model: FutureRequest,\n path = \"/api/kos/future\"\n) => {\n log.info(`sending modify request for Future: ${id}`);\n const response = modifyModel({\n model,\n id,\n urlOverride: `${URL}${path}/${id}`,\n });\n return response;\n};\n\n/**\n * Cancels a Future from the server based on the id.\n *\n * @param id - the id of the Future to be modified\n * @returns an empty response with status 200.\n */\nexport const cancelFuture = async (id: string, path = \"/api/kos/future\") => {\n log.info(`sending cancel request for Future: ${id}`);\n const response = postModel({\n urlOverride: `${URL}${path}/${id}/cancel`,\n ordered: true,\n model: {},\n });\n return response;\n};\n","import { runInAction } from \"mobx\";\nimport { KosLog, ModelFactory, kosAction, pipe } from \"../../../core\";\nimport type { FutureResponse } from \"../../services/future\";\nimport type { IFutureModel, IFutureModelOptions } from \"./future-types\";\n\n/**\n * Maps a `FutureResponse` DTO to an `IFutureModelOptions` object.\n *\n * @remarks\n * This function will perform any type conversion or data mapping required\n * by the IKosDataModel. For example, date conversion or changes in interfaces\n * can be managed at this layer rather than having the models deal with the\n * various versions of the interface directly.\n *\n * @params dto - the Data Transfer Object received from the backend\n * @returns - a valid `IFutureModelOptions` that can be used to\n * instantiate a new model.\n * @internal\n * @category future\n */\nexport const mapDtoToFutureOptions = (dto: FutureResponse) => {\n const options: IFutureModelOptions = {\n id: String(dto.id),\n progress: dto.progress,\n remainingTimeMs: dto.remainingTimeMs,\n endState: dto.endState,\n reason: dto.reason,\n clientData: dto.clientData,\n reasonData: dto.reasonData,\n note: dto.note,\n tracker: dto.tracker,\n };\n\n return options;\n};\n\n/**\n * Maps a `FutureResponse` DTO to an `IFutureModel` object.\n *\n * @remarks\n * This function will run as a mobx action ensuring that all observers are notified\n * if any changes are made.\n *\n * @params dto - the Data Transfer Object received from the backend\n * @params model - the IModel to be update\n * @internal\n * @category future\n */\nexport const mapDtoToFutureModel = (\n dto: FutureResponse,\n model: IFutureModel\n) => {\n KosLog.debug(`future dto ${dto.id} end state ${dto.endState}`);\n KosLog.debug(`future model ${model.id} end state ${model.endState}`);\n if (!model.endState) {\n KosLog.debug(`updating future model ${model.id}`);\n // This just maps to the new options and auto updates the model with the props\n runInAction(() => {\n const options = mapDtoToFutureOptions(dto);\n\n kosAction(() => {\n Object.keys(options).forEach((prop) => {\n if (prop === \"id\") {\n model[\"futureId\"] = options[\"id\"];\n if (!options[\"tracker\"]) {\n model.id = options[\"id\"];\n }\n } else if (prop === \"tracker\") {\n model.id = options[\"tracker\"]!;\n } else {\n // checked if the model is already in an if (!model.endState) {\n model[prop] = options[prop];\n }\n });\n });\n });\n } else {\n KosLog.debug(`future model ${model.id} is already complete`);\n }\n};\n\n/**\n * Curried function that will produce a function that can be used to retrieve or create\n * new instances of a `IFutureModel` given an ID and options.\n *\n * @remarks\n * This serves as a convenience allowing for models to consumers to use a shorthand method when\n * multiple models need to be created.\n * The first level of function will accept a KOS Model Factory and return a function that can accept a single\n * model ID parameter. This will return a factory function that can accept a model options parameter and\n * instantiate a new instance of a model or retrieve a an existing model.\n *\n * @param factory - the model factory to be used\n * @returns - an instance of the `IFutureModel` that was either created\n * or retrieved from the KOS Model framework if already existing.\n *\n * @internal\n * @category future\n */\nexport const buildFutureModel =\n (factory: ModelFactory<IFutureModel, IFutureModelOptions>) =>\n (modelId: string) =>\n (futureOptions: IFutureModelOptions) => {\n const futureModel = factory.build(String(modelId), futureOptions);\n return futureModel;\n };\n\n/**\n * Factory function that simplifies the creation of a new model\n *\n * @remarks\n * This method will map the response object to an `IFutureModelOptions` instance and\n * construct a new instance of a model using the provided factory. This will provide a shorthand\n * for consumers when creating instances of models and allows for additional operations to be performed\n * as part of the creation process.\n *\n * @example\n * // create a new (potentially static) instance of the factory that can be used throughout the code.\n * const buildFutureModel = buildFuture((FutureModel.Factory));\n *\n * // use the builder to create a new instance of the model from an options instance.\n * const future: IFutureResponse = someFunctionToGetResponseFromServer();\n * const futureModel = buildFutureModel(future);\n *\n * @param factory - The model factory that can be used to\n *\n * @internal\n * @category future\n */\nexport const buildFuture =\n (factory: ModelFactory<IFutureModel, IFutureModelOptions>) =>\n (future: FutureResponse) =>\n pipe(\n mapDtoToFutureOptions,\n buildFutureModel(factory)(future.tracker || future.id)\n )(future);\n","/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */\nimport {\n KosLog,\n destroyKosModel,\n kosModel,\n kosTopicHandler,\n kosWhen,\n type KosContextLogger,\n type KosCreationContext,\n} from \"../../../core\";\nimport {\n FutureEndState,\n cancelFuture,\n cancelFuture as cancelFutureService,\n type FutureResponse,\n} from \"../../services/future\";\nimport { mapDtoToFutureModel } from \"./future-model-builder\";\nimport type { IFutureModel, IFutureModelOptions } from \"./future-types\";\n\nimport { KOS_MODEL_ID } from \"../../../common\";\nimport { FUTURE_NOT_ASSIGNED } from \"../../constants\";\nimport { FutureFactory } from \"./future-factory\";\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\ninterface FutureModel extends IFutureModel {}\ntype TimeUnits = \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\";\nconst log = KosLog.getLogger(FutureFactory.type);\n\n/**\n * @category future\n * @name FutureModel\n * @version 1.0.0\n * @author Matthew Holman <maholman@coca-cola.com>\n *\n * Represents a future.\n */\n@kosModel(FutureFactory.type)\nclass FutureModel implements IFutureModel {\n private logger: KosContextLogger;\n private _cancelFuture: (\n id: string,\n path?: string\n ) => ReturnType<typeof cancelFutureService>;\n futureId: string;\n /**\n * @category Constructor\n *\n * @param modelId - the unique modelId for this Future\n * @param options - any options that should be merged into the Future\n * @params options.id - the unique id of the Future\n * @params options.name - the name of the Future\n *\n */\n constructor(\n modelId: string,\n options: IFutureModelOptions,\n context: KosCreationContext\n ) {\n Object.assign(this, options);\n\n this.logger = context.logger;\n // assign the id from the passed in model id\n this.id = modelId;\n this.futureId = options.id;\n this.namespace = options.namespace || \"kos\";\n // assign private methods from options\n\n this._cancelFuture = cancelFuture;\n\n kosWhen(\n () =>\n this.status === FutureEndState.Success ||\n this.status === FutureEndState.Fail,\n () => {\n log.info(`Future ${this.id} has completed with status ${this.status}`);\n destroyKosModel(this);\n }\n );\n }\n\n /**\n * @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 await this._cancelFuture(this.futureId, path);\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","import {\n createClient,\n type AvailableMethods,\n type ClientResponse,\n} from \"../../core\";\nimport type { paths } from \"./types\";\n\nexport const api = createClient<paths>();\n\nexport type BaseResponseType<\n K extends keyof paths,\n M extends AvailableMethods<paths[K]>\n> = ClientResponse<paths, K, M>;\n","import {\n BrowserKosRouter,\n type IKosDataModel,\n type IKosIdentifiable,\n type KosContextLogger,\n type KosCreationContext,\n type KosMethodTypes,\n type KosMiddleware,\n kosModel,\n type KosRequest,\n type KosResponse,\n kosTopicHandler,\n type PublicModelInterface,\n sendKosHttpMessageResponse,\n} from \"../../../core\";\n\nimport type { BrowserRouterOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"browser-router-model\";\n\nconst HTTP_REQUEST_TOPIC = \"kos.http.request\";\nconst HTTP_RESPONSE_TOPIC = \"kos.http.response\";\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 };\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","import { modelFactory } from \"../../../core\";\n\nimport type {\n IFutureContainerModel,\n IFutureContainerModelOptions,\n} from \"./future-container-types\";\n\nexport const FUTURE_CONTAINER_MODEL_TYPE = \"future-container-model\";\nexport const FutureContainerFactory = modelFactory<\n IFutureContainerModel,\n IFutureContainerModelOptions\n>(FUTURE_CONTAINER_MODEL_TYPE);\n","import type { IFutureModel } from \"../../models/future/future-types\";\nimport { FutureFactory } from \"../../models/future/future-factory\";\nimport { buildFuture } from \"../../models/future/future-model-builder\";\nimport { FutureResponse } from \"../../services/future\";\nimport { FutureContainerFactory } from \"../../models/future-container/future-container-factory\";\n\nconst buildFutureModel = (payload: FutureResponse): IFutureModel => {\n /**\n * Handle all plumbing for creating a new Future.\n */\n const buildFutureModelFactory = buildFuture(FutureFactory);\n const newFutureModel = buildFutureModelFactory(payload);\n return newFutureModel;\n\n /** Callback where once an event comes it, we can immediately create the Future\n * and push it into the container.\n */\n /** Initiate Future - call the 'buildFuture' and then add it to the container */\n};\n\nconst initiateFuture = (payload: FutureResponse) => {\n const futureModel = buildFutureModel(payload);\n\n // get the Future container to add a model\n const futureContainer = FutureContainerFactory.build(\n FutureContainerFactory.type,\n {}\n );\n\n futureContainer.addFutureModel(futureModel);\n return futureModel;\n};\n\nconst getFuture = <T extends {}>(id: string) => {\n const futureContainer = FutureContainerFactory.build(\n FutureContainerFactory.type,\n {}\n );\n\n return futureContainer.getFuture(String(id)) as IFutureModel<T>;\n};\n\nexport const FutureManager = {\n buildFutureModel,\n initiateFuture,\n getFuture,\n};\n","/**\n * @internal\n */\nimport {\n KosContextLogger,\n KosLog,\n KosModelContainer,\n kosChild,\n kosModel,\n kosTopicHandler,\n type IKosModelContainer,\n type KosCreationContext,\n type KosServiceResponse,\n} from \"../../../core\";\nimport type { FutureRequest, FutureResponse } from \"../../services/future\";\n\nimport { EventBus, type ApiCallback } from \"../../../common\";\nimport {\n addFuture as addFutureService,\n deleteFuture as deleteFutureService,\n} from \"../../services/future\";\nimport { FutureManager } from \"../../utils/future-manager\";\nimport type { IFutureModel } from \"../future\";\nimport { buildFuture } from \"../future\";\nimport { FutureFactory } from \"../future/future-factory\";\nimport { FutureContainerFactory } from \"./future-container-factory\";\nimport type {\n IFutureContainerModel,\n IFutureContainerModelOptions,\n} from \"./future-container-types\";\nconst log = KosLog.getLogger(FutureContainerFactory.type);\n\n/**\n * @category future\n * @name FutureContainerModel\n * @version 1.0.0\n * @author Matthew Holman <maholman@coca-cola.com>\n * @internal\n * Represents a list of Future\n */\n@kosModel(FutureContainerFactory.type)\nclass FutureContainerModel implements IFutureContainerModel {\n id: string;\n private logger: KosContextLogger;\n private _deleteFuture: (\n groupId: string\n ) => Promise<KosServiceResponse<unknown> | undefined>;\n private _addFuture: (\n future: FutureRequest\n ) => Promise<KosServiceResponse<any> | undefined>;\n\n @kosChild\n private _futures: IKosModelContainer<IFutureModel>;\n createModel: <T = void>(request: FutureRequest) => Promise<T>;\n deleteModel: (id: string) => Promise<void>;\n\n constructor(\n modelId: string,\n options: IFutureContainerModelOptions,\n context: KosCreationContext\n ) {\n const { deleteFuture = deleteFutureService, addFuture = addFutureService } =\n options;\n this.logger = context.logger;\n this._deleteFuture = deleteFuture;\n this._addFuture = addFuture;\n this.id = modelId;\n this._futures = new KosModelContainer();\n this.createModel = this.createFuture;\n this.deleteModel = this.removeFuture;\n }\n\n /**\n * @category Computed\n * @getter\n * Computed value that will recalculate automatically whenever Futures\n * are added or removed from the map.\n *\n * @returns the list of Futures\n *\n * @internal\n */\n get futures() {\n return this._futures.data;\n }\n\n get models() {\n return this.futures;\n }\n\n /**\n * Convenience function that will retrieve the IFutureModel based on\n * the id.\n *\n * @param futureId - the id of the future to be retrieved\n * @returns the `IFutureModel` or `undefined` if not available in the list\n * @internal\n */\n getFuture(futureId: string) {\n return this._futures.getModel(futureId);\n }\n\n /**\n * @category Action\n * Internally adds the provided Future to the map\n *\n * @param group - The Future model to add\n * @internal\n */\n addFutureModel(model: IFutureModel) {\n this._futures.addModel(model);\n }\n\n /**\n * @category Action\n * Internally adds the provided Future to the map\n *\n * @param group - The Future model to add\n * @internal\n */\n removeFutureModel(id: string) {\n this._futures.removeModel(id);\n }\n\n /**\n * This is the entry point which enables an this model to be “visited” by a visitor object.\n *\n * @remarks\n * Futures as part of a KOS Model Visitor pattern allowing clients\n * to traverse the KOS Model hierarchy and perform operations on elements\n * as they are \"visited\".\n *\n * Ths method serves as an entry point for visitors allowing them to dispatch\n * actions on elements in a collection without requiring the models to have\n * explicit knowledge of the operation being performed.\n *\n * @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\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} from \"./kos-expression-evaluator-model\";\nexport type * from \"./types\";\n\nexport const KosExpressionEvaluator =\n KosExpressionEvaluatorModelImpl.Registration;\n","import {\n createClient,\n type PathsByMethod,\n type ClientResponse,\n} from \"../../core/util/kos-service-request\";\nimport { paths } from \"./openapi\";\n\nconst api = createClient<paths>();\n\nexport type KosApi = paths;\nexport type ApiPath = keyof paths;\nexport type ValidPaths = PathsByMethod<paths>;\n\nexport type GetPaths = ValidPaths[\"get\"];\nexport type PostPaths = ValidPaths[\"post\"];\nexport type PutPaths = ValidPaths[\"put\"];\nexport type DeletePaths = ValidPaths[\"delete\"];\n\nexport type ApiResponse<\n Path extends ApiPath,\n Method extends \"get\" | \"post\" | \"put\" | \"delete\" = \"get\"\n> = ClientResponse<KosApi, Path, Method>;\n\nexport default api;\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 const loggers = this.resolveLoggers();\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 KosLog,\n ServiceFactory,\n resolveServiceUrl,\n type KosServiceResponse,\n} from \"../../../../core\";\nconst { URL } = resolveServiceUrl(\"KOS-TIME_SERVICE\");\nconst { postModel, getOne } = ServiceFactory.build({\n basePath: `${URL}/api/kos-time`,\n});\n\ninterface TimeBean {\n hour: number;\n min: number;\n sec: number;\n}\n\ninterface DateBean {\n month: number;\n day: number;\n year: number;\n}\n\ninterface TimezoneResponse {\n timeZone: string;\n}\n\nconst log = KosLog.createLogger({\n name: \"kos-time-service\",\n group: \"Services\",\n});\ninterface KosTimeResponse {\n id: string;\n}\n\nexport const setTime = async (time: TimeBean) => {\n const response: KosServiceResponse<any> | undefined =\n await postModel<TimeBean>({\n model: time,\n urlOverride: `${URL}/api/kos/time/time`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set time\");\n }\n\n return response.data;\n};\n\nexport const setDate = async (date: DateBean) => {\n const response: KosServiceResponse<any> | undefined =\n await postModel<DateBean>({\n model: date,\n urlOverride: `${URL}/api/kos/time/date`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set time\");\n }\n\n return response.data;\n};\n\nexport const setTimezone = async (timezone: string) => {\n const response: KosServiceResponse<any> | undefined = await postModel({\n model: {},\n urlOverride: `${URL}/api/kos/time/timezone?tz=${timezone}`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set timezone\");\n }\n\n return response.data;\n};\n\nexport const getTimezone = async () => {\n const response: KosServiceResponse<TimezoneResponse> | undefined =\n await getOne<TimezoneResponse>({\n urlOverride: `${URL}/api/kos/time/timezone`,\n });\n if (response?.status !== 200) {\n throw Error(\"Failed to set timezone\");\n }\n\n return response.data.timeZone;\n};\n","import { EventBus } from \"../../../common\";\nimport type {\n IKosDataModel,\n IKosModelLogger,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosModel, kosTopicHandler } from \"../../../core\";\nimport { Topics } from \"../../constants\";\nimport { getTimezone, setDate, setTime, setTimezone } from \"./services\";\nimport { type DateBean, type KosTimeOptions, type TimeBean } from \"./types\";\nexport const MODEL_TYPE = \"kos-time-model\";\n\nconst TOPIC_TIME_CHANGE = \"/kos/time/time\";\nconst TOPIC_DAY_CHANGE = \"/kos/time/day\";\nconst TOPIC_TIMEZONE_CHANGE = \"/kos/time/timezone\";\n\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 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 {\n getQueryParams,\n KosLog,\n type ClientResponse,\n type DeepRequired,\n type ElementType,\n type ServiceResponse,\n} from \"../../../../core\";\n\nimport API, { type ApiPath, type KosApi } from \"../../../utils/service\";\nimport type { LogLinesType } from \"../../log-block\";\n\nconst log = KosLog.createLogger({\n name: \"log-stream-container-service\",\n group: \"Services\",\n});\n\nexport const getKosConnectionId = (): string | undefined => {\n const params = getQueryParams();\n const connId = (params as any)?.connId;\n const result = connId || (window as any)?.kosBridge?.(\"connId\");\n\n KosLog.error(`getKosConnectionId: ${result}`);\n\n return result;\n};\n\nconst destinationAddress = getKosConnectionId();\n\nconst SERVICE_PATH: ApiPath = \"/api/kos/logs/node/{nodeId}/streams\";\nexport type LogStreamContainerClientResponse = ClientResponse<\n KosApi,\n typeof SERVICE_PATH,\n \"get\"\n>;\nexport type LogStreamContainerResponse = DeepRequired<\n ElementType<LogStreamContainerClientResponse>\n>;\n\n/**\n * @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 log.debug(\"sending GET for log-stream-container\");\n return await API.get(\n SERVICE_PATH,\n {\n path: {\n nodeId: \"primary\",\n },\n },\n {\n destinationAddress,\n }\n );\n};\n\nexport const subscribeToLogStream = async (\n stream: string,\n nodeId = \"primary\"\n): Promise<void> => {\n const repsonse = await API.post(\n \"/api/kos/logs/node/{nodeId}/{stream}/subscribe\",\n {\n path: {\n nodeId: nodeId,\n stream,\n },\n },\n undefined,\n {\n destinationAddress,\n }\n );\n};\n\nexport const unsubscribeFromLogStream = async (\n stream: string\n): Promise<void> => {\n const repsonse = await API.post(\n \"/api/kos/logs/node/{nodeId}/{stream}/unsubscribe\",\n { path: { nodeId: \"primary\", stream } },\n undefined,\n {\n destinationAddress,\n }\n );\n};\n\nexport const createOverride = async (): Promise<void> => {\n const repsonse = await API.post(\n \"/api/kos/logs/overrides\",\n {},\n {\n level: \"WARN\",\n name: \"com.example\",\n nodeType: \"java\",\n type: \"package\",\n },\n {\n destinationAddress,\n }\n );\n};\n\nconst SERVICE_BLOCKS_PATH: ApiPath =\n \"/api/kos/logs/node/{nodeId}/{stream}/blocks\";\nexport type LogStreamBlocksClientResponse = ClientResponse<\n KosApi,\n typeof SERVICE_BLOCKS_PATH,\n \"get\"\n>;\n\nexport const getLogStreamBlocks = async (\n stream: string\n): Promise<ServiceResponse<LogStreamBlocksClientResponse>> => {\n const response = await API.get(\n \"/api/kos/logs/node/{nodeId}/{stream}/blocks\",\n {\n path: {\n nodeId: \"primary\",\n stream,\n },\n },\n {\n destinationAddress,\n }\n );\n return response;\n};\n\nexport const getLogStreamBlock = async (\n stream: string,\n blockId: number\n): Promise<ServiceResponse<LogLinesType>> => {\n const response = await API.get(\n \"/api/kos/logs/node/{nodeId}/{stream}/blocks/{blockId}\",\n {\n path: {\n nodeId: \"primary\",\n stream,\n blockId,\n },\n },\n {\n destinationAddress,\n }\n );\n return response as ServiceResponse<LogLinesType>;\n};\n","import { kosModel } from \"../../../core/core/decorators\";\nimport type {\n IKosDataModel,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core/core/kosModel\";\nimport type { IKosIdentifiable } from \"../../../core/core/types\";\nimport type { PublicModelInterface } from \"../../../core/types\";\nimport { getLogStreamBlock } from \"../log-stream/services\";\n\nimport type { LogBlockOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"log-block-model\";\n\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 KosServiceResponse,\n ServiceFactory,\n resolveServiceUrl,\n} from \"../../../../core\";\nimport { FutureEndState, FutureResponse } from \"../../../services/future\";\nimport { FutureManager } from \"../../../utils/future-manager\";\nconst { URL } = resolveServiceUrl(\"TROUBLE_SERVICE\");\nconst { getAll, postModel } = ServiceFactory.build({\n basePath: `${URL}/api/kos/troubles`,\n});\n\nexport interface TroubleResponse {\n reason: string;\n createTime: string;\n resolvable: boolean;\n ifaces: string[];\n id: string;\n clientData: any;\n type: string;\n tags: string[];\n info: any;\n}\n/**\n * @category Service\n * @internal\n * Retrieves the initial Trouble data.\n */\nexport const getTroubles = async (servicePath: string) => {\n const response = await getAll<TroubleResponse>({\n urlOverride: `${URL}${servicePath}`,\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 response: KosServiceResponse<FutureResponse> = (await postModel({\n model: {},\n urlOverride: `${URL}${servicePath}/resolve/${troubleId}`,\n tracker,\n })) as KosServiceResponse<FutureResponse>;\n if (response?.data) {\n FutureManager.initiateFuture(response.data);\n }\n return response.data;\n } catch (error) {\n const futureResponse: FutureResponse = {\n id: tracker || \"\",\n endState: FutureEndState.Fail,\n tracker: tracker,\n reason: \"Failed to resolve trouble\",\n };\n FutureManager.initiateFuture(futureResponse);\n return futureResponse;\n }\n};\n\nexport const bulkResolveTroubles = async (\n troubleIds: string[],\n servicePath = \"/api/kos/troubles\",\n tracker?: string\n) => {\n try {\n const response: KosServiceResponse<FutureResponse> = (await postModel({\n model: troubleIds,\n urlOverride: `${URL}${servicePath}/resolve/`,\n tracker,\n })) as KosServiceResponse<FutureResponse>;\n\n if (response?.data) {\n FutureManager.initiateFuture(response.data);\n }\n return response.data;\n } catch (error) {\n const futureResponse: FutureResponse = {\n id: tracker || \"\",\n endState: FutureEndState.Fail,\n tracker: tracker,\n reason: \"Failed to resolve troubles\",\n };\n FutureManager.initiateFuture(futureResponse);\n return futureResponse;\n }\n};\n","import { KosLog, registerExtensionPoint } from \"../../../../core\";\nimport type { TroubleModel } from \"../types\";\nexport const EXTENSION_TROUBLE_DATA_MAPPER = \"troubleDataMapper\";\nexport type TroubleDataMapper = (\n trouble: TroubleModel\n) => Promise<Record<string, any>>;\nconst troubleMappers = new Map<string, TroubleDataMapper[]>();\nregisterExtensionPoint(EXTENSION_TROUBLE_DATA_MAPPER, {\n register: (id: string, mapper: TroubleDataMapper) => {\n if (!troubleMappers.has(id)) {\n troubleMappers.set(id, []);\n }\n troubleMappers.get(id)?.push(mapper);\n },\n execute: async (id: string, trouble: TroubleModel) => {\n const mapper = troubleMappers.get(id);\n if (!mapper) {\n return {\n ...trouble.data,\n };\n }\n const promises = mapper.map((m) => m(trouble));\n const results = await Promise.allSettled(promises);\n const data = results.reduce(\n (acc, r) => {\n if (r.status === \"fulfilled\") {\n acc = { ...acc, ...r.value };\n } else {\n KosLog.info(`Trouble mapper ${id} failed: ${r.reason}`);\n }\n\n return acc;\n },\n { ...trouble.data }\n );\n\n return data;\n },\n});\n","import { KosLog, registerExtensionPoint } from \"../../../../core\";\nimport type { TroubleModel } from \"../types\";\nexport const EXTENSION_TROUBLE_MAPPER = \"troubleMapper\";\nexport type TroubleMapper = (trouble: TroubleModel) => Promise<string[]>;\nconst troubleMappers = new Map<string, TroubleMapper[]>();\nregisterExtensionPoint(EXTENSION_TROUBLE_MAPPER, {\n register: (id: string, mapper: TroubleMapper) => {\n if (!troubleMappers.has(id)) {\n troubleMappers.set(id, []);\n }\n troubleMappers.get(id)?.push(mapper);\n },\n execute: async (id: string, trouble: TroubleModel) => {\n const mapper = troubleMappers.get(id);\n if (!mapper) {\n return [];\n }\n const promises = mapper.map((m) => m(trouble));\n const results = await Promise.allSettled(promises);\n const paths = results\n\n .map((r) => {\n if (r.status === \"fulfilled\") {\n return r.value;\n } else {\n KosLog.info(`Trouble mapper ${id} failed: ${r.reason}`);\n return [];\n }\n })\n .flat();\n\n return Array.from(new Set(paths));\n },\n});\n","import { ExtensionManager } from \"../../../core\";\nimport type {\n HandleTroubleData,\n NozzleTroubleData,\n TroubleModel,\n} from \"../trouble/types\";\nimport \"../trouble/utils/trouble-data-extension\";\nimport { EXTENSION_TROUBLE_DATA_MAPPER } from \"../trouble/utils/trouble-data-extension\";\nimport \"../trouble/utils/trouble-extension\";\nimport { EXTENSION_TROUBLE_MAPPER } from \"../trouble/utils/trouble-extension\";\n\nExtensionManager[EXTENSION_TROUBLE_MAPPER].register(\n \"nozzle\",\n async (trouble: TroubleModel<NozzleTroubleData>) => [trouble.data.nozzlePath]\n);\n\nExtensionManager[EXTENSION_TROUBLE_MAPPER].register(\n \"path\",\n async (trouble: TroubleModel<HandleTroubleData>) => [trouble.data.path]\n);\n\nexport const troublePathFactory = async (trouble: TroubleModel) => {\n const result = new Set<string>();\n const ifaces = trouble.ifaces;\n\n const promises = ifaces?.map(\n (iface) =>\n ExtensionManager[EXTENSION_TROUBLE_MAPPER].execute(\n iface,\n trouble\n ) as Promise<string[]>\n );\n\n const results = await Promise.allSettled(promises);\n\n results.forEach((r) => {\n if (r.status === \"fulfilled\") {\n (r.value as string[]).forEach((path) => result.add(path));\n }\n });\n\n return Array.from(result);\n};\n\nexport const troubleDataFactory = async (trouble: TroubleModel) => {\n const ifaces = trouble.ifaces;\n\n const promises = ifaces?.map(\n (iface) =>\n ExtensionManager[EXTENSION_TROUBLE_DATA_MAPPER].execute(\n iface,\n trouble\n ) as Promise<Record<string, any>>\n );\n\n const troubleExtension = ExtensionManager[\n EXTENSION_TROUBLE_DATA_MAPPER\n ].execute(trouble.type, trouble) as Promise<Record<string, any>>;\n\n promises.push(troubleExtension);\n\n const results = await Promise.allSettled(promises);\n\n const result = results.reduce((acc, r) => {\n if (r.status === \"fulfilled\") {\n acc = { ...acc, ...r.value };\n }\n return acc;\n }, {});\n\n return { ...trouble.data, ...result };\n};\n","import { TroubleHandler } from \"../../../../core\";\n\nexport class ResolvableTroubleHandler implements TroubleHandler {\n type = \"ResolvableTrouble\";\n title = \"Resolvable Trouble\";\n subtitle = \"Trouble\";\n}\n\nexport class BlockPumpTroubleHandler implements TroubleHandler {\n type = \"BlockPumpTrouble\";\n title = \"Block Pump Trouble\";\n subtitle = \"Trouble\";\n}\n\nexport class TroubleHandlerFactory {\n static getHandler(type: string): TroubleHandler | undefined {\n switch (type) {\n case \"ResolvableTrouble\":\n return new ResolvableTroubleHandler();\n case \"BlockPumpTrouble\":\n return new BlockPumpTroubleHandler();\n default:\n return undefined;\n }\n }\n}\n","import {\n kosModel,\n resolveKosCompanion,\n type IKosModelLogger,\n type KosContextLogger,\n type KosCreationContext,\n} from \"../../../core\";\nimport { kosFuture } from \"../../decorators/future-service\";\nimport { FutureHandler } from \"../future/future-aware\";\nimport type { FutureAwareContainer } from \"../future/future-types\";\nimport { troubleDataFactory } from \"../trouble-container/trouble-utils\";\nimport { TroubleHandlerFactory } from \"./handlers/resolvable-trouble-handler\";\nimport { resolveTrouble } from \"./services\";\nimport type { DeferAware, TroubleModel, TroubleOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"trouble-model\";\n\nfunction isDeferAware(obj: any): obj is DeferAware {\n return typeof obj.shouldDefer === \"boolean\";\n}\n\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 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 ...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.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 kosLoggerAware,\n kosModel,\n kosTopicHandler,\n type IKosDataModel,\n type IKosIdentifiable,\n type KosContainerAwareWithProp,\n type KosLoggerAware,\n type KosModelRegistrationType,\n type PublicModelInterface,\n} from \"../../../core\";\n\nimport { KosCoreModelPropertyMapper } from \"../../constants\";\nimport {\n defaultTroubleColorMapper,\n defaultTroubleRankMapper,\n defaultTroubleRoleMapper,\n} from \"../../utils/trouble-utils\";\nimport { getTroubles, type TroubleResponse } from \"../trouble/services\";\nimport { Trouble } from \"../trouble/trouble-registration\";\nimport type { TroubleModel } from \"../trouble/types\";\nimport { troublePathFactory } from \"./trouble-utils\";\nimport type { TroubleContainerOptions } from \"./types\";\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 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@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\n async load(): Promise<void> {\n this.logger.debug(\"loading trouble container\");\n const _troubles = await getTroubles(this.servicePath);\n try {\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 };\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 @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 };\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 * 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","/**\n * @internal\n */\n// eslint-disable-next-line @nx/enforce-module-boundaries\nimport { FetchError, KosLog, resolveBaseUrl } from \"../../../../core\";\nimport { api, type BaseResponseType } from \"../../../utils\";\nimport { createCancellableService } from \"../../../utils/cancellable-service\";\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 log.debug(\"sending GET for software-info\");\n const [error, response] = await api.get(\"/api/kos/manifest/info\", undefined, {\n signal,\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","/**\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 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: `state-bean-${PATH_PROP}`,\n options: { path: PATH_PROP },\n })\n stateBean!: StateBeanModel;\n\n constructor(\n modelId: string,\n options: StatePropOptions,\n context: KosCreationContext\n ) {\n this.id = modelId;\n this.logger = context.logger;\n this.path = options.path;\n this.attribute = options.attribute;\n if (options) {\n // Assign options properties here.\n }\n }\n\n /** 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","/**\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","export const CONTEXT_LANG_RESOLVER = \"langResolver\";\n","/**\n * @ignore\n * @internal\n */\nimport { IReactionDisposer, reaction } from \"mobx\";\nimport type {\n IKosDataModel,\n IKosIdentifiable,\n KosContext,\n KosContextLogger,\n KosCreationContext,\n} from \"../../../core\";\nimport {\n KosContextManager,\n kosAction,\n kosModel,\n kosParentAware,\n} from \"../../../core\";\nimport 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 (typeof obj[key] === \"object\" && obj[key] !== null) {\n const flattenedChild = flattenObject(obj[key], newKey);\n return { ...acc, ...flattenedChild };\n } else {\n return { ...acc, [newKey]: obj[key] };\n }\n }, {});\n}\nfunction mergeObjects<T extends Record<string, any>>(\n base: T,\n overlay: Partial<T>\n): T {\n const result: any = { ...base };\n\n for (const key in overlay) {\n if (Object.prototype.hasOwnProperty.call(overlay, key)) {\n if (\n typeof overlay[key] === \"object\" &&\n overlay[key] !== null &&\n typeof base[key] === \"object\" &&\n base[key] !== null\n ) {\n result[key] = mergeObjects(base[key], (overlay as any)[key]);\n } else {\n result[key] = overlay[key];\n }\n }\n }\n\n return result;\n}\n\nexport const expandMacros = (text: string, data: Record<string, any>) => {\n const regex = /__(.*?)__/g;\n\n const replacedText = text.replace(\n regex,\n (match, key) =>\n // Use the key to access the corresponding value in the data object\n Object.prototype.hasOwnProperty.call(data || {}, key.trim())\n ? data?.[key.trim()]\n : match // Replace with the value from the data object or keep the original match if no value found\n );\n\n // If the text hasn't changed, return it\n if (replacedText === text) {\n return replacedText;\n }\n if (regex.test(replacedText)) {\n return expandMacros(replacedText, data);\n }\n return replacedText;\n};\n\nexport const replaceText = (\n text: string,\n data: Record<string, any>,\n context?: Record<string, any>\n) => {\n const regex = /{{(.*?)}}/g;\n\n const expandedText = expandMacros(text, data);\n const replacedText = expandedText.replace(\n regex,\n (match, key) =>\n // Use the key to access the corresponding value in the data object\n Object.prototype.hasOwnProperty.call(context || {}, key.trim())\n ? context?.[key.trim()]\n : match // Replace with the value from the data object or keep the original match if no value found\n );\n\n const result = expandMacros(replacedText, data);\n return result;\n};\n\nconst splitKey = (currentNamespace: string, _key: string) => {\n if (_key.includes(\":\")) {\n const [namespace, key] = _key.split(\":\");\n return { namespace, key };\n } else {\n return { namespace: currentNamespace, key: _key };\n }\n};\n@kosParentAware()\n@kosModel(MODEL_TYPE)\nexport class TranslationModelImpl implements IKosDataModel, IKosIdentifiable {\n /** 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 key;\n }\n }\n if (context && this.data[contextKey]) {\n const value = this.data[contextKey];\n if (Array.isArray(value)) {\n return value.map((v) => replaceText(v, this.data, data as any));\n }\n return replaceText(this.data[contextKey], this.data, data as any);\n }\n if (this.data[key]) {\n const value = this.data[contextKey];\n if (Array.isArray(value)) {\n return value.map((v) => replaceText(v, this.data, data as any));\n }\n return replaceText(this.data[key], this.data, data as any);\n }\n\n return defaultValue ?? key;\n }\n\n /**\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 this.disposer = reaction(\n () => this.currentLocale,\n (value, previous) => {\n this.logger.info(\n `translation langs for namespace ${this.id} changed from ${previous} to ${value}`\n );\n this.loadTranslations();\n }\n );\n }\n}\n","import type { KosModelRegistrationBean } from \"../../../core\";\nimport { Kos, isKosModel } from \"../../../core\";\nimport type { TranslationModel } from \"./translation-model\";\nimport { MODEL_TYPE, TranslationModelImpl } from \"./translation-model\";\nimport type { TranslationOptions } from \"./types\";\n\n/**\n * # Translation\n *\n * The registration bean includes convenience methods for creating and working with TranslationModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: Translation.type, id: \"translationId\"})\n * private translationModel: TranslationModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new TranslationModel instances.\n *\n \n * The factory function is a curried function that takes the model id as the first argument and the options as the second argument.\n *\n * If a model with the specified id already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = Translation.factory(\"translationId\")({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a TranslationModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (Translation.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to TranslationModel\n * // and the compiler will know that the model has the TranslationModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { Translation } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...Translation.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The translation model is NOT a singleton model. This means that each time the factory function is called with a unique ID, a new model instance will be created.\n * If the factory function is called with an ID that already exists, the existing model will be returned.\n \n * */\nexport const Translation: Readonly<\n KosModelRegistrationBean<TranslationModel, TranslationOptions>\n> = {\n registration: {\n [MODEL_TYPE]: {\n class: TranslationModelImpl,\n singleton: false,\n },\n },\n type: MODEL_TYPE,\n predicate: isKosModel(MODEL_TYPE),\n factory: Kos.Factory.create<TranslationModel, TranslationOptions>(MODEL_TYPE),\n};\n","/**\n * @internal\n * @ignore\n */\nimport type {\n IKosDataModel,\n IKosIdentifiable,\n IKosModelContainer,\n IKosModelHolder,\n KosContextLogger,\n KosCreationContext,\n ReloadAware,\n} from \"../../../core\";\nimport {\n KosModelContainer,\n kosAction,\n kosChild,\n kosModel,\n 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 } 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 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 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 });\n\n this.addModel(translation);\n return translation;\n } else {\n const firstLocale = Object.keys(\n this.descriptor.namespaces[namespace].locales\n )[0];\n const namespaceDefault =\n this.descriptor.namespaces[namespace].locales[firstLocale]\n .defaultLocale;\n const translation = Translation.factory(\"translation-\" + namespace)({\n kosParentId: this.id,\n namespace,\n rootUrl: this.rootUrl,\n currentLocale: this.lang,\n defaultLocale: namespaceDefault,\n descriptor: this.descriptor.namespaces[namespace].locales,\n resolver: this.resolver,\n });\n\n this.addModel(translation);\n if (!this.namespaces.includes(namespace)) {\n kosAction(() => {\n this.namespaces.push(namespace);\n });\n }\n return translation;\n }\n }\n\n addModel(model: TranslationModel) {\n this._models.addModel(model);\n }\n\n removeModel(id: string) {\n this._models.removeModel(id);\n }\n // -------------------LIFECYCLE----------------------------\n\n /**\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 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 { 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 { 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: boolean = 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(\"timeupdate\", this.handleTimeUpdate.bind(this));\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 (typeof this.loopConfig === \"number\" && this.currentLoopCount < this.loopConfig - 1) {\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 * 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) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, '0');\n return `#${toHex(color.r)}${toHex(color.g)}${toHex(color.b)}`;\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, g = 0, 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, ImageRenderDataSpecification, 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(data: OverlayRenderDataSpecification, rendererFactory: (type: string, data: any) => Renderer) {\n // Create the base renderer\n this.baseRenderer = rendererFactory(data.baseRenderer.type, data.baseRenderer.data);\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 ('onDone' in this.baseRenderer && typeof this.baseRenderer.onDone === 'function') {\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(basePixels, width, height);\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(overlay, canvasWidth, canvasHeight);\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 ('isOneShot' in this.baseRenderer && typeof this.baseRenderer.isOneShot === 'function') {\n return (this.baseRenderer as any).isOneShot();\n }\n return false;\n }\n}","import type {\n DoneAware,\n ImageRenderDataSpecification,\n Renderer,\n} from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { normalizeColor, 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 (this.loopConfig && this.pauseDuration === 0 && this.position > gap) {\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 (this.loopConfig && this.pauseDuration === 0 && xPos - gap - drawWidth > -drawWidth) {\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 (this.loopConfig && this.pauseDuration === 0 && yPos + drawHeight + gap < height) {\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 (this.loopConfig && this.pauseDuration === 0 && yPos - gap - drawHeight > -drawHeight) {\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 case \"right\":\n const xPosRight = -drawWidth + this.position;\n isOffScreen = xPosRight > width + buffer;\n break;\n case \"up\":\n const yPosUp = height - this.position;\n isOffScreen = yPosUp < -drawHeight - buffer;\n break;\n case \"down\":\n const yPosDown = -drawHeight + this.position;\n isOffScreen = yPosDown > height + buffer;\n break;\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 let 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 let 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 case \"right\":\n const xPosRight = -this.textWidth + this.position;\n isOffScreen = xPosRight > width + buffer;\n break;\n case \"up\":\n const yPosUp = height - this.position;\n isOffScreen = yPosUp < -this.textHeight - buffer;\n break;\n case \"down\":\n const yPosDown = -this.textHeight + this.position;\n isOffScreen = yPosDown > height + buffer;\n break;\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 { DoneAware, Renderer, SequenceRenderDataSpecification, RenderSpecification } 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(data: SequenceRenderDataSpecification & { patternStore?: Map<string, RenderSpecification<any>> }) {\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(`Failed to create renderer for pattern \"${patternId}\":`, error);\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 (typeof this.loopConfig === \"number\" && this.currentLoopCount < this.loopConfig - 1) {\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}","import type { OneShotCapable, Renderer, ColorRenderDataSpecification } from \"../../types\";\nimport { Canvas2DRendererBase } from \"./base/canvas-2d-renderer\";\nimport { OneShotRendererMixin } from \"./mixins/one-shot-renderer-mixin\";\nimport { normalizeColor, 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 (data.r !== undefined && data.g !== undefined && data.b !== undefined) {\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 = { ...patternData.data, ...requestData } as RenderDataSpecification<any>;\n \n // If it's a sequence renderer, pass the pattern store\n const rendererData = 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\";\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 log.debug(\"sending GET for copy-logs\");\n\n try {\n const response = await getAll<NetworkInterfaceData>({});\n\n return [undefined, response?.data];\n } catch (error) {\n if (error instanceof FetchError) {\n log.error(`Error fetching log file size: ${error.payload.error}`);\n return [error.payload.error, undefined];\n }\n }\n\n return [\"unknownError\", undefined];\n };\n","import type {\n IKosDataModel,\n IKosIdentifiable,\n IKosModelContainer,\n IKosModelHolder,\n KosContextLogger,\n KosCreationContext,\n PublicModelInterface,\n} from \"../../../core\";\nimport { kosChild, kosModel, KosModelContainer } from \"../../../core\";\nimport type { NetworkInterfaceModel } from \"./network-interface-model\";\nimport { NetworkInterface } from \"./network-interface-registration\";\nimport { getNetworkInterfaces } from \"./services\";\nimport type { NetworkInterfaceContainerOptions } from \"./types\";\n\nexport const MODEL_TYPE = \"network-interface-container-model\";\n\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 // -------------------LIFECYCLE----------------------------\n\n get isUsbInserted(): boolean {\n return this.storageService.isStorageInserted;\n }\n\n get hasAvailableUpdates(): boolean {\n return this._models.data.length > 0;\n }\n\n async syncAvailableUpdates() {\n const updates = await getAvailableUpdates();\n\n kosAction(() => {\n const allKeys = updates.map(\n (update) => `${update.deviceId}-${update.manifestId}`\n );\n\n this._models.data\n .filter((model) => !allKeys.includes(model.id))\n .forEach((model) => this.removeModel(model.id));\n\n updates.forEach((update) => {\n const modelId = `${update.deviceId}-${update.manifestId}`;\n const model = UsbUpdate.instance(modelId)\n .forceUpdate.options({\n ...update,\n createTime: new Date(update.createTime),\n })\n .build();\n\n this.addModel(model);\n });\n\n if (this.data.length === 1) {\n this.updateActiveUpdate(this.data[0]);\n } else {\n this.clearActiveUpdate();\n }\n });\n }\n\n @kosModelEffect({ dependencies: (model) => [model.isUsbInserted] })\n usbInsertedEffect() {\n if (this.isUsbInserted) {\n this.syncAvailableUpdates();\n } else {\n this._models.clear();\n this.clearActiveUpdate();\n }\n }\n\n async init(): Promise<void> {\n this.logger.debug(`initializing usb-update-container container ${this.id}`);\n }\n\n unload(): void {\n this.disposer?.();\n }\n\n async activate(): Promise<void> {\n this.logger.debug(`activating usb-update-container container ${this.id}`);\n\n await this.syncAvailableUpdates();\n }\n\n async load(): Promise<void> {\n this.logger.debug(`loading usb-update-container container ${this.id}`);\n }\n}\n","import { SingletonKosModelRegistrationFactory } from \"../../../core\";\nimport type { UsbUpdateContainerOptions } from \"./types\";\nimport type { UsbUpdateContainerModel } from \"./usb-update-container-model\";\nimport {\n MODEL_TYPE,\n UsbUpdateContainerModelImpl,\n} from \"./usb-update-container-model\";\nimport { UsbUpdate } from \"./usb-update-registration\";\n\n/**\n * # UsbUpdateContainer\n *\n * The registration bean includes convenience methods for creating and working with UsbUpdateContainerModel instances.\n *\n * ## type\n * The type property is a string that identifies the model type.\n * The type is used to identify the model type in the model registry and to narrow down the model type in type predicates. It's most frequently\n * used when declaring dependencies on models.\n *\n * @example\n * ```typescript\n *\n * @kosDependency({modelType: UsbUpdateContainer.type, id: \"usbUpdateContainerId\"})\n * private usbUpdateContainerModel: UsbUpdateContainerModel;\n * ```\n *\n *\n * ## factory\n *\n * The factory method creates a factory function that can be used to create new UsbUpdateContainerModel instances.\n *\n \n * As this is a singleton model, the factory function accepts the model options as its argument.\n *\n * If a model with the same model type already exists, the factory function will return the existing model. The options will be ignored\n * in this case and the existing model will be returned in its current state.\n *\n * @example\n * ```typescript\n * const model = UsbUpdateContainer.factory({\n * // Add option data\n * });\n * ```\n \n\n *\n * ## predicate\n *\n * [Typescript type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function that will identify and narrow down a model to a UsbUpdateContainerModel.\n *\n * @example\n * ```typescript\n *\n * const model: IKosDataModel = ...; // some model\n *\n * if (UsbUpdateContainer.predicate(model)) {\n * // if the function evaluates to true, the model is narrowed down to UsbUpdateContainerModel\n * // and the compiler will know that the model has the UsbUpdateContainerModel interface\n * model.updateAvailability(false);\n * }\n * ```\n *\n * ## registration\n *\n * The registration property is an object that can be used to simplify registration of the model with the model registry. The registration object\n * can be spread into the model registration and provides all of the required information to register the model implementation class against the model type.\n *\n *\n * @example\n *\n * In an application registration file you can declare the model registration as follows:\n *\n * **registration.ts**\n * ```typescript\n * import { UsbUpdateContainer } from \"@kosdev-code/kos-dispense-sdk\";\n * ...\n * import { ExtensionManager, IKosRegistry } from \"@kosdev-code/kos-ui-sdk\";\n * export const kosModels: IKosRegistry[\"models\"] = {\n * ...UsbUpdateContainer.registration,\n * };\n * ```\n *\n * ## registration.singleton\n \n * The usbUpdateContainer model is a singleton model. This means that each time the factory function is called , the same instance will be returned.\n * If the model does not yet exist, it will be created passing in the provided options to initialize it.\n *\n * Singleton models don't require an ID as they will use the model type as their ID to guarantee uniqueness throughout the system.\n \n * */\nexport const UsbUpdateContainer = new SingletonKosModelRegistrationFactory<\n UsbUpdateContainerModel,\n UsbUpdateContainerOptions\n>({\n class: UsbUpdateContainerModelImpl,\n type: MODEL_TYPE,\n});\n\nUsbUpdateContainer.addRelatedModel(UsbUpdate);\n","import { FutureFactory, FutureModel } from \"./models/future\";\nimport {\n FutureContainerFactory,\n FutureContainerModel,\n} from \"./models/future-container\";\nimport { KosTime } from \"./models/kos-time/kos-time-registration\";\nimport { StateBean } from \"./models/state-bean/state-bean-registration\";\nimport { StateProp } from \"./models/state-prop/state-prop-registration\";\n// ------- PREPEND IMPORTS --------\n\nimport { KosConfigPropertySpec } from \"./models/config-bean-prop\";\nimport { RegionInfo } from \"./models/region-info\";\nimport { Translation, TranslationContainer } from \"./models/translation\";\nimport { TroubleContainer } from \"./models/trouble-container\";\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, PRELOAD);\n\n Object.keys(coreModels).forEach((key) => {\n const model = coreModels[key];\n registerLegacyModel(KosModelRegistry)(key, model);\n });\n\n return {\n preload: RegistrationManager.model.preloadModel(root),\n model: RegistrationManager.model.register(root),\n companion: RegistrationManager.companion.register(root),\n legacy: RegistrationManager.model.registerLegacyModel(root),\n };\n };\n\ntype ModelRegistry<R> = {\n core: { models: () => RegistrationResult<R> };\n preload: ReturnType<typeof RegistrationManager.model.preloadModel>;\n model: ReturnType<typeof RegistrationManager.model.register>;\n companion: ReturnType<typeof RegistrationManager.companion.register>;\n};\n\nconst _KosModelRegistry = {};\n\n(_KosModelRegistry as any).core = {\n models: registerCoreModels(_KosModelRegistry),\n};\n(_KosModelRegistry as any).preload =\n RegistrationManager.model.preloadModel(_KosModelRegistry);\n(_KosModelRegistry as any).model =\n RegistrationManager.model.register(_KosModelRegistry);\n(_KosModelRegistry as any).companion =\n RegistrationManager.companion.register(_KosModelRegistry);\n(_KosModelRegistry as any).legacy =\n RegistrationManager.model.registerLegacyModel(_KosModelRegistry);\n\ntype KosModelRegistryType = ModelRegistry<typeof _KosModelRegistry>;\n\nconst KosModelRegistry: KosModelRegistryType = _KosModelRegistry as any;\n\nexport { KosModelRegistry };\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { ExtensionManager, PropertyMapper, type DataLoader } from \"../../core\";\nimport { KosCoreModelPropertyMapper } from \"../constants\";\nimport { CanvasDispatcher } from \"../models/canvas-dispatcher\";\nimport type { TroubleModel } from \"../models/trouble/types\";\n\ntype TroubleRankMapper<AdditionalData extends object = Record<string, any>> =\n PropertyMapper<TroubleModel<AdditionalData>, number, any>;\n\ntype TroubleColorMapper<AdditionalData extends object = Record<string, any>> =\n PropertyMapper<TroubleModel<AdditionalData>, string, any>;\n\ntype TroubleRoleMapper<AdditionalData extends object = Record<string, any>> =\n PropertyMapper<TroubleModel<AdditionalData>, string, any>;\n\nexport class CoreExtensionManager {\n /**\n * Maps the rank property of the trouble into the {@link TroubleModel}\n * */\n registerTroubleRankMapper(troubleRankMapper: TroubleRankMapper) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRank,\n troubleRankMapper\n );\n return this;\n }\n\n /**\n * Maps the role property of the trouble into the {@link TroubleModel}\n * */\n registerTroubleRoleMapper(troubleRoleMapper: TroubleRoleMapper) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleRole,\n troubleRoleMapper\n );\n return this;\n }\n\n /**\n * Maps the color property of the trouble into the {@link TroubleModel}\n * */\n registerTroubleColorMapper(troubleColorMapper: TroubleRoleMapper) {\n ExtensionManager.propertyMapper.registerPropertyMapper(\n KosCoreModelPropertyMapper.TroubleColor,\n troubleColorMapper\n );\n return this;\n }\n\n registerModelLoader(id: string, loader: DataLoader) {\n ExtensionManager.loader.registerLoader(id, loader);\n }\n\n registerCanvasPatternLoader(loader: DataLoader) {\n ExtensionManager.loader.registerLoader(CanvasDispatcher.loader, loader);\n }\n}\n","import { destroyKosModel, whenReady } from \"../../core\";\nimport { KeyValue } from \"../models/key-value\";\n\n/**\n * A persistence store that can be used to store data for a given session id and key\n * The store is namespaced by the stateKey and the sessionId allows for multiple instances\n * of data to be created with the same store using the session id as the discriminator.\n * The store is backed by a {@link KeyValue} model.\n * @public\n * @interface\n */\nexport interface PersistenceStoreAware {\n /** The key value data store */\n store: KosPersistenceStore;\n\n /** The sessionId to be used when multiple instances of a persistence store are required for a given namespace */\n sessionId: string;\n\n /** The stateKey used to namespace the store */\n stateKey: string;\n}\nexport interface KosPersistenceStore {\n /**\n * Update the state of the store for a given key. The session id of the store instance\n * will be used to segregate the data. For example, if the session id is \"my-session\" and the\n * key is \"my-key\", the data will be stored as \"my-session-my-key\". However the session id is not\n * externally visible and is managed by the store.\n *\n * @param key - the key to update\n * @param value - the value to update\n *\n */\n updateState(\n key: string,\n value: string | number | boolean | undefined\n ): Promise<void>;\n\n /**\n * Clean all the data from the store for the given session id\n */\n clean(): void;\n\n /**\n * Retrieve the state of the store for a given key. The session id of the store instance\n * will be used to retrieve the data.\n * @param key - the key to retrieve\n * @returns the value of the key or undefined if the key does not exist\n */\n getState(key: string): string | number | boolean | undefined;\n\n /**\n * Unsubscribe from the store. This will remove the store from the persistence layer\n */\n unsubscribe(): void;\n}\n\n/**\n * Subscribe to a KOS Persistence Store or create a new one\n * The store will be namespaced by the stateKey and the sessionId allows\n * for multiple instances of data to be created with the same store using eh session id\n * as the discriminator.\n *\n * If the sessionId is not provided, the store will be global\n *\n * @param stateKey - the namespace of the given persistence store\n * @param sessionId - the data partition with the namespace that the store will operate within\n * @returns a {@link KosPersistenceStore} instance\n */\nexport const subscribeStore = async (\n stateKey: string,\n sessionId?: string\n): Promise<KosPersistenceStore> => {\n const toolState = KeyValue.instance(stateKey).options({}).build();\n const prefix = sessionId ? `${sessionId}-` : \"\";\n await whenReady(toolState);\n return {\n getState: (key: string) => toolState.data[`${prefix}${key}`],\n updateState: async (\n key: string,\n value: string | number | boolean | undefined\n ) => {\n await toolState.updateState(`${prefix}${key}`, value);\n },\n clean: async () => {\n for (const key of toolState.data.keys) {\n await toolState.updateState(`${prefix}${key}`, undefined);\n }\n },\n unsubscribe: () => {\n destroyKosModel(toolState);\n },\n };\n};\n","import { whenReady } from \"../../core\";\nimport { KosConfigPropertySpec } from \"../models/config-bean-prop\";\n\nconst REGION_PATH = \"kos:service:region\";\nconst REGION_ATTRIBUTE = \"regionId\";\nconst REGION_ID = `${REGION_PATH}-${REGION_ATTRIBUTE}`;\n\nexport const updateRegion = async (region: string) => {\n const regionInfo = KosConfigPropertySpec.factory(REGION_ID)({\n path: REGION_PATH,\n attribute: REGION_ATTRIBUTE,\n });\n await whenReady(regionInfo);\n\n regionInfo.updateProperty(region);\n};\n","/// <reference types=\"@types/node/timers\"/>\n/**\n * @module TimerManager\n * @description\n * The TimerManager module provides functionality for managing timers and executing actions at specific intervals.\n * It includes a `KosTimer` class for individual timers and a set of utility functions to interact with timers.\n *\n * @example\n * // Create a timer with a 60-second timeout and default actions\n * const timer = TimerManager.createTimer(\"myTimer\", 60, [{ name: \"customAction\" }]);\n *\n * // Start the timer\n * TimerManager.startTimer(\"myTimer\");\n *\n * // Add a timeout action to the timer\n * TimerManager.addTimeoutAction(\"myTimer\", { name: \"newAction\", remainingTime: 30 });\n *\n * // Reset the timer\n * TimerManager.resetTimer(\"myTimer\");\n */\n\nimport { EventBus } from \"../../common\";\nimport { KosLog, kosAutoEffect } from \"../../core\";\nimport type { KosConfigProperty } from \"../models\";\n\n/**\n * Event name for timer-related events.\n */\nexport const TIMER_EVENT = `/kos-timer-event`;\n\n/**\n * 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","import {\n FutureService,\n FutureAliases,\n kosAction,\n kosAutoEffect,\n KosLog,\n uuid,\n whenReady,\n type KosServiceResponse,\n} from \"../../core\";\nimport { FUTURE_NOT_ASSIGNED } from \"../constants\";\nimport { mapDtoToFutureModel } from \"../models/future\";\nimport { FutureContainer } from \"../models/future/future-types\";\nimport { FutureResponse } from \"../services\";\nimport { FutureEndState } from \"../services/future\";\nimport { FutureManager } from \"../utils\";\ninterface 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\nconst isFutureResponse = (response: any): response is FutureResponse =>\n !response || !response.data;\ntype FutureHandler = (\n this: FutureContainer,\n ...args: Array<unknown>\n) => Promise<KosServiceResponse<FutureResponse> | undefined>;\nexport function kosFuture(props: FutureProps = {}) {\n const { alias, namespace, abortController = false } = 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\n const handler = async function (\n this: FutureContainer,\n ...args: Array<unknown>\n ): Promise<FutureResponse | undefined> {\n // create a tracker id to track the future\n const tracker = uuid();\n KosLog.debug(\n `Calling future service ${propertyKey} with tracker ${tracker}`\n );\n\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 this.futureHandler.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 // Add tracker as final parameter (preserves existing behavior)\n enhancedArgs.push(tracker);\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 this.futureHandler.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 ${propertyKey} was cancelled`);\n throw cancelledError;\n }\n\n KosLog.error(e);\n throw e;\n }\n };\n\n target[FutureService][propertyKey] = {\n handler,\n };\n };\n}\n","import { DependencyLifecycle, DependencyModels } from \"../../core\";\nimport { StateBean } from \"../models/state-bean\";\n\ninterface KosStateParams {\n path: string;\n}\n\nexport const kosStateBean =\n ({ path }: KosStateParams) =>\n (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: StateBean.type,\n id: `${StateBean.type}-${path}`,\n options: {\n path,\n },\n lifecycle: DependencyLifecycle.INIT,\n };\n };\n","import { DependencyLifecycle, DependencyModels } from \"../../core\";\n\nimport { StateProp } from \"../models/state-prop\";\nimport { StatePropertyTypes } from \"../models/types\";\n\ntype StateKeys<T extends Record<string, StatePropertyTypes>> = keyof T;\n\ninterface KosStateParams<T extends Record<string, StatePropertyTypes> = any> {\n path: string;\n attribute: `${string & StateKeys<T>}`;\n}\n\nexport function kosStateProp<\n T extends Record<string, StatePropertyTypes> = any\n>(params: KosStateParams<T>) {\n const { path, attribute } = params;\n\n return (target: {} | any, name: PropertyKey): any => {\n target[DependencyModels] = target[DependencyModels] || {};\n // eslint-disable-next-line max-len\n target[DependencyModels][name] = {\n modelType: StateProp.type,\n id: `${path}-${attribute}`,\n options: {\n path,\n attribute,\n },\n\n lifecycle: DependencyLifecycle.INIT,\n };\n };\n}\n","import { BASE_URL, kosFetch, KosLog, KosServiceResponse } from \"../../../core\";\n\nconst log = KosLog.createLogger({ name: \"services\", group: \"Services\" });\n\ninterface LoginResponse {\n token: string;\n}\n\n/**\n * Convienience function to provide Studio specific login functions defaulting the url\n * Studio endpoint.\n * @param username - the username of the user to log in\n * @param password - the password of the user to log in\n * @returns a login response with the token of the logged in user\n *\n * @internal\n * @see login\n */\nexport const studioLogin = async (username: string, password: string) =>\n login(username, password, `${BASE_URL}/api/server/login`);\n\n/**\n * Attempts a log in against the specified URL.\n * @param username - the username of the user to log in\n * @param password - the password of the user to log in\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n *\n * @returns a login response with the token of the logged in user\n */\nexport const login = async (\n username: string,\n password: string,\n url = `${BASE_URL}/api/login`\n) => {\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n email: username,\n password,\n }),\n });\n if (!response.ok) {\n const configResponse = await response.json();\n\n throw Error(`${configResponse?.error}`);\n }\n const configResponse: KosServiceResponse<LoginResponse> | null =\n await response.json();\n return configResponse;\n};\n\n/**\n * Convienience function to provide Studio specific password reset functions defaulting the url\n * Studio endpoint.\n * @param username - the userID of the user to start the password reset process.\n * @returns an API response with no value.\n *\n * @see startPasswordReset\n * @internal\n */\nexport const studioStartPasswordReset = async (userId: string) =>\n startPasswordReset(userId, `${BASE_URL}/api/server/startPasswordReset`, \"\");\n\n/**\n * When a user is first created or if the password is forgotten. A user can request\n * a password reset from thier Organization administrator. The administrator will end\n * up calling this function in order to initiate the request and have reset token sent\n * to the user on thier specified e-mail address (or other method.)\n * The token, received by the user, can be used as part of the reset call to provide a new password.\n *\n * @param userId - the user ID of the suer to start the password reset process.\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n * @returns an API response with no value.\n * @internal\n * @see resetPassword\n */\nexport const startPasswordReset = async (\n userId: string,\n url = `${BASE_URL}/api/startPasswordReset`,\n destinationAddress = \"server\"\n) => {\n const response = await kosFetch(`${url}?email=${userId}`, {\n method: `POST`,\n destinationAddress,\n });\n if (!response.ok) {\n throw Error(\n `There was a problem reseting config; returned status ${response.status}`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n\n/**\n * Convienience function to provide Studio specific password reset functions defaulting the url\n * Studio endpoint.\n * @param token - the reset token recieved as part of the `startPasswordReset` process\n * @param password - the new password to be used by the user specified in the token.\n * @returns an API response with no value.\n * @internal\n * @see startPasswordReset\n */\nexport const studioResetPassword = async (token: string, password: string) =>\n resetPassword(token, password, `${BASE_URL}/api/server/resetPassword`);\n\n/**\n * Resets the password for the user.\n *\n * @param token - the reset token recieved as part of the `startPasswordReset` process\n * @param password - the new password to be used by the user specified in the token.\n * @param url - the url to send the login request to.\n * @defaultValue - defaults to the Admin server URL.\n * @returns an API response with no value.\n *\n * @internal\n * @see resetPassword\n */\nexport const resetPassword = async (\n token: string,\n password: string,\n url = `${BASE_URL}/api/resetPassword`\n) => {\n log.debug(\n `resetting password with token ${token} and password ${password.replace(\n /./g,\n \"*\"\n )}`\n );\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n token,\n password,\n }),\n });\n log.debug(`password reset returned status ${response.status}`);\n if (!response.ok) {\n log.error(`password reset failed with message ${response.statusText}`);\n\n const configResponse = await response.json();\n\n throw Error(\n `${configResponse?.error}:There was a problem resetting the password.`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n\nexport const studioAcceptOrgInvitation = async (\n token: string,\n password: string,\n name: string\n) =>\n acceptOrgInvitation(\n token,\n password,\n name,\n `${BASE_URL}/api/server/acceptInvite`\n );\nexport const acceptOrgInvitation = async (\n token: string,\n password: string,\n name: string,\n url = `${BASE_URL}/api/server/acceptInvite`\n) => {\n log.debug(\n `accepting invite with token ${token} and password ${password.replace(\n /./g,\n \"*\"\n )}`\n );\n const response = await kosFetch(`${url}`, {\n method: `POST`,\n destinationAddress: \"\",\n body: JSON.stringify({\n token,\n password,\n name,\n }),\n });\n log.debug(`invitation accept returned status ${response.status}`);\n if (!response.ok) {\n log.error(`invite failed with message ${response.statusText}`);\n\n const configResponse = await response.json();\n\n throw Error(\n `${configResponse?.error}:There was a problem accepting the invite.`\n );\n }\n const configResponse: KosServiceResponse<unknown> | null =\n await response.json();\n return configResponse;\n};\n","import { autorun as kosAutoEffect } from \"mobx\";\n\n/**\n * A Promise that can be cancelled and provides progress/state tracking\n */\nexport interface CancellablePromise<T> extends Promise<T> {\n /**\n * Cancel this specific operation\n */\n cancel(): Promise<void>;\n\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 * Current progress of the operation (0-1)\n */\n readonly progress: number;\n\n /**\n * Current status of the operation\n */\n readonly status: string;\n\n /**\n * Whether the operation is currently running\n */\n readonly isRunning: 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 * 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","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\";\n\nexport interface ErrorBoundaryState {\n error: Error | null;\n errorInfo: ErrorInfo | null;\n}\n\nexport interface ErrorBoundaryProps extends React.PropsWithChildren {\n fallback?: React.ReactNode;\n}\nclass ErrorBoundary extends React.Component<\n ErrorBoundaryProps,\n ErrorBoundaryState\n> {\n constructor(props: ErrorBoundaryProps) {\n super(props);\n this.state = { error: null, errorInfo: null };\n }\n\n override componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n // Catch errors in any components below and re-render with error message\n this.setState({\n error: error,\n errorInfo: errorInfo,\n });\n // You can also log error messages to an error reporting service here\n }\n\n override render() {\n if (this.state.errorInfo) {\n // Error path\n return (\n this.props.fallback || (\n <div>\n <h2>Something went wrong.</h2>\n <details style={{ whiteSpace: `pre-wrap` }}>\n {this.state.error && this.state.error.toString()}\n <br />\n {this.state.errorInfo.componentStack}\n </details>\n </div>\n )\n );\n }\n // Normally, just render children\n return this.props.children;\n }\n}\n\nexport default ErrorBoundary;\n","import { css } from \"@emotion/react\";\ntype Status = \"error\" | \"warn\" | \"normal\";\ninterface Props {\n value: number;\n title?: JSX.Element;\n subtitle?: string;\n status?: Status;\n}\n\nconst statusMap: Record<Status, string> = {\n normal: \"#B5F7F6\",\n warn: \"#F3D78A\",\n error: \"#FC8486\",\n};\nexport const ProgressBar = ({\n value = 0,\n title,\n status = \"normal\",\n subtitle,\n}: Props) => {\n const progressBarContainer = css`\n display: flex;\n flex-direction: column;\n `;\n const progressContainer = css`\n position: relative;\n height: 18px;\n width: 100%;\n background-color: #ddd;\n border-radius: 5px;\n overflow: hidden;\n `;\n\n const titleContainer = css`\n position: absolute;\n top: 50%; /* position the top edge of the element at the middle of the parent */\n left: 50%; /* position the left edge of the element at the middle of the parent */\n z-index: 5;\n transform: translate(-50%, -50%);\n font-size: smaller;\n `;\n\n const progress = css`\n width: ${value}%;\n height: 35px;\n background-color: ${statusMap[status]};\n text-align: center;\n line-height: 32px;\n color: black;\n `;\n\n const indeterminate = css`\n animation: indeterminateAnimation 1s infinite linear;\n transform-origin: 0% 50%;\n @keyframes indeterminateAnimation {\n 0% {\n transform: translateX(0) scaleX(0);\n }\n 40% {\n transform: translateX(0) scaleX(0.4);\n }\n 100% {\n transform: translateX(100%) scaleX(0.5);\n }\n }\n `;\n\n return (\n <div css={progressBarContainer}>\n <div css={progressContainer}>\n <div css={titleContainer}>{title}</div>\n <div css={[progress, value < 0 ? indeterminate : \"\"]}></div>\n </div>\n <div>{subtitle}</div>\n </div>\n );\n};\n","import {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useState,\n} from \"react\";\nimport { IKosDataModel } from \"../../../../core\";\n\ninterface KosModelContextProps {\n model?: IKosDataModel;\n setModel: (model: IKosDataModel) => boolean;\n}\n\nconst defaultProps: KosModelContextProps = {\n setModel: () => false,\n};\n\nexport const KosModelContext =\n createContext<KosModelContextProps>(defaultProps);\n\nexport const useContextModel = <T extends IKosDataModel>(): T | undefined => {\n const context = useContext(KosModelContext);\n if (context == undefined) {\n throw new Error(`useModels must be used within a KosModelProvider`);\n }\n return context.model as T;\n};\n\nexport const KosModelProvider: React.FunctionComponent<PropsWithChildren> = ({\n children,\n}) => {\n const [model, setModel] = useState<IKosDataModel>();\n const setKosModel = useCallback(\n (kosModel: IKosDataModel) => {\n setModel(kosModel);\n return true;\n },\n [setModel]\n );\n return (\n <KosModelContext.Provider value={{ model, setModel: setKosModel }}>\n {children}\n </KosModelContext.Provider>\n );\n};\n","import {\n createContext,\n PropsWithChildren,\n useCallback,\n useContext,\n useMemo,\n useState,\n} from \"react\";\nimport { getKosModelSync, IKosDataModel, KosLog } from \"../../../../core\";\n\ninterface KosNestedModelContextProps {\n models: IKosDataModel[];\n addModel: (model: IKosDataModel) => void;\n}\n\nconst log = KosLog.createLogger({ name: \"kos-model-hierarchy-context\" });\nconst defaultNestedProps: KosNestedModelContextProps = {\n models: [],\n addModel: () => {\n log.debug(\"Default implementation being used. Do Nothing.\");\n },\n};\n\nexport const NestedModelContext =\n createContext<KosNestedModelContextProps>(defaultNestedProps);\n\nexport const KosModelCollectionProvider: React.FunctionComponent<\n PropsWithChildren\n> = ({ children }) => {\n const [models, setModels] = useState<IKosDataModel[]>([]);\n const addModel = useCallback(\n (model: IKosDataModel) => {\n if (!models.includes(model)) {\n log.debug(\"adding to hierarchy context\", model.id);\n setModels((prevModels) => [...prevModels, model]);\n }\n },\n [models]\n );\n return (\n <NestedModelContext.Provider value={{ models, addModel }}>\n {children}\n </NestedModelContext.Provider>\n );\n};\n\ninterface ModelHierarchyProps {\n filter?: (model: IKosDataModel) => boolean;\n}\n\nconst DEFAULT_FILTER = () => true;\nexport const useContextModelHierarchy = (\n props?: ModelHierarchyProps\n): IKosDataModel[] => {\n const context = useContext(NestedModelContext);\n if (!context) {\n throw new Error(\n `useContextModelHierarchy must be used within a KosModelCollectionProvider`\n );\n }\n\n const filter = props?.filter || DEFAULT_FILTER;\n const filteredModels = useMemo(\n () => context.models.filter(filter),\n [context.models, filter]\n );\n return filteredModels;\n};\n\nexport const useModelFromHierarchy = <T extends IKosDataModel = IKosDataModel>(\n type: string\n): T | undefined => {\n const context = useContextModelHierarchy({\n filter: (model) => {\n const _model = getKosModelSync(model.id);\n return _model?.type === type;\n },\n });\n return context[0] as T;\n};\n","import {\n PropsWithChildren,\n Suspense,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport { IKosDataModel, KosLog } from \"../../../core\";\nimport { ErrorBoundaryWithFallback } from \"../error-boundary\";\nimport { ErrorBoundaryProps } from \"../error-boundary/error-boundary\";\nimport {\n KosModelContext,\n KosModelProvider,\n} from \"./contexts/kos-model-context\";\nimport { NestedModelContext } from \"./contexts/kos-model-hierarchy-context\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-loader\" });\nexport interface KosModelLoaderProps {\n model?: IKosDataModel;\n ready: boolean;\n error?: string;\n loading?: React.ReactElement;\n}\n\nconst DefaultLoader = () => <div></div>;\n\nexport const KosModelLoader: React.FunctionComponent<\n PropsWithChildren<ErrorBoundaryProps & KosModelLoaderProps>\n> = ({ fallback, children, ...modelProps }) => (\n <KosModelProvider>\n <ErrorBoundaryWithFallback fallback={fallback}>\n <Suspense>\n <KosModelLoaderDisplay {...modelProps}>\n {children}\n </KosModelLoaderDisplay>\n </Suspense>\n </ErrorBoundaryWithFallback>\n </KosModelProvider>\n);\nexport const KosModelLoaderDisplay: React.FunctionComponent<\n PropsWithChildren<KosModelLoaderProps>\n> = (props) => {\n const [model, setCurrentModel] = useState<IKosDataModel>();\n const [isReady, setIsReady] = useState(false);\n const { setModel } = useContext(KosModelContext);\n const hierarchyContext = useContext(NestedModelContext);\n useEffect(() => {\n if (props.model) {\n setCurrentModel(props.model);\n setModel(props.model);\n setIsReady(true);\n if (hierarchyContext) {\n hierarchyContext.addModel(props.model);\n }\n }\n }, [hierarchyContext, props.model, setModel]);\n\n if (props.error) {\n log.error(props.error);\n throw new Error(props.error);\n }\n\n const loader = props.loading || <DefaultLoader></DefaultLoader>;\n return <>{model && isReady ? props.children : loader}</>;\n};\n","import React from \"react\";\n\ninterface HeaderTranslations {\n title: string;\n createLabel: string;\n deleteLabel: string;\n}\ninterface ModalTranslations {\n okText: string;\n cancelText: string;\n title: string;\n}\nexport interface Translations {\n header?: Partial<HeaderTranslations>;\n createModal?: Partial<ModalTranslations>;\n}\nconst DEFAULT_TRANSLATIONS: ContextTranslations = {\n header: {\n title: \"Model\",\n createLabel: \"Create new Model\",\n deleteLabel: \"Delete\",\n },\n createModal: {\n okText: \"OK\",\n cancelText: \"Cancel\",\n title: \"Create New Model\",\n },\n};\n\ninterface ContextTranslations {\n header: HeaderTranslations;\n createModal: ModalTranslations;\n}\ninterface Props {\n translations?: Translations;\n children: React.ReactNode;\n}\nconst CreateModelTranslationsContext =\n React.createContext<ContextTranslations>(DEFAULT_TRANSLATIONS);\n\nconst CreateModelTranslationsProvider: React.FC<Props> = ({\n translations = DEFAULT_TRANSLATIONS,\n children,\n}) => {\n const merged: ContextTranslations = {\n header: { ...DEFAULT_TRANSLATIONS.header, ...translations.header },\n createModal: {\n ...DEFAULT_TRANSLATIONS.createModal,\n ...translations.createModal,\n },\n };\n return (\n <CreateModelTranslationsContext.Provider value={merged}>\n {children}\n </CreateModelTranslationsContext.Provider>\n );\n};\n\nexport { CreateModelTranslationsContext, CreateModelTranslationsProvider };\n","import type { IKosCoreManager, IKosRegistry } from \"../../core\";\nimport { KosCore, wrapPromise } from \"../../core\";\n\nexport function fetchKosCore(registration: IKosRegistry, alias?: string) {\n const kosCore = KosCore.create(registration, false, alias);\n const promise = kosCore.whenReady().then(() => kosCore);\n return wrapPromise<IKosCoreManager>(promise);\n}\n","import { observer } from \"mobx-react-lite\";\nimport React, { useEffect } from \"react\";\nimport { IKosCoreManager, IKosRegistry, kosAutoEffect } from \"../../core\";\nimport { fetchKosCore } from \"./fetch-kos-core\";\n\nexport interface ProviderProps {\n children?: React.ReactNode;\n}\n\ninterface IKosContext {\n kosCore: IKosCoreManager;\n online: boolean;\n}\nconst KosContext = React.createContext<IKosContext | undefined>(undefined);\nconst initKosProvider = (\n registration: IKosRegistry = { models: {}, preloadModels: [] },\n alias?: string\n) => {\n const resource = fetchKosCore(registration, alias);\n\n const KosCoreContextProvider: React.FC<ProviderProps> = ({ children }) => {\n const kosCore = resource.read();\n const [online, setOnline] = React.useState(kosCore.isOnline);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setOnline(kosCore.isOnline);\n });\n\n return () => {\n disposer();\n };\n }, [kosCore]);\n return (\n <KosContext.Provider value={{ kosCore, online }}>\n {children}\n </KosContext.Provider>\n );\n };\n\n return { KosCoreContextProvider: observer(KosCoreContextProvider) };\n};\n\nexport const useKosCore = () => {\n const context = React.useContext(KosContext);\n if (context === undefined) {\n throw new Error(`useKosCore must be used within a KosCoreContextProvider`);\n }\n\n return context;\n};\n\nexport default initKosProvider;\n","import {\n destroyKosModel,\n IKosCoreManager,\n IKosDataModel,\n kosAutoEffect,\n KosCore,\n ModelFactory,\n} from \"../../core\";\n\nimport { useEffect, useState } from \"react\";\nimport { useKosCore } from \"../contexts/kos-core-context\";\n\nimport type { IReactionDisposer } from \"mobx\";\nimport { KosModelEvents, KosModelState } from \"../../core\";\nimport { 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\nconst cache = new Map();\n\nfunction fetchData(key, fetcher) {\n // Check if there's already a cached promise or result.\n if (cache.has(key)) {\n const entry = cache.get(key);\n if (entry.status === \"finished\") {\n const kosModel = KosCore.getInstance().modelManager.getModelById(key);\n return { kosModel, model: kosModel?.modelData };\n } else {\n throw entry.promise;\n }\n } else {\n // If no cache exists, create a new promise.\n const promise = fetcher().then(\n () => {\n cache.set(key, { status: \"finished\", key });\n },\n (error) => {\n cache.set(key, { status: \"error\", error });\n throw error;\n }\n );\n\n // Store the promise in the cache with a pending status.\n const entry = { status: \"pending\", promise };\n cache.set(key, entry);\n\n // Suspend by throwing the promise.\n throw promise;\n }\n}\n\nfunction useSuspenseData<T>(\n key: string,\n fetcher: (...args: any[]) => Promise<T>\n) {\n // Attempt to fetch the data (or retrieve from cache), throwing a promise if it's not ready.\n const data = fetchData(key, fetcher) as T;\n\n // If the data is available, return it.\n return data;\n}\n\nasync function fetchModel<T extends IKosDataModel, O extends Object = {}>(\n kosCore: IKosCoreManager,\n modelOptions: Options<T, O>\n) {\n const { modelId, factory, modelType, options, activate } = modelOptions;\n let retryCount = 0;\n await kosCore.whenReady();\n let _model: T;\n if (options) {\n const _factory =\n typeof modelType === \"string\"\n ? kosCore.modelManager.getModelFactory<T>(modelType)\n : factory;\n\n if (!_factory) {\n throw Error(\"No Factory Specified. Cannot create a new instance\");\n }\n // build the model first\n _model = _factory.build(modelId!, options);\n }\n const kosModel = kosCore.modelManager.getModelById<T>(modelId!);\n\n if (!kosModel) {\n if (retryCount > MAX_RETRIES) {\n throw Error(`KOS Model ${modelId} has not been found`);\n }\n\n await waitForRetry(retryCount);\n const count = retryCount + 1;\n retryCount = count;\n }\n await kosModel?.whenReady();\n\n if (kosModel) {\n _model = kosModel.modelData;\n return { kosModel, model: _model };\n }\n\n return { kosModel: undefined, model: undefined };\n}\nexport const useKosModel = <T extends IKosDataModel, O extends Object = {}>(\n modelOptions: Options<T, O>\n) => {\n const { modelId, modelType, activate, destroyOnUnmount } = modelOptions;\n const kosCoreContext = useKosCore();\n const [ready, setReady] = useState(false);\n\n const [error, setError] = useState<string | undefined>();\n\n const { kosModel, model } = useSuspenseData(\n modelId || modelType || \"\",\n () => {\n const response = fetchModel(kosCoreContext.kosCore, modelOptions);\n return response;\n }\n );\n\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 cache.delete(modelId);\n disposer?.();\n });\n }\n });\n }\n } else {\n if (destroyOnUnmount && model) {\n destroyKosModel(model).then(() => {\n cache.delete(modelId);\n disposer?.();\n });\n }\n }\n };\n }, [\n activate,\n destroyOnUnmount,\n kosCoreContext.kosCore,\n kosModel,\n model,\n modelId,\n ]);\n\n return {\n model,\n ready,\n error,\n status: {\n model,\n ready,\n error,\n },\n KosModelLoader,\n };\n};\n","import { KosTime, KosTimeModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useKosTime = () => {\n const modelId = KosTime.type;\n const result = useKosModel<KosTimeModel>({\n modelId,\n modelType: KosTime.type,\n options: {},\n });\n\n return result;\n};\n","import { PropsWithChildren, createContext, useContext, useMemo } from \"react\";\nimport { KosTimeModel } from \"../../../models\";\nimport { useKosTime } from \"../../hooks/kos-time/use-kos-time\";\n\ninterface KosTimeType {\n model?: KosTimeModel;\n}\nexport const KosTimeContext = createContext<KosTimeType | undefined>(undefined);\n\ninterface KosTimeProviderProps {}\n\nexport const KosTimeProvider: React.FunctionComponent<\n PropsWithChildren<KosTimeProviderProps>\n> = ({ children }) => {\n const { model, ready } = useKosTime();\n const value: KosTimeType = useMemo(() => {\n if (ready && model) {\n return { model };\n }\n return {};\n }, [ready, model]);\n return (\n <KosTimeContext.Provider value={value}>{children}</KosTimeContext.Provider>\n );\n};\nexport const useKosTimeContext = () => {\n const context = useContext(KosTimeContext);\n if (!context) {\n throw new Error(\"useKosTimeContext must be used within a KosTimeProvider\");\n }\n return context;\n};\n","import { SoftwareInfo, type SoftwareInfoModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useSoftwareInfo = () => {\n const modelId = SoftwareInfo.type;\n const result = useKosModel<SoftwareInfoModel>({\n modelId,\n modelType: SoftwareInfo.type,\n options: {},\n });\n\n return result;\n};\n","import type { SoftwareInfoModel } from \"../../../models\";\nimport { useSoftwareInfo } from \"./use-software-info\";\n\ninterface SoftwareInfoProps {\n softwareInfo: SoftwareInfoModel;\n}\n// react HOC to provide a SoftwareInfo to a component\nexport function withSoftwareInfo<\n T extends SoftwareInfoProps = SoftwareInfoProps\n>(WrappedComponent: React.ComponentType<T>) {\n return () => (props: Omit<T, keyof SoftwareInfoProps>) => {\n const { model, status, KosModelLoader } = useSoftwareInfo();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} softwareInfo={model} />\n </KosModelLoader>\n );\n };\n}\n","import { PropsWithChildren, createContext, useContext, useMemo } from \"react\";\nimport type { SoftwareInfoModel } from \"../../../models\";\nimport { useSoftwareInfo } from \"../../hooks/software-info\";\n\ninterface SoftwareInfoType {\n model?: SoftwareInfoModel;\n}\nexport const SoftwareInfoContext = createContext<SoftwareInfoType | undefined>(\n undefined\n);\n\ninterface SoftwareInfoProviderProps {\n id: string;\n}\n\nexport const SoftwareInfoProvider: React.FunctionComponent<\n PropsWithChildren<SoftwareInfoProviderProps>\n> = ({ children }) => {\n const { model, ready } = useSoftwareInfo();\n const value: SoftwareInfoType = useMemo(() => {\n if (ready && model) {\n return { model };\n }\n return {};\n }, [ready, model]);\n return (\n <SoftwareInfoContext.Provider value={value}>\n {children}\n </SoftwareInfoContext.Provider>\n );\n};\nexport const useSoftwareInfoContext = () => {\n const context = useContext(SoftwareInfoContext);\n if (!context) {\n throw new Error(\n \"useSoftwareInfoContext must be used within a SoftwareInfoProvider\"\n );\n }\n return context;\n};\n","import React from \"react\";\nimport { KosToken } from \"../../core\";\n\nconst token = new KosToken();\nconst TokenContext = React.createContext<KosToken>(token);\n\nfunction TokenProvider({ children }: { children: React.ReactNode }) {\n return (\n <TokenContext.Provider value={token}>{children}</TokenContext.Provider>\n );\n}\nexport { TokenContext, TokenProvider };\n","import { KosLog, getQueryParams } from \"../../../core\";\nimport {\n KosTranslations,\n Localization,\n TranslationContainerModel,\n getKosLocalizationDescriptor,\n} from \"../../../models\";\n\nimport {\n PropsWithChildren,\n createContext,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\n\ninterface TranslationContainerType {\n setLocale: (locale: string) => void;\n}\nexport const TranslationContainerContext = createContext<\n TranslationContainerType | undefined\n>(undefined);\n\ninterface TranslationContainerProviderProps {\n appContext?: string | string[];\n rootUrl?: string;\n locale?: string;\n descriptorResolver?: () => Promise<Localization>;\n resolver?: (\n this: TranslationContainerModel,\n namespace: string,\n locale: string\n ) => string;\n}\n\nconst getDefaultHost = () => {\n const defaultHost = window.location.origin;\n const params = getQueryParams();\n const hostUrl = (params as any)?.host;\n const result = hostUrl || defaultHost;\n return result;\n};\n\nexport const KosTranslationProvider: React.FunctionComponent<\n PropsWithChildren<TranslationContainerProviderProps>\n> = ({\n children,\n appContext,\n locale = \"en\",\n resolver,\n rootUrl,\n descriptorResolver,\n}) => {\n const [ready, setReady] = useState(false);\n const [localization, setLocalization] = useState<Localization>();\n const [translations, setTranslations] = useState<TranslationContainerModel>();\n const resolvedRootUrl = rootUrl || getDefaultHost();\n 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 const localizationDescriptor = descriptors\n .reverse()\n .reduce<Localization>((acc, val) => {\n const basePath = val.path;\n Object.keys(val.namespaces).forEach((namespaceKey) => {\n const namespace = val.namespaces[namespaceKey];\n namespace.basePath = basePath;\n });\n return {\n ...acc,\n namespaces: { ...acc.namespaces, ...val.namespaces },\n };\n }, {} as Localization);\n setLocalization(localizationDescriptor);\n }\n initTools();\n }, [_appContext, descriptorResolver]);\n\n useEffect(() => {\n async function initLocalization() {\n if (localization) {\n const _rootUrl = resolvedRootUrl;\n const { translations } = await KosTranslations.init({\n lang: locale,\n descriptor: localization,\n defaultNamespace: \"common\",\n resolver: resolver,\n rootUrl: _rootUrl,\n });\n setTranslations(translations);\n setReady(true);\n }\n }\n\n initLocalization();\n }, [locale, localization, resolver, resolvedRootUrl]);\n\n const value: TranslationContainerType = useMemo(() => {\n if (ready) {\n return {\n setLocale: (locale: string) => {\n if (translations) {\n translations.currentLocale = locale;\n }\n },\n };\n }\n return {\n setLocale: () => {\n throw new Error(\"Translations not ready\");\n },\n };\n }, [ready, translations]);\n\n const content = ready ? children : null;\n return (\n <TranslationContainerContext.Provider value={value}>\n {content}\n </TranslationContainerContext.Provider>\n );\n};\nexport const useKosTranslationContext = () => {\n const context = useContext(TranslationContainerContext);\n if (!context) {\n throw new Error(\n \"useTranslationContainerContext must be used within a TranslationContainerProvider\"\n );\n }\n return context;\n};\n","import {\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(decode, width, height);\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\nexport const useDevice = () => {\n const modelId = Device.type;\n const result = useKosModel<DeviceModel>({\n modelId,\n modelType: Device.type,\n options: {},\n });\n\n return result;\n};\n","import { DeviceModel } from \"../../../models\";\nimport { useDevice } from \"./use-device\";\n\nexport interface DeviceProps {\n device: DeviceModel;\n}\n\ntype HoCDeviceProps = DeviceProps;\n// react HOC to provide a Device to a component\nexport function withDevice<T extends HoCDeviceProps = HoCDeviceProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof DeviceProps>) => {\n const { model, status, KosModelLoader } = useDevice();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} device={model} />\n </KosModelLoader>\n );\n };\n}\n","import { IKosDataModel, KosCore, wrapPromise } from \"../../core\";\n\nexport default function fetchModel<\n T extends IKosDataModel,\n O extends object = Record<string, unknown>\n>(modelType: string, id?: string, options?: O) {\n const corePromise = new Promise<T>((resolve) => {\n KosCore.getInstance()\n .whenReady()\n .then(() => {\n const { model } =\n KosCore.getInstance().modelManager.createModelInstance<T>(\n modelType,\n id ?? modelType,\n options\n );\n return model.whenReady().then(() => {\n resolve(model.modelData);\n });\n });\n });\n\n return wrapPromise<T>(corePromise);\n}\n","import { KosTimeModel } from \"../../../models\";\nimport { useKosTime } from \"./use-kos-time\";\n\ninterface KosTimeProps {\n kosTime: KosTimeModel;\n}\n// react HOC to provide a KosTime to a component\nexport function withKosTime<T extends KosTimeProps = KosTimeProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof KosTimeProps>) => {\n const { model, status, KosModelLoader } = useKosTime();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} kosTime={model} />\n </KosModelLoader>\n );\n };\n}\n","import {\n NetworkInterfaceContainer,\n NetworkInterfaceContainerModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useNetworkInterfaceContainer = () => {\n const modelId = NetworkInterfaceContainer.type;\n const result = useKosModel<NetworkInterfaceContainerModel>({\n modelId,\n modelType: NetworkInterfaceContainer.type,\n options: {},\n });\n\n return result;\n};\n","import { NetworkInterfaceContainerModel } from \"../../../models\";\nimport { useNetworkInterfaceContainer } from \"./use-network-interface-container\";\n\ninterface NetworkInterfaceContainerProps {\n networkInterfaceContainer: NetworkInterfaceContainerModel;\n}\n\ntype HoCNetworkInterfaceContainerProps = NetworkInterfaceContainerProps;\n// react HOC to provide a NetworkInterfaceContainer to a component\nexport function withNetworkInterfaceContainer<\n T extends HoCNetworkInterfaceContainerProps = HoCNetworkInterfaceContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof NetworkInterfaceContainerProps>) => {\n const { model, status, KosModelLoader } = useNetworkInterfaceContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} networkInterfaceContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { Ota, type OtaModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useOta = () => {\n const modelId = Ota.type;\n const result = useKosModel<OtaModel>({\n modelId,\n modelType: Ota.type,\n options: {},\n });\n\n return result;\n};\n","import type { OtaModel } from \"../../../models\";\nimport { useOta } from \"./use-ota\";\n\ninterface OtaProps {\n oTA: OtaModel;\n}\n\ntype HoCOtaProps = OtaProps;\n// react HOC to provide a Ota to a component\nexport function withOta<T extends HoCOtaProps = HoCOtaProps>(\n WrappedComponent: React.ComponentType<T>\n) {\n return (props: Omit<T, keyof OtaProps>) => {\n const { model, status, KosModelLoader } = useOta();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} oTA={model} />\n </KosModelLoader>\n );\n };\n}\n","import { useRef, useEffect, PropsWithChildren } from \"react\";\n\n/**\n * Hook that alerts clicks outside of the passed ref\n */\nfunction useOutsideAlerter(ref, onAction) {\n useEffect(() => {\n /**\n * Alert if clicked on outside of element\n */\n function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n onAction();\n }\n }\n\n function handleEscFunction(event) {\n if (event.key === \"Escape\") {\n onAction();\n }\n }\n // Bind the event listener\n document.addEventListener(\"mousedown\", handleClickOutside);\n document.addEventListener(\"keydown\", handleEscFunction, false);\n return () => {\n // Unbind the event listener on clean up\n document.removeEventListener(\"mousedown\", handleClickOutside);\n document.removeEventListener(\"keydown\", handleEscFunction, false);\n };\n }, [ref, onAction]);\n}\n\ninterface Props {\n onAlert: () => void;\n}\n/**\n * Component that alerts if you click outside of it\n */\nexport default function OutsideAlerter(props: PropsWithChildren<Props>) {\n const wrapperRef = useRef(null);\n const onAction = props.onAlert;\n useOutsideAlerter(wrapperRef, onAction);\n\n return (\n <div ref={wrapperRef} style={{ width: \"100%\" }}>\n {props.children}\n </div>\n );\n}\n","import { KosStateProp, StatePropertyTypes } from \"../../../models\";\n\nimport { useEffect, useState } from \"react\";\nimport { kosAutoEffect, whenReady } from \"../../../core\";\n\ninterface UseStatePropertyProps<T extends StatePropertyTypes = any> {\n stateProp?: KosStateProp<T>;\n}\n\ntype StatePropertyStatus<T extends StatePropertyTypes = any> = [\n value: T | undefined,\n status: { ready: boolean; error?: string }\n];\nexport const useStateProperty = <T extends StatePropertyTypes = any>(\n props: UseStatePropertyProps<T>\n): StatePropertyStatus<T> => {\n const { stateProp } = props;\n const [value, setValue] = useState<T | undefined>(props.stateProp?.value);\n const [ready, setReady] = useState(false);\n const [error, setError] = useState<string | undefined>(undefined);\n\n useEffect(() => {\n async function waitForProp(prop?: KosStateProp) {\n try {\n if (prop) {\n await whenReady(prop);\n setReady(true);\n }\n } catch (e) {\n setError((e as Error).message);\n }\n }\n\n waitForProp(stateProp);\n }, [stateProp]);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (stateProp && ready) {\n setValue(stateProp.value);\n }\n });\n return () => {\n disposer();\n };\n }, [ready, stateProp]);\n\n const status = { ready, error };\n return [value, status];\n};\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport {\n StorageDeviceContainer,\n StorageDeviceContainerModel,\n type StorageDeviceModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useStorageDeviceContainer = () => {\n const [inserted, setInserted] = useState<boolean>(false);\n const [devices, setDevices] = useState<StorageDeviceModel[]>([]);\n const modelId = StorageDeviceContainer.type;\n const result = useKosModel<StorageDeviceContainerModel>({\n modelId,\n modelType: StorageDeviceContainer.type,\n options: {},\n });\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setInserted(result.model?.isStorageInserted ?? false);\n setDevices(result.model?.data ?? []);\n });\n\n return () => {\n disposer();\n };\n }, [result.model]);\n\n return { ...result, inserted, devices };\n};\n","import { StorageDeviceContainerModel } from \"../../../models\";\nimport { useStorageDeviceContainer } from \"./use-storage-device-container\";\n\ninterface StorageDeviceContainerProps {\n storageDeviceContainer: StorageDeviceContainerModel;\n}\n\ntype HoCStorageDeviceContainerProps = StorageDeviceContainerProps;\n// react HOC to provide a StorageDeviceContainer to a component\nexport function withStorageDeviceContainer<\n T extends HoCStorageDeviceContainerProps = HoCStorageDeviceContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof StorageDeviceContainerProps>) => {\n const { model, status, KosModelLoader } = useStorageDeviceContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} storageDeviceContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { 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\";\nimport { css } from \"@emotion/react\";\n\nconst escapeRegExp = (toEscape: string) => {\n const escapableChars = /[\\\\^$.*+?()[\\]{}|]/g;\n const hasEscapableChar = RegExp(escapableChars.source);\n\n return hasEscapableChar.test(toEscape)\n ? toEscape.replace(escapableChars, \"\\\\$&\")\n : toEscape;\n};\n\nconst isRegExp = (toTest: string | RegExp): toTest is RegExp =>\n toTest instanceof RegExp;\n\nconst isString = (toTest: string | RegExp | ReactNode): toTest is string =>\n typeof toTest === \"string\";\n\nconst replaceString = (\n source: string,\n _toMatch: string | RegExp,\n callback: (match: string, index: number) => ReactNode\n) => {\n if (source === \"\" || _toMatch === \"\") return source;\n\n let toMatch = _toMatch;\n\n if (!isRegExp(toMatch)) {\n toMatch = new RegExp(\"(\" + escapeRegExp(toMatch) + \")\", \"gi\");\n }\n\n const result: ReactNode[] = source.split(toMatch);\n\n // Matches will be every odd string in the array, iterate over them and\n // call the callback to insert our component for each match.\n for (let i = 1, length = result.length; i < length; i += 2) {\n result[i] = callback(result[i] as string, i);\n }\n\n return result;\n};\n\nexport const stringComponentInsert = (\n _source: string | (string | ReactNode)[],\n toMatch: string | RegExp,\n callback: (match: string, index: number) => string | ReactElement\n) => {\n let source = _source;\n if (!Array.isArray(source)) source = [source];\n\n return source.flatMap((x) =>\n isString(x) ? replaceString(x, toMatch, callback) : x\n );\n};\n\ninterface Components {\n [key: string]: JSX.Element;\n}\n\ntype ComponentArray = JSX.Element[];\n\ntype ComponentMap = Components | ComponentArray;\ninterface TransProps {\n t: TFunction;\n i18nKey: string;\n defaults?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n values?: Record<string, any | undefined>;\n components?: ComponentMap;\n context?: string;\n className?: string;\n}\n\nfunction substituteBlocks(stringValue: string, componentsMap: ComponentMap) {\n let blocks: string | ReactNode[] = stringValue;\n\n Object.entries(componentsMap).forEach(([key, value]) => {\n const regex = new RegExp(`<${key}>(.*?)</${key}>|<${key}/>`, \"g\");\n\n blocks = stringComponentInsert(blocks, regex, (match, index) => {\n if (value.type === \"br\") {\n return <br />;\n }\n return React.cloneElement(value, { key: `${key}-${index}` }, match);\n });\n });\n\n return blocks;\n}\n\nexport const Trans: React.FunctionComponent<TransProps> = (props) => {\n const { i18nKey, t, defaults, components, values = {}, context } = props;\n const translated = t(i18nKey, {\n defaultValue: defaults,\n data: values,\n context,\n returnObjects: true,\n });\n\n const element = substituteBlocks(translated, components || {});\n return <span className={props.className}>{element}</span>;\n};\n","import { useCallback, useMemo } from \"react\";\nimport { KosLog, getKosModel, whenReady } from \"../../../core\";\nimport {\n ResolveTranslationOptions,\n TranslationContainer,\n TranslationContainerModel,\n} from \"../../../models\";\n\nconst cache = new Map();\n\nfunction fetchData(key, fetcher) {\n // Check if there's already a cached promise or result.\n if (cache.has(key)) {\n const entry = cache.get(key);\n if (entry.status === \"finished\") {\n return entry.result;\n } else {\n throw entry.promise;\n }\n } else {\n // If no cache exists, create a new promise.\n const promise = fetcher().then(\n (result) => {\n cache.set(key, { status: \"finished\", result });\n },\n (error) => {\n cache.set(key, { status: \"error\", error });\n throw error;\n }\n );\n\n // Store the promise in the cache with a pending status.\n const entry = { status: \"pending\", promise };\n cache.set(key, entry);\n\n // Suspend by throwing the promise.\n throw promise;\n }\n}\n\nexport function useSuspenseData<T>(\n key: string,\n fetcher: (...args: any[]) => Promise<T>\n) {\n // Attempt to fetch the data (or retrieve from cache), throwing a promise if it's not ready.\n const data = fetchData(key, fetcher) as T;\n\n // If the data is available, return it.\n return data;\n}\n\nconst fetchTranslationContainer = async () => {\n const container = await getKosModel(TranslationContainer.type);\n await whenReady(container.model);\n return container.model as TranslationContainerModel;\n};\nconst fetchTranslations = async (\n parent: TranslationContainerModel,\n namespace: string,\n additionalNamespaces: string[]\n) => {\n const trans = parent.resolveNamespace(namespace);\n await whenReady(trans);\n for (const ns of additionalNamespaces) {\n const additional = parent.resolveNamespace(ns);\n await whenReady(additional);\n\n //TODO: This is a hack to force the model to resolve the translations\n cache.set(ns, { status: \"finished\", result: additional });\n }\n return trans;\n};\n\nexport type TFunction = <T = string>(\n key: string,\n options?: ResolveTranslationOptions<T> | string\n) => T | string;\n\nexport interface UseKosTranslationOptions {\n keyPrefix?: string;\n}\nexport const useKosTranslation = (\n namespace: string | string[],\n baseOptions?: UseKosTranslationOptions\n) => {\n const allNamespaces = [namespace].flat();\n const [defaultNamespace, ...additionalNamespaces] = allNamespaces;\n\n const model = useSuspenseData(\n TranslationContainer.type,\n fetchTranslationContainer\n );\n\n const allKeys = allNamespaces.join(\"__\");\n const translationModel = useSuspenseData(allKeys, () =>\n fetchTranslations(model, defaultNamespace, additionalNamespaces)\n );\n\n const i18n = useMemo(() => {\n return {\n exists: (key: string) => {\n const expandedKey = baseOptions?.keyPrefix\n ? `${baseOptions.keyPrefix}.${key}`\n : key;\n if (translationModel) {\n return translationModel.exists(expandedKey);\n }\n\n return false;\n },\n };\n }, [baseOptions?.keyPrefix, translationModel]);\n const t = useCallback<TFunction>(\n <T = string>(\n key: string,\n options?: ResolveTranslationOptions<T> | string\n ) => {\n const expandedKey = baseOptions?.keyPrefix\n ? `${baseOptions.keyPrefix}.${key}`\n : key;\n if (translationModel) {\n return translationModel.resolveKey(expandedKey, options) as T;\n }\n\n KosLog.debug(\n `Translation model ${namespace} not ready for key: ${expandedKey}`\n );\n return expandedKey;\n },\n [baseOptions?.keyPrefix, namespace, translationModel]\n );\n return { t, i18n };\n};\n","import {\n TranslationContainer,\n type TranslationContainerModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useTranslationContainer = () => {\n const modelId = TranslationContainer.type;\n const result = useKosModel<TranslationContainerModel>({\n modelId,\n modelType: TranslationContainer.type,\n options: {},\n });\n\n return result;\n};\n","import type { TranslationContainerModel } from \"../../../models\";\nimport { useTranslationContainer } from \"./use-translation-container\";\n\ninterface TranslationContainerProps {\n translationContainer: TranslationContainerModel;\n}\n\ntype HoCTranslationContainerProps = TranslationContainerProps;\n// react HOC to provide a TranslationContainer to a component\nexport function withTranslationContainer<\n T extends HoCTranslationContainerProps = HoCTranslationContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof TranslationContainerProps>) => {\n const { model, status, KosModelLoader } = useTranslationContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} translationContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { Trouble, type TroubleModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useTroubleModel = (id: string) => {\n const modelId = id;\n\n const result = useKosModel<TroubleModel>({\n modelId,\n modelType: Trouble.type,\n });\n\n return result;\n};\n","import { TroubleContainer, type TroubleContainerModel } from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useTroubleContainerModel = () => {\n const result = useKosModel<TroubleContainerModel>({\n modelId: TroubleContainer.type,\n modelType: TroubleContainer.type,\n options: {},\n });\n return result;\n};\n","import { useCallback, useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport type { TroubleModel } from \"../../../models/models/trouble\";\nimport type { FutureResponse } from \"../../../models/services/future\";\nimport { useTroubleContainerModel } from \"../trouble/use-trouble-container\";\n\ninterface Props {\n troubleType?: string;\n condition?: (trouble: TroubleModel) => boolean;\n}\n\ntype TroubleVisibility = [\n boolean,\n () => Promise<FutureResponse | undefined>,\n TroubleModel | undefined,\n TroubleModel[]\n];\nexport const useTroublePresence = ({\n troubleType,\n condition,\n}: Props): TroubleVisibility => {\n const { model } = useTroubleContainerModel();\n const [active, setActive] = useState<boolean>(false);\n const [troubles, setTroubles] = useState<TroubleModel[]>([]);\n\n const onComplete = useCallback(() => {\n if (troubles.length > 0 && troubles[0]?.resolvable) {\n return troubles[0]?.resolve();\n }\n return Promise.resolve(undefined);\n }, [troubles]);\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n const troublesByType =\n (troubleType\n ? model?.troubles.getIndexByKey(\"byType\", troubleType)\n : model?.troubles.data) || [];\n const activeTroubles = condition\n ? troublesByType.filter(condition)\n : troublesByType;\n setActive(activeTroubles.length > 0);\n setTroubles(activeTroubles);\n });\n return disposer;\n }, [condition, model, troubleType]);\n\n return [\n active,\n onComplete,\n troubles.length > 0 ? troubles[0] : undefined,\n troubles,\n ];\n};\n","import type { TroubleContainerModel } from \"../../../models\";\nimport { useTroubleContainerModel } from \"./use-trouble-container\";\n\ninterface TroubleContainerProps {\n troubleContainer: TroubleContainerModel;\n}\n// react HOC to provide a BoardContainer to a component\nexport function withTroubleContainer<\n T extends TroubleContainerProps = TroubleContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof TroubleContainerProps>) => {\n const { model, status, KosModelLoader } = useTroubleContainerModel();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} troubleContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect } from \"../../../core\";\nimport {\n UsbUpdateContainer,\n type UsbUpdateContainerModel,\n type UsbUpdateModel,\n} from \"../../../models\";\nimport { useKosModel } from \"../use-kos-model\";\n\nexport const useUsbUpdateContainer = () => {\n const modelId = UsbUpdateContainer.type;\n const result = useKosModel<UsbUpdateContainerModel>({\n modelId,\n modelType: UsbUpdateContainer.type,\n options: {},\n activate: true,\n destroyOnUnmount: true,\n });\n\n const [inserted, setInserted] = useState<boolean>(false);\n const [updateAvailable, setUpdateAvailable] = useState<boolean>(false);\n const [updates, setUpdates] = useState<UsbUpdateModel[]>([]);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n setInserted(result.model?.isUsbInserted ?? false);\n setUpdateAvailable(result.model?.hasAvailableUpdates ?? false);\n setUpdates(result.model?.data ?? []);\n });\n\n return () => {\n disposer();\n };\n }, [result.model]);\n\n return { ...result, inserted, updateAvailable, updates };\n};\n","import type { UsbUpdateContainerModel } from \"../../../models\";\nimport { useUsbUpdateContainer } from \"./use-usb-update-container\";\n\ninterface UsbUpdateContainerProps {\n usbUpdateContainer: UsbUpdateContainerModel;\n}\n\ntype HoCUsbUpdateContainerProps = UsbUpdateContainerProps;\n// react HOC to provide a UsbUpdateContainer to a component\nexport function withUsbUpdateContainer<\n T extends HoCUsbUpdateContainerProps = HoCUsbUpdateContainerProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof UsbUpdateContainerProps>) => {\n const { model, status, KosModelLoader } = useUsbUpdateContainer();\n\n return (\n <KosModelLoader {...status}>\n <WrappedComponent {...(props as T)} usbUpdateContainer={model} />\n </KosModelLoader>\n );\n };\n}\n","import { autorun } from \"mobx\";\nimport { useEffect, useState } from \"react\";\nimport type { IConfigBeanModel, IConfigBeanModelOptions } from \"../../models\";\nimport { ConfigBean, ConfigPropertyTypes } from \"../../models\";\nimport { useKosModel } from \"./use-kos-model\";\n\ninterface UseConfigBeanParams {\n path: string;\n propKey?: string;\n}\nexport const useConfigBean = ({ path, propKey }: UseConfigBeanParams) => {\n const { status } = useKosModel<IConfigBeanModel, IConfigBeanModelOptions>({\n modelType: ConfigBean.type,\n modelId: path,\n options: {\n path,\n },\n });\n const [ready, setReady] = useState(false);\n const [config, setConfig] = useState<IConfigBeanModel>();\n const [value, setValue] = useState<ConfigPropertyTypes>(\"\");\n const [error, setError] = useState<string>();\n const updateValue = (val: string) => {\n if (config && propKey) {\n config.updateProperty(propKey, val);\n }\n };\n useEffect(() => {\n if (status.model) {\n setConfig(status.model);\n }\n\n if (status.model && propKey) {\n if (status.model?.props.has(propKey)) {\n setValue(status.model.props[propKey]!);\n } else {\n setError(`property ${propKey} not found`);\n }\n }\n\n if (status.ready) {\n setReady(status.ready);\n }\n }, [status.ready, status.model, propKey]);\n\n useEffect(() => {\n if (propKey) {\n autorun(() => {\n const prop = config?.props[propKey];\n setValue(prop || \"\");\n });\n }\n }, [config, propKey]);\n\n return {\n config,\n ready,\n value,\n error,\n updateValue,\n };\n};\n","import {\n ChangeEvent,\n Reducer,\n useCallback,\n useEffect,\n useReducer,\n useState,\n} from \"react\";\nimport { kosAutoEffect, whenReady } from \"../../core\";\nimport type {\n ConfigPropertyTypes,\n OptionsType,\n SchemaOptionsType,\n} from \"../../models\";\nimport { KosConfigProperty } from \"../../models\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\nexport type OptionsTransformer = (options?: OptionsType[]) => any[];\n\ntype KosConfigProp =\n | KosConfigProperty<ConfigPropertyTypes>\n | KosConfigProperty<string>\n | KosConfigProperty<number>\n | KosConfigProperty<boolean>;\ninterface Props {\n configProperty?: KosConfigProp;\n optionsTransformer?: OptionsTransformer;\n}\n\ninterface UpdateAction<T extends object = any> {\n type: \"UPDATE\";\n payload: Partial<ConfigPropertyState<T>>;\n}\ninterface ConfigPropertyState<O extends object = any> {\n value: string;\n displayValue: string;\n significantValue: any;\n unit: string;\n options: OptionsType[];\n mappedOptions: O[];\n updateProperty?: (value: string) => void;\n displayOptions?: SchemaOptionsType;\n}\nconst reducer = <T extends object = any>(\n state: Partial<ConfigPropertyState<T>>,\n action: UpdateAction\n) => {\n switch (action.type) {\n case \"UPDATE\":\n return action.payload;\n default:\n return state;\n }\n};\nexport const useConfigProperty = <T extends object = any>({\n configProperty,\n optionsTransformer,\n}: Props) => {\n const [ready, setReady] = useState(false);\n const [error, setError] = useState(\"\");\n\n const [state, dispatch] = useReducer<\n Reducer<Partial<ConfigPropertyState<T>>, UpdateAction<T>>\n >(reducer, {\n value: String(configProperty?.value),\n displayValue: configProperty?.displayValue,\n significantValue: configProperty?.significantValue,\n unit: configProperty?.unit,\n options: configProperty?.options,\n mappedOptions: [],\n updateProperty: configProperty?.updateProperty,\n displayOptions: configProperty?.displayOptions,\n });\n\n const handleUpdate = useCallback(\n (e: SelectCallback) => {\n let value = \"factory\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n configProperty?.updateProperty(value);\n }\n },\n [configProperty]\n );\n useEffect(() => {\n async function waitForProp(prop?: KosConfigProp) {\n try {\n if (prop) {\n await whenReady(prop);\n setReady(true);\n }\n } catch (e) {\n setError((e as Error).message);\n }\n }\n\n waitForProp(configProperty);\n }, [configProperty]);\n\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (configProperty && ready) {\n let mapped: any[] = [];\n if (optionsTransformer) {\n mapped = optionsTransformer(configProperty.options);\n }\n dispatch({\n type: \"UPDATE\",\n payload: {\n value: String(configProperty.value),\n displayValue: configProperty.displayValue,\n significantValue: configProperty.significantValue,\n unit: configProperty.unit,\n options: configProperty.options,\n mappedOptions: mapped,\n updateProperty: configProperty.updateProperty,\n displayOptions: configProperty?.displayOptions,\n },\n });\n }\n });\n return () => {\n disposer();\n };\n }, [configProperty, optionsTransformer, ready]);\n\n return {\n ...state,\n configSelectProps: {\n onChange: handleUpdate,\n value: state.value,\n options: optionsTransformer\n ? state.mappedOptions || []\n : state.options || [],\n },\n ready,\n error,\n };\n};\n","/**\n * Type for month represented as zero-based (0 for January, 11 for December).\n */\ntype Month = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11;\n\n/**\n * Utility method to get an array of zero-based month options (0 through 11).\n */\nexport function getMonthOptions(): Month[] {\n return Array.from({ length: 12 }, (_, index) => index as Month);\n}\n\n/**\n * Utility method to determine the number of days in a given month of a particular year.\n * @param month - Zero-based month (0 for January, 11 for December).\n * @param year - The year to account for leap years (optional, default is current year).\n * @returns The number of days in the specified month.\n */\nexport function getDaysInMonth(month: Month, year?: number): number {\n const yearToUse = year ?? new Date().getFullYear();\n const daysInEachMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n // Adjust for leap year\n if (\n month === 1 &&\n ((yearToUse % 4 === 0 && yearToUse % 100 !== 0) || yearToUse % 400 === 0)\n ) {\n return 29;\n }\n\n return daysInEachMonth[month] ?? 0;\n}\n\n/**\n * Utility method to get an array of zero-based day options for a specific month and year.\n * @param month - Zero-based month (0 for January, 11 for December).\n * @param year - The year to account for leap years (optional, default is current year).\n * @returns The array of zero-based day options.\n */\nexport function getDayOptions(month: Month, year?: number): number[] {\n const daysInMonth = getDaysInMonth(month, year);\n return Array.from({ length: daysInMonth }, (_, index) => index);\n}\n\n/**\n * Utility method to get an array of year options.\n * @param startYear - The starting year for the array.\n * @param endYear - The ending year for the array.\n * @returns The array of year options.\n */\nexport function getYearOptions(startYear: number, endYear: number): number[] {\n if (startYear > endYear) {\n throw new Error(\"Start year must be less than or equal to end year\");\n }\n return Array.from(\n { length: endYear - startYear + 1 },\n (_, index) => startYear + index\n );\n}\n","import { getDaysInMonth } from \"./date\";\n\n// Returns the number of days in a given month & year\nexport function getDays(year: number, month: number): number {\n return new Date(year, month, 0).getDate();\n}\n\n// Returns an array of all days in a given month & year\n// TODO: Make numbers locale specific\nexport function getDaysArray(year: number, month: number): number[] {\n const numberOfDays = getDaysInMonth(month as any, year);\n const daysAry: number[] = [];\n for (let i = 1; i <= numberOfDays; i++) {\n daysAry.push(i);\n }\n return daysAry;\n}\n\n// Returns an array of months from 0 - 11\n// Note: The array needs to be 0-11 for date functions\nexport function getMonthsArray(): number[] {\n const months = [...Array(12).keys()].map((key) =>\n new Date(0, key).getMonth()\n );\n return months;\n}\n\n// Returns an array of full years\n// When passed a tupple of numbers, it will generate an array with the\n// provided year range.\nexport function getYearsArray(\n number: [number, number] = [2018, 2028]\n): number[] {\n // Create an array +- number of years from current year\n const yearsArray: number[] = [];\n for (let i = number[0]; i <= number[1]; i++) {\n yearsArray.push(i);\n }\n // Return the array\n return yearsArray;\n}\n\nexport type YearFormat = \"short\" | \"long\";\n\nexport function getFormattedYearsArray(\n format: YearFormat,\n range: [number, number] = [2018, 2028]\n): number[] {\n const fullYearsArray = getYearsArray(range);\n if (format === \"long\") {\n return fullYearsArray;\n }\n // Modify the values of the full years array to only return YY instead\n return fullYearsArray.map((year) => Number(year.toString().substring(2)));\n}\n\nexport type MonthFormat = \"numeric\" | \"short\" | \"long\";\n\nexport function getFormattedMonthsArray(\n monthFormat: MonthFormat = \"numeric\",\n locale = \"en-US\"\n) {\n const format = new Intl.DateTimeFormat(locale, {\n month: monthFormat,\n timeZone: \"UTC\",\n }).format;\n\n return [...Array(12).keys()].map((m) => format(new Date(Date.UTC(0, m, 1))));\n}\n\ninterface GetFormattedDateProps {\n locale?: string;\n year: number;\n month: number;\n day: number;\n formatOptions?: Intl.DateTimeFormatOptions;\n displayOrder?: string;\n}\n\n// Formats a given year, month, date based on an optional local and format options\nexport function getFormattedDate({\n locale = \"en-US\",\n year,\n month,\n day,\n formatOptions = {\n weekday: \"long\",\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n },\n displayOrder,\n}: GetFormattedDateProps): string {\n // Correct the month, due to it being an index in the Date method\n const correctedMonth = month - 1;\n const dateFormat = new Date(year, correctedMonth, day);\n const monthName = new Intl.DateTimeFormat(locale, {\n month: formatOptions.month,\n }).format(dateFormat);\n const yearName = new Intl.DateTimeFormat(locale, {\n year: formatOptions.year,\n }).format(dateFormat);\n const dayName = new Intl.DateTimeFormat(locale, {\n day: formatOptions.day,\n }).format(dateFormat);\n\n if (displayOrder) {\n if (displayOrder == \"MMDDYY\") {\n return `${monthName} ${dayName} ${yearName}`;\n } else if (displayOrder === \"DDMMYY\") {\n return `${dayName} ${monthName} ${yearName}`;\n } else if (displayOrder === \"YYMMDD\") {\n return `${yearName} ${monthName} ${dayName}`;\n } else {\n return `${yearName} ${dayName} ${monthName}`;\n }\n }\n // If a displayOrder override isn't provided, format according to the locale:\n return new Intl.DateTimeFormat(locale, formatOptions).format(dateFormat);\n}\n\n// Formats a year to the full 4 digit year to be used in Date methods\nexport function getFormattedYear(year: number): number {\n const formattedYear =\n year.toString().length === 2\n ? new Date(Date.parse(`01 Jan 20${year}`)).getFullYear()\n : year;\n return formattedYear;\n}\n\n// Formats a month to the 2 digit month code to be used in Date methods\nexport function getFormattedMonth(month: number | string): number {\n const formattedMonth =\n typeof month === \"string\"\n ? new Date(Date.parse(`01 ${month.substring(0, 3)} 2023`)).getMonth() + 1\n : month;\n return formattedMonth;\n}\n\n// Return an array assuming the calendar week starts on Sunday\nexport function getCalendarMonthArray(\n month,\n year,\n dayOptions: { label: string; value: number; disabled: boolean }[]\n): { label: string; value: number; disabled: boolean }[] {\n const formattedYear = getFormattedYear(year);\n const firstDay = new Date(formattedYear, month, 1).getDay();\n const numberOfDays = new Date(formattedYear, month + 1, 0).getDate();\n\n const monthArray = [...Array(42).keys()].map((index) => {\n if (index < firstDay || index > numberOfDays + firstDay - 1) {\n return { label: \"\", value: 0, disabled: true };\n } else {\n return dayOptions[index - firstDay];\n }\n });\n\n return monthArray;\n}\n\n// Returns a boolean value of if a provided month, day and year form a valid date\nexport function isValidDate(year, month, day): boolean {\n const zeroIndexedMonth = month - 1;\n const d = new Date(year, zeroIndexedMonth, day);\n return (\n new Date(d).getMonth() === zeroIndexedMonth && new Date(d).getDate() === day\n );\n}\n\n// Returns the last of the month in a provided month and year\nexport function getLastDayOfMonth(year, month): number {\n const lastDay = new Date(year, month, 0).getDate();\n return lastDay;\n}\n\nexport type DayFormatOptions = \"short\" | \"long\" | \"narrow\" | undefined;\n\nexport function getDayStrings(\n locale = \"en-US\",\n dayFormat: DayFormatOptions = \"short\"\n) {\n const format = new Intl.DateTimeFormat(locale, { weekday: dayFormat }).format;\n return [...Array(7).keys()].map((day) =>\n format(new Date(Date.UTC(2021, 5, day)))\n );\n}\n","import { format, parseISO } from \"date-fns\";\nimport { Dispatch, SetStateAction, useEffect, useMemo, useState } from \"react\";\nimport { RegionInfo, RegionInfoModel, RegionInfoOptions } from \"../../models\";\nimport {\n DayFormatOptions,\n MonthFormat,\n YearFormat,\n getCalendarMonthArray,\n getDayStrings,\n getDaysArray,\n getFormattedMonthsArray,\n getFormattedYear,\n getFormattedYearsArray,\n getLastDayOfMonth,\n getMonthsArray,\n isValidDate,\n} from \"../utils/date-utils\";\nimport { useKosModel } from \"./use-kos-model\";\n\nexport type DaysOfWeekFilter = [\n number?,\n number?,\n number?,\n number?,\n number?,\n number?,\n number?\n];\n\nexport interface UseDateArrayFormatOptions {\n yearFormat?: YearFormat;\n monthFormat?: MonthFormat;\n dayFormat?: DayFormatOptions;\n}\nexport interface UseDateArraysProps {\n locale?: string;\n // TODO: Can we tighten the typing on the number?\n year?: number;\n // TODO: Can we tighten the typing on the number?\n month?: number;\n // TODO: Can we tighten the typing on the number?\n day?: number;\n formatOptions?: UseDateArrayFormatOptions;\n yearRange?: [number, number];\n daysOfWeekFilter?: DaysOfWeekFilter;\n}\n\nexport function useDateArrays({\n locale = \"en-US\",\n year = new Date().getFullYear(),\n month = new Date().getMonth(),\n yearRange = [2018, 2028],\n daysOfWeekFilter = [],\n formatOptions: {\n yearFormat = \"long\",\n monthFormat = \"long\",\n dayFormat = \"short\",\n } = {},\n}: UseDateArraysProps) {\n const yearsArray = useYears(yearFormat, yearRange);\n const yearsOptionsArray = useYearsOptions(yearFormat, yearRange, locale);\n const monthsArray = useMonths(monthFormat, locale);\n const monthsOptionsArray = useMonthsOptions(monthFormat, locale);\n const daysArray = useDays(year, month);\n const daysOptionsArray = useDayOptions(year, month, locale, daysOfWeekFilter);\n const calendarDayArray = useCalendarDayArray(month, year, daysOptionsArray);\n const dayNamesArray = useDayNames(locale, dayFormat);\n\n return {\n daysArray,\n monthsArray,\n yearsArray,\n yearsOptionsArray,\n monthsOptionsArray,\n daysOptionsArray,\n calendarDayArray,\n dayNamesArray,\n };\n}\n\n// TODO: Tighten the range type to only be positive numbers within a range\nexport function useYears(\n format: YearFormat = \"long\",\n range: [number, number] = [2018, 2028]\n): number[] {\n const yearsArray = useMemo(\n () => getFormattedYearsArray(format, range),\n [format, range]\n );\n return yearsArray;\n}\n\nexport function useYearsOptions(\n format: YearFormat = \"long\",\n range: [number, number] = [2018, 2028],\n locale = \"en-US\"\n): { label: string; value: number }[] {\n const rawYearsArray = useYears(format, range);\n const yearsOptionsArray = useMemo(\n () =>\n rawYearsArray.map((year) => {\n return {\n label: year.toLocaleString(locale).replace(\",\", \"\"),\n value: year,\n };\n }),\n [locale, rawYearsArray]\n );\n return yearsOptionsArray;\n}\n\nexport function useMonths(\n format: MonthFormat,\n locale = \"en-US\"\n): number[] | string[] {\n const monthsArray = useMemo(\n () => getFormattedMonthsArray(format, locale),\n [format, locale]\n );\n return monthsArray;\n}\n\nexport function useMonthsOptions(\n format: MonthFormat,\n locale = \"en-US\"\n): { label: string; value: number }[] {\n const monthsArray = useMemo(() => getMonthsArray(), []);\n const monthLabelsArray = useMemo(\n () => getFormattedMonthsArray(format, locale),\n [format, locale]\n );\n const monthsOptionsArray = useMemo(\n () =>\n [...Array(12).keys()].map((index) => {\n return {\n label: monthLabelsArray[index],\n value: Number(monthsArray[index]),\n };\n }),\n [monthLabelsArray, monthsArray]\n );\n\n return monthsOptionsArray;\n}\n\nexport function useDays(year: number, month: number): number[] {\n // Convert year\n const formattedYear = getFormattedYear(year);\n\n const daysArray = useMemo(\n () => getDaysArray(formattedYear, month),\n [month, formattedYear]\n );\n\n return daysArray;\n}\n\nconst isFilteredDayOfWeek = (\n year: number,\n month: number,\n day: number,\n filters: DaysOfWeekFilter = []\n): boolean => {\n const dateToCheck: number = new Date(year, month, day).getDay();\n return filters.length > 0 && filters.includes(dateToCheck);\n};\n\nexport function useDayOptions(\n year: number,\n month: number,\n locale = \"en-US\",\n daysOfWeekFilter: DaysOfWeekFilter = []\n): { label: string; value: number; disabled: boolean }[] {\n // TODO: Refactor to be able to pass in additional metadata\n const rawDaysArray = useDays(year, month);\n\n const daysOptionsArray = useMemo(\n () =>\n rawDaysArray.map((day) => {\n return {\n label: day.toLocaleString(locale),\n value: day,\n disabled: isFilteredDayOfWeek(year, month, day, daysOfWeekFilter),\n };\n }),\n [daysOfWeekFilter, locale, month, rawDaysArray, year]\n );\n\n return daysOptionsArray;\n}\nexport function useDayNames(\n locale = \"en-US\",\n dayFormat: DayFormatOptions = \"short\"\n): string[] {\n const dayNamesArray = useMemo(\n () => getDayStrings(locale, dayFormat),\n [locale, dayFormat]\n );\n return dayNamesArray;\n}\n\ninterface UseFormattedDateProps {\n // TODO: Can we tighten the typing on the number?\n year: number;\n // TODO: Can we tighten the typing on the number?\n month: number;\n // TODO: Can we tighten the typing on the number?\n day: number;\n yearRange?: number;\n formatString: string;\n}\n\nexport function useFormattedDate({\n year = new Date().getFullYear(),\n month = new Date().getMonth(),\n day = new Date().getDate(),\n formatString,\n}: UseFormattedDateProps): { formattedDate: string } {\n const indexedMonth = month;\n const date = new Date(year, indexedMonth, day);\n const formattedDate = format(date, formatString);\n\n return { formattedDate };\n}\n\nexport function useCalendarDayArray(\n month: number,\n year: number,\n dayOptionsArray: { label: string; value: number; disabled: boolean }[]\n): { label: string; value: number; disabled: boolean }[] {\n const calendarDayArray = useMemo(\n () => getCalendarMonthArray(month, year, dayOptionsArray),\n [month, year, dayOptionsArray]\n );\n return calendarDayArray;\n}\n\nexport interface UseDatePropsReturnActions {\n setYear: Dispatch<SetStateAction<number>>;\n setYearRange: Dispatch<SetStateAction<[number, number]>>;\n setMonth: Dispatch<SetStateAction<number>>;\n setDay: Dispatch<SetStateAction<number>>;\n nextMonth: () => void;\n previousMonth: () => void;\n nextYear: () => void;\n previousYear: () => void;\n}\n\nexport interface UseDatePropsReturnState {\n year: number;\n yearRange: [number, number];\n month: number;\n day: number;\n yearsArray: number[];\n yearsOptionsArray: { label: string; value: number; disabled?: boolean }[];\n monthsArray: string[] | number[];\n monthsOptionsArray: {\n label: string | number;\n value: number;\n disabled?: boolean;\n }[];\n daysArray: number[];\n daysOptionsArray: { label: string; value: number; disabled?: boolean }[];\n calendarDayNames: string[];\n calendarDayArray: {\n label: string;\n value: number;\n disabled?: boolean;\n }[];\n formattedDate: string;\n}\n\nexport interface UseDatePropsReturn {\n dateActions: UseDatePropsReturnActions;\n dateState: UseDatePropsReturnState;\n}\n\nexport enum DateDisplayFormat {\n \"MMDDYY\" = \"MMDDYY\",\n \"DDMMYY\" = \"DDMMYY\",\n \"YYMMDD\" = \"YYMMDD\",\n \"YYDDMM\" = \"YYDDMM\",\n}\n\ninterface UseDatePropsFormatOptions extends UseDateArrayFormatOptions {\n formatString?: string;\n}\ninterface UseDatePropsFilterOptions {\n yearsRange?: [number, number];\n daysOfWeekFilter?: DaysOfWeekFilter;\n}\n\ninterface UseDateProps {\n locale?: string;\n date?: { day?: number; month?: number; year?: number };\n formatOptions?: UseDatePropsFormatOptions;\n filterOptions?: UseDatePropsFilterOptions;\n}\n\nexport function useDateProps({\n locale = \"en-US\",\n date: {\n year: yearProp = new Date().getFullYear(),\n month: monthProp = new Date().getMonth(),\n day: dayProp = new Date().getDate(),\n } = {\n year: new Date().getFullYear(),\n month: new Date().getMonth(),\n day: new Date().getDate(),\n },\n formatOptions: {\n yearFormat = \"long\",\n monthFormat = \"long\",\n dayFormat = \"short\",\n formatString = \"yyyy/MM/dd\",\n } = {},\n filterOptions: {\n yearsRange = [2018, 2028] as [number, number],\n daysOfWeekFilter = [] as DaysOfWeekFilter,\n } = {},\n}: UseDateProps): UseDatePropsReturn {\n const [year, setYear] = useState<number>(yearProp);\n const [yearRange, setYearRange] = useState<[number, number]>(yearsRange);\n const [month, setMonth] = useState<number>(monthProp);\n const [day, setDay] = useState<number>(dayProp);\n\n useEffect(() => {\n setYear(yearProp);\n }, [yearProp]);\n\n useEffect(() => {\n setMonth(monthProp);\n }, [monthProp]);\n\n useEffect(() => {\n setDay(dayProp);\n }, [dayProp]);\n\n const {\n yearsArray,\n yearsOptionsArray,\n monthsArray,\n monthsOptionsArray,\n daysArray,\n daysOptionsArray,\n calendarDayArray,\n dayNamesArray,\n } = useDateArrays({\n locale,\n year,\n yearRange,\n month,\n formatOptions: {\n yearFormat,\n monthFormat,\n dayFormat,\n },\n daysOfWeekFilter,\n });\n\n const { formattedDate } = useFormattedDate({\n year,\n month,\n day,\n formatString,\n });\n\n const nextMonth = (): void => {\n // Account for going past December\n const formattedYear =\n month < 11 ? getFormattedYear(year) : getFormattedYear(year + 1);\n const nextMonth = month < 11 ? month + 1 : 0;\n\n // Account for the day and if it's valid in the month\n if (!isValidDate(formattedYear, nextMonth, day)) {\n const lastValidDay = getLastDayOfMonth(formattedYear, nextMonth);\n setDay(lastValidDay);\n }\n if (nextMonth === 0) {\n setYear(formattedYear);\n }\n setMonth(nextMonth);\n };\n\n const previousMonth = (): void => {\n // Account for going before January\n const formattedYear =\n month === 0 ? getFormattedYear(year - 1) : getFormattedYear(year);\n\n const prevMonth = month === 0 ? 11 : month - 1;\n // Account for the day and if it's valid in the month\n if (!isValidDate(formattedYear, prevMonth, day)) {\n const lastValidDay = getLastDayOfMonth(formattedYear, prevMonth);\n setDay(lastValidDay);\n }\n if (prevMonth === 11) {\n setYear(formattedYear);\n }\n setMonth(prevMonth);\n };\n\n const nextYear = (): void => {\n const nextYear = year < yearRange[1] ? year + 1 : yearRange[0];\n // Account for the day and if it's valid in the month\n const formattedYear = getFormattedYear(nextYear);\n\n if (isValidDate(formattedYear, month, day)) {\n setYear(nextYear);\n } else {\n // If it's not a valid day, change the day to the last day of the month\n const lastValidDay = getLastDayOfMonth(getFormattedYear(year + 1), month);\n setDay(lastValidDay);\n setYear(nextYear);\n }\n };\n\n const previousYear = (): void => {\n const prevYear = year > yearRange[0] ? year - 1 : yearRange[0];\n const formattedYear = getFormattedYear(prevYear);\n\n if (isValidDate(formattedYear, month, day)) {\n setYear(prevYear);\n } else {\n // If it's not a valid day, change the day to the last day of the month\n const lastValidDay = getLastDayOfMonth(getFormattedYear(year - 1), month);\n setDay(lastValidDay);\n setYear(prevYear);\n }\n };\n\n return {\n dateActions: {\n setYear,\n setYearRange,\n setMonth,\n setDay,\n nextMonth,\n previousMonth,\n nextYear,\n previousYear,\n },\n dateState: {\n year,\n yearRange,\n month,\n day,\n yearsArray,\n yearsOptionsArray,\n monthsArray,\n monthsOptionsArray,\n daysArray,\n daysOptionsArray,\n calendarDayNames: dayNamesArray,\n calendarDayArray,\n formattedDate,\n },\n };\n}\n\nexport interface UseRegionalFormatProps {\n date?: Date | string;\n dateFormat?: string;\n timeFormat?: string;\n options?: {\n ignoreDateFormat?: boolean;\n };\n}\n\nexport function useRegionalTimeDate({\n date = new Date(),\n dateFormat,\n timeFormat,\n options = {},\n}: UseRegionalFormatProps): { formattedDate: string; formattedTime: string } {\n const [formattedTime, setFormattedTime] = useState(\"Formatting Time...\");\n const [formattedDate, setFormattedDate] = useState(\"Formatting Date...\");\n\n const ignoreDate = !!options.ignoreDateFormat;\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelId: RegionInfo.type,\n modelType: RegionInfo.type,\n options: {},\n });\n const dateToFormat = typeof date === \"string\" ? parseISO(date) : date;\n\n useEffect(() => {\n if (ignoreDate) {\n setFormattedDate(\"\");\n } else if (dateFormat) {\n // Set date according to format string\n setFormattedDate(format(dateToFormat, dateFormat));\n } else {\n // Set date according to model if no date format string provided\n if (ready) {\n setFormattedDate(\n format(\n dateToFormat,\n model?.selectedDateFormat ? model?.selectedDateFormat : \"\"\n )\n );\n }\n }\n }, [ignoreDate, date, dateFormat, dateToFormat, model, ready]);\n\n useEffect(() => {\n if (timeFormat) {\n // Set date according to format string\n setFormattedTime(format(dateToFormat, timeFormat));\n } else {\n // Set date according to model if no time format string provided\n if (ready) {\n setFormattedTime(\n format(\n dateToFormat,\n model?.selectedTimeFormat ? model?.selectedTimeFormat : \"\"\n )\n );\n }\n }\n }, [date, timeFormat, dateToFormat, model, ready]);\n\n return { formattedDate, formattedTime };\n}\n","import { useEffect, useRef, useState } from \"react\";\nimport type { KosConfigProperty } from \"../../models\";\nimport { useConfigProperty } from \"./use-config-property\";\nimport { useRegionalTimeDate } from \"./use-date-props\";\n\ninterface Props {\n configProperty?: KosConfigProperty<number>;\n is24Hr?: boolean;\n}\n\ninterface DateRelative {\n hours: number;\n minutes: number;\n seconds: number;\n formattedTime;\n timeActions: {\n setHours: (hours: number) => void;\n setMinutes: (minutes: number) => void;\n setSeconds: (seconds: number) => void;\n };\n}\ninterface DateRelativeDataProps {\n secondsFromMidnight?: number;\n}\n\n/**\n * Hook to convert seconds from midnight to a human readable time format\n *\n * The hook will use the time format based on the regional settings\n *\n * @param secondsFromMidnight - The number of seconds from midnight\n * @returns The hours, minutes, seconds, formatted time and actions to update the time\n */\nexport const useDateRelativeData = ({\n secondsFromMidnight = 0,\n}: DateRelativeDataProps) => {\n const [hours, setHours] = useState(0);\n const [minutes, setMinutes] = useState(0);\n const [seconds, setSeconds] = useState(0);\n const [date, setDate] = useState(new Date());\n const { formattedTime } = useRegionalTimeDate({\n date,\n options: {\n ignoreDateFormat: true,\n },\n });\n useEffect(() => {\n const numericValue = Number(secondsFromMidnight);\n const _hours = Math.floor(numericValue / 3600);\n const _minutes = Math.floor((numericValue % 3600) / 60);\n const _seconds = numericValue % 60;\n setHours(_hours);\n setMinutes(_minutes);\n setSeconds(_seconds);\n const midnight = new Date();\n midnight.setHours(0, 0, 0, 0);\n\n // Add the seconds to the midnight time\n const time = new Date(midnight.getTime() + numericValue * 1000);\n setDate(new Date(time));\n }, [secondsFromMidnight]);\n\n return {\n hours,\n minutes,\n seconds,\n formattedTime,\n timeActions: {\n setHours,\n setMinutes,\n setSeconds,\n },\n };\n};\n\n/**\n * Hook to translate date relative configuration properties to human readable time\n *\n * @param configProperty - The configuration property to use\n * @returns\n * @see useDateRelativeData\n */\nexport const useDateRelativeConfig = ({\n configProperty,\n}: Props): DateRelative => {\n const { value } = useConfigProperty({ configProperty });\n\n const secondsFromMidnight = parseInt(value || \"0\", 10);\n const { hours, minutes, seconds, formattedTime, timeActions } =\n useDateRelativeData({\n secondsFromMidnight,\n });\n\n const timeoutRef = useRef<NodeJS.Timeout>();\n\n useEffect(() => {\n // Calculate the new value only once per effect run\n const newValue = hours * 3600 + minutes * 60 + seconds;\n\n // Clear any previously set timeout to ensure only the latest update is applied\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n // Set a new timeout to update the property after 100ms\n timeoutRef.current = setTimeout(() => {\n if (configProperty) {\n configProperty.updateProperty(newValue.toString());\n }\n }, 100); // 100 milliseconds delay\n\n // Cleanup function to clear the timeout if the component is unmounted or dependencies change\n return () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n };\n }, [configProperty, hours, minutes, seconds]); // Dependencies list\n return {\n hours,\n minutes,\n seconds,\n formattedTime,\n timeActions,\n };\n};\n","import { 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 options: {},\n });\n\n const regionInfo: KosConfigProperty<string> = KosConfigPropertySpec.factory(\n REGION_ID\n )({\n path: REGION_PATH,\n attribute: REGION_ATTRIBUTE,\n }) as KosConfigProperty<string>;\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setRegions(model?.availableRegions.map(regionMap) || []);\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, regionMap]);\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setSelectedRegion(regionInfo.value || \"factory\");\n });\n\n return () => {\n cleanup();\n };\n }, [regionInfo.value]);\n\n const handleUpdate = useCallback((e: SelectCallback) => {\n let value = \"factory\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n updateRegion(value);\n }\n }, []);\n\n return {\n raw: model?.availableRegions ?? [],\n regionModel: model,\n regionData: model?.selectedRegion,\n selectedRegion,\n updateRegion: handleUpdate,\n\n regionSelectProps: {\n onChange: handleUpdate,\n value: selectedRegion,\n options: regions,\n },\n };\n};\n","import { RegionInfo } from \"../../models/models/region-info\";\n\nimport { kosAutoEffect } from \"../../core\";\nimport type {\n RegionInfoModel,\n RegionInfoOptions,\n TimeFormatOptions,\n} from \"../../models/models/region-info\";\n\nimport { ChangeEvent, useCallback, useEffect, useState } from \"react\";\nimport { useKosModel } from \"./use-kos-model\";\n\ntype SelectCallback = string | ChangeEvent<HTMLSelectElement>;\ntype TimeFormatMap<T extends {} = any> = (format: TimeFormatOptions) => T;\nconst DEFAULT_FORMAT_MAP: TimeFormatMap = (format: TimeFormatOptions) => (\n <option title={format.id} key={format.id} value={format.format}>\n {format.format}\n </option>\n);\n\n/**\n * The data returned from the useKosRegions hook.\n * @typeParam RegionData - the region data returned from the backend service. The type must extend BaseRegionResponse from the kos-core-model.\n * @typeParam T - the type of the options returned from the regionMap function.\n */\nexport interface KosTimeFormatHookData<T extends {} = any> {\n /**the raw region data returned from the backend service. */\n raw: string[];\n\n /**the region model returned from the backend service. */\n regionModel?: RegionInfoModel;\n\n /**the currently selected region. */\n selectedTimeFormat: string;\n\n timeFormatId: string;\n /**a function that can be used to update the region. */\n updateTimeFormat: (e: SelectCallback) => void;\n\n /**the props that can be spread into a select box component. */\n props: {\n onChange: (e: SelectCallback) => void;\n value: string;\n options: T[];\n };\n}\n\n/**\n * A hook that will help manage the use of region information on a dispenser.\n * @typeParam RegionData - the region data returned from the backend service. The type must extend BaseRegionResponse from the kos-core-model.\n * @param timeFormatMap - a function that maps a region string a structure that can be\n * used as an option in a select box. The default is to return an option element\n * with the region as the value and label.\n * @returns KosRegionHookData - the data returned from the hook.\n * @example\n * In this example the default region map is used to populate a select box with the available regions. If using a third party select box component where the options\n * are passed in as a prop, the options property can be spread into the props for the component. In this case, a region map function could be passed in to map the region\n * to a structure that the component expects.\n *\n *\n * ```typescript\n * interface RegionData extends RegionServices.BaseRegionResponse {\n * rfidRegion: string;\n * }\n * const { regionSelectProps, regionModel, regionData, selectedRegion, updateRegion } = useKosRegions<RegionData>();\n * const { options, ...selectAttributes } = regionSelectProps;\n * ...\n * <div>\n * <label>Select region: </label>\n * <select {...selectAttributes}>{options}</select>\n * </div>\n * <div>Selected Region: {selectedRegion}</div>\n * <div>Region Data: {regionData?.rfidRegion}</div>\n * ```\n */\nexport const useKosTimeFormats = <T extends {} = any>(\n timeFormatMap: TimeFormatMap<T> = DEFAULT_FORMAT_MAP\n): KosTimeFormatHookData<T> => {\n const [timeFormats, setTimeFormats] = useState<T[]>([]);\n const [selectedTimeFormat, setSelectedTimeFormat] = useState<{\n id: string;\n value: string;\n }>();\n const { model, ready } = useKosModel<RegionInfoModel, RegionInfoOptions>({\n modelType: RegionInfo.type,\n modelId: RegionInfo.type,\n options: {},\n });\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n setTimeFormats(model?.timeFormatOptions.map(timeFormatMap) || []);\n });\n\n return () => {\n cleanup();\n };\n }, [model, ready, timeFormatMap]);\n\n useEffect(() => {\n const cleanup = kosAutoEffect(() => {\n if (model?.timeFormatId && model?.selectedTimeFormat) {\n setSelectedTimeFormat({\n id: model?.timeFormatId,\n value: model?.selectedTimeFormat,\n });\n }\n });\n\n return () => {\n cleanup();\n };\n }, [model?.selectedTimeFormat, model?.timeFormatId]);\n\n const handleTimeFormatChange = useCallback(\n (e: SelectCallback) => {\n let value = \"\";\n if (typeof e === \"string\") {\n value = e;\n } else if (e?.target?.value) {\n value = e.target.value;\n }\n\n if (value) {\n model?.setSelectedTimeFormat(value);\n }\n },\n [model]\n );\n\n return {\n raw: model?.timeFormatOptions.map((o) => o.id) ?? [],\n regionModel: model,\n selectedTimeFormat: selectedTimeFormat?.value ?? \"\",\n timeFormatId: selectedTimeFormat?.id ?? \"\",\n updateTimeFormat: handleTimeFormatChange,\n props: {\n onChange: handleTimeFormatChange,\n value: selectedTimeFormat?.id ?? \"\",\n options: timeFormats,\n },\n };\n};\n","import { useMemo } from \"react\";\nimport { kosComputed } from \"../../core\";\n\n/**\n * @description An abstraction of React's useMemo for observable dependencies.\n * @param callback A function that returns a desired value.\n * @param dependencies An array of non-observable variables that are required to run the callback.\n */\nexport const useLocalComputed = <T>(\n callback: () => T,\n dependencies: ReadonlyArray<unknown>\n) => useMemo(() => kosComputed(callback), dependencies);\n","import { useEffect, useState } from \"react\";\nimport { KosLog } from \"../../core/core/log\";\n\ninterface MutationObserverOptions {\n config: MutationObserverInit;\n}\n\n// Default options for the MutationObserver\nconst DEFAULT_OPTIONS: MutationObserverOptions = {\n config: { attributes: true, childList: true, subtree: true },\n};\n\n/**\n * A hook that creates a MutationObserver and observes a DOM element for mutations. When a mutation occurs, the callback function is executed.\n *\n * @param targetEl The DOM element to observe\n * @param cb The callback function to execute when a mutation occurs\n * @param options Options to pass to the MutationObserver to configure what mutations to observe\n */\nexport function useMutationObserver<T extends Node>(\n targetEl: T,\n cb: MutationCallback,\n options: MutationObserverOptions = DEFAULT_OPTIONS\n) {\n const [observer, setObserver] = useState<MutationObserver | null>(null);\n useEffect(() => {\n // Validate the callback function\n if (!cb || typeof cb !== \"function\") {\n throw new Error(\"A valid callback function is required\");\n }\n const obs = new MutationObserver(cb);\n setObserver(obs);\n }, [cb, options, setObserver]);\n\n useEffect(() => {\n // Validate the observer\n if (!observer) return () => {};\n\n // Validate the target element\n if (!targetEl) {\n throw new Error(\"A valid DOM element is required\");\n }\n const { config } = options;\n try {\n // Start observing the target element for configured mutations\n observer.observe(targetEl, config);\n } catch (e) {\n KosLog.error(e);\n }\n return () => {\n // Stop observing the target element\n if (observer) {\n observer.disconnect();\n }\n };\n }, [observer, targetEl, options]);\n}\n","import {\n IntersectionStrategy,\n IntersectionStrategyState,\n} from \"./intersection-strategy\";\n\nexport const DomIntersectionStrategy: IntersectionStrategy = {\n validateStart: function (_state: IntersectionStrategyState): boolean {\n return true;\n },\n validateStop: function (state: IntersectionStrategyState): boolean {\n const boundingRect = (\n state.event.currentTarget as HTMLElement\n ).getBoundingClientRect();\n const [clientX, clientY] = state.xy;\n\n const isOutside =\n clientX < boundingRect.left ||\n clientX > boundingRect.right ||\n clientY < boundingRect.top ||\n clientY > boundingRect.bottom;\n\n return isOutside;\n },\n};\n","import { useGesture } from \"@use-gesture/react\";\nimport { useRef } from \"react\";\nimport { KosLog } from \"../../../core/core/log\";\nimport { DomIntersectionStrategy } from \"./strategy/dom-intersection-strategy\";\nimport { IntersectionStrategy } from \"./strategy/intersection-strategy\";\n\ninterface PressHandlers {\n onPressed?: () => void;\n onRelease?: () => void;\n intersectionStrategy?: IntersectionStrategy;\n}\n\nconst logger = KosLog.createLogger({\n name: \"usePressGesture\",\n group: \"kos-hooks\",\n});\nexport function usePressGesture({\n onPressed,\n onRelease,\n intersectionStrategy = DomIntersectionStrategy,\n}: PressHandlers) {\n const isDraggingInside = useRef<boolean>(false);\n\n const bind = useGesture({\n onDragStart: (state) => {\n logger.info(\"onDragStart\", state.type);\n if (!intersectionStrategy.validateStart(state)) return;\n\n if (onPressed) onPressed();\n isDraggingInside.current = true;\n },\n onDrag: (state) => {\n logger.info(\"onDrag\", state.type);\n if (!isDraggingInside.current) return;\n\n if (intersectionStrategy.validateStop(state)) {\n if (onRelease) onRelease();\n isDraggingInside.current = false;\n }\n },\n onDragEnd: (state) => {\n logger.info(\"onDragEnd\", state.type);\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n },\n });\n\n const handlePointerDown = () => {\n if (onPressed) onPressed();\n isDraggingInside.current = true;\n };\n\n const handlePointerUp = () => {\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n };\n\n const handlePointerOut = () => {\n if (isDraggingInside.current && onRelease) {\n onRelease();\n isDraggingInside.current = false;\n }\n };\n\n return {\n dom: bind,\n mesh: () => {\n return {\n onPointerDown: handlePointerDown,\n onPointerUp: handlePointerUp,\n onPointerOut: handlePointerOut,\n };\n },\n };\n}\n","import { useEffect, useState } from \"react\";\nimport { kosAutoEffect, KosCore } from \"../../core\";\nexport const useProjectReload = () => {\n const [reloading, setReloading] = useState(false);\n const core = KosCore.getInstance();\n useEffect(() => {\n const disposer = kosAutoEffect(() => {\n if (!core) return;\n if (core.reloading === reloading) return;\n setReloading(core.reloading);\n });\n\n return () => {\n disposer();\n };\n }, [core, reloading]);\n\n return [reloading];\n};\n","import { useCallback, useMemo, useState } from \"react\";\nimport { format } from \"date-fns\";\n\ntype TimeFormat = \"2-digit\" | \"numeric\";\n\nexport function useHourValues(hour12 = false, format: TimeFormat = \"2-digit\") {\n return useMemo(() => {\n const hours = hour12 ? 12 : 24;\n\n return Array.from({ length: hours }, (_, i) => {\n const hour = hour12 && i === 0 ? 12 : i % hours;\n\n return {\n id: i,\n label:\n format === \"2-digit\"\n ? hour.toString().padStart(2, \"0\")\n : hour.toString(),\n };\n });\n }, [format, hour12]);\n}\n\nexport function useTimeValues(\n length: number,\n format: TimeFormat = \"2-digit\",\n labelOffset = 0,\n valueOffset = 0\n) {\n return useMemo(\n () =>\n Array.from({ length }, (_, i) => {\n const label = String(i + labelOffset);\n\n return {\n id: i + valueOffset,\n label: format === \"2-digit\" ? label.padStart(2, \"0\") : label,\n };\n }),\n [length, labelOffset, valueOffset, format]\n );\n}\n\nexport function useAmPmValues(locale = \"en-US\") {\n return useMemo(\n () =>\n [\"AM\", \"PM\"].map((period) => {\n const formattedPeriod = new Intl.DateTimeFormat(locale, {\n hour: \"2-digit\",\n hour12: true,\n }).formatToParts(new Date().setHours(period === \"AM\" ? 0 : 12))[2]\n .value;\n\n return { id: formattedPeriod, label: formattedPeriod };\n }),\n [locale]\n );\n}\n\nexport interface UseTimeOptionsProps {\n formatOptions?: Intl.DateTimeFormatOptions;\n locale?: string;\n}\n\nexport function useTimeOptions({\n formatOptions: {\n hour12 = true,\n hour = \"2-digit\",\n minute = \"2-digit\",\n second = \"2-digit\",\n } = { hour12: true, hour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\" },\n locale = \"en-US\",\n}: UseTimeOptionsProps) {\n const hourOptions = useHourValues(hour12, hour);\n const minuteOptions = useTimeValues(60, minute);\n const secondOptions = useTimeValues(60, second);\n const amPmOptions = useAmPmValues(locale);\n\n return {\n hourOptions,\n minuteOptions,\n secondOptions,\n amPmOptions,\n };\n}\n\nexport function useFormattedTime(date: Date, formatString: string): string {\n const formattedDate = format(date, formatString);\n\n return formattedDate;\n}\n\nexport interface UseTimeProps {\n formatOptions?: Intl.DateTimeFormatOptions;\n initialDate?: Date;\n locale?: string;\n format?: string;\n}\n\nexport function useTimeProps({\n formatOptions,\n initialDate = new Date(),\n locale = \"en-US\",\n format = \"HH:mm\",\n}: UseTimeProps) {\n const [date, setDate] = useState(initialDate);\n\n const setHours = useCallback((hours: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setHours(Number(hours));\n\n return newDate;\n });\n }, []);\n\n const setMinutes = useCallback((minutes: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setMinutes(Number(minutes));\n\n return newDate;\n });\n }, []);\n\n const setSeconds = useCallback((seconds: number) => {\n setDate((prevDate) => {\n const newDate = new Date(prevDate);\n newDate.setSeconds(Number(seconds));\n\n return newDate;\n });\n }, []);\n\n const setTime = useCallback((date: Date) => {\n const newDate = new Date(date);\n\n setDate(newDate);\n }, []);\n\n const formattedTime = useFormattedTime(date, format);\n\n const { hourOptions, minuteOptions, secondOptions, amPmOptions } =\n useTimeOptions({\n formatOptions,\n locale,\n });\n\n return {\n amPmOptions,\n formattedTime,\n hourOptions,\n minuteOptions,\n secondOptions,\n setHours,\n setMinutes,\n setSeconds,\n setTime,\n time: new Date(date),\n };\n}\n","import { useMemo } from \"react\";\nimport { useKosRegions } from \"./use-kos-regions\";\nimport { useTimeProps, type UseTimeProps } from \"./use-time-props\";\n\nexport const useRegionTimeProps = (props?: UseTimeProps) => {\n const { regionModel } = useKosRegions();\n\n const formatOptions = useMemo(() => {\n return { hour12: regionModel?.is12HourTimeFormat };\n }, [regionModel?.is12HourTimeFormat]);\n\n return useTimeProps({\n ...props,\n locale: regionModel?.regionId,\n format: regionModel?.selectedTimeFormat,\n formatOptions,\n });\n};\n","import LoadingMessage from \"../components/loading-message\";\nimport { useProjectReload } from \"./use-project-reloading\";\n\ninterface ProjectReloadingProps {\n reloading: boolean;\n}\n// react HOC to provide a NodeTargetContainer to a component\nexport function withProjectReloading<\n T extends ProjectReloadingProps = ProjectReloadingProps\n>(WrappedComponent: React.ComponentType<T>) {\n return (props: Omit<T, keyof ProjectReloadingProps>) => {\n const [reloading] = useProjectReload();\n\n return reloading ? (\n <LoadingMessage message=\"Wait a moment while your project reloads...\" />\n ) : (\n <WrappedComponent {...(props as T)} />\n );\n };\n}\n","import {\n KosLog,\n type ServiceResponse,\n} 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<typeof SERVICE_PATH, \"get\">;\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"],"names":["HEADER_METHOD","HEADER_TOPIC","HEADER_URL","HEADER_REQUEST_ID","HEADER_RESPONSE_ID","STATUS","HEADER_DESTINATION_ADDR","HEADER_SOURCE_ADDR","HEADER_REQUEST_TYPE","HEADER_ORDERED","HEADER_WORK_TRACKER","HEADER_CONTENT_TYPE","HEADER_CACHE_CONTROL","HEADER_FOS_REQUEST_ID","LOGIN_HOST","PORT","LOGIN_URL","KOS_MODEL_ID","KosWsEvents","KosMockEvents","EVENT_KOS_MODEL_READY","log","subscriptions","getNextUniqueId","hasEventSubscriptions","eventType","subscribe","callback","id","publish","msg","headers","count","responseId","response","reset","key","once","subscription","waitFor","timeout","resolve","reject","timeoutId","unsubscribe","waitForAll","eventTypes","promises","race","unsubscribers","resolved","cleanup","unsub","filter","predicate","map","transform","transformed","debounce","delay","throttle","interval","lastEmit","pendingTimeout","now","timeSinceLastEmit","buffer","bufferTime","flush","replay","bufferSize","event","merge","sub","stateMachine","initialState","transitions","currentState","allEvents","stateTransitions","request","requestEvent","responseEvent","responsePromise","eventIterator","queue","waiters","EventBusFunctional","waitForOrGetState","options","getCurrentState","transformState","shouldUseFetchedState","eventPromise","normalizedState","subscribeWithInitialState","initialized","state","error","createStatefulEventStream","stateApi","subscribers","fetchState","ensureInitialized","checkState","waitForAllWithState","eventTypesOrType","eventPromises","results","createResilientEventHandler","handler","recoveryStrategy","fetchMissedEvents","checkInterval","deduplicateById","processedIds","intervalId","missed","events","createConnectionStateManager","config","connectEvent","disconnectEvent","errorEvent","dataEvent","fetchInitialState","reconnectDelay","manager","result","notifySubscribers","data","EventBusState","convertFileSizeRaw","bytes","decimals","k","dm","sizes","i","value","scale","wrapPromise","promise","status","suspender","res","err","uuid","c","r","applyMixins","derivedCtor","baseCtors","baseCtor","name","descriptor","arraysEqual","_a","_b","a","b","val","index","deltas","projectedModels","currentModels","newIds","entity","modelId","DEFAULT_REMOVE_MAPPER","DEFAULT_ID_MAPPER","resolveContainerDeltas","container","onAddItem","onUpdateItem","onRemoveItem","idMapper","entities","mappedEntities","removedIds","toAdd","existing","resolveListDeltas","mappedLayers","resolveItemListDeltas","items","processId","prefix","_id","formatter","DIVISIONS","formatDateSince","date","duration","division","isLeapYear","year","getDaysInMonth","month","addMonthsToDate","d","n","addDaysToDate","DEFAULT_LOCALE","dateStyleMap","timeStyleMap","formatDate","dateStyle","locales","formatTime","timeStyle","formatDateTime","context","func","timer","args","EXTENSION_CANVAS_RENDERER","dataMappers","dataLoaders","propertyMappers","indexExtensions","registerExtensionPoint","extensionPoint","_ExtensionManager","extension","extensions","loader","mapper","mappers","_interim","renderer","ExtensionManager","executeLoaderExtension","contextData","executeDataMapperExtension","executePropertyMapperExtension","PLUGIN_EXTENSION_NAME","PluginExtensionManager","__publicField","component","getQueryParams","query","pair","PROFILE_TOOLS_PREVIEW","PROFILE_RELAX_STORE_VALIDATION","PROFILE_LOG_DEBUG","PROFILE_LOG_INFO","defaultConfig","configObj","KosGlobalConfig","resolveKosProfiles","hasKosProfile","profile","isKosLoggingEnabled","resolveLogLevelProfile","showDebugLogProfile","showInfoLogProfile","getLogLevel","params","profileLogLevel","logLevel","getKosMessageLogging","getLogMessageToStudio","WS_LOG","originalFactory","enableMessageLogging","enableStudioMessageLogging","methodName","loggerName","rawMethod","_name","message","arg","level","_level","wsLog","styles","received","conditionallyLog","fn","KosLog","group","_log","override","_d","_c","str","EXTENSION_FEATURE_FLAG_RESOLVER","flagResolvers","input","resolver","m","paths","uniquePaths","acc","path","KosFeatureFlags","LOADER_FEATURE_FLAG","FeatureFlagService","initialFlags","flag","newFlags","hslToHex","h","s","l","f","color","hslStringToHex","hsl","match","resolveVariable","element","variable","variableToHex","defaultMapper","_model","parsedData","mapDataToModel","model","partial","kosAction","deletionMap","KosDeletionManager","timeouts","KosDependencyManager","dependencyId","usedBy","uses","KosModelState","KosModelEvents","KosModelCache","preloadKeys","observable","createFn","SubscriptionHandlers","DependencyModels","FutureService","ChildModels","ParentModel","LogConfig","ReferenceConfig","KosModelSymbol","ModelEffects","CompanionParentModel","FutureContainerSetup","MultipleFutureContainerSetup","FutureAliases","TroubleAwareSetup","LoggerSetup","ContainerAwareSetup","kosChild","target","createPropKey","createOptionKey","DEFAULT_OPTION_KEY","kosParentAware","constructor","parentId","kosCompanion","mode","parentProperty","excludeProperties","kosContainerAware","containerProperty","includeMethods","includeGetters","modelsProperty","containerOptions","kosContext","_target","_propertyKey","originalMethod","ctx","KosContextManager","kosFutureAware","handlerProperty","kosMultipleFutureAware","DependencyLifecycle","HttpRouteHandlers","BROWSER_ROUTER_DEPENDENCY_KEY","createHttpMethodDecorator","method","propertyKey","routeConfig","get","post","put","del","httpDelete","hasHttpRouteHandlers","getHttpRouteHandlers","kosLogger","KosLoggerFactory","modelTypeName","nameParts","kosLoggerAware","loggerProperty","loggerContext","getModelType","sharedLogger","modelType","kosModelEffect","props","kosReference","kosTroubleAware","pathProperty","kosDependency","lifecycle","MultipleFutureHandler","defaultContext","kosObservable","makeAutoObservable","future","alias","disposer","kosAutoEffect","FutureHandler","e","troubleByTypeReducer","trouble","type","KosObservableData","ObservableDataMap","property","createAtom","makeObservable","hadKey","action","initialData","createObservableData","BaseClass","instance","ObservableData","od","arraysAreEqual","arr1","arr2","item1","KosContainerIndex","autorun","currentValue","values","set","runInAction","tempMap","tempData","valueItem","models","observeComputedProperties","keys","descriptors","isComputedProp","p","prop","reaction","newValue","oldValue","KosModelContainer","extensionOptions","indexMap","tmp","curr","modelKey","idx","sortKey","list","ids","defer","_disposer","_entries","_values","_reverseMap","v","change","fnIndexs","computedDisposers","observe","indexName","indexKey","destroyKosModel","thisArg","compareFn","callbackfn","whenReady","dataModel","KosCore","unloadKosModel","resetKosModel","isKosModelReady","getKosModelType","getKosModel","getKosModelSync","findModels","findModel","getKosCompanionModel","kosModel","companionModel","getAllKosCompanionModels","getObservableCompanions","resolveKosCompanion","isKosModel","KosModelFactory","factory","Kos","coreModels","preloadModels","companionModels","RegistrationManager","root","registration","preload","register","isKosModelRegistration","parentType","companion","companions","registerLegacyModel","registerKosModel","registerCompanionModel","preloadKosModel","isUpdateable","item","KosBaseModelRegistration","KosModelRegistrationFactory","optionsFactory","SingletonKosModelRegistrationFactory","resolveParameters","modelData","_value","propRegex","_depId","hasUnresolvedProp","isOnlyPropKey","propName","resolveParentContext","TargetClass","parentIdRaw","injectFutureServices","modelInstance","injectDependencies","dependencies","dependency","resolvedId","optKey","optVal","injectFutureContainerSupport","futureSetup","futureHandler","injectMultipleFutureContainerSupport","setup","aliases","futureGetterName","injectTroubleAwareSupport","troubleSetup","pathValue","injectContainerAwareSupport","containerSetup","legacy","finalContainerOptions","injectCompanionSupport","companionConfig","parentModel","lifecycleMethods","internalMethods","isTopicHandler","subscriptionHandlers","handlerFunc","shouldExclude","properties","prototype","propertyName","parentValue","makeSafeObservable","modelConstructorProxy","logger","typedCtor","modelConfig","proxiedCtor","kosSubscribe","topic","websocket","condition","t","extractTrailingWildcard","pattern","actualTopic","wildcardName","captured","hasTrailingWildcard","kosTopicHandler","_payload","fos","bridge","skipParse","destinationAddress","flow","enhancedHandler","debounceDelay","throttleInterval","createDebouncedHandler","createThrottledHandler","createBufferedHandler","createOnceHandler","enhancedCondition","originalCondition","payload","raw","handlerConfig","setupReplayHandler","originalHandler","discardIntermediate","accumulated","batch","lastCall","pendingFlush","timeSinceLastCall","bufferConfig","maxSize","called","EventBusFunctional.replay","modelEventTopicFactory","modelTypeEventTopicFactory","awaitFirstMatchingWhen","conditions","disposers","onMatch","when","PROMISE_TIMEOUT","ModelError","rejectAfterDelay","ms","_","transitionToActive","transitionToReady","transitionToLoad","transitionToUnload","transitionToInit","Transitions","TransitionMap","createModelDependency","_dataModelId","dataModelId","getDependenciesByLifecycle","dependentModel","readyFn","cancel","executeListLifecycle","sourceModel","sourceLifecycle","childPromises","modelPromise","failedChildren","timeoutPromise","timeoutCancel","executeChildrenModelLifecycle","child","executeDependentModelLifecycle","failed","isPrintable","isKosDataModel","isKosModelContainer","resolveChild","attribute","ObservableMap","applyKosModelDevtoolsSupport","hiddenFields","enhanceModelDataForDevtools","children","json","KosChildResolver","uniqueChildren","resolvedModels","childModel","rawChildren","KosCompanionModelManager","hostModel","KosEffectManager","modelEffects","effectName","autoRunHandler","dispose","activeMachine","machine","createMachine","transition","invoke","interpret","_service","onlineMachine","service","active","online","immediate","fsm","KosFSMManager","BROWSER_ROUTER_MODEL_TYPE","KosHttpRouteManager","router","routes","route","pathTemplate","resolvedPath","propValue","boundHandler","req","totalRemoved","removed","registerHttpRoutes","KosOfflineQueue","KosOnlineLifecycleManager","onlineUnsub","EventBus.subscribe","offlineUnsub","AsyncEventIterator","originalSubscribe","iterate","KosFetchMethods","createStudioMessage","requestId","createFosBaseMessage","ordered","tracker","createBaseMessage","createMessageBody","body","_msg","createHeaders","_headers","callbackFn","createReadableStream","sent","controller","push","done","createStudioMessageRequest","createKosMessage","requestType","sendKosMessage","wrappedMsg","socketTransport","createStudioMessageResponse","sendStudioMessageRequest","sendStudioMessage","createBroadcastMessageResponse","createKosHtpMessageResponse","sourceAddress","createKosMessageResponse","sendBroadcastMessage","sendKosMessageResponse","sendKosHttpMessageResponse","getMessageBody","WebSocketBridgeTransport","address","processKosMessage","MESSAGE_SEPARATOR","SEPARATOR","HEADER_SEPARATOR","headerText","line","header","processKosSnifferMessage","BaseTransport","host","port","protocol","onConnectionEstablished","onConnectionLost","Transport","subscriptionTopic","msgBody","msgHeaders","snifferHeaders","snifferBody","EventBus.publish","ex","returnData","BridgeTransport","addr","that","BridgeMessageTransport","FosTransport","KosTransport","TransportFactory","fosPort","Logger","KosWSTransportStatus","WebSocketEvents","WebSocketTransport","token","initialize","computed","connectionEstablished","ev","connectionId","connectionParam","connId","dstAddr","socket","FlowControlManager","eventStream","batchConfig","queuedEvent","maxWait","lastFlush","flushBatch","currentBatch","filteredBatch","timeSinceLastFlush","flushed","shouldProcess","windowStart","currentCount","window","waitTime","maxConcurrent","maxQueue","dropPolicy","onQueueFull","overflow","droppedEvents","timeSinceLastProcessed","KosSubscriptionManager","offlineQueue","topicLifecycle","resolvedTopic","allDisposers","activatable","socketSub","subscribedDestinationAddress","matchedDestinationAddress","wildcardCapture","offlineHandler","extendedPayload","template","flowManager","flowProcessor","eventSource","AsyncEventBus.iterate","processedData","handlerPromise","originalError","retryConfig","lastError","attempt","stats","createTaggedLogger","base","tag","hasModelEffects","hasSubscriptionHandlers","KosModelComponentFactory","companionManager","childResolver","components","subLogger","MODEL_LOADER","KosModel","activeStatus","onlineStatus","companionParent","MODEL_LOADER_TYPE","loadedContext","_e","childrenUnload","_f","visitor","isKosCompanionTypeFactory","obj","KosModelInstantiator","registry","cache","typeId","modelRegistry","dataInstance","activeModel","companionDefs","companionType","companionId","KosModelRegistry$1","_registry","reg","builder","modelFactory","MODEL_DELETION_DELAY","KosModelManager","KosModelRegistry","modelFilter","companionRegistration","KosCoreState","KosCoreEvents","coreFsm","core","getConnectionAlias","envAlias","getDefaultProtocol","defaultProtocol","hostUrl","getDefaultHost","defaultHost","envHost","getDefaultPort","defaultPort","envPort","isReloadable","isUnloadable","AuthState","connectionAlias","ws","currentTime","modelManager","elapsed","transport","dataMapper","propertyMapper","arrayBufferToBase64","binary","base64ToArrayBuffer","base64","blobToArrayBuffer","blob","arrayBufferToBlob","serializeFormData","formData","fields","files","entries","createChunkedStream","onPull","processRequestBody","serialized","WS_TIMEOUT","fetchMessageFactory","kosFetchWs","url","urlObj","TIMEOUT","messageFactory","processedBody","additionalHeaders","responseMsg","responseHeaders","contentType","encoding","responseBody","bodyData","text","parsed","encoder","BASE_URL","kosFetch","KosModelVisitor","rootModel","stopVisiting","resolveBaseUrl","ERROR_UNKNOWN","clientRequest","endpoint","fullUrl","fetchOptions","createClient","MiddlewareChain","middleware","next","processMiddleware","chain","updateModelRegistration","modelRegistration","updateCompanionModelRegistration","TOPIC","pairedClientHeartbeat","relationshipId","onAbort","beatTime","lastHeartBeat","_waitTime","waitInterval","timeDiff","_beatTime","beatInterval","cleanUpHeartbeat","handleAbort","pipe","fns","x","BASE_OPTIONS","retryWithExponentialBackoff","operation","_options","maxAttempts","baseDelayMs","backoffFactor","delayMs","resolveServiceUrl","deleteModel","_fetch","urlOverride","studio","destinationAddressOverride","addCommonParams","getAll","FetchError","getOne","resolvedUrl","getModelById","add","modifyModel","ServiceFactory","basePath","getAllPath","getOnePath","deleteModelPath","addModelPath","modifyModelPath","mock","_sessionKey","getKosSessionKey","isLocalRefId","waitForRequest","op","sendRequest","requestPromise","refId","syncPublish","_requestId","contextMap","KosContextBean","parent","resolveKosContext","KosDataContainer","observableData","isObservable","KosRegistration","childRegistration","KosSingletonRegistration","KosToken","BrowserKosRouter","middlewares","initialRoutesLength","rawReq","routePath","part","param","requestPath","queryString","routeParts","requestParts","sendIntent","intent","EventBus.hasEventSubscriptions","sendAsyncIntent","waitForAppsToStart","appIds","throwOnTimeout","requirePostStarted","eventTopics","appId","startedApps","EventBusState.waitForAllWithState","api","apps","app","notStartedApps","waitForAppToStart","checkAppsStarted","serviceResponse","getStartedApps","kosWhen","kosComputed","kosEffect","FUTURE_NOT_ASSIGNED","EVENT_TROUBLE_ADDED","EVENT_TROUBLE_REMOVED","KosCoreModelPropertyMapper","Topics","URL","hasDecimals","option","postModel","modifyConfigBean","getConfigBean","isBoolean","isNumber","evaluateScopes","scopes","overrides","flattenObject","parentKey","newKey","mapDtoToConfigBeanModel","dto","bean","flattened","mapUpdateDtoToConfigBeanModel","previousValue","mapConfigBeanModelToDto","buildConfigBeanModel","configBeanOptions","matchValue","patterns","CONFIG_BEAN_MODEL_TYPE","PATH_PROP","ConfigBeanModelImpl","modifyConfigBeanService","getConfigBeanService","schemaResponse","configBean","__decorateClass","ConfigBean","kosConfigBean","lazy","serviceBasePath","getRegionInfo","getRegions","UnitTupleKeys","timeTuples","unitSystemMapReducer","unitSystem","system","units","unit","unitTuple","measureMapReducer","systemAcc","measures","measure","systemMeasure","defaultMeasureMapReducer","MODEL_TYPE","RegionInfoModelImpl","_timeFormatId","selectedTimeFormatId","resolvedTimeFormatId","_dateFormatId","selectedDateFormatId","timeFormatId","dateFormatId","unitSystemId","_unit","measureUnitSystems","unitSystemUnits","defaultUnit","fromUnit","toUnit","fromOffset","fromScale","toScale","toOffset","from","to","fromName","toName","measureSystems","regions","region","regionInfo","timeFormat","dateFormat","Registration","createUnitSource","source","defaultSystem","defaultMeasure","convert","RegionInfo","defaultToSource","formatUnit","format","normalized","locale","maxDecimals","minDecimals","convertWithUnits","convertedValue","defaultDecimals","_format","generateEvenlyDistributedArray","start","end","step","generateIntervalArray","conversionMap","configOptionsFactory","schema","displayOptionsFactory","isEnum","convertFormats","secondsToFormattedTime","secondsSinceMidnight","formatString","midnight","time","SERVICE_PATH_PROP","KosConfigPropertyImpl","defaultUnitSystem","converter","defaultOptions","backend","display","_val","current","timeFormatString","currentSystem","defaultFormatter","_formatter","formatOptions","globalMeasure","toMeasure","fromMeasure","_measure","_g","_i","_h","toSystem","_k","_j","fromSystem","updateValue","kosConfigProperty","optionsExpander","_converter","KosConfigPropertySpec","FUTURE_MODEL_TYPE","FutureFactory","isMock","FutureEndState","addModel","getFutures","deleteFuture","addFuture","modifyFuture","cancelFuture","mapDtoToFutureOptions","mapDtoToFutureModel","buildFutureModel","futureOptions","buildFuture","FutureModel","remaining","milliseconds","parts","FutureModel$1","HTTP_REQUEST_TOPIC","HTTP_RESPONSE_TOPIC","BrowserRouterModelImpl","destination","src","code","BrowserRouter","FUTURE_CONTAINER_MODEL_TYPE","FutureContainerFactory","initiateFuture","futureModel","getFuture","FutureManager","FutureContainerModel","deleteFutureService","addFutureService","futureId","newFutureModel","FutureContainerModel$1","deleteKeyValue","namespace","updateKeyValue","getKeyValue","deleteKeyValueNamespace","KeyValueModelImpl","studioState","update","KeyValue","INUMBER","IOP1","IOP2","IOP3","IVAR","IVARNAME","IFUNCALL","IFUNDEF","IEXPR","IEXPREVAL","IMEMBER","IENDSTATEMENT","IARRAY","Instruction","unaryInstruction","binaryInstruction","ternaryInstruction","simplify","tokens","unaryOps","binaryOps","ternaryOps","nstack","newexpression","n1","n2","n3","substitute","expr","j","expritem","replitem","evaluate","argCount","isExpressionEvaluator","resolveExpression","numTokens","scope","len","createExpressionEvaluator","expressionToString","toJS","escapeValue","contains","array","getSymbols","symbols","withMembers","prevVar","Expression","parser","vars","functions","variables","TEOF","TOP","TNUMBER","TSTRING","TPAREN","TBRACKET","TCOMMA","TNAME","TSEMICOLON","Token","TokenStream","expression","pos","startPos","quote","rawString","hasLetter","codePointPattern","codePoint","backslash","radix","validDigit","valid","resetPos","foundDot","foundDigits","acceptSign","validExponent","column","newline","coords","ParserState","tokenStream","instr","isPrefixOperator","exprInstr","varName","varValue","lastInstrIndex","trueBranch","falseBranch","COMPARISON_OPERATORS","ADD_SUB_OPERATORS","TERM_OPERATORS","mul","div","mod","concat","equal","notEqual","greaterThan","lessThan","greaterThanEqual","lessThanEqual","andOperator","orOperator","inOperator","sinh","cosh","tanh","asinh","acosh","atanh","log10","neg","not","trunc","random","factorial","gamma","isInteger","GAMMA_G","GAMMA_P","twoN","threeN","fourN","fiveN","stringOrArrayLength","hypot","sum","larg","cond","yep","nope","roundTo","exp","setVar","arrayIndex","max","min","arrayMap","arrayFold","init","arrayFilter","stringOrArrayIndexOf","arrayJoin","sep","sign","ONE_THIRD","cbrt","expm1","log1p","log2","Parser","parserState","sharedParser","optionNameMap","getOptionName","optionName","operators","ReactiveExpression","getContextData","KosExpressionEvaluatorModelImpl","newData","pathSegments","lastSegment","segment","expressionString","reactiveExpression","newResult","currentResult","anonymousId","KosExpressionEvaluator","SERVICE_PATH","getLogOverrides","API","TOPIC_OVERRIDE_ADD","TOPIC_OVERRIDE_REMOVE","getLogLevelName","KosLogManagerModelImpl","loggers","resultMap","_req","_logger","uiOverrides","KosLogManager","setTime","setDate","setTimezone","timezone","getTimezone","TOPIC_TIME_CHANGE","TOPIC_DAY_CHANGE","TOPIC_TIMEZONE_CHANGE","KosTimeModelImpl","tz","KosTime","LogBlockContainerModelImpl","getKosConnectionId","getLogStreams","subscribeToLogStream","stream","nodeId","unsubscribeFromLogStream","createOverride","getLogStreamBlocks","getLogStreamBlock","blockId","LogBlockModelImpl","blockData","lines","replace","baseLines","LogBlock","LogBlockContainer","LogStreamModelImpl","firstBlock","currentBlockId","block","blockNum","lastBlock","previousBlocks","secondLastBlock","resolveQueue","currentIndex","prev","latestBlock","newLines","LogStream","TOPIC_ADD_BLOCK","TOPIC_UPDATE_BLOCK","TOPIC_REMOVE_BLOCK","TOPIC_LOG_LINES","TOPIC_ADD_STREAM","LogStreamContainerModelImpl","streamName","logStream","streams","LogStreamContainer","isRankedInfo","isRoleAwareInfo","isColorAwareInfo","defaultTroubleRankMapper","info","defaultTroubleColorMapper","defaultTroubleRoleMapper","getTroubles","servicePath","resolveTrouble","troubleId","futureResponse","bulkResolveTroubles","troubleIds","EXTENSION_TROUBLE_DATA_MAPPER","troubleMappers","EXTENSION_TROUBLE_MAPPER","troublePathFactory","ifaces","iface","troubleDataFactory","troubleExtension","ResolvableTroubleHandler","BlockPumpTroubleHandler","TroubleHandlerFactory","isDeferAware","TroubleModelImpl","resolvable","tags","clientData","rank","createTime","role","rest","kosFuture","Trouble","troubleRankMapper","troubleColorMapper","troubleRoleMapper","Troubles","TroubleContainerModelImpl","_troubles","newTrouble","TroubleContainer","getArtifacts","getLastRequest","requests","lastRequest","provider","currentConfig","currentLastUpdateTime","mapOTAArtifactResponseToUpdaterItem","otaArtifactResponse","artifactInfo","manifest","OtaModelImpl","artifacts","Ota","createCancellableService","serviceFunction","wrappedFunction","currentController","getSoftwareInfos","signal","getSoftwareInfosWithCancel","SoftwareInfoModelImpl","arr","cur","nodes","updatedList","el","SoftwareInfo","getStateBeanData","StateBeanModelImpl","stateBean","StateBean","StatePropModelImpl","StateProp","getStateProps","getTranslations","rootUrl","getLocalizationDescriptor","getKosLocalizationDescriptor","CONTEXT_LANG_RESOLVER","extractOptions","isBasicOptions","isDataObject","defaultValue","flattenedChild","mergeObjects","overlay","expandMacros","regex","replacedText","replaceText","splitKey","currentNamespace","_key","TranslationModelImpl","_locale","langs","reversed","allTranslations","lang","translationsPath","ns","contextKey","previous","Translation","pathJoin","defaultResolver","namespaceDescriptor","localePath","TranslationContainerModelImpl","firstLocale","namespaceDefault","translation","TranslationContainer","TranslationContext","KosTranslations","tc","isTroubleAware","WS_EVENT_TYPE","WsEventFactory","stringify","WsEventModel","_data","isSend","isUnique","msgId","rawKey","rawData","DEBUG","PATH_CANVAS_DATA","sendCanvasData","apiPathOverride","FULL_PATH","encodeFrame","rgba","stripAlpha","rgb","isDoneAware","CanvasRendererModelImpl","clear","apiPath","isOneShot","dataString","clearCanvas","canvasWidth","canvasHeight","pixelCount","blankPixels","doneAware","shouldClear","initialPixels","renderLoop","pixels","CanvasRenderer","VideoRendererBase","width","height","intervalMs","WebGLRendererBase","gl","flipped","y","dst","DropRenderer","speedPx","vertexShaderSource","fragmentShaderSource","vertexShader","fragmentShader","normalizedSpeed","shader","program","Canvas2DRendererBase","OneShotRendererMixin","Base","Mixin","cb","GradientBase","GradientRenderer","colors","direction","speed","loop","startX","endX","gradient","ImageRenderer","LoopingVideoRenderer","hexToRgb","hex","cleanHex","g","normalizeColor","toRgbString","MatrixRenderer","fadeFactor","imageData","colY","trailIndex","OverlayRenderer","rendererFactory","img","basePixels","position","ScrollingImageRenderer","gap","deltaTime","moveDistance","aspectRatio","drawWidth","drawHeight","offsetX","offsetY","xPos","nextXPos","yPos","nextYPos","isOffScreen","svgText","processedSvg","dataUrl","svgContent","newColor","ScrollingTextRenderer","maxWidth","lineWidth","totalTextHeight","startY","baseOffsetX","baseOffsetY","alignment","lineX","lineY","SequenceRenderer","patternId","patternSpec","modifiedData","getRenderer","store","SolidColorRenderer","colorValue","SweepRenderer","minHue","maxHue","hue2rgb","q","hue","mappedHue","canvasRenderers","RendererClass","ImageRendererFactory","OverlayRendererFactory","rendererData","num","CanvasDispatcherModelImpl","contentUrl","rendererModel","patternData","requestData","CanvasDispatcher","getSerialNumber","getDeviceDetails","TOPIC_CRITICAL_DATA_CHANGED","TOPIC_CRITICAL_DATA_AVAILABLE","DeviceModelImpl","nodeType","nodeName","device","serialNumber","Device","NetworkInterfaceModelImpl","NetworkInterface","getNetworkInterfaces","NetworkInterfaceContainerModelImpl","networkInterfaces","networkInterfaceData","networkInterfaceModel","NetworkInterfaceContainer","getStorageDevices","StorageDeviceModelImpl","StorageDevice","TOPIC_STORAGE_AVAILABILITY","StorageDeviceContainerModelImpl","devices","storageDevice","StorageDeviceContainer","getAvailableUpdates","installUpdate","manifestId","deviceId","UsbUpdateModelImpl","UsbUpdate","UsbUpdateContainerModelImpl","updates","allKeys","UsbUpdateContainer","CoreModels","Registry","PRELOAD","registerCoreModels","_KosModelRegistry","CoreExtensionManager","subscribeStore","stateKey","sessionId","toolState","REGION_PATH","REGION_ATTRIBUTE","REGION_ID","updateRegion","TIMER_EVENT","TOPIC_TIMER_TICK_EVENT","TIMER_END","isConfigProperty","KosTimer","defaultActions","timeoutValue","timerAction","existingAction","actionName","actions","updatedActions","timers","executeOnTimer","TimerManager","REGION_SETTINGS_PATH","TIMEZONE_ATTRIBUTE","REGION_TIMEZONE_ID","updateTimeZone","timezoneInfo","isFutureResponse","abortController","original","abortControllerInstance","effectDisposer","enhancedArgs","lastArg","cancelledError","kosStateBean","kosStateProp","studioLogin","username","password","login","configResponse","studioStartPasswordReset","userId","startPasswordReset","studioResetPassword","resetPassword","studioAcceptOrgInvitation","acceptOrgInvitation","createCancellablePromise","promiseOrOptions","cancelFn","futureRef","cancellablePromise","currentProgress","currentStatus","isRunning","progressCallbacks","newProgress","newStatus","newIsRunning","run","keyframes","loadingDot","css","Portal","createPortal","LoadingMessage","theme","jsx","jsxs","MessageContainer","styled","ErrorBoundary","React","errorInfo","statusMap","ProgressBar","title","subtitle","progressBarContainer","progressContainer","titleContainer","progress","indeterminate","defaultProps","KosModelContext","createContext","useContextModel","useContext","KosModelProvider","setModel","useState","setKosModel","useCallback","defaultNestedProps","NestedModelContext","KosModelCollectionProvider","setModels","prevModels","DEFAULT_FILTER","useContextModelHierarchy","useMemo","useModelFromHierarchy","DefaultLoader","KosModelLoader","fallback","modelProps","ErrorBoundaryWithFallback","Suspense","KosModelLoaderDisplay","setCurrentModel","isReady","setIsReady","hierarchyContext","useEffect","Fragment","DEFAULT_TRANSLATIONS","CreateModelTranslationsContext","CreateModelTranslationsProvider","translations","merged","fetchKosCore","kosCore","KosContext","initKosProvider","resource","KosCoreContextProvider","setOnline","observer","useKosCore","MAX_RETRIES","waitForRetry","depth","fetchData","fetcher","entry","useSuspenseData","fetchModel","modelOptions","activate","retryCount","_factory","useKosModel","destroyOnUnmount","kosCoreContext","ready","setReady","setError","waitForModel","_ready","useKosTime","KosTimeContext","KosTimeProvider","useKosTimeContext","useSoftwareInfo","withSoftwareInfo","WrappedComponent","SoftwareInfoContext","SoftwareInfoProvider","useSoftwareInfoContext","TokenContext","TokenProvider","TranslationContainerContext","KosTranslationProvider","appContext","descriptorResolver","localization","setLocalization","setTranslations","resolvedRootUrl","_appContext","initTools","descriptorPromises","localizationDescriptor","namespaceKey","initLocalization","_rootUrl","content","useKosTranslationContext","useCanvasDispatcher","withCanvasDispatcher","decodeBase64RGB","renderDecodedPreview","pixelSize","decode","tempCanvas","tempCtx","PIXEL_SIZE","CanvasStreamerBase","kosComponent","canvasDispatcher","defaultFps","showPreview","canvasRef","useRef","setRenderer","_endpoint","onFrame","previewCtx","Main","PreviewContainer","CanvasStreamer","useDevice","withDevice","corePromise","withKosTime","useNetworkInterfaceContainer","withNetworkInterfaceContainer","useOta","withOta","useOutsideAlerter","ref","onAction","handleClickOutside","handleEscFunction","OutsideAlerter","wrapperRef","useStateProperty","stateProp","setValue","waitForProp","useStorageDeviceContainer","inserted","setInserted","setDevices","withStorageDeviceContainer","LOG","useTimer","timerName","onTimerExpired","onTimerTick","timerEventActions","autoStart","remainingTime","TOPIC_TIMER_TICK","pause","escapeRegExp","toEscape","escapableChars","isRegExp","toTest","isString","replaceString","_toMatch","toMatch","length","stringComponentInsert","_source","substituteBlocks","stringValue","componentsMap","blocks","Trans","i18nKey","defaults","translated","fetchTranslationContainer","fetchTranslations","additionalNamespaces","trans","additional","useKosTranslation","baseOptions","allNamespaces","defaultNamespace","translationModel","i18n","expandedKey","useTranslationContainer","withTranslationContainer","useTroubleModel","useTroubleContainerModel","useTroublePresence","troubleType","setActive","troubles","setTroubles","onComplete","troublesByType","activeTroubles","withTroubleContainer","useUsbUpdateContainer","updateAvailable","setUpdateAvailable","setUpdates","withUsbUpdateContainer","useConfigBean","propKey","setConfig","reducer","useConfigProperty","configProperty","optionsTransformer","dispatch","useReducer","handleUpdate","mapped","yearToUse","daysInEachMonth","getDays","getDaysArray","numberOfDays","daysAry","getMonthsArray","getYearsArray","number","yearsArray","getFormattedYearsArray","range","fullYearsArray","getFormattedMonthsArray","monthFormat","getFormattedDate","day","displayOrder","correctedMonth","monthName","yearName","dayName","getFormattedYear","getFormattedMonth","getCalendarMonthArray","dayOptions","formattedYear","firstDay","isValidDate","zeroIndexedMonth","getLastDayOfMonth","getDayStrings","dayFormat","useDateArrays","yearRange","daysOfWeekFilter","yearFormat","useYears","yearsOptionsArray","useYearsOptions","monthsArray","useMonths","monthsOptionsArray","useMonthsOptions","daysArray","useDays","daysOptionsArray","useDayOptions","calendarDayArray","useCalendarDayArray","dayNamesArray","useDayNames","rawYearsArray","monthLabelsArray","isFilteredDayOfWeek","filters","dateToCheck","rawDaysArray","useFormattedDate","indexedMonth","dayOptionsArray","DateDisplayFormat","useDateProps","yearProp","monthProp","dayProp","yearsRange","setYear","setYearRange","setMonth","setDay","formattedDate","nextMonth","lastValidDay","prevMonth","nextYear","prevYear","useRegionalTimeDate","formattedTime","setFormattedTime","setFormattedDate","ignoreDate","dateToFormat","parseISO","useDateRelativeData","secondsFromMidnight","hours","setHours","minutes","setMinutes","seconds","setSeconds","numericValue","_hours","_minutes","_seconds","useDateRelativeConfig","timeActions","timeoutRef","useFunctionWarmup","warmup","DEFAULT_FORMAT_MAP","useKosDateFormats","dateFormatMap","dateFormats","setDateFormats","selectedDateFormat","setSelectedDateFormat","handleDateFormatChange","o","DEFAULT_OPTION_MAP","useKosTimeZones","optionsMap","timeZones","setTimeZones","selectedTimeZone","setSelectedTimeZone","DEFAULT_REGION_MAP","useKosRegions","regionMap","setRegions","selectedRegion","setSelectedRegion","useKosTimeFormats","timeFormatMap","timeFormats","setTimeFormats","selectedTimeFormat","setSelectedTimeFormat","handleTimeFormatChange","useLocalComputed","DEFAULT_OPTIONS","useMutationObserver","targetEl","setObserver","obs","DomIntersectionStrategy","_state","boundingRect","clientX","clientY","usePressGesture","onPressed","onRelease","intersectionStrategy","isDraggingInside","bind","useGesture","handlePointerDown","handlePointerUp","handlePointerOut","useProjectReload","reloading","setReloading","useHourValues","hour12","hour","useTimeValues","labelOffset","valueOffset","label","useAmPmValues","period","formattedPeriod","useTimeOptions","minute","second","hourOptions","minuteOptions","secondOptions","amPmOptions","useFormattedTime","useTimeProps","initialDate","prevDate","newDate","useRegionTimeProps","regionModel","withProjectReloading","getStudioProperties","TOPIC_PROPERTIES","DEFAULT_STUDIO_PROPERTIES","StudioPropertiesModelImpl","StudioProperties"],"mappings":"kiBAAaA,GAAgB,SAChBC,GAAe,QACfC,GAAa,MACbC,GAAoB,aACpBC,GAAqB,cACrBC,GAAS,SACTC,GAA0B,WAC1BC,GAAqB,WACrBC,GAAsB,OACtBC,GAAiB,UACjBC,GAAsB,UACtBC,GAAsB,eACtBC,GAAuB,gBAEvBC,GAAwB,YACxBC,GAAa,QAAQ,IAAI,eAAiB,mBAC1CC,GAAO,QAAQ,IAAI,cAAgB,OAEnCC,GAAY,GAAGF,EAAU,IAAIC,EAAI,GAEjCE,GAAe,aAErB,IAAKC,IAAAA,IACVA,EAAA,KAAO,mBACPA,EAAA,SAAW,sBAFDA,IAAAA,IAAA,CAAA,CAAA,EAKAC,IAAAA,IACVA,EAAA,YAAc,oBADJA,IAAAA,IAAA,CAAA,CAAA,EAGL,MAAMC,GAAwB,oBC7BrCC,EAAI,KAAK,wBAAwB,EACjC,WAAW,IAAM,WAAW,KAAO,CAAA,EACnC,WAAW,IAAI,cAAgB,WAAW,IAAI,eAAiB,CAAA,EAC/D,MAAMC,EAAqC,WAAW,IAAI,cACpDC,GAAkB,IAAM,OAAO,UAAU,EAaxC,SAASC,GAAsBC,EAA4B,CAChE,OACEH,EAAcG,CAAS,GACvB,OAAO,sBAAsBH,EAAcG,CAAS,CAAC,EAAE,OAAS,CAEpE,CAcO,SAASC,EACdD,EACAE,EACA,CACA,MAAMC,EAAKL,GAAA,EAC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