@kosdev-code/kos-ui-sdk 3.0.21 → 3.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/core/core/kosCore.d.ts +1 -0
  2. package/core/core/kosCore.d.ts.map +1 -1
  3. package/core/core/kosModel.d.ts +11 -0
  4. package/core/core/kosModel.d.ts.map +1 -1
  5. package/core/core/kosModelManager.d.ts +8 -0
  6. package/core/core/kosModelManager.d.ts.map +1 -1
  7. package/core/core/lifecycle/constants.d.ts +1 -1
  8. package/core/core/lifecycle/constants.d.ts.map +1 -1
  9. package/core/core/model/kos-subscription-manager.d.ts +1 -0
  10. package/core/core/model/kos-subscription-manager.d.ts.map +1 -1
  11. package/core/core/registration/index.d.ts +1 -1
  12. package/core/core/registration/index.d.ts.map +1 -1
  13. package/core/core/registration/model-registration.d.ts +11 -0
  14. package/core/core/registration/model-registration.d.ts.map +1 -1
  15. package/core/index.d.ts +1 -1
  16. package/core/index.d.ts.map +1 -1
  17. package/core/util/kos-model-utils.d.ts +13 -0
  18. package/core/util/kos-model-utils.d.ts.map +1 -1
  19. package/{index-DUoSahlA.cjs → index-CRb8ucfF.cjs} +115 -48
  20. package/index-CRb8ucfF.cjs.map +1 -0
  21. package/{index-BUwbSjst.js → index-YzHb2lnB.js} +116 -49
  22. package/index-YzHb2lnB.js.map +1 -0
  23. package/index.cjs +113 -26
  24. package/index.cjs.map +1 -1
  25. package/index.js +114 -27
  26. package/index.js.map +1 -1
  27. package/models/decorators/kos-config-bean-prop.d.ts +5 -0
  28. package/models/decorators/kos-config-bean-prop.d.ts.map +1 -1
  29. package/models/decorators/kos-config-bean.d.ts +7 -1
  30. package/models/decorators/kos-config-bean.d.ts.map +1 -1
  31. package/models/models/config-bean/config-bean-model.d.ts +9 -0
  32. package/models/models/config-bean/config-bean-model.d.ts.map +1 -1
  33. package/models/models/config-bean/config-bean-types.d.ts +2 -0
  34. package/models/models/config-bean/config-bean-types.d.ts.map +1 -1
  35. package/models/models/config-bean-prop/config-bean-prop-model.d.ts +3 -0
  36. package/models/models/config-bean-prop/config-bean-prop-model.d.ts.map +1 -1
  37. package/models/models/config-bean-prop/types/index.d.ts +10 -0
  38. package/models/models/region-info/region-info-model.d.ts +12 -1
  39. package/models/models/region-info/region-info-model.d.ts.map +1 -1
  40. package/models/models/region-info/services/region-info-services.d.ts +2 -2
  41. package/models/models/region-info/services/region-info-services.d.ts.map +1 -1
  42. package/models/models/region-info/types/index.d.ts +7 -0
  43. package/models/models/region-info/types/index.d.ts.map +1 -1
  44. package/models/services/config-bean/index.d.ts +2 -2
  45. package/models/services/config-bean/index.d.ts.map +1 -1
  46. package/package.json +2 -2
  47. package/testing/index.d.ts +51 -9
  48. package/testing/index.d.ts.map +1 -1
  49. package/testing.cjs +57 -3
  50. package/testing.cjs.map +1 -1
  51. package/testing.js +57 -3
  52. package/testing.js.map +1 -1
  53. package/index-BUwbSjst.js.map +0 -1
  54. package/index-DUoSahlA.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-BUwbSjst.js","sources":["../../../packages/kos-ui-sdk/src/common/constants/index.ts","../../../packages/kos-ui-sdk/src/common/events/eventBus.ts","../../../packages/kos-ui-sdk/src/common/events/eventBus.functional.ts","../../../packages/kos-ui-sdk/src/common/events/eventBus.state.ts","../../../packages/kos-ui-sdk/src/core/util/get-query-params.ts","../../../packages/kos-ui-sdk/src/core/util/kos-config-init.ts","../../../packages/kos-ui-sdk/src/core/util/log-utils.ts","../../../packages/kos-ui-sdk/src/core/core/log/log.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/propKeys.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/fsm-injection-utils.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-execution-context.ts","../../../packages/kos-ui-sdk/src/core/types/kos-dependency.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-http-decorators.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-logger-factory.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-reload-aware.ts","../../../packages/kos-ui-sdk/src/core/util/service-request-error.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/resolve-parameters.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-service-request-helpers.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-service-request.ts","../../../packages/kos-ui-sdk/src/core/types/service-response-store.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-state-machine.ts","../../../packages/kos-ui-sdk/src/models/models/future/future-aware.ts","../../../packages/kos-ui-sdk/src/models/models/trouble/utils/trouble-reducer.ts","../../../packages/kos-ui-sdk/src/core/util/observable-proxy-map.ts","../../../packages/kos-ui-sdk/src/core/core/extension/extension-manager.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/topics.ts","../../../packages/kos-ui-sdk/src/core/core/indexing/types.ts","../../../packages/kos-ui-sdk/src/core/core/kos-container-index.ts","../../../packages/kos-ui-sdk/src/core/core/kos-container-model.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/constants.ts","../../../packages/kos-ui-sdk/src/core/util/when-ready.ts","../../../packages/kos-ui-sdk/src/core/util/kos-model-utils.ts","../../../packages/kos-ui-sdk/src/core/core/kos-model-factory.ts","../../../packages/kos-ui-sdk/src/core/core/registration/registration-manager.ts","../../../packages/kos-ui-sdk/src/core/core/registration/model-registration.ts","../../../packages/kos-ui-sdk/src/core/core/registration/base-kos-model-registration.ts","../../../packages/kos-ui-sdk/src/core/core/registration/singleton-kos-model-registration-factory.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kosModel.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kosTopicHandler.ts","../../../packages/kos-ui-sdk/src/core/core/kos-deletion-manager.ts","../../../packages/kos-ui-sdk/src/core/core/dependency-manager.ts","../../../packages/kos-ui-sdk/src/core/core/model-cache.ts","../../../packages/kos-ui-sdk/src/core/core/model/model-hook-cache.ts","../../../packages/kos-ui-sdk/src/core/util/model-error-utils.ts","../../../packages/kos-ui-sdk/src/core/util/error-logger.ts","../../../packages/kos-ui-sdk/src/core/core/types/registration.ts","../../../packages/kos-ui-sdk/src/core/core/companion-instantiator.ts","../../../packages/kos-ui-sdk/src/models/utils/model-event-utils.ts","../../../packages/kos-ui-sdk/src/core/util/await-first-matching-when.ts","../../../packages/kos-ui-sdk/src/core/constants/model-constants.ts","../../../packages/kos-ui-sdk/src/core/util/model-transition-utils.ts","../../../packages/kos-ui-sdk/src/core/util/promise-utils.ts","../../../packages/kos-ui-sdk/src/core/util/model-type-guards.ts","../../../packages/kos-ui-sdk/src/core/util/model-utils.ts","../../../packages/kos-ui-sdk/src/core/core/model/apply-kos-dev-tool-support.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-child-resolver.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-companion-model-manager.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-effects-manager.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/model-active-machine.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/model-online-machine.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/model-machine.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/kosModelLifecycle.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-fsm-manager.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-http-route-manager.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-offline-queue.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-online-lifecycle-manager.ts","../../../packages/kos-ui-sdk/src/core/util/api-request-id.ts","../../../packages/kos-ui-sdk/src/core/util/binary-utils.ts","../../../packages/kos-ui-sdk/src/core/util/kos-message-utils.ts","../../../packages/kos-ui-sdk/src/core/util/transport-not-ready-error.ts","../../../packages/kos-ui-sdk/src/core/util/kos-fetch.ts","../../../packages/kos-ui-sdk/src/core/util/kos-service-request.ts","../../../packages/kos-ui-sdk/src/models/utils/service.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-service-request-manager.ts","../../../packages/kos-ui-sdk/src/common/events/async-event-bus.ts","../../../packages/kos-ui-sdk/src/core/core/decorators/kos-topic-handler-flow-control.ts","../../../packages/kos-ui-sdk/src/core/util/abortable-when.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-frames.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/future-simulator.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-fixtures.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/route-matcher.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-playback.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-recorder.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-setups.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-config.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-registry.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/mock-interceptor.ts","../../../packages/kos-ui-sdk/src/core/core/transport/web-socket-transport-adapter.ts","../../../packages/kos-ui-sdk/src/core/core/transport/base-message-transport.ts","../../../packages/kos-ui-sdk/src/core/core/transport/bridge-transport.ts","../../../packages/kos-ui-sdk/src/core/core/transport/bridge-message-transport.ts","../../../packages/kos-ui-sdk/src/core/core/transport/fos-message-transport.ts","../../../packages/kos-ui-sdk/src/core/core/transport/kos-message-transport.ts","../../../packages/kos-ui-sdk/src/core/core/transport/mock/standalone-mock-socket.ts","../../../packages/kos-ui-sdk/src/core/core/transport/transport-factory.ts","../../../packages/kos-ui-sdk/src/core/core/transport/webSocketTransport.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-subscription-manager.ts","../../../packages/kos-ui-sdk/src/core/core/model/logger-utils.ts","../../../packages/kos-ui-sdk/src/core/core/model/model-introspection-utils.ts","../../../packages/kos-ui-sdk/src/core/core/model/service-response-store.ts","../../../packages/kos-ui-sdk/src/core/core/model/kos-model-component-factory.ts","../../../packages/kos-ui-sdk/src/core/core/kosModel.ts","../../../packages/kos-ui-sdk/src/core/core/model-instantiator.ts","../../../packages/kos-ui-sdk/src/core/core/model-registry.ts","../../../packages/kos-ui-sdk/src/core/core/kosModelManager.ts","../../../packages/kos-ui-sdk/src/core/core/lifecycle/kosCoreLifecycle.ts","../../../packages/kos-ui-sdk/src/core/core/kosCore.ts","../../../packages/kos-ui-sdk/src/core/util/kos-model-visitor.ts","../../../packages/kos-ui-sdk/src/core/util/feature-flags.ts","../../../packages/kos-ui-sdk/src/core/util/model-factory.ts","../../../packages/kos-ui-sdk/src/core/util/service-factory.ts","../../../packages/kos-ui-sdk/src/core/util/session-utils.ts","../../../packages/kos-ui-sdk/src/core/core/context/kos-context-manager.ts","../../../packages/kos-ui-sdk/src/core/core/kos-data-container.ts","../../../packages/kos-ui-sdk/src/core/core/services/intent-service.ts","../../../packages/kos-ui-sdk/src/core/core/services/app-startup-service.ts","../../../packages/kos-ui-sdk/src/core/index.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 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\n/**\n * @kosService core.event-bus\n * @kosApiLevel 2\n */\nexport interface ApiCallback<T = string> {\n headers: Record<string, string>;\n body: T;\n}\n/**\n * @kosService core.event-bus\n */\nexport type EventCallback<T = ApiCallback> = (msg?: T) => void;\n\n/**\n * @kosService core.event-bus\n * @kosApiLevel 2\n */\nexport interface PublishResponse {\n eventType: string;\n subscribers: number;\n}\n\n/**\n * @kosService core.event-bus\n * @kosApiLevel 7\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 *\n * @kosService core.event-bus\n * @kosApiLevel 2\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 *\n * @kosService core.event-bus\n * @kosApiLevel 2\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 *\n * @kosService core.event-bus\n * @kosApiLevel 2\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 *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function once<T = ApiCallback>(\n eventType: string,\n callback: EventCallback<T>\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n // Unsubscribe immediately after first call\n subscription.unsubscribe();\n callback(msg);\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Wait for a specific event to occur, returning a Promise\n *\n * @param eventType - The event type to wait for\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the event data\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function waitFor<T = ApiCallback>(\n eventType: string,\n timeout?: number\n): Promise<T> {\n return new Promise((resolve, reject) => {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const unsubscribe = once(eventType, (msg?: T) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n resolve(msg!);\n });\n\n if (timeout) {\n timeoutId = setTimeout(() => {\n unsubscribe();\n reject(new Error(`Timeout waiting for event: ${eventType}`));\n }, timeout);\n }\n });\n}\n","/**\n * Functional programming utilities for the EventBus\n * Provides reactive and promise-based patterns for event handling\n */\n\nimport { ApiCallback, EventCallback, publish, subscribe } from \"./eventBus\";\n\n/**\n * Subscribe to an event that will automatically unsubscribe after the first occurrence\n *\n * @param eventType - The event type to listen for\n * @param callback - The callback to execute once\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function once<T = ApiCallback>(\n eventType: string,\n callback: EventCallback<T>\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n // Unsubscribe immediately after first call\n subscription.unsubscribe();\n callback(msg);\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Wait for a specific event to occur, returning a Promise\n *\n * @param eventType - The event type to wait for\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the event data\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function waitFor<T = ApiCallback>(\n eventType: string,\n timeout?: number\n): Promise<T> {\n return new Promise((resolve, reject) => {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const unsubscribe = once(eventType, (msg?: T) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n resolve(msg!);\n });\n\n if (timeout) {\n timeoutId = setTimeout(() => {\n unsubscribe();\n reject(new Error(`Timeout waiting for event: ${eventType}`));\n }, timeout);\n }\n });\n}\n\n/**\n * Wait for multiple events to occur (Promise.all pattern)\n *\n * @param eventTypes - Array of event types to wait for\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves when all events have occurred\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function waitForAll<T = ApiCallback>(\n eventTypes: string[],\n timeout?: number\n): Promise<T[]> {\n const promises = eventTypes.map((eventType) =>\n waitFor<T>(eventType, timeout)\n );\n return Promise.all(promises);\n}\n\n/**\n * Wait for the first event to occur from a list (Promise.race pattern)\n *\n * @param eventTypes - Array of event types to race\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the first event\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function race<T = ApiCallback>(\n eventTypes: string[],\n timeout?: number\n): Promise<{ eventType: string; data: T }> {\n return new Promise((resolve, reject) => {\n const unsubscribers: (() => void)[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n let resolved = false;\n\n const cleanup = () => {\n unsubscribers.forEach((unsub) => unsub());\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n };\n\n eventTypes.forEach((eventType) => {\n const unsubscribe = once(eventType, (msg?: T) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n resolve({ eventType, data: msg! });\n }\n });\n unsubscribers.push(unsubscribe);\n });\n\n if (timeout) {\n timeoutId = setTimeout(() => {\n if (!resolved) {\n resolved = true;\n cleanup();\n reject(\n new Error(`Timeout waiting for any event: ${eventTypes.join(\", \")}`)\n );\n }\n }, timeout);\n }\n });\n}\n\n/**\n * Filter events based on a predicate function\n *\n * @param eventType - The event type to filter\n * @param predicate - Function to test each event\n * @param callback - Callback for events that pass the filter\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function filter<T = ApiCallback>(\n eventType: string,\n predicate: (msg: T) => boolean,\n callback: EventCallback<T>\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg && predicate(msg)) {\n callback(msg);\n }\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Transform events using a map function\n *\n * @param eventType - The event type to transform\n * @param transform - Function to transform the event data\n * @param callback - Callback for transformed events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function map<T = ApiCallback, R = any>(\n eventType: string,\n transform: (msg: T) => R,\n callback: (msg: R) => void\n): () => void {\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n const transformed = transform(msg);\n callback(transformed);\n }\n });\n\n return subscription.unsubscribe;\n}\n\n/**\n * Debounce events - only emit after a period of inactivity\n *\n * @param eventType - The event type to debounce\n * @param delay - Delay in milliseconds\n * @param callback - Callback for debounced events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function debounce<T = ApiCallback>(\n eventType: string,\n delay: number,\n callback: EventCallback<T>\n): () => void {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n callback(msg);\n }, delay);\n });\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Throttle events - limit emissions to once per interval\n *\n * @param eventType - The event type to throttle\n * @param interval - Minimum interval between emissions in milliseconds\n * @param callback - Callback for throttled events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function throttle<T = ApiCallback>(\n eventType: string,\n interval: number,\n callback: EventCallback<T>\n): () => void {\n let lastEmit = 0;\n let pendingTimeout: NodeJS.Timeout | null = null;\n\n const subscription = subscribe(eventType, (msg?: T) => {\n const now = Date.now();\n const timeSinceLastEmit = now - lastEmit;\n\n if (timeSinceLastEmit >= interval) {\n lastEmit = now;\n callback(msg);\n } else if (!pendingTimeout) {\n // Schedule emission for the remaining time\n pendingTimeout = setTimeout(() => {\n lastEmit = Date.now();\n callback(msg);\n pendingTimeout = null;\n }, interval - timeSinceLastEmit);\n }\n });\n\n return () => {\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Buffer events and emit them as an array\n *\n * @param eventType - The event type to buffer\n * @param bufferTime - Time window to collect events in milliseconds\n * @param callback - Callback for buffered events\n * @returns Unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function buffer<T = ApiCallback>(\n eventType: string,\n bufferTime: number,\n callback: (events: T[]) => void\n): () => void {\n let buffer: T[] = [];\n let timeoutId: NodeJS.Timeout | null = null;\n\n const flush = () => {\n if (buffer.length > 0) {\n callback([...buffer]);\n buffer = [];\n }\n };\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n buffer.push(msg);\n\n if (!timeoutId) {\n timeoutId = setTimeout(() => {\n flush();\n timeoutId = null;\n }, bufferTime);\n }\n }\n });\n\n return () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n flush(); // Emit any remaining buffered events\n }\n subscription.unsubscribe();\n };\n}\n\n/**\n * Create a replay subject that remembers the last N events\n *\n * @param eventType - The event type to replay\n * @param bufferSize - Number of events to remember\n * @returns Object with subscribe method that replays buffered events\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function replay<T = ApiCallback>(eventType: string, bufferSize = 1) {\n const buffer: T[] = [];\n\n // Subscribe to capture events\n subscribe(eventType, (msg?: T) => {\n if (msg) {\n buffer.push(msg);\n if (buffer.length > bufferSize) {\n buffer.shift();\n }\n }\n });\n\n return {\n subscribe: (callback: EventCallback<T>) => {\n // Replay buffered events immediately\n buffer.forEach((event) => callback(event));\n\n // Then subscribe for future events\n return subscribe(eventType, callback);\n },\n };\n}\n\n/**\n * Merge multiple event streams into one\n *\n * @param eventTypes - Array of event types to merge\n * @param callback - Callback for all merged events\n * @returns Unsubscribe function for all subscriptions\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function merge<T = ApiCallback>(\n eventTypes: string[],\n callback: (eventType: string, msg: T) => void\n): () => void {\n const subscriptions = eventTypes.map((eventType) =>\n subscribe(eventType, (msg?: T) => {\n if (msg) {\n callback(eventType, msg);\n }\n })\n );\n\n return () => {\n subscriptions.forEach((sub) => sub.unsubscribe());\n };\n}\n\n/**\n * Create a state machine that transitions based on events\n *\n * @param initialState - The initial state\n * @param transitions - Object mapping states to event handlers\n * @returns Object with current state and unsubscribe function\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function stateMachine<TState extends string, T = ApiCallback>(\n initialState: TState,\n transitions: Record<TState, Record<string, (msg: T) => TState>>\n) {\n let currentState = initialState;\n const subscriptions: (() => void)[] = [];\n\n // Subscribe to all events mentioned in transitions\n const allEvents = new Set<string>();\n Object.values(transitions).forEach((stateTransitions) => {\n Object.keys(stateTransitions as Record<string, any>).forEach((event) => {\n allEvents.add(event);\n });\n });\n\n allEvents.forEach((eventType) => {\n const { unsubscribe } = subscribe(eventType, (msg?: T) => {\n const stateTransitions = transitions[currentState];\n if (stateTransitions && stateTransitions[eventType]) {\n const nextState = stateTransitions[eventType](msg!);\n currentState = nextState;\n }\n });\n subscriptions.push(unsubscribe);\n });\n\n return {\n get state() {\n return currentState;\n },\n unsubscribe: () => {\n subscriptions.forEach((unsub) => unsub());\n },\n };\n}\n\n/**\n * Utility to create a promise that can be resolved by publishing an event\n *\n * @param requestEvent - Event type to publish the request\n * @param responseEvent - Event type to wait for the response\n * @param request - The request data to publish\n * @param timeout - Optional timeout in milliseconds\n * @returns Promise that resolves with the response\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport function request<TRequest = any, TResponse = ApiCallback>(\n requestEvent: string,\n responseEvent: string,\n request: TRequest,\n timeout?: number\n): Promise<TResponse> {\n const responsePromise = waitFor<TResponse>(responseEvent, timeout);\n publish(requestEvent, request);\n return responsePromise;\n}\n\n/**\n * Create an async iterator for events\n *\n * @param eventType - The event type to iterate\n * @returns Async iterator for use with for-await-of\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport async function* eventIterator<T = ApiCallback>(\n eventType: string\n): AsyncIterableIterator<T> {\n const queue: T[] = [];\n const waiters: ((value: T) => void)[] = [];\n\n const subscription = subscribe(eventType, (msg?: T) => {\n if (msg) {\n if (waiters.length > 0) {\n const waiter = waiters.shift()!;\n waiter(msg);\n } else {\n queue.push(msg);\n }\n }\n });\n\n try {\n while (true) {\n if (queue.length > 0) {\n yield queue.shift()!;\n } else {\n yield await new Promise<T>((resolve) => {\n waiters.push(resolve);\n });\n }\n }\n } finally {\n subscription.unsubscribe();\n }\n}\n\n/**\n * Namespace collecting all functional event bus utilities.\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport const EventBusFunctional = {\n once,\n waitFor,\n waitForAll,\n race,\n filter,\n map,\n debounce,\n throttle,\n buffer,\n replay,\n merge,\n stateMachine,\n request,\n eventIterator,\n};\n","/**\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 *\n * @kosService core.event-bus\n * @kosApiLevel 11\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 *\n * @kosService core.event-bus\n * @kosApiLevel 11\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 *\n * @kosService core.event-bus\n * @kosApiLevel 11\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 *\n * @kosService core.event-bus\n * @kosApiLevel 11\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 *\n * @kosService core.event-bus\n * @kosApiLevel 11\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 *\n * @kosService core.event-bus\n * @kosApiLevel 11\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 *\n * @kosService core.event-bus\n * @kosApiLevel 11\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 *\n * @kosService core.event-bus\n * @kosApiLevel 11\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 *\n * @kosService core.event-bus\n * @kosApiLevel 11\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/**\n * Namespace collecting all state-aware event bus utilities.\n *\n * @kosService core.event-bus\n * @kosApiLevel 11\n */\nexport const EventBusState = {\n waitForOrGetState,\n subscribeWithInitialState,\n createStatefulEventStream,\n waitForAllWithState,\n createResilientEventHandler,\n createConnectionStateManager,\n};\n","/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport 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","import { getQueryParams } from \"./get-query-params\";\n\ninterface KosConfig {\n logging: boolean;\n profiles: string[];\n [key: string]: boolean | string[] | string | number | undefined;\n}\n\n/**\n * @kosService core.utils\n * @kosApiLevel 20\n */\nexport const PROFILE_ENABLE_RELEASES = \"studio.enable.releases\";\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const PROFILE_TOOLS_PREVIEW = \"studio.tools.preview\";\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const PROFILE_RELAX_STORE_VALIDATION = \"studio.relax.store.validation\";\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const PROFILE_LOG_DEBUG = \"studio.log.debug\";\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\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: KosConfig = JSON.parse(config);\n\n/**\n * Profiles named on the URL, comma separated, added to whatever the host\n * supplied. Only a launched window gets `getKosConfig`, so a dev-server tab\n * would otherwise be stuck with the defaults and no way to turn a profile on.\n */\nconst urlProfiles = (): string[] => {\n if (typeof window === \"undefined\") {\n return [];\n }\n const value = getQueryParams()?.[\"kosProfiles\"];\n return value\n ? value\n .split(\",\")\n .map((profile) => profile.trim())\n .filter(Boolean)\n : [];\n};\n\nconfigObj.profiles = [\n ...(configObj.profiles ?? []),\n ...urlProfiles().filter((profile) => !configObj.profiles?.includes(profile)),\n];\n\nglobalThis.kosConfig = configObj;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const KosGlobalConfig: KosConfig = configObj;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const resolveKosProfiles = () => KosGlobalConfig.profiles || [];\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const hasKosProfile = (profile: string) =>\n resolveKosProfiles().includes(profile);\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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};\n/**\n * @kosService core.logging\n * @kosApiLevel 2\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\n/**\n * @kosService core.logging\n * @kosApiLevel 2\n */\nexport const getKosMessageLogging = (): boolean => {\n const enableAll =\n window.kosMessageLogging || process.env.KOS_MESSAGE_LOGGING === \"true\";\n return enableAll;\n};\n\n/**\n * @kosService core.logging\n * @kosApiLevel 2\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","/**\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`);\nexport const StateMachineSetup = Symbol(`StateMachineSetup`);\nexport const StateEntryHandlers = Symbol(`StateEntryHandlers`);\nexport const StateExitHandlers = Symbol(`StateExitHandlers`);\nexport const StateActionHandlers = Symbol(`StateActionHandlers`);\nexport const OptionsRequired = Symbol(`OptionsRequired`);\nexport const KosViewModelSymbol = Symbol(`KosViewModelSymbol`);\nexport const ViewModelConfig = Symbol(`ViewModelConfig`);\nexport const ReloadAwareSetup = Symbol(`ReloadAwareSetup`);\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-param-reassign */\nimport { KosLog } from \"../log\";\nimport {\n StateEntryHandlers,\n StateExitHandlers,\n StateMachineSetup,\n} from \"./propKeys\";\n\nconst log = KosLog.createLogger({ group: \"decorators\", name: \"fsm-injection\" });\n\n// ============================================================================\n// Zone 2: Coordination Functions\n// ============================================================================\n\n/**\n * Main coordinator for injecting FSM support into a model instance.\n * Delegates to Zone 3 functions for actual implementation.\n *\n * @param modelInstance The model instance to inject FSM support into\n */\nexport function injectStateMachineSupport(modelInstance: any) {\n const fsmSetup = modelInstance[StateMachineSetup];\n if (!fsmSetup) return;\n\n const { config, options } = fsmSetup;\n\n // Store configuration for later access\n storeFsmConfiguration(modelInstance, config, options);\n\n // Initialize FSM properties\n initializeFsmProperties(modelInstance, options);\n\n // Retrieve handlers from prototype\n const handlers = retrieveHandlers(modelInstance);\n\n // Attach FSM methods\n attachFsmMethods(modelInstance, config, options, handlers);\n\n // Setup FSM getters\n setupFsmGetters(modelInstance, config, options);\n}\n\n/**\n * Attach all FSM methods to the model instance.\n *\n * @param modelInstance The model instance\n * @param config FSM configuration\n * @param options FSM options\n * @param handlers Entry/exit handlers\n */\nfunction attachFsmMethods(\n modelInstance: any,\n config: any,\n options: any,\n handlers: { entry: Map<string, string>; exit: Map<string, string> }\n) {\n modelInstance.transition = createTransitionMethod(\n modelInstance,\n config,\n options,\n handlers.entry,\n handlers.exit\n );\n\n modelInstance.canTransition = createCanTransitionMethod(\n modelInstance,\n config,\n options\n );\n modelInstance.isInState = createIsInStateMethod(modelInstance, options);\n}\n\n/**\n * Setup reactive getters for FSM state.\n *\n * @param modelInstance The model instance\n * @param config FSM configuration\n * @param options FSM options\n */\nfunction setupFsmGetters(modelInstance: any, config: any, options: any) {\n defineIsFsmInitializedGetter(modelInstance);\n defineAllowedTransitionsGetter(modelInstance, config, options);\n}\n\n/**\n * Retrieve entry and exit handlers from prototype.\n *\n * @param modelInstance The model instance\n * @returns Object containing entry and exit handler maps\n */\nfunction retrieveHandlers(modelInstance: any): {\n entry: Map<string, string>;\n exit: Map<string, string>;\n} {\n const entryHandlers =\n modelInstance.constructor.prototype[StateEntryHandlers] || new Map();\n const exitHandlers =\n modelInstance.constructor.prototype[StateExitHandlers] || new Map();\n\n return { entry: entryHandlers, exit: exitHandlers };\n}\n\n// ============================================================================\n// Zone 3: Implementation Functions\n// ============================================================================\n\n/**\n * Store FSM configuration on the model instance.\n *\n * @param modelInstance The model instance\n * @param config FSM configuration\n * @param options FSM options\n */\nfunction storeFsmConfiguration(modelInstance: any, config: any, options: any) {\n modelInstance._fsmConfig = config;\n modelInstance._fsmOptions = options;\n}\n\n/**\n * Initialize FSM state properties on the model instance.\n * Uses computeInitialState if provided, otherwise uses the static initial state from config.\n *\n * When computeInitialState is provided, the FSM is immediately active since it\n * represents current state (not a transition) — no entry handlers are needed.\n * Otherwise, initialization is deferred to the configured lifecycle phase so\n * that initializeStateMachine can fire the initial state's entry handler.\n *\n * @param modelInstance The model instance\n * @param options FSM options\n */\nfunction initializeFsmProperties(modelInstance: any, options: any) {\n const { stateProperty, trackHistory, computeInitialState } = options;\n const config = modelInstance._fsmConfig;\n\n // Use computeInitialState if provided, otherwise use static initial from config\n const initialState = computeInitialState\n ? computeInitialState(modelInstance)\n : config.initial;\n\n // Validate that the computed state exists in the config\n if (computeInitialState && !config.states[initialState]) {\n log.warn(\n `computeInitialState returned \"${initialState}\" which is not a valid state. Falling back to \"${config.initial}\".`\n );\n modelInstance[stateProperty] = config.initial;\n } else {\n modelInstance[stateProperty] = initialState;\n }\n\n // Only mark as initialized when computeInitialState is provided.\n // For the standard path, initializeStateMachine will set this at the\n // configured lifecycle phase and fire the initial state's entry handler.\n modelInstance._fsmInitialized = !!computeInitialState;\n modelInstance.isTransitioning = false;\n\n if (trackHistory) {\n // Pre-populate history only for computeInitialState (already active).\n // For the standard path, initializeStateMachine will add the first entry.\n modelInstance.stateHistory = computeInitialState\n ? [{ state: modelInstance[stateProperty], timestamp: new Date() }]\n : [];\n }\n}\n\n/**\n * Define the isFsmInitialized getter on the model instance.\n *\n * @param modelInstance The model instance\n */\nfunction defineIsFsmInitializedGetter(modelInstance: any) {\n Object.defineProperty(modelInstance, \"isFsmInitialized\", {\n get() {\n return this._fsmInitialized;\n },\n enumerable: true,\n configurable: true,\n });\n}\n\n/**\n * Define the allowedTransitions computed getter on the model instance.\n *\n * @param modelInstance The model instance\n * @param _config FSM configuration (unused, provided for consistency)\n * @param options FSM options\n */\nfunction defineAllowedTransitionsGetter(\n modelInstance: any,\n _config: any,\n options: any\n) {\n const { stateProperty } = options;\n\n Object.defineProperty(modelInstance, \"allowedTransitions\", {\n get() {\n if (!this._fsmInitialized) return [];\n const currentState = this[stateProperty];\n const stateConfig = this._fsmConfig.states[currentState];\n return stateConfig?.on ? Object.keys(stateConfig.on) : [];\n },\n enumerable: true,\n configurable: true,\n });\n}\n\n/**\n * Create the transition method for the model instance.\n *\n * @param _instance The model instance (unused, provided for consistency)\n * @param config FSM configuration\n * @param options FSM options\n * @param entryHandlers Map of entry handlers\n * @param exitHandlers Map of exit handlers\n * @returns The transition function\n */\nfunction createTransitionMethod(\n _instance: any,\n config: any,\n options: any,\n entryHandlers: Map<string, string>,\n exitHandlers: Map<string, string>\n): (event: string) => void {\n const { stateProperty, throwOnInvalid } = options;\n\n return function (this: any, event: string) {\n // Validate FSM is initialized\n if (!this._fsmInitialized) {\n handleUninitializedFsm(config.initializeAt, throwOnInvalid);\n return;\n }\n\n // Get current state and resolve next state\n const currentState = this[stateProperty];\n const nextState = resolveNextState(\n currentState,\n event,\n this._fsmConfig,\n throwOnInvalid\n );\n\n if (!nextState) return;\n\n // Execute the transition\n executeTransition(\n this,\n currentState,\n nextState,\n event,\n stateProperty,\n entryHandlers,\n exitHandlers,\n options\n );\n };\n}\n\n/**\n * Handle case when FSM is not initialized.\n *\n * @param initializeAt The lifecycle phase FSM initializes at\n * @param throwOnInvalid Whether to throw or warn\n */\nfunction handleUninitializedFsm(initializeAt: string, throwOnInvalid: boolean) {\n const message = `Cannot transition: FSM not initialized. Waiting for ${initializeAt} lifecycle phase.`;\n if (throwOnInvalid) {\n throw new Error(message);\n } else {\n console.warn(message);\n }\n}\n\n/**\n * Resolve the next state for a given event from the current state.\n *\n * @param currentState The current state\n * @param event The event to trigger\n * @param config FSM configuration\n * @param throwOnInvalid Whether to throw or warn on invalid transition\n * @returns The next state, or undefined if invalid\n */\nfunction resolveNextState(\n currentState: string,\n event: string,\n config: any,\n throwOnInvalid: boolean\n): string | undefined {\n const stateConfig = config.states[currentState];\n const nextState = stateConfig?.on?.[event];\n\n if (!nextState) {\n handleInvalidTransition(currentState, event, throwOnInvalid);\n return undefined;\n }\n\n return nextState;\n}\n\n/**\n * Handle invalid transition attempt.\n *\n * @param currentState The current state\n * @param event The invalid event\n * @param throwOnInvalid Whether to throw or warn\n */\nfunction handleInvalidTransition(\n currentState: string,\n event: string,\n throwOnInvalid: boolean\n) {\n const message = `Invalid transition: Event \"${event}\" not allowed from state \"${currentState}\"`;\n if (throwOnInvalid) {\n throw new Error(message);\n } else {\n console.warn(message);\n }\n}\n\n/**\n * Execute a state transition with entry/exit handlers.\n *\n * @param instance The model instance\n * @param currentState The current state\n * @param nextState The next state\n * @param event The triggering event\n * @param stateProperty The property name for storing state\n * @param entryHandlers Map of entry handlers\n * @param exitHandlers Map of exit handlers\n * @param options FSM options\n */\nfunction executeTransition(\n instance: any,\n currentState: string,\n nextState: string,\n event: string,\n stateProperty: string,\n entryHandlers: Map<string, string>,\n exitHandlers: Map<string, string>,\n options: any\n) {\n instance.isTransitioning = true;\n\n try {\n // Call exit handler for current state\n executeExitHandler(instance, currentState, exitHandlers);\n\n // Update state\n instance[stateProperty] = nextState;\n\n // Track history if enabled\n trackTransitionHistory(instance, nextState, event, options);\n\n // Call entry handler for next state\n const result = executeEntryHandler(instance, nextState, entryHandlers);\n\n // Handle async entry handlers with onDone/onError auto-transitions\n handleAsyncEntryResult(instance, nextState, stateProperty, result);\n } finally {\n instance.isTransitioning = false;\n }\n}\n\n/**\n * Execute exit handler for a state if it exists.\n *\n * @param instance The model instance\n * @param state The state being exited\n * @param exitHandlers Map of exit handlers\n */\nfunction executeExitHandler(\n instance: any,\n state: string,\n exitHandlers: Map<string, string>\n) {\n const exitHandler = exitHandlers.get(state);\n if (exitHandler && typeof instance[exitHandler] === \"function\") {\n instance[exitHandler]();\n }\n}\n\n/**\n * Execute entry handler for a state if it exists.\n *\n * @param instance The model instance\n * @param state The state being entered\n * @param entryHandlers Map of entry handlers\n * @returns The handler's return value (may be a Promise for async handlers)\n */\nfunction executeEntryHandler(\n instance: any,\n state: string,\n entryHandlers: Map<string, string>\n): unknown {\n const entryHandler = entryHandlers.get(state);\n if (entryHandler && typeof instance[entryHandler] === \"function\") {\n return instance[entryHandler]();\n }\n return undefined;\n}\n\n/**\n * Handle async entry handler results for onDone/onError auto-transitions.\n *\n * If the entry handler returns a Promise and the state config has onDone/onError,\n * automatically sends the configured event when the Promise resolves/rejects.\n * Only triggers if the FSM is still in the same state when the handler completes\n * (guards against races where another event already moved the FSM forward).\n *\n * @param instance The model instance\n * @param state The state whose entry handler was called\n * @param stateProperty The property name for storing state\n * @param result The return value from the entry handler\n */\nfunction handleAsyncEntryResult(\n instance: any,\n state: string,\n stateProperty: string,\n result: unknown\n) {\n // Only handle Promise results\n if (!result || typeof (result as Promise<unknown>).then !== \"function\") {\n return;\n }\n\n const stateConfig = instance._fsmConfig?.states?.[state];\n if (!stateConfig?.onDone && !stateConfig?.onError) {\n return;\n }\n\n (result as Promise<unknown>).then(\n () => {\n // Only auto-transition if still in the same state\n if (stateConfig.onDone && instance[stateProperty] === state) {\n instance.transition(stateConfig.onDone);\n }\n },\n (err: unknown) => {\n if (stateConfig.onError && instance[stateProperty] === state) {\n instance.transition(stateConfig.onError);\n } else {\n log.error(`Async entry handler for state \"${state}\" failed:`, err);\n }\n }\n );\n}\n\n/**\n * Track state transition in history if enabled.\n *\n * @param instance The model instance\n * @param nextState The new state\n * @param event The triggering event\n * @param options FSM options\n */\nfunction trackTransitionHistory(\n instance: any,\n nextState: string,\n event: string,\n options: any\n) {\n if (options.trackHistory && instance.stateHistory) {\n instance.stateHistory.push({\n state: nextState,\n timestamp: new Date(),\n event,\n });\n }\n}\n\n/**\n * Create the canTransition method for the model instance.\n *\n * @param _instance The model instance (unused, provided for consistency)\n * @param _config FSM configuration (unused, provided for consistency)\n * @param options FSM options\n * @returns The canTransition function\n */\nfunction createCanTransitionMethod(\n _instance: any,\n _config: any,\n options: any\n): (event: string) => boolean {\n const { stateProperty } = options;\n\n return function (this: any, event: string): boolean {\n if (!this._fsmInitialized) return false;\n const currentState = this[stateProperty];\n const stateConfig = this._fsmConfig.states[currentState];\n return stateConfig?.on?.[event] !== undefined;\n };\n}\n\n/**\n * Create the isInState method for the model instance.\n *\n * @param _instance The model instance (unused, provided for consistency)\n * @param options FSM options\n * @returns The isInState function\n */\nfunction createIsInStateMethod(\n _instance: any,\n options: any\n): (state: string) => boolean {\n const { stateProperty } = options;\n\n return function (this: any, state: string): boolean {\n if (!this._fsmInitialized) return false;\n return this[stateProperty] === state;\n };\n}\n\n// ============================================================================\n// Initialization Functions\n// ============================================================================\n\n/**\n * Initialize the state machine at a specific lifecycle phase.\n * Called from KosModel lifecycle hooks.\n *\n * @param modelInstance The model instance\n * @param lifecycle The current lifecycle phase\n */\nexport function initializeStateMachine(modelInstance: any, lifecycle: string) {\n const fsmSetup = modelInstance[StateMachineSetup];\n if (!fsmSetup) return;\n\n const { config, options } = fsmSetup;\n const { stateProperty } = options;\n\n // Only initialize if we're at the configured lifecycle phase\n if (config.initializeAt !== lifecycle) return;\n\n // Only initialize once\n if (modelInstance._fsmInitialized) return;\n\n // Set initial state\n setInitialState(modelInstance, stateProperty, config.initial);\n modelInstance._fsmInitialized = true;\n\n // Track initial state in history if enabled\n trackInitialStateInHistory(modelInstance, config.initial, options);\n\n // Call entry handler for initial state\n executeInitialStateEntryHandler(modelInstance, config.initial);\n\n log.debug(\n `FSM initialized for model ${modelInstance.id} at lifecycle ${lifecycle} with initial state \"${config.initial}\"`\n );\n}\n\n/**\n * Set the initial state on the model instance.\n *\n * @param instance The model instance\n * @param stateProperty The property name for storing state\n * @param initialState The initial state value\n */\nfunction setInitialState(\n instance: any,\n stateProperty: string,\n initialState: string\n) {\n instance[stateProperty] = initialState;\n}\n\n/**\n * Track initial state in history if tracking is enabled.\n *\n * @param instance The model instance\n * @param initialState The initial state\n * @param options FSM options\n */\nfunction trackInitialStateInHistory(\n instance: any,\n initialState: string,\n options: any\n) {\n if (options.trackHistory && instance.stateHistory) {\n instance.stateHistory.push({\n state: initialState,\n timestamp: new Date(),\n });\n }\n}\n\n/**\n * Execute entry handler for initial state if it exists.\n *\n * @param instance The model instance\n * @param initialState The initial state\n */\nfunction executeInitialStateEntryHandler(instance: any, initialState: string) {\n const entryHandlers =\n instance.constructor.prototype[StateEntryHandlers] || new Map();\n const entryHandler = entryHandlers.get(initialState);\n if (entryHandler && typeof instance[entryHandler] === \"function\") {\n instance[entryHandler]();\n }\n}\n","import type { HttpMethod, ServiceRequestExecutor } from \"./kos-service-request\";\nimport type { ClientResponse } from \"../../util/kos-service-request\";\n\n/**\n * Symbol used to uniquely identify KosExecutionContext objects.\n * Decorators use this to reliably detect if the last parameter is an execution context.\n * @internal\n */\nexport const KOS_EXECUTION_CONTEXT = Symbol(\"KosExecutionContext\");\n\n/**\n * Execution context passed to decorated methods for accessing decorator-injected functionality.\n *\n * This context provides a type-safe way for decorators to inject runtime functionality\n * into methods without polluting the class interface or relying on magic parameters.\n *\n * Currently used by @kosServiceRequest to inject the $request executor.\n * Designed to be extensible for future decorators that need to inject runtime functionality.\n *\n * @example Using with @kosServiceRequest\n * ```typescript\n * @kosServiceRequest({\n * path: PATH_VM_INSTALL,\n * method: 'post'\n * })\n * async createRelease(\n * path: string,\n * keysetId?: string,\n * ctx: KosExecutionContext<paths, typeof PATH_VM_INSTALL, 'post'>\n * ): Promise<void> {\n * const [error, response] = await ctx.$request({\n * queryParams: { keySetId: keysetId },\n * body: { path }\n * });\n * if (error) throw new Error(error);\n * return response?.data;\n * }\n * ```\n *\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport interface KosExecutionContext<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\",\n Transformed = ClientResponse<Paths, Path, Method>\n> {\n /**\n * Symbol marker to identify this as a KosExecutionContext\n * @internal\n */\n [KOS_EXECUTION_CONTEXT]: true;\n\n /**\n * Service request executor (injected by @kosServiceRequest)\n * Executes the service request defined in the decorator configuration.\n */\n $request?: ServiceRequestExecutor<Paths, Path, Method>;\n\n /**\n * What the request yields once the decorator's `transform` has run — the raw\n * response when it declares none.\n *\n * Type-only: never populated at runtime. It exists so `executeServiceRequest`\n * can read the shape off the context, while `$request` keeps returning `any`\n * on its data half, as it always has.\n */\n readonly $transformed?: Transformed;\n\n /**\n * Future tracker ID string (injected by @kosFuture when trackerPolicy is 'context')\n * This is the tracker ID that can be used with future management utilities.\n */\n $tracker?: string;\n\n /**\n * Name of the decorated method (injected by @kosServiceRequest).\n *\n * Lets helpers attribute a failure to its method without the caller passing\n * the name in — a hand-written label silently outlives the rename that\n * invalidates it, and a stale one points at code that no longer exists.\n */\n $name?: string;\n}\n\n/**\n * Type guard to check if an object is a KosExecutionContext\n * @internal\n */\nexport function isKosExecutionContext(obj: any): obj is KosExecutionContext {\n return obj && typeof obj === \"object\" && KOS_EXECUTION_CONTEXT in obj;\n}\n","/**\n * @kosService core.dependency\n */\nexport enum DependencyLifecycle {\n INIT = \"init\",\n LOAD = \"load\",\n READY = \"ready\",\n ACTIVATE = \"activate\",\n ONLINE = \"online\",\n}\n\n/**\n * Policy for handling dependency resolution failures.\n *\n * @kosService core.dependency\n *\n * All policies follow a lookup-first approach: The framework first checks if a model\n * with the specified ID already exists. If found and the type matches, it returns the\n * existing instance. Only if no existing model is found does the framework apply the\n * resolution policy below.\n */\nexport enum DependencyResolutionPolicy {\n /**\n * CREATE (default) - After lookup fails, attempt to create a new instance of the model.\n * If the model requires options (via optionsRequired flag) and none are provided,\n * it will fail with an exception.\n */\n CREATE = \"create\",\n /**\n * CONTINUE - After lookup fails, do not attempt to create a new instance.\n * The property will be set to undefined. Log the failure but allow execution to continue.\n * Use for optional dependencies that can degrade gracefully.\n */\n CONTINUE = \"continue\",\n /**\n * FAIL - After lookup fails, throw an exception with detailed diagnostic logging.\n * Use for critical dependencies where failure should halt execution.\n */\n FAIL = \"fail\",\n}\n\n/**\n * The parameters for the kosDependency decorator.\n *\n * @kosService core.dependency\n * @kosApiLevel 2\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 * Policy for handling dependency resolution failures.\n *\n * All policies first attempt to look up an existing model instance. If found and the type\n * matches, the existing instance is returned. Only if lookup fails does the policy apply:\n *\n * - CREATE (default): Attempts to create model instance after lookup fails\n * - CONTINUE: Returns undefined after lookup fails, allows graceful degradation\n * - FAIL: Throws exception with detailed logging after lookup fails\n * @kosApiLevel 16\n */\n resolutionPolicy?: DependencyResolutionPolicy;\n}\n","import { DependencyLifecycle } from \"../../types/kos-dependency\";\nimport type {\n KosMethodTypes,\n KosRequest,\n KosResponse,\n} from \"../services/browser-router\";\nimport { DependencyModels } from \"./propKeys\";\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 *\n * @kosService core.http-route\n * @kosApiLevel 12\n */\nexport interface IHttpRouteConfig {\n method: KosMethodTypes;\n path: string;\n handler: string; // Method name\n middleware?: Array<\n (req: KosRequest, res: KosResponse, next: () => void) => void\n >;\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 *\n * @kosService core.http-route\n * @kosApiLevel 12\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 *\n * @kosService core.http-route\n * @kosApiLevel 12\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 *\n * @kosService core.http-route\n * @kosApiLevel 12\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 *\n * @kosService core.http-route\n * @kosApiLevel 12\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","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","/**\n * Symbol marker indicating a model manages its own reload lifecycle.\n * Models with this marker are skipped by KosCore's destructive\n * unload() + reload() cycle, allowing them to handle reconnection\n * and state refresh through their own mechanisms (e.g., model effects,\n * topic handlers, or application-specific decorators like @kosStudioStateAware).\n */\nexport const SelfManagedReload = Symbol(\"SelfManagedReload\");\n\n/**\n * Class decorator that marks a model as self-managing its reload lifecycle.\n *\n * When KOS Core performs a reload (e.g., after reconnection), it normally\n * calls unload() then reload() on every model with a reload() method.\n * This destructive cycle removes all child models and recreates them,\n * which can cause UI disruption (skeleton flashes, lost selection state).\n *\n * Models decorated with @kosReloadAware manage their own reload through\n * reactive mechanisms (model effects watching for state changes) and use\n * incremental strategies like resolveContainerDeltas to update in place.\n *\n * @example\n * ```typescript\n * @kosModel(\"my-container-model\")\n * @kosReloadAware()\n * class MyContainerModel {\n * async reload() {\n * // Called by the model's own effect/decorator, NOT by KOS Core\n * await this.loadItems(); // uses resolveContainerDeltas\n * }\n * }\n * ```\n *\n * @category Decorator\n */\nexport function kosReloadAware(): ClassDecorator {\n return (target: any) => {\n target.prototype[SelfManagedReload] = true;\n };\n}\n","/**\n * (C) Copyright 2025, TCCC, All rights reserved.\n */\n\n/**\n * Rich error class for service request failures.\n *\n * Extends `Error` so it is backward-compatible with any code that expects\n * a plain `Error`. Adds HTTP response context so `onError` handlers in\n * `@kosServiceRequest` can inspect status codes, response bodies, and headers.\n *\n * @example\n * ```typescript\n * errorHandler: {\n * strategy: 'log',\n * defaultValue: [],\n * onError: (error, model) => {\n * if (error instanceof ServiceRequestError) {\n * console.error('HTTP', error.status, error.responseBody);\n * }\n * }\n * }\n * ```\n *\n * @category Service Request\n * @kosService core.service-request\n * @kosApiLevel 22\n */\nexport class ServiceRequestError extends Error {\n /** HTTP status code (e.g. 404, 500) */\n readonly status: number;\n\n /** HTTP status text (e.g. \"Not Found\") */\n readonly statusText: string;\n\n /**\n * Parsed response body (JSON) or raw text.\n * `undefined` if the body could not be read.\n */\n readonly responseBody: unknown;\n\n /** Response headers as a plain key/value map */\n readonly responseHeaders: Record<string, string>;\n\n constructor(\n message: string,\n details: {\n status: number;\n statusText: string;\n responseBody?: unknown;\n responseHeaders?: Record<string, string>;\n }\n ) {\n super(message);\n this.name = \"ServiceRequestError\";\n this.status = details.status;\n this.statusText = details.statusText;\n this.responseBody = details.responseBody;\n this.responseHeaders = details.responseHeaders ?? {};\n }\n}\n\n/**\n * Context captured from an HTTP error response.\n * Used internally to thread rich error info through the service request pipeline.\n * @internal\n * @kosService core.service-request\n * @kosApiLevel 22\n */\nexport interface ErrorResponseContext {\n status: number;\n statusText: string;\n responseBody: unknown;\n responseHeaders: Record<string, string>;\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 !== null && prop !== undefined) {\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 null or undefined${\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","import type { ErrorResponseContext } from \"../../util/service-request-error\";\nimport { ServiceRequestError } from \"../../util/service-request-error\";\nimport { KosLog } from \"../log\";\nimport { resolveParameters } from \"./resolve-parameters\";\n\nconst log = KosLog.createLogger({ name: \"ServiceRequestHelpers\" });\n/**\n * Helper functions for kosServiceRequest decorator.\n *\n * These functions are extracted to reduce complexity and improve maintainability\n * of the service request decorator implementation.\n */\n\n/**\n * Resolves all parameters for a service request.\n *\n * This helper function handles the complex parameter resolution logic including:\n * - Resolving PropKeys in path\n * - Merging decorator-defined params with runtime params\n * - Building the final API params object\n *\n * @param metadata - Service request metadata\n * @param modelInstance - The model instance (this context)\n * @param args - Original method arguments\n * @param runtimeOptions - Runtime execution options\n * @returns Resolved parameters for the API request\n */\nexport function resolveServiceRequestParameters(\n metadata: any,\n modelInstance: any,\n args: any[],\n runtimeOptions: any\n) {\n // Resolve PropKeys in path\n const resolvedPath = resolveParameters({\n value: metadata.path,\n modelId: modelInstance.id,\n modelData: modelInstance,\n }) as string;\n\n // Merge decorator-defined params with runtime params\n const finalPathParams = resolveParameters({\n modelId: modelInstance.id,\n modelData: modelInstance,\n value: {\n ...(typeof metadata.pathParams === \"function\"\n ? metadata.pathParams(modelInstance)\n : metadata.pathParams || {}),\n ...(runtimeOptions?.pathParams || {}),\n },\n });\n\n const finalQueryParams = resolveParameters({\n modelId: modelInstance.id,\n modelData: modelInstance,\n value: {\n ...(typeof metadata.queryParams === \"function\"\n ? metadata.queryParams(modelInstance)\n : metadata.queryParams || {}),\n ...(runtimeOptions?.queryParams || {}),\n },\n });\n\n const finalBody =\n runtimeOptions?.body ||\n (typeof metadata.body === \"function\"\n ? metadata.body(modelInstance)\n : metadata.body);\n\n // Merge decorator-defined requestOptions with runtime requestOptions\n const decoratorRequestOptions =\n typeof metadata.requestOptions === \"function\"\n ? metadata.requestOptions(modelInstance, ...args)\n : metadata.requestOptions;\n\n const finalRequestOptions = {\n ...(decoratorRequestOptions || {}),\n ...(runtimeOptions?.requestOptions || {}),\n };\n\n // Build params object for API client\n const apiParams: any = {};\n if (finalPathParams && Object.keys(finalPathParams).length > 0) {\n apiParams.path = finalPathParams;\n }\n if (finalQueryParams && Object.keys(finalQueryParams).length > 0) {\n apiParams.query = finalQueryParams;\n }\n\n return {\n resolvedPath,\n apiParams,\n finalBody,\n finalRequestOptions,\n };\n}\n\n/**\n * Executes an API method with the appropriate HTTP verb.\n *\n * This helper function handles the complexity of method selection and execution,\n * supporting GET, POST, PUT, and DELETE operations with proper parameter passing.\n *\n * @param API - The API client instance\n * @param method - HTTP method (get, post, put, delete)\n * @param path - Resolved API path\n * @param params - API parameters (path, query)\n * @param body - Request body (for POST, PUT, DELETE)\n * @param requestOptions - Additional request options\n * @returns Error-first tuple with response\n */\nexport async function executeApiMethod(\n API: any,\n method: string | undefined,\n path: string,\n params: any,\n body: any,\n requestOptions: any\n): Promise<[string | null, any, ErrorResponseContext?]> {\n const httpMethod = (method || \"get\").toLowerCase();\n const api = API as any;\n\n switch (httpMethod) {\n case \"get\":\n return await api.get(path, params, requestOptions);\n case \"post\":\n return await api.post(path, params, body, requestOptions);\n case \"put\":\n return await api.put(path, params, body, requestOptions);\n case \"delete\":\n return await api.delete(path, params, body, requestOptions);\n default:\n return await api.get(path, params, requestOptions);\n }\n}\n\n/**\n * Handles service request errors according to the configured error handling strategy.\n *\n * This helper function implements the error handling strategies defined in metadata:\n * - \"throw\": Return error tuple for caller to handle\n * - \"log\": Log error and return default value\n * - \"ignore\": Silently return default value\n * - \"default\": Return default value\n *\n * @param error - Error message from API call\n * @param response - API response (may contain status code)\n * @param errorHandler - Error handler configuration from metadata\n * @param modelInstance - The model instance (this context)\n * @returns Error-first tuple with default value or error\n */\nexport function handleServiceRequestError(\n error: string,\n response: any,\n errorHandler: any,\n modelInstance: any,\n errorContext?: ErrorResponseContext\n): [string | null, any] {\n if (!errorHandler) {\n return [error, null];\n }\n\n // Build a rich error object for the onError callback\n const richError = errorContext\n ? new ServiceRequestError(error, errorContext)\n : new ServiceRequestError(error, {\n status: response?.status ?? 0,\n statusText: error,\n });\n\n switch (errorHandler.strategy) {\n case \"log\":\n log.error(`Service request status ${richError.status} error: ${error}`);\n if (errorHandler.onError) {\n errorHandler.onError(richError, modelInstance);\n }\n return [null, errorHandler.defaultValue];\n case \"ignore\":\n if (errorHandler.onError) {\n errorHandler.onError(richError, modelInstance);\n }\n return [null, errorHandler.defaultValue];\n case \"default\":\n if (errorHandler.onError) {\n errorHandler.onError(richError, modelInstance);\n }\n return [null, errorHandler.defaultValue];\n case \"throw\":\n default:\n if (errorHandler.onError) {\n errorHandler.onError(richError, modelInstance);\n }\n return [error, null];\n }\n}\n","/**\n * (C) Copyright 2025, TCCC, All rights reserved.\n */\n\nimport { DependencyLifecycle } from \"../../types\";\nimport { ResponseCacheConfig } from \"../../types/service-response-store\";\nimport type { KosFetchOptions } from \"../../types/utils/kos-fetch\";\nimport type { ClientBody, ClientParams } from \"../../util/kos-service-request\";\nimport type { ServiceRequestError } from \"../../util/service-request-error\";\nimport { IKosDataModel } from \"../kosModel\";\nimport { type KosModelRegistrationType } from \"../registration/model-registration\";\nimport {\n type KosExecutionContext,\n KOS_EXECUTION_CONTEXT,\n isKosExecutionContext,\n} from \"./kos-execution-context\";\nimport {\n executeApiMethod,\n handleServiceRequestError,\n resolveServiceRequestParameters,\n} from \"./kos-service-request-helpers\";\n\n/**\n * @kosService core.service-request\n */\nexport type RequestOptions = Omit<KosFetchOptions, \"method\" | \"body\">;\n\n// Re-export for convenience\nexport type { KosExecutionContext };\n\n/**\n * Symbol for storing service request handlers metadata on model instances\n * @internal\n */\nexport const ServiceRequestHandlers = Symbol(\"ServiceRequestHandlers\");\n\n/**\n * WeakMap to store method-specific metadata for $serviceRequest\n * Key: The wrapped method function\n * Value: The service request metadata\n * @internal\n */\nconst methodMetadataMap = new WeakMap<\n // eslint-disable-next-line @typescript-eslint/ban-types\n Function,\n ServiceRequestMetadata<any, any, any, any, any>\n>();\n\n/**\n * HTTP methods supported by kosServiceRequest\n *\n * @kosService core.service-request\n */\nexport type HttpMethod =\n | \"get\"\n | \"GET\"\n | \"post\"\n | \"POST\"\n | \"put\"\n | \"PUT\"\n | \"delete\"\n | \"DELETE\"\n | \"patch\"\n | \"PATCH\";\n\n/**\n * API path type - string representing an API endpoint\n *\n * @kosService core.service-request\n */\nexport type ApiPath = string;\n\n/**\n * Configuration for field mapping in data transformation\n *\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport interface FieldMapping {\n /**\n * Source field path (dot notation supported, e.g., 'data.user.name')\n */\n from: string;\n\n /**\n * Target field name in the model\n */\n to: string;\n\n /**\n * Optional transformation to apply\n * Built-in: 'string', 'number', 'boolean', 'date', 'json'\n * Custom: function name or transformer function\n */\n transform?: string | ((value: any) => any);\n\n /**\n * Whether this field is required\n */\n required?: boolean;\n\n /**\n * Default value if field is missing\n */\n default?: any;\n}\n\n/**\n * Configuration for extension points during transformation\n *\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport interface ExtensionConfig {\n /**\n * Type of extension point\n */\n type: \"loader\" | \"data-mapper\" | \"validator\";\n\n /**\n * Extension identifier (e.g., ExtensionType.IngredientMapper)\n */\n extension: any;\n\n /**\n * When to execute the extension\n */\n phase?: \"before\" | \"after\" | \"transform\";\n}\n\n/**\n * Configuration for error handling in service requests.\n *\n * Provides multiple strategies for handling request failures, enabling soft failures\n * with cached default values and error-first parameter patterns.\n *\n * @remarks\n * All strategies except 'throw' cache defaultValue in the response store, ensuring\n * consistency across model lifecycle. Lifecycle-triggered handlers receive error-first\n * parameters: (error, data), while method-driven requests use $request executor\n * returning tuple: [error, data].\n *\n * @example\n * ```typescript\n * // Soft failure with logging\n * @kosServiceRequest({\n * path: '/api/data',\n * errorHandler: {\n * strategy: 'log',\n * defaultValue: []\n * }\n * })\n * async loadData(error: string | null, data: DataType[]): Promise<void> {\n * if (error) {\n * this.logger.error(`Load failed: ${error}`);\n * }\n * this.processData(data); // Either real data or defaultValue\n * }\n * ```\n *\n * @category Service Request\n * @see {@link KosServiceRequestConfig} for complete decorator configuration\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport interface ErrorHandlerConfig {\n /**\n * How to handle errors:\n *\n * - 'throw': Re-throw error (default) - handler not called, no caching\n *\n * - 'log': Log error, cache defaultValue, and call handler with (error, defaultValue)\n * Enables soft failure - log the error but continue processing with default data\n *\n * - 'ignore': Cache defaultValue and call handler with (error, defaultValue)\n * Soft failure without logging - silent recovery\n *\n * - 'default': Same as 'ignore' - cache defaultValue and call handler\n * (Kept for backward compatibility, behaves identically to 'ignore')\n *\n * All strategies except 'throw' cache defaultValue in response store for consistency.\n *\n * Note: For lifecycle requests, handler receives error-first parameters: (error, data)\n * For method-driven requests, $request executor returns tuple: [error, data]\n */\n strategy: \"throw\" | \"log\" | \"ignore\" | \"default\";\n\n /**\n * Default value to use when an error occurs.\n * Used with 'log', 'ignore', or 'default' strategies.\n * - Stored in response cache for subsequent access\n * - Passed to handler as second parameter: handler(errorMessage, defaultValue)\n */\n defaultValue?: any;\n\n /**\n * Custom error handler function called when a request fails.\n *\n * When the failure is an HTTP error response, `error` will be a\n * {@link ServiceRequestError} instance with `status`, `statusText`,\n * `responseBody`, and `responseHeaders` properties.\n *\n * For non-HTTP failures (network errors, timeouts), `error` is a\n * plain `Error`.\n *\n * @example\n * ```typescript\n * onError: (error, model) => {\n * if (error instanceof ServiceRequestError) {\n * console.error(`HTTP ${error.status}`, error.responseBody, error.responseHeaders);\n * }\n * }\n * ```\n */\n onError?: (error: Error | ServiceRequestError, model: IKosDataModel) => void;\n}\n\n/**\n * Configuration parameters for @kosServiceRequest decorator\n * Enables lifecycle-driven HTTP requests with declarative data transformation\n *\n * @typeparam Paths - The OpenAPI paths type (from your OpenAPI schema)\n * @typeparam Path - The specific API path being requested\n * @typeparam Method - The HTTP method type\n * @typeparam Response - The raw response type from the API\n * @typeparam TransformedResponse - The transformed response type after mappings\n *\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport interface IKosServiceRequestParams<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n> {\n /**\n * API path to request\n *\n * @example\n * path: '/api/kos/ingredients'\n * path: `/api/devices/${PROP_DEVICE_ID}/status` // with PropKey\n */\n path: Path;\n\n /**\n * HTTP method\n *\n * @default 'get'\n */\n method?: Method;\n\n /**\n * When to execute this request during model lifecycle\n *\n * If omitted, the request executes when the decorated method is called (method-driven).\n * If specified, the request executes automatically during the given lifecycle phase (lifecycle-driven).\n *\n * @example\n * // Lifecycle-driven (auto-execute during LOAD phase)\n * lifecycle: DependencyLifecycle.LOAD\n *\n * @example\n * // Method-driven (execute when method is called)\n * lifecycle: undefined // or omit entirely\n */\n lifecycle?: DependencyLifecycle;\n\n /**\n * Path parameters to expand in the URL\n * Strongly typed from OpenAPI schema\n * Can be static values or PropKey references\n *\n * @example\n * // Static value\n * pathParams: { deviceId: 'device-123' }\n *\n * @example\n * // PropKey reference (use PROP_ prefix)\n * pathParams: { deviceId: PROP_DEVICE_ID }\n *\n * @example\n * // Dynamic from method arguments\n * pathParams: (model, deviceId, status) => ({ deviceId })\n */\n pathParams?:\n | (ClientParams<Paths, Path, Method> extends { path?: infer P } ? P : never)\n | ((\n model: IKosDataModel,\n ...args: any[]\n ) => ClientParams<Paths, Path, Method> extends { path?: infer P }\n ? P\n : never);\n\n /**\n * Query parameters\n * Strongly typed from OpenAPI schema\n *\n * @example\n * // Static\n * queryParams: { includeMetadata: true, format: 'json' }\n *\n * @example\n * // Dynamic from method arguments\n * queryParams: (model, deviceId, debug) => ({ debug })\n */\n queryParams?:\n | (ClientParams<Paths, Path, Method> extends { query?: infer Q }\n ? Q\n : never)\n | ((\n model: IKosDataModel,\n ...args: any[]\n ) => ClientParams<Paths, Path, Method> extends { query?: infer Q }\n ? Q\n : never);\n\n /**\n * Request body (for POST/PUT/PATCH)\n * Strongly typed from OpenAPI schema\n *\n * @example\n * // Static body\n * body: { action: 'start' }\n *\n * @example\n * // Dynamic from method arguments\n * body: (model, vehicleType, speed) => ({ vehicleType, speed })\n */\n body?:\n | ClientBody<Paths, Path, Method>\n | ((\n model: IKosDataModel,\n ...args: any[]\n ) => ClientBody<Paths, Path, Method>);\n\n /**\n * JSON path to iterate over in response\n * Creates models for each item in the array\n *\n * @example\n * iterateOver: 'data.ingredients' // Iterates response.data.ingredients array\n */\n iterateOver?: string;\n\n /**\n * Model registration object for creating instances from array items\n * Used with iterateOver to create child models using the builder pattern\n *\n * @example\n * modelFactory: IngredientModel // The registration object itself\n *\n * deprecated The old curried function signature is deprecated:\n * modelFactory?: (id: string) => (options: any) => IKosDataModel\n */\n modelFactory?:\n | KosModelRegistrationType<IKosDataModel, any>\n | ((id: string) => (options: any) => IKosDataModel); // Deprecated legacy signature\n\n /**\n * Function to extract the model ID from response data items\n * Required when using modelFactory if items don't have an 'id' field\n *\n * @example\n * idExtractor: (item) => item.ingredientId\n * idExtractor: (item) => `${item.type}-${item.index}`\n */\n idExtractor?: (item: any) => string;\n\n /**\n * Field mappings for data transformation\n * Same format as @kosTopicHandler mappings\n *\n * @example\n * mappings: [\n * { from: 'id', to: 'id' },\n * { from: 'ingredientId', to: 'ingredientId' },\n * { from: 'metadata.calories', to: 'calories', transform: 'number' }\n * ]\n */\n mappings?: FieldMapping[];\n\n /**\n * Extension points to execute during transformation\n *\n * @example\n * extensions: [\n * { type: 'data-mapper', extension: ExtensionType.IngredientMapper }\n * ]\n */\n extensions?: ExtensionConfig[];\n\n /**\n * Transformation function for response data\n * Applied before mappings\n *\n * @example\n * transform: (response) => response.data\n */\n transform?: (response: Response) => TransformedResponse;\n\n /**\n * Condition to determine if request should execute\n *\n * @example\n * condition: (model) => model.isInitialized\n */\n condition?: (model: IKosDataModel) => boolean;\n\n /**\n * Error handling strategy\n *\n * @example\n * errorHandler: {\n * strategy: 'default',\n * defaultValue: [],\n * onError: (error, model) => model.logger.error('Failed to load', error)\n * }\n */\n errorHandler?: ErrorHandlerConfig;\n\n /**\n * Response caching configuration\n * Controls how long responses are stored and when they're cleaned up\n *\n * @default { retention: ResponseRetention.SINGLE }\n *\n * @example\n * // No caching - clear immediately after handler\n * cache: { retention: ResponseRetention.IMMEDIATE }\n *\n * @example\n * // Cache for 5 minutes\n * cache: { retention: ResponseRetention.TTL, ttl: 5 * 60 * 1000 }\n *\n * @example\n * // Keep for model lifetime\n * cache: { retention: ResponseRetention.PERMANENT }\n */\n cache?: ResponseCacheConfig;\n\n /**\n * Request options for controlling fetch behavior\n * These are merged with runtime options passed to ctx.$request()\n * Runtime options take precedence over decorator options\n *\n * @example\n * // Set default timeout and destination for all requests\n * requestOptions: {\n * destinationAddress: 'device-123',\n * timeout: 10000\n * }\n *\n * @example\n * // Dynamic from method arguments\n * requestOptions: (model, ...args) => ({\n * destinationAddress: model.deviceId,\n * headers: { 'X-Session': model.sessionId }\n * })\n * @kosApiLevel 18\n */\n requestOptions?:\n | RequestOptions\n | ((model: IKosDataModel, ...args: any[]) => RequestOptions);\n}\n\n/**\n * Metadata stored for each service request handler\n * @internal\n */\nexport interface ServiceRequestMetadata<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n> extends IKosServiceRequestParams<\n Paths,\n Path,\n Method,\n Response,\n TransformedResponse\n > {\n /**\n * The method name that handles the response\n */\n handlerMethod: string;\n\n /**\n * The original handler function\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n originalHandler: Function;\n}\n\n/**\n * Runtime service request executor injected into method context\n * Allows imperative execution of the service request defined by the decorator\n *\n * @kosService core.service-request\n */\nexport interface ServiceRequestExecutor<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\"\n> {\n (options?: {\n pathParams?: ClientParams<Paths, Path, Method> extends { path?: infer P }\n ? P\n : never;\n queryParams?: ClientParams<Paths, Path, Method> extends { query?: infer Q }\n ? Q\n : never;\n body?: ClientBody<Paths, Path, Method>;\n requestOptions?: RequestOptions;\n }): Promise<[string | null, any]>;\n}\n\n/**\n * Type alias for the service request executor function signature.\n * This executor is automatically passed as the last parameter to methods\n * decorated with @kosServiceRequest (without lifecycle).\n *\n * @example\n * ```typescript\n * type CreateReleaseExecutor = ServiceRequestExecutor<paths, typeof PATH_VM_INSTALL, 'post'>;\n * ```\n *\n * @kosService core.service-request\n */\nexport type ServiceRequestExecutorFn<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\"\n> = ServiceRequestExecutor<Paths, Path, Method>;\n\n/**\n * Decorator for lifecycle-driven service requests within KOS models\n *\n * Eliminates service boilerplate by integrating HTTP requests directly into\n * the model lifecycle. Responses are cached in ServiceResponseStore for access\n * via utility functions, avoiding \"magic last parameter\" patterns.\n *\n * @param params - Configuration for the service request\n * @returns Method decorator\n *\n * @example Basic GET request during LOAD\n * ```typescript\n * @kosServiceRequest({\n * path: PATH_DEVICE_STATUS,\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD,\n * cache: { retention: ResponseRetention.SINGLE }\n * })\n * private onStatusLoaded(): void {\n * const response = getServiceResponse(this, PATH_DEVICE_STATUS, 'get');\n * this.status = response?.status;\n * }\n * ```\n *\n * @example Method-driven request with execution context\n * ```typescript\n * @kosServiceRequest({\n * path: PATH_VM_INSTALL,\n * method: 'post',\n * requestOptions: {\n * timeout: 10000 // Decorator-level default timeout\n * }\n * })\n * async createRelease(\n * path: string,\n * keysetId?: string,\n * ctx: KosExecutionContext<paths, typeof PATH_VM_INSTALL, 'post'>\n * ): Promise<void> {\n * const [error, response] = await ctx.$request({\n * queryParams: { keySetId: keysetId },\n * body: { path },\n * requestOptions: {\n * destinationAddress: 'device-123', // Runtime options merged with decorator options\n * headers: { 'X-Custom-Header': 'value' }\n * }\n * });\n * if (error) throw new Error(error);\n * return response?.data;\n * }\n * ```\n *\n * @example Container model with iteration\n * ```typescript\n * @kosServiceRequest({\n * path: PATH_INGREDIENTS,\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD,\n * iterateOver: 'data.ingredients',\n * modelFactory: Ingredient.factory,\n * mappings: [\n * { from: 'id', to: 'id' },\n * { from: 'name', to: 'name' }\n * ]\n * })\n * private onIngredientsLoaded(): void {\n * const response = getServiceResponse(this, PATH_INGREDIENTS, 'get');\n * // Mappings already applied to response data\n * response?.forEach(i => this.ingredients.addModel(i));\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport function kosServiceRequest<\n Paths extends Record<string, any> = Record<string, any>,\n Path extends keyof Paths = string,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n Paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n // Ensure the ServiceRequestHandlers property exists on the target object\n target[ServiceRequestHandlers] = target[ServiceRequestHandlers] || {};\n\n const originalHandler = descriptor.value;\n\n // Store metadata for this service request\n const metadata: ServiceRequestMetadata<\n Paths,\n Path,\n Method,\n Response,\n TransformedResponse\n > = {\n ...params,\n handlerMethod: propertyKey,\n originalHandler,\n };\n\n // Keyed by method so a lifecycle handler and a reload may share one path.\n target[ServiceRequestHandlers][propertyKey] = metadata;\n\n // For method-driven requests (no lifecycle), wrap the handler to inject execution context\n if (!params.lifecycle) {\n const wrappedMethod = function (this: any, ...args: any[]) {\n const lastArg = args[args.length - 1];\n\n // Create executor bound to THIS SPECIFIC METHOD's metadata (inlined logic)\n const executor: ServiceRequestExecutor<Paths, Path, Method> = async (\n runtimeOptions\n ) => {\n // Get metadata for the CURRENT method (from WeakMap)\n const currentMetadata = methodMetadataMap.get(wrappedMethod);\n if (!currentMetadata) {\n throw new Error(\"Service request metadata not found for method\");\n }\n\n try {\n // Dynamically import API to avoid circular dependencies\n const { default: API } = await import(\n \"../../../models/utils/service\"\n );\n\n // Resolve all parameters using helper function\n const { resolvedPath, apiParams, finalBody, finalRequestOptions } =\n resolveServiceRequestParameters(\n currentMetadata,\n this,\n args,\n runtimeOptions\n );\n\n // Execute API request using helper function\n const result = await executeApiMethod(\n API,\n currentMetadata.method,\n resolvedPath,\n apiParams,\n finalBody,\n finalRequestOptions\n );\n const [error, response] = result;\n const errorContext = result[2];\n\n // Handle errors using helper function\n if (error) {\n return handleServiceRequestError(\n error,\n response,\n currentMetadata.errorHandler,\n this,\n errorContext\n );\n }\n\n // Apply transformation if specified\n let transformedResponse = response;\n if (currentMetadata.transform) {\n transformedResponse = currentMetadata.transform(response);\n }\n\n return [null, transformedResponse];\n } catch (error: any) {\n return [error.message || \"Unknown error\", null];\n }\n };\n\n // If last parameter is a KosExecutionContext, inject $request into it\n // Otherwise, create new context and append it\n if (isKosExecutionContext(lastArg)) {\n (lastArg as any).$request = executor;\n (lastArg as any).$name = String(propertyKey);\n return originalHandler.apply(this, args);\n } else {\n const context: any = {\n [KOS_EXECUTION_CONTEXT]: true,\n $request: executor,\n $name: String(propertyKey),\n };\n return originalHandler.apply(this, [...args, context]);\n }\n };\n\n // Store metadata in WeakMap keyed by wrapped method\n methodMetadataMap.set(wrappedMethod, metadata);\n\n descriptor.value = wrappedMethod;\n }\n\n // Return descriptor (modified for method-driven, unchanged for lifecycle-driven)\n // ServiceRequestManager will handle execution during lifecycle for lifecycle-driven requests\n return descriptor;\n };\n}\n","/**\n * Response retention policies for ServiceResponseStore\n * Controls how long service responses are cached and when they're cleaned up\n *\n * @kosService core.service-request\n */\nexport enum ResponseRetention {\n /**\n * Clear immediately after handler completes\n * Use for one-time operations with no caching needs\n *\n * Note: Response remains available during handler execution (including async handlers).\n * Cleanup happens AFTER the handler returns/resolves via ServiceRequestManager.\n */\n IMMEDIATE = \"immediate\",\n\n /**\n * Keep until next response for same path\n * Default behavior - previous response replaced on new request\n */\n SINGLE = \"single\",\n\n /**\n * Keep for specified duration (ms)\n * Automatic cleanup after TTL expires\n */\n TTL = \"ttl\",\n\n /**\n * Keep until model is destroyed\n * Use for data needed throughout model lifetime\n */\n PERMANENT = \"permanent\",\n\n /**\n * Keep until explicitly cleared\n * Manual cleanup required via clearServiceResponse()\n */\n MANUAL = \"manual\",\n}\n\n/**\n * Configuration for response caching behavior\n *\n * @kosService core.service-request\n * @kosApiLevel 15\n */\nexport interface ResponseCacheConfig {\n /**\n * Retention policy determining when response is cleaned up\n */\n retention: ResponseRetention;\n\n /**\n * Time-to-live in milliseconds (required for TTL retention)\n */\n ttl?: number;\n\n /**\n * For TTL retention: extend TTL instead of replacing data on new request\n *\n * When false (default): New request clears old data and stores new data with fresh TTL\n * When true: If cached data exists and hasn't expired, extend TTL without replacing data\n *\n * Use extendOnRefresh=true to avoid re-running expensive operations when cached data is still valid.\n *\n * @default false\n *\n * @example\n * // Replace on each request (default)\n * cache: { retention: ResponseRetention.TTL, ttl: 5 * 60 * 1000 }\n *\n * @example\n * // Extend TTL on refresh - avoid re-fetching if cache valid\n * cache: { retention: ResponseRetention.TTL, ttl: 5 * 60 * 1000, extendOnRefresh: true }\n */\n extendOnRefresh?: boolean;\n\n /**\n * Maximum number of responses to cache per path (future use)\n */\n maxSize?: number;\n}\n\n/**\n * Replay strategy for baseline-delta race condition handling\n * Determines which queued events to replay after baseline loads\n *\n * @kosService core.topic-handler\n */\nexport enum ReplayStrategy {\n /**\n * Replay all queued events\n * Use for: State machines, audit trails requiring complete event history\n */\n ALL = \"all\",\n\n /**\n * Replay events received at or after baseline request was sent\n * Use for: High-frequency idempotent updates (quantities, sensor readings, status)\n */\n AFTER_REQUEST = \"after-request\",\n\n /**\n * Replay events received at or after baseline response was received\n * Use for: Low-frequency config where baseline likely includes recent changes\n */\n AFTER_RESPONSE = \"after-response\",\n\n /**\n * Discard all queued events\n * Use for: Baseline is always complete source of truth\n */\n NONE = \"none\",\n}\n\n/**\n * Baseline dependency configuration for topic handlers\n *\n * @kosService core.topic-handler\n * @kosApiLevel 15\n */\nexport interface BaselineDependency {\n /**\n * API path of the baseline request this handler depends on\n */\n path: string;\n\n /**\n * HTTP method of the baseline request\n * @default 'get'\n */\n method?: string;\n\n /**\n * Strategy for replaying queued events after baseline loads\n * @default ReplayStrategy.AFTER_REQUEST\n */\n replayStrategy?: ReplayStrategy;\n}\n\n/**\n * Cached response with metadata\n */\nexport interface CachedResponse<T = unknown> {\n /**\n * The response data\n */\n data: T;\n\n /**\n * When the response was cached (timestamp)\n * @deprecated Use requestedAt or receivedAt for temporal comparisons\n */\n timestamp: number;\n\n /**\n * When the HTTP request was sent (timestamp)\n * Used for baseline-delta temporal filtering\n */\n requestedAt: number;\n\n /**\n * When the HTTP response was received (timestamp)\n * Used for baseline-delta temporal filtering\n */\n receivedAt: number;\n\n /**\n * The API path this response came from\n */\n path: string;\n\n /**\n * The HTTP method used\n */\n method: string;\n\n /**\n * When this response expires (for TTL retention)\n */\n expiresAt?: number;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-param-reassign */\nimport { DependencyLifecycle } from \"../../types\";\nimport { KosLog } from \"../log\";\nimport {\n StateEntryHandlers,\n StateExitHandlers,\n StateMachineSetup,\n} from \"./propKeys\";\n\nconst log = KosLog.createLogger({ name: \"kos-state-machine\" });\n/**\n * Configuration for a KOS state machine.\n *\n * @template TState Union type of valid state strings\n * @template TEvent Union type of valid event strings\n *\n * @example\n * ```typescript\n * const config: KosStateMachineConfig<'idle' | 'active', 'START' | 'STOP'> = {\n * initial: 'idle',\n * initializeAt: DependencyLifecycle.READY,\n * states: {\n * idle: { on: { START: 'active' } },\n * active: { on: { STOP: 'idle' } }\n * }\n * };\n * ```\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport interface KosStateMachineConfig<\n TState extends string,\n TEvent extends string\n> {\n /**\n * The initial state when the state machine is initialized.\n * This state will be set when the FSM reaches its configured lifecycle phase.\n */\n initial: TState;\n\n /**\n * The lifecycle phase at which the state machine should be initialized.\n * Before this phase, currentState will be undefined and isFsmInitialized will be false.\n *\n * @default DependencyLifecycle.READY\n *\n * @example\n * ```typescript\n * // FSM initializes when model is ready (most common)\n * initializeAt: DependencyLifecycle.READY\n *\n * // FSM initializes only when UI activates the model\n * initializeAt: DependencyLifecycle.ACTIVATE\n *\n * // FSM initializes during model initialization (rare)\n * initializeAt: DependencyLifecycle.INIT\n * ```\n */\n initializeAt?: DependencyLifecycle;\n\n /**\n * State machine definition mapping states to their allowed transitions.\n *\n * @example\n * ```typescript\n * states: {\n * idle: { on: { PREPARE: 'preparing' } },\n * preparing: { on: { READY: 'ready', ERROR: 'error' } },\n * ready: { on: { POUR: 'pouring' } },\n * pouring: { on: { COMPLETE: 'idle', ERROR: 'error' } },\n * error: { on: { RESET: 'idle' } }\n * }\n * ```\n */\n states: Record<\n TState,\n {\n /**\n * Mapping of events to target states.\n * When an event occurs in this state, transition to the target state.\n */\n on?: Partial<Record<TEvent, TState>>;\n\n /**\n * Event to auto-send when an async @kosStateEntry handler resolves.\n * Only triggers if the FSM is still in this state when the handler completes.\n *\n * @example\n * ```typescript\n * cancelling: {\n * on: { CANCELLED: 'cancelled', FAIL: 'error' },\n * onDone: 'CANCELLED', // auto-transition on success\n * onError: 'FAIL', // auto-transition on failure\n * }\n * ```\n */\n onDone?: TEvent;\n\n /**\n * Event to auto-send when an async @kosStateEntry handler rejects.\n * Only triggers if the FSM is still in this state when the handler fails.\n */\n onError?: TEvent;\n }\n >;\n}\n\n/**\n * Options for configuring state machine behavior.\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport interface KosStateMachineOptions {\n /**\n * Property name for storing the current state.\n *\n * @default \"currentState\"\n */\n stateProperty?: string;\n\n /**\n * Whether to track state history.\n * When enabled, a stateHistory array is maintained with timestamps and events.\n *\n * @default false\n */\n trackHistory?: boolean;\n\n /**\n * Whether to throw errors on invalid transitions.\n * When false, invalid transitions are logged as warnings instead.\n *\n * @default true\n */\n throwOnInvalid?: boolean;\n\n /**\n * Optional function to compute the initial FSM state dynamically at instance creation time.\n * When provided, this function is called with the model instance and its return value\n * is used as the initial state instead of the static `initial` from the config.\n *\n * This is useful for ViewModels that wrap an existing model which may already be in\n * a non-default state (e.g., a connection that is already CONNECTED on app load).\n *\n * Note: Entry handlers are NOT called for the computed initial state since it\n * represents current state, not a transition.\n *\n * @param instance The model/ViewModel instance (after constructor, before makeAutoObservable)\n * @returns The initial FSM state to use\n *\n * @example\n * ```typescript\n * @kosStateMachine(fsmConfig, {\n * computeInitialState: (instance) => {\n * const state = instance.connection?.state;\n * return state === 'CONNECTED' ? 'connected' : 'inactive';\n * }\n * })\n * ```\n * @kosApiLevel 21\n */\n computeInitialState?: (instance: any) => string;\n}\n\n/**\n * Interface for models using the @kosStateMachine decorator.\n *\n * **IMPORTANT**: Use TypeScript interface merging to add FSM properties to your model class.\n * This provides full type safety and IntelliSense support for all injected FSM functionality.\n *\n * ## Interface Merging Pattern\n *\n * ```typescript\n * // 1. Define state and event types\n * type PourState = 'idle' | 'preparing' | 'ready' | 'pouring' | 'error';\n * type PourEvent = 'PREPARE' | 'READY' | 'POUR' | 'COMPLETE' | 'ERROR';\n *\n * // 2. Declare interface merging BEFORE the class\n * interface DispenserModelImpl extends KosStateMachineAware<PourState, PourEvent> {}\n *\n * // 3. Apply decorators and implement the class\n * @kosModel({ modelTypeId: \"dispenser-model\" })\n * @kosStateMachine<PourState, PourEvent>({\n * initial: 'idle',\n * initializeAt: DependencyLifecycle.READY,\n * states: {\n * idle: { on: { PREPARE: 'preparing' } },\n * preparing: { on: { READY: 'ready', ERROR: 'error' } },\n * ready: { on: { POUR: 'pouring' } },\n * pouring: { on: { COMPLETE: 'idle', ERROR: 'error' } },\n * error: {}\n * }\n * })\n * export class DispenserModelImpl implements IKosDataModel {\n * // All FSM properties are now available with full type safety\n * }\n * ```\n *\n * ## Lifecycle-Aware Initialization\n *\n * The FSM is uninitialized until the configured lifecycle phase:\n * - Before initialization: `currentState === undefined`, `isFsmInitialized === false`\n * - After initialization: `currentState === initial`, `isFsmInitialized === true`\n *\n * ```typescript\n * @kosStateMachine({\n * initial: 'idle',\n * initializeAt: DependencyLifecycle.READY, // FSM starts when model is ready\n * states: { ... }\n * })\n * class MyModel {\n * async ready(): Promise<void> {\n * // Before this completes: this.currentState === undefined\n * // After this completes: this.currentState === 'idle'\n * }\n * }\n * ```\n *\n * ## Injected Properties and Methods\n *\n * The decorator automatically injects the following members:\n *\n * - **`currentState`**: Current state (undefined until FSM initialized, observable)\n * - **`isFsmInitialized`**: Boolean indicating if FSM has been initialized\n * - **`isTransitioning`**: Boolean indicating if a transition is in progress\n * - **`allowedTransitions`**: Computed array of valid events for current state\n * - **`transition(event)`**: Method to trigger state transitions\n * - **`canTransition(event)`**: Check if a transition is valid from current state\n * - **`isInState(state)`**: Check if currently in a specific state\n * - **`stateHistory`**: Array of historical states (if trackHistory enabled)\n *\n * All properties are reactive and will automatically update UI components when state changes.\n *\n * @template TState Union type of valid state strings\n * @template TEvent Union type of valid event strings\n *\n * @see {@link kosStateMachine} - The decorator function\n * @see {@link KosStateMachineConfig} - Configuration interface\n * @see {@link KosStateMachineOptions} - Options interface\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport interface KosStateMachineAware<\n TState extends string,\n TEvent extends string\n> {\n /**\n * Current state of the state machine.\n * Observable property that updates automatically via @kosModel.\n * Always initialized to the initial state immediately.\n */\n currentState: TState;\n\n /**\n * Indicates whether the state machine has been initialized.\n * FSM initializes at the configured lifecycle phase (READY, ACTIVATE, etc.).\n *\n * - Before initialization: `false`, `currentState === undefined`\n * - After initialization: `true`, `currentState === initial`\n */\n readonly isFsmInitialized: boolean;\n\n /**\n * Indicates whether a state transition is currently in progress.\n * Observable property that updates during transitions.\n */\n isTransitioning: boolean;\n\n /**\n * Computed array of valid events that can be triggered from the current state.\n * Updates automatically when state changes.\n * Returns empty array if FSM is not initialized.\n */\n readonly allowedTransitions: TEvent[];\n\n /**\n * Trigger a state transition by event.\n *\n * @param event The event to trigger\n * @throws Error if FSM not initialized (unless `throwOnInvalid` is false)\n * @throws Error if transition is invalid (unless `throwOnInvalid` is false)\n *\n * @example\n * ```typescript\n * this.transition('START'); // idle -> active\n * this.transition('STOP'); // active -> idle\n * ```\n */\n transition(event: TEvent): void;\n\n /**\n * Check if a transition is valid from the current state.\n * Returns false if FSM is not initialized.\n *\n * @param event The event to check\n * @returns true if the transition is valid, false otherwise\n *\n * @example\n * ```typescript\n * if (this.canTransition('START')) {\n * this.transition('START');\n * }\n * ```\n */\n canTransition(event: TEvent): boolean;\n\n /**\n * Check if the state machine is currently in a specific state.\n * Returns false if FSM is not initialized.\n *\n * @param state The state to check\n * @returns true if currently in the specified state, false otherwise\n *\n * @example\n * ```typescript\n * if (this.isInState('idle')) {\n * console.log('System is idle');\n * }\n * ```\n */\n isInState(state: TState): boolean;\n\n /**\n * History of state transitions (if trackHistory is enabled).\n * Each entry contains the state, timestamp, and optional event that caused the transition.\n *\n * Only available when `trackHistory: true` is set in options.\n */\n stateHistory?: Array<{\n state: TState;\n timestamp: Date;\n event?: TEvent;\n }>;\n}\n\n/**\n * Class decorator that adds finite state machine capabilities to a KOS model.\n *\n * This decorator eliminates manual state management boilerplate by:\n * - **Adding lifecycle-aware FSM initialization** at configured phase (READY, ACTIVATE, etc.)\n * - **Managing state transitions** automatically with validation\n * - **Providing observable state** that integrates with @kosModel reactive system\n * - **Supporting entry/exit handlers** via @kosStateEntry and @kosStateExit decorators\n * - **Enabling state guards** via @kosStateGuard decorator\n *\n * ## Two-Level State System\n *\n * **Framework Lifecycle (Universal, Not Customizable):**\n * - CREATED → INIT → LOAD → READY → ACTIVATE → UNLOAD → DESTROY\n * - Managed by KOS framework\n * - Same for all models\n *\n * **Application FSM (This Decorator):**\n * - Runs WITHIN an active model\n * - Application-specific business logic\n * - Different for each model type\n * - Examples: Pour states, connection states, workflow states\n *\n * ## Lifecycle Integration\n *\n * The FSM initializes at the configured lifecycle phase:\n *\n * ```typescript\n * @kosStateMachine({\n * initial: 'idle',\n * initializeAt: DependencyLifecycle.READY, // Default\n * states: { ... }\n * })\n * ```\n *\n * - **INIT**: FSM needs to be active during model initialization (rare)\n * - **READY**: FSM operational as soon as data loaded (most common)\n * - **ACTIVATE**: FSM only relevant when UI is active (UI-bound models)\n *\n * ## TypeScript Usage\n *\n * **IMPORTANT**: Use TypeScript interface merging to get proper type information:\n *\n * ```typescript\n * type MyState = 'idle' | 'active';\n * type MyEvent = 'START' | 'STOP';\n *\n * interface MyModelImpl extends KosStateMachineAware<MyState, MyEvent> {}\n *\n * @kosStateMachine<MyState, MyEvent>({ ... })\n * class MyModelImpl implements IKosDataModel {\n * // All FSM properties are now available with full type safety\n * }\n * ```\n *\n * @param config State machine configuration\n * @param options Optional configuration for FSM behavior\n * @returns A class decorator that modifies the target class prototype\n *\n * @see {@link KosStateMachineAware} - Interface for TypeScript merging\n * @see {@link KosStateMachineConfig} - Configuration interface\n * @see {@link KosStateMachineOptions} - Options interface\n *\n * @example\n * ```typescript\n * // Basic FSM with default READY initialization\n * type PourState = 'idle' | 'pouring' | 'complete';\n * type PourEvent = 'START' | 'FINISH';\n *\n * interface PourModelImpl extends KosStateMachineAware<PourState, PourEvent> {}\n *\n * @kosModel({ modelTypeId: \"pour-model\" })\n * @kosStateMachine<PourState, PourEvent>({\n * initial: 'idle',\n * states: {\n * idle: { on: { START: 'pouring' } },\n * pouring: { on: { FINISH: 'complete' } },\n * complete: {}\n * }\n * })\n * class PourModelImpl implements IKosDataModel {\n * async ready(): Promise<void> {\n * // After this completes, FSM is initialized to 'idle'\n * }\n *\n * startPour(): void {\n * this.transition('START'); // idle -> pouring\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // UI-bound FSM with ACTIVATE initialization\n * type WorkflowState = 'draft' | 'review' | 'approved';\n * type WorkflowEvent = 'SUBMIT' | 'APPROVE' | 'REJECT';\n *\n * interface DocumentModelImpl extends KosStateMachineAware<WorkflowState, WorkflowEvent> {}\n *\n * @kosModel({ modelTypeId: \"document-model\" })\n * @kosStateMachine<WorkflowState, WorkflowEvent>({\n * initial: 'draft',\n * initializeAt: DependencyLifecycle.ACTIVATE, // UI-bound\n * states: {\n * draft: { on: { SUBMIT: 'review' } },\n * review: { on: { APPROVE: 'approved', REJECT: 'draft' } },\n * approved: {}\n * }\n * })\n * class DocumentModelImpl implements IKosDataModel {\n * // FSM only initializes when UI activates this model\n * }\n * ```\n *\n * @example\n * ```typescript\n * // FSM with history tracking\n * interface HistoryModelImpl extends KosStateMachineAware<'idle' | 'active', 'TOGGLE'> {}\n *\n * @kosStateMachine<'idle' | 'active', 'TOGGLE'>(\n * {\n * initial: 'idle',\n * states: {\n * idle: { on: { TOGGLE: 'active' } },\n * active: { on: { TOGGLE: 'idle' } }\n * }\n * },\n * {\n * trackHistory: true,\n * stateProperty: 'status'\n * }\n * )\n * class HistoryModelImpl implements IKosDataModel {\n * // Access via this.stateHistory\n * }\n * ```\n *\n * @category KOS Model Decorator\n * @since 2.1.0\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport function kosStateMachine<TState extends string, TEvent extends string>(\n config: KosStateMachineConfig<TState, TEvent>,\n options?: KosStateMachineOptions\n): ClassDecorator {\n return (target: any) => {\n // Store configuration on prototype\n // This will be processed by kosModel.ts during model instantiation\n target.prototype[StateMachineSetup] = {\n config: {\n ...config,\n // Default to READY if not specified\n initializeAt: config.initializeAt || DependencyLifecycle.READY,\n },\n options: {\n stateProperty: options?.stateProperty || \"currentState\",\n trackHistory: options?.trackHistory || false,\n throwOnInvalid: options?.throwOnInvalid !== false,\n computeInitialState: options?.computeInitialState,\n },\n };\n\n return target;\n };\n}\n\n/**\n * Method decorator that marks a method as a state entry handler.\n * The decorated method will be called when the state machine enters the specified state.\n *\n * @param state The state to handle entry for\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * @kosStateEntry('pouring')\n * handlePouringStart(): void {\n * this.logger.info('Pour started');\n * EventBus.publish(TOPIC_POUR_STARTED, { id: this.id });\n * }\n * ```\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport function kosStateEntry<TState extends string>(\n state: TState\n): MethodDecorator {\n return (target: any, propertyKey: string | symbol) => {\n // Initialize the handlers map if it doesn't exist\n if (!target[StateEntryHandlers]) {\n target[StateEntryHandlers] = new Map<string, string>();\n }\n\n // Store the handler method name for this state\n target[StateEntryHandlers].set(state, propertyKey as string);\n };\n}\n\n/**\n * Method decorator that marks a method as a state exit handler.\n * The decorated method will be called when the state machine exits the specified state.\n *\n * @param state The state to handle exit for\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * @kosStateExit('pouring')\n * handlePouringEnd(): void {\n * this.logger.info('Pour ended');\n * EventBus.publish(TOPIC_POUR_ENDED, { id: this.id });\n * }\n * ```\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport function kosStateExit<TState extends string>(\n state: TState\n): MethodDecorator {\n return (target: any, propertyKey: string | symbol) => {\n // Initialize the handlers map if it doesn't exist\n if (!target[StateExitHandlers]) {\n target[StateExitHandlers] = new Map<string, string>();\n }\n\n // Store the handler method name for this state\n target[StateExitHandlers].set(state, propertyKey as string);\n };\n}\n\n/**\n * Options for @kosStateGuard decorator.\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport interface KosStateGuardOptions<TState extends string> {\n /**\n * Array of states in which the decorated method can be called.\n * The method will throw an error (or log a warning) if called from any other state.\n */\n allowedStates: TState[];\n\n /**\n * Whether to throw an error on invalid state.\n * When false, logs a warning instead.\n *\n * @default true (uses the FSM's throwOnInvalid setting)\n */\n throwOnInvalid?: boolean;\n}\n\n/**\n * Method decorator that guards a method with state validation.\n * The decorated method can only be called when the state machine is in one of the allowed states.\n *\n * **IMPORTANT**: This decorator gracefully handles uninitialized FSM:\n * - If FSM is not yet initialized, the guard allows the method to proceed\n * - Once FSM is initialized, the guard enforces state validation\n *\n * @param options Guard configuration\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * @kosStateGuard({ allowedStates: ['ready'] })\n * async pourBeverage(bevId: string): Promise<void> {\n * // This method can only be called when currentState === 'ready'\n * this.transition('POUR');\n * await this.deviceService.dispense(bevId);\n * this.transition('COMPLETE');\n * }\n * ```\n *\n * @kosService core.state-machine\n * @kosApiLevel 15\n */\nexport function kosStateGuard<TState extends string>(\n options: KosStateGuardOptions<TState>\n): MethodDecorator {\n return (\n _target: any,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor\n ) => {\n const originalMethod = descriptor.value;\n\n descriptor.value = function (this: any, ...args: any[]) {\n // Check if FSM is initialized\n const isFsmInitialized = this.isFsmInitialized;\n\n // If FSM is not initialized, allow the method to proceed\n // This handles the case where methods are called during model initialization\n if (!isFsmInitialized) {\n return originalMethod.apply(this, args);\n }\n\n // Get current state\n const currentState = this.currentState;\n\n // Check if current state is allowed\n const isAllowed = options.allowedStates.includes(currentState);\n\n if (!isAllowed) {\n const message = `Method ${String(\n propertyKey\n )} cannot be called from state \"${currentState}\". Allowed states: ${options.allowedStates.join(\n \", \"\n )}`;\n\n // Use FSM's throwOnInvalid setting if not explicitly overridden\n const shouldThrow =\n options.throwOnInvalid !== undefined\n ? options.throwOnInvalid\n : this[StateMachineSetup]?.options?.throwOnInvalid !== false;\n\n if (shouldThrow) {\n throw new Error(message);\n } else {\n log.warn(message);\n return undefined; // Don't execute the method when state is invalid\n }\n }\n\n return originalMethod.apply(this, args);\n };\n\n return descriptor;\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 // Capture alias in closure for callback\n const capturedAlias = alias;\n const disposer = kosAutoEffect(() => {\n if (future.endState || future.progress) {\n this.container?.onFutureUpdate?.(future, capturedAlias);\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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const KosObservableData = Symbol(\"KosObservableData\");\nconst REVISION = Symbol(\"revision\");\n\nclass ObservableDataMap<T extends Record<string | number | symbol, any>> {\n private map: Map<keyof T, T[keyof T]>;\n [REVISION] = 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 using Symbol key\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 // eslint-disable-next-line no-unused-expressions\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 symbol\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: (_target) => {\n const mapKeys = Array.from(this.map.keys()) as (string | symbol)[];\n // Include REVISION symbol - it's an own property of the target\n return [...mapKeys, REVISION];\n },\n getOwnPropertyDescriptor: (_target, property) => {\n // Make all map keys appear as enumerable, configurable properties\n // This is required for Object.keys() to include them\n if (this.map.has(property as keyof T)) {\n return {\n enumerable: true,\n configurable: true,\n writable: true,\n value: this.getValue(property as keyof T),\n };\n }\n // Handle REVISION symbol\n if (property === REVISION) {\n return {\n enumerable: false,\n configurable: true,\n writable: true,\n value: _target[REVISION],\n };\n }\n return undefined;\n },\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\n/**\n * @kosService core.utils\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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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","/* 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\";\nimport { KosLog } from \"../log\";\n\n/**\n * @kosService core.extension\n */\nexport type ExtensionType = number | string | boolean;\n/**\n * @kosService core.extension\n */\nexport type FailurePolicy = \"throw\" | \"continue\";\n\n/**\n * @kosService core.extension\n * @kosApiLevel 20\n */\nexport interface ExtensionOptions {\n failurePolicy?: FailurePolicy;\n}\n\nconst DEFAULT_EXTENSION_OPTIONS: Required<ExtensionOptions> = {\n failurePolicy: \"throw\",\n};\n\n/**\n * @kosService core.extension\n * @kosApiLevel 20\n */\nexport class ExtensionException extends Error {\n public readonly extensionId: string;\n public readonly extensionType: string;\n public override readonly cause: unknown;\n\n constructor(\n extensionId: string,\n extensionType: string,\n cause: unknown,\n message?: string\n ) {\n super(\n message || `Extension failure in ${extensionType} for id \"${extensionId}\"`\n );\n this.name = \"ExtensionException\";\n this.extensionId = extensionId;\n this.extensionType = extensionType;\n this.cause = cause;\n }\n}\n\n/**\n * @kosService core.extension\n */\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\ninterface RegisteredDataMapper {\n mapper: DataMapper;\n options: Required<ExtensionOptions>;\n}\n\n/**\n * @kosService core.extension\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\ninterface RegisteredPropertyMapper {\n mapper: PropertyMapper;\n options: Required<ExtensionOptions>;\n}\n\n/**\n * @kosService core.extension\n */\nexport type DataLoader<I extends object = any, O extends object = any> = (\n input: I\n) => Promise<O>;\n\ninterface RegisteredDataLoader {\n loader: DataLoader;\n options: Required<ExtensionOptions>;\n}\n\n/**\n * @kosService core.extension\n */\nexport type IndexExtension<T extends IKosDataModel = any> = Record<\n string,\n keyof T | IndexMapper<any>\n>;\n\n/**\n * @kosService core.extension\n * @kosApiLevel 10\n */\nexport const EXTENSION_CANVAS_RENDERER = \"canvas-renderer\";\n/**\n * @kosService core.extension\n * @kosApiLevel 22\n */\nexport const EXTENSION_FUTURE_LIFECYCLE_WRAPPER =\n \"kos.declarative.futureLifecycleWrapper\";\nconst dataMappers = new Map<string, RegisteredDataMapper[]>();\nconst dataLoaders = new Map<string, RegisteredDataLoader>();\nconst propertyMappers = new Map<string, RegisteredPropertyMapper>();\nconst indexExtensions = new Map<string, IndexExtension>();\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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}\n/**\n * @kosService core.extension\n * @kosApiLevel 2\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: (\n id: string,\n loader: DataLoader,\n options?: ExtensionOptions\n ) => {\n dataLoaders.set(id, {\n loader,\n options: { ...DEFAULT_EXTENSION_OPTIONS, ...options },\n });\n },\n executeLoader: async <T extends object = any>(id: string, data: T) => {\n const registered = dataLoaders.get(id);\n if (!registered) {\n return undefined;\n }\n const { loader, options } = registered;\n try {\n return await loader(data);\n } catch (e) {\n if (options.failurePolicy === \"continue\") {\n KosLog.error(`Error executing data loader for id ${id}`);\n KosLog.error(e);\n return undefined;\n }\n throw new ExtensionException(id, \"dataLoader\", e);\n }\n },\n },\n propertyMapper: {\n registerPropertyMapper: (\n id: string,\n mapper: PropertyMapper,\n options?: ExtensionOptions\n ) => {\n propertyMappers.set(id, {\n mapper,\n options: { ...DEFAULT_EXTENSION_OPTIONS, ...options },\n });\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 registered = propertyMappers.get(id);\n if (!registered) {\n return \"\" as O;\n }\n const { mapper, options } = registered;\n try {\n return mapper(data, context) as O;\n } catch (e) {\n if (options.failurePolicy === \"continue\") {\n KosLog.error(`Error executing property mapper for id ${id}`);\n KosLog.error(e);\n return \"\" as O;\n }\n throw new ExtensionException(id, \"propertyMapper\", e);\n }\n },\n },\n dataMapper: {\n registerDataMapper: (\n id: string,\n mapper: DataMapper,\n options?: ExtensionOptions\n ) => {\n const mappers = dataMappers.get(id) || [];\n mappers.push({\n mapper,\n options: { ...DEFAULT_EXTENSION_OPTIONS, ...options },\n });\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, options } of mappers) {\n try {\n const _interim = await mapper(data, context);\n Object.assign(result, _interim);\n } catch (e) {\n if (options.failurePolicy === \"continue\") {\n KosLog.error(`Error executing data mapper for id ${id}`);\n KosLog.error(e);\n continue;\n }\n throw new ExtensionException(id, \"dataMapper\", e);\n }\n }\n\n return result as O;\n },\n },\n canvas: {\n registerRenderer: (id: string, renderer: RendererConstructor) => {\n if (!ExtensionManager[EXTENSION_CANVAS_RENDERER]) {\n KosLog.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\n/**\n * @kosService core.extension\n */\nexport interface IExtensionManager {}\ntype ExtensionManagerType = typeof _ExtensionManager &\n IExtensionManager & {\n [key: string]: ExtensionPoint;\n };\n\n/**\n * @kosService core.extension\n * @kosApiLevel 2\n */\nexport const ExtensionManager = _ExtensionManager as ExtensionManagerType;\n","/**\n * EventBus topic constants for the kos-ui-sdk container indexing\n * system.\n *\n * `KosModelContainer` publishes ADDED and REMOVED directly when its\n * items are mutated. The `@kosIndexAware` decorator publishes CHANGED\n * via a model-effect over its declared fields. The\n * `@kosContainerIndexAware` decorator publishes SEED on demand and\n * PURGE on unload, and subscribes to REQUEST_SEED for late-attach\n * consumer handshakes.\n *\n * Topic naming is intentionally flat (`kos/model/container/index/<verb>`)\n * — the collection is carried in the payload, not the topic, so a\n * single subscribe gives a consumer visibility into the entire index.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\nexport enum KosContainerIndexEvents {\n /** A new item was added to an indexable collection. */\n ADDED = \"kos/model/container/index/added\",\n\n /** An item was removed from an indexable collection. */\n REMOVED = \"kos/model/container/index/removed\",\n\n /** An item's declared index fields changed. */\n CHANGED = \"kos/model/container/index/changed\",\n\n /**\n * A container's current contents as a single snapshot. Emitted in\n * response to REQUEST_SEED so late-attaching consumers can\n * re-establish their index without per-item events.\n */\n SEED = \"kos/model/container/index/seed\",\n\n /**\n * A container is being unloaded; the index should drop all records\n * matching the carried collection.\n */\n PURGE = \"kos/model/container/index/purge\",\n\n /**\n * Consumer-initiated request that all already-`ready()`\n * containers re-emit a SEED. Lets subscribe order stop mattering.\n */\n REQUEST_SEED = \"kos/model/container/index/request-seed\",\n}\n","/**\n * Type contracts for the kos-ui-sdk container indexing system.\n *\n * The contracts live here rather than alongside any particular\n * decorator so the decorators, the EventBus payloads, and downstream\n * consumers can all import the same shapes without circular\n * dependencies.\n *\n * @kosService core.indexing\n * @kosApiLevel 22\n */\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Symbol-keyed accessor on item models\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Property key used by `@kosIndexAware` to expose an item model's\n * current index record. Keyed by `Symbol.for` so cross-bundle\n * equality holds — the SDK is built separately from consumer code.\n *\n * Container-side publishers read this off each item they're about to\n * broadcast.\n */\nexport const INDEX_RECORD_SYMBOL = Symbol.for(\n \"@kosdev-code/kos-ui-sdk.indexRecord\"\n);\n\n/**\n * String key used by `@kosContainerIndexAware` to publish its\n * declared collection onto its own `KosContext`. Items inherit it\n * via `KosContext.get(INDEX_COLLECTION_KEY)`, which auto-walks the\n * parent chain.\n *\n * String-keyed because `KosContext.get/set` only accept strings.\n * Namespaced to avoid collision with any feature-level context value\n * an author might define.\n */\nexport const INDEX_COLLECTION_KEY = \"@kosdev-code/kos-ui-sdk.collection\";\n\n/**\n * Structural contract for any item model that participates in\n * indexing. The container-side publisher uses this shape to read\n * records off items at publish time.\n */\nexport interface IndexableItem {\n readonly [INDEX_RECORD_SYMBOL]: IndexRecordContribution;\n}\n\n/**\n * Runtime check used by `KosModelContainer` to decide whether to\n * publish for a given item.\n */\nexport function isIndexableItem(value: unknown): value is IndexableItem {\n return (\n typeof value === \"object\" && value !== null && INDEX_RECORD_SYMBOL in value\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Index records\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * What an item contributes via `INDEX_RECORD_SYMBOL`. `collection`\n * is optional — when absent, the item resolves it from its\n * `KosContext` (auto-walking the parent chain).\n *\n * Additional fields beyond identity + collection are arbitrary and\n * driven by the item-level decorator's `fields` declaration.\n */\nexport interface IndexRecordContribution {\n /** Stable id of the indexed item. */\n id: string;\n /** Model type id (e.g. `\"virtual-machine-model\"`). */\n modelType: string;\n /** Per-item collection tag. Falls back to container declaration if absent. */\n collection?: string;\n /** Declared index-relevant fields. Shape is per-modelType. */\n [field: string]: unknown;\n}\n\n/**\n * What the container actually publishes on the EventBus. Identical\n * shape to `IndexRecordContribution`, but `collection` is required\n * — by publish time the fallback rule has already been applied.\n */\nexport interface IndexRecord extends IndexRecordContribution {\n collection: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// EventBus payloads\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Payload for `KosContainerIndexEvents.ADDED`. */\nexport interface IndexAddedEvent {\n record: IndexRecord;\n}\n\n/** Payload for `KosContainerIndexEvents.REMOVED`. */\nexport interface IndexRemovedEvent {\n id: string;\n modelType: string;\n collection: string;\n}\n\n/** Payload for `KosContainerIndexEvents.CHANGED`. Full record, not deltas. */\nexport interface IndexChangedEvent {\n record: IndexRecord;\n}\n\n/**\n * Payload for `KosContainerIndexEvents.SEED`. Emitted in response to\n * REQUEST_SEED. The items array may carry mixed collections\n * (heterogeneous containers where items are tagged by their own\n * properties). Subscribers route per record, not per top-level field.\n */\nexport interface IndexSeedEvent {\n modelType: string;\n items: IndexRecord[];\n}\n\n/**\n * Payload for `KosContainerIndexEvents.PURGE`. Collection-scoped;\n * the consumer drops all matching records.\n */\nexport interface IndexPurgeEvent {\n modelType: string;\n collection: string;\n}\n\n/**\n * Payload for `KosContainerIndexEvents.REQUEST_SEED`. Optional\n * `collections` filter lets a targeted consumer ask only for what it\n * cares about; an empty/absent filter means \"all\".\n */\nexport interface IndexRequestSeedEvent {\n /** Free-form id used for diagnostics (e.g. `\"index-service\"`). */\n requestedBy: string;\n /** Optional filter; undefined or empty means \"all collections\". */\n collections?: string[];\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","/**\n * KosModelContainer - Container with automatic capacity management\n *\n * ## Capacity Management (Safety Net)\n *\n * Containers can automatically evict models when capacity is exceeded to prevent\n * memory overflow. This is particularly useful for event-driven containers that\n * accumulate models based on incoming events (logs, sensor data, transient records).\n *\n * ### Usage Examples\n *\n * **1. FIFO Strategy (Event Streams, Logs)**\n * ```typescript\n * @kosContainerAware<LogBlockModel>({\n * containerProperty: \"logs\",\n * containerOptions: {\n * maxCapacity: 1000, // Keep last 1000 log blocks\n * evictionStrategy: 'fifo', // Remove oldest first (default)\n * evictionBatchSize: 100, // Remove 100 at a time when exceeded\n * }\n * })\n * export class LogContainerModelImpl {\n * // No explicit cleanup needed - FIFO manages size automatically\n * }\n * ```\n *\n * **2. LRU Strategy (Caches)**\n * ```typescript\n * @kosContainerAware<CachedDataModel>({\n * containerOptions: {\n * maxCapacity: 500,\n * evictionStrategy: 'lru', // Remove least recently accessed\n * }\n * })\n * export class CacheContainerModelImpl {\n * // Frequently accessed models stay, unused ones are evicted\n * }\n * ```\n *\n * **3. Custom Strategy (Business Logic)**\n * ```typescript\n * @kosContainerAware<TroubleModel>({\n * containerProperty: \"troubles\",\n * containerOptions: {\n * maxCapacity: 5000, // Safety net - normally < 100\n * evictionStrategy: 'custom',\n * customEvictionFilter: (troubles) => {\n * // Evict resolved troubles older than 1 hour\n * return troubles.filter(t =>\n * t.status === 'resolved' &&\n * Date.now() - t.resolvedAt > 3600000\n * );\n * }\n * }\n * })\n * export class TroubleContainerModelImpl {\n * // Primary cleanup via explicit handlers\n * // Custom eviction as fallback for edge cases\n * }\n * ```\n *\n * **4. Safety Net (Prevent Crashes)**\n * ```typescript\n * @kosContainerAware<SensorReadingModel>({\n * containerOptions: {\n * maxCapacity: 10000, // Set higher than expected (normally ~100-1000)\n * // If this triggers, investigate upstream data inconsistency\n * }\n * })\n * ```\n *\n * ### Eviction Logging\n *\n * All evictions are logged at INFO level with details:\n * ```\n * INFO: Container capacity exceeded (1001/1000). Evicting 100 models using fifo strategy.\n * INFO: Evicting model: log-12345 (type: LogBlockModel)\n * INFO: Evicted 100 models. Current size: 901/1000\n * ```\n *\n * This allows for easy filtering of eviction messages while still providing\n * visibility into container capacity management.\n */\n\nimport {\n isComputedProp,\n runInAction as kosAction,\n makeAutoObservable,\n observable,\n observe,\n reaction,\n} from \"mobx\";\n\nimport * as EventBus from \"../../common/events/eventBus\";\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 { KosContainerIndexEvents } from \"./indexing/topics\";\nimport {\n INDEX_RECORD_SYMBOL,\n isIndexableItem,\n type IndexAddedEvent,\n type IndexRecord,\n type IndexRemovedEvent,\n} from \"./indexing/types\";\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 removeAndDestroy: (id: string) => Promise<void>;\n removeAndDestroyAll: (ids: string[]) => Promise<void>;\n toJSON?: () => object;\n}\nconst log = KosLog.createLogger({ name: \"kos-container-model\" });\ntype PropType = string | number | symbol | undefined;\n\n/**\n * Eviction strategy for container capacity management\n *\n * - **fifo**: First-In-First-Out - removes oldest models first (default for event streams)\n * - **lru**: Least Recently Used - removes models not accessed recently (good for caches)\n * - **custom**: Uses customEvictionFilter function to determine which models to evict\n *\n * @category Container Capacity Management\n * @see {@link ContainerOptions.maxCapacity}\n * @see {@link ContainerOptions.evictionStrategy}\n */\nexport type EvictionStrategy = \"fifo\" | \"lru\" | \"custom\";\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\n /**\n * SAFETY NET: Maximum number of models this container can hold.\n * When exceeded, models are automatically evicted and destroyed based on evictionStrategy.\n *\n * **Primary use case**: Prevent memory overflow when cleanup handlers are missing or\n * data becomes inconsistent. Set higher than normal usage to catch edge cases.\n *\n * **Eviction is logged**: All automatic evictions are logged at WARNING level\n * to aid in debugging and identifying data inconsistencies.\n *\n * @category Capacity Management\n * @see {@link EvictionStrategy}\n * @see {@link evictionBatchSize}\n *\n * @example\n * ```typescript\n * containerOptions: {\n * maxCapacity: 10000, // Safety net: expect ~100-1000 normally\n * evictionStrategy: 'fifo'\n * }\n * ```\n */\n maxCapacity?: number;\n\n /**\n * Strategy for selecting which models to evict when maxCapacity is exceeded.\n *\n * - **fifo** (default): Remove oldest models first - best for event streams, logs\n * - **lru**: Remove least recently accessed models - best for caches\n * - **custom**: Use customEvictionFilter to determine eviction candidates\n *\n * @category Capacity Management\n * @see {@link EvictionStrategy}\n * @see {@link maxCapacity}\n * @see {@link customEvictionFilter}\n *\n * @default 'fifo'\n */\n evictionStrategy?: EvictionStrategy;\n\n /**\n * Number of models to evict when maxCapacity is exceeded.\n * Removing in batches prevents thrashing at the capacity boundary.\n *\n * @category Capacity Management\n * @see {@link maxCapacity}\n *\n * @default Math.max(10, Math.ceil(maxCapacity * 0.1))\n */\n evictionBatchSize?: number;\n\n /**\n * Custom filter function for 'custom' eviction strategy.\n * Should return models that are candidates for eviction.\n * The container will evict up to evictionBatchSize models from the returned array.\n *\n * @category Capacity Management\n * @see {@link EvictionStrategy}\n * @see {@link maxCapacity}\n *\n * @example\n * ```typescript\n * // Evict resolved troubles older than 1 hour\n * customEvictionFilter: (models) => {\n * return models.filter(m =>\n * m.status === 'resolved' &&\n * Date.now() - m.resolvedAt > 3600000\n * );\n * }\n * ```\n */\n customEvictionFilter?: (models: T[]) => T[];\n}\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\n // Capacity management fields\n private _maxCapacity?: number;\n private _evictionStrategy: EvictionStrategy;\n private _evictionBatchSize: number;\n private _insertionOrder: string[] = []; // For FIFO strategy\n private _accessTimes?: Map<string, number>; // For LRU strategy\n private _customEvictionFilter?: (models: T[]) => T[];\n\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 // Initialize capacity management\n this._maxCapacity = options?.maxCapacity;\n this._evictionStrategy = options?.evictionStrategy || \"fifo\";\n this._evictionBatchSize =\n options?.evictionBatchSize ??\n Math.max(10, Math.ceil((options?.maxCapacity ?? 100) * 0.1));\n this._customEvictionFilter = options?.customEvictionFilter;\n\n // Initialize LRU access tracking if needed\n if (this._evictionStrategy === \"lru\" && this._maxCapacity) {\n this._accessTimes = observable.map(new Map());\n }\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 /**\n * Remove a model from the container and destroy it.\n * This is a convenience method that combines removeModel() and destroyKosModel().\n *\n * Use this when:\n * - The model is being permanently removed from the system\n * - The model should be cleaned up and disposed\n *\n * Use removeModel() alone when:\n * - Moving models between containers\n * - Temporarily removing without destroying\n * - Managing models that may be re-added later\n *\n * @param id - The unique identifier of the model to remove and destroy\n */\n async removeAndDestroy(id: string): Promise<void> {\n const model = this.getModel(id);\n if (!model) {\n log.debug(`Model ${id} not found in container, skipping destroy`);\n return;\n }\n\n this.removeModel(id);\n\n try {\n await destroyKosModel(model);\n } catch (error) {\n log.error(`Failed to destroy model ${id}:`, error);\n throw error;\n }\n }\n\n /**\n * Remove multiple models from the container and destroy them.\n * This is a convenience method that combines removeAll() and destroyKosModel().\n *\n * Operations are performed in parallel for efficiency, but each destruction\n * is independent - failures in one won't prevent others from being destroyed.\n *\n * @param ids - Array of unique identifiers of the models to remove and destroy\n * @returns Promise that resolves when all models have been removed and destroyed\n */\n async removeAndDestroyAll(ids: string[]): Promise<void> {\n const models = ids\n .map((id) => this.getModel(id))\n .filter((model): model is T => model !== undefined);\n\n if (models.length === 0) {\n log.debug(\"No models found to destroy\");\n return;\n }\n\n // Remove all from container first (synchronous)\n this.removeAll(ids);\n\n // Destroy in parallel, collecting errors\n const results = await Promise.allSettled(\n models.map((model) => destroyKosModel(model))\n );\n\n // Log any failures\n results.forEach((result, index) => {\n if (result.status === \"rejected\") {\n log.error(\n `Failed to destroy model ${models[index].id}:`,\n result.reason\n );\n }\n });\n\n // If any failures occurred, throw an aggregate error\n const failures = results.filter((r) => r.status === \"rejected\");\n if (failures.length > 0) {\n throw new Error(\n `Failed to destroy ${failures.length} of ${models.length} models`\n );\n }\n }\n\n /**\n * Add a model to the container (Zone 2: Workflow orchestration)\n *\n * @param model - The model to add\n * @param defer - If true, skip incrementing revision (for batch operations)\n */\n addModel(model: T, defer?: boolean) {\n // Zone 2: High-level workflow orchestration\n this._persistModel(model);\n this._trackModelMetadata(model);\n this._establishModelRelationships(model);\n this._enforceCapacityLimits();\n this._configureModelMonitoring(model);\n\n // Publishing happens AFTER relationship establishment so the\n // item's INDEX_RECORD_SYMBOL accessor can auto-walk to the\n // container's KosContext for an inherited collection.\n this._publishIndexAdded(model);\n\n if (!defer) {\n this.increment();\n }\n }\n\n /**\n * Persist model to container storage (Zone 3)\n * @private\n */\n private _persistModel(model: T): void {\n this._data.set(model.id || \"\", model);\n }\n\n /**\n * Track model metadata for capacity management (Zone 3)\n * @private\n */\n private _trackModelMetadata(model: T): void {\n if (!this._maxCapacity) return;\n\n // Track insertion order for FIFO eviction\n this._insertionOrder.push(model.id || \"\");\n\n // Track initial access time for LRU eviction\n if (this._accessTimes) {\n this._accessTimes.set(model.id || \"\", Date.now());\n }\n }\n\n /**\n * Establish parent-child relationships (Zone 3)\n * @private\n */\n private _establishModelRelationships(model: T): void {\n if (model.id && this._parentId) {\n KosContextManager.setParentContext(model.id, this._parentId);\n }\n }\n\n /**\n * Enforce capacity limits and trigger eviction if needed (Zone 3)\n * @private\n */\n private _enforceCapacityLimits(): void {\n if (!this._maxCapacity) return;\n\n if (this._data.size > this._maxCapacity) {\n this._evictModels();\n }\n }\n\n /**\n * Configure MobX observers for model property changes (Zone 3)\n * @private\n */\n private _configureModelMonitoring(model: T): void {\n // Clean up existing disposer if present\n const existingDisposer = this._disposerMap.get(model.id);\n if (existingDisposer) {\n existingDisposer();\n this._disposerMap.delete(model.id);\n }\n\n // Setup index mapping infrastructure\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\n // Create change handler for index refresh\n const handler = (change) => {\n // Refresh specific index if indexed property changed\n if (values.includes(change.name as keyof T)) {\n this.index.get(reverseMap.get(change.name) as string)?.refresh();\n }\n\n // Refresh all function-based indexes\n const fnIndexes = entries.filter(\n ([, value]) => typeof value === \"function\"\n );\n for (const [key] of fnIndexes) {\n this.index.get(key)?.refresh();\n }\n };\n\n // Setup observers\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\n // Store combined disposer\n this._disposerMap.set(model.id || \"\", () =>\n [disposer, ...computedDisposers].forEach((d) => d())\n );\n }\n\n /**\n * Publish KosContainerIndexEvents.ADDED for an indexable item.\n * No-op when the model carries no INDEX_RECORD_SYMBOL (not opted\n * into indexing) or when the record has no resolvable collection\n * (item has no own tag and no inheritable container context).\n *\n * @private\n */\n private _publishIndexAdded(model: T): void {\n if (!isIndexableItem(model)) return;\n const contribution = model[INDEX_RECORD_SYMBOL];\n if (!contribution.collection) return;\n const payload: IndexAddedEvent = {\n record: contribution as IndexRecord,\n };\n EventBus.publish(KosContainerIndexEvents.ADDED, payload);\n }\n\n /**\n * Publish KosContainerIndexEvents.REMOVED for an indexable item.\n * Called with the model BEFORE it's deleted from the container so\n * the payload can carry modelType + collection.\n *\n * @private\n */\n private _publishIndexRemoved(model: T | undefined): void {\n if (!model || !isIndexableItem(model)) return;\n const contribution = model[INDEX_RECORD_SYMBOL];\n if (!contribution.collection) return;\n const payload: IndexRemovedEvent = {\n id: contribution.id,\n modelType: contribution.modelType,\n collection: contribution.collection,\n };\n EventBus.publish(KosContainerIndexEvents.REMOVED, payload);\n }\n\n removeModel(id: string, defer?: boolean) {\n // Capture the model BEFORE deleting it so the index payload can\n // carry the right modelType + collection; after delete, the\n // record is gone.\n const removedModel = this._data.get(id);\n this._publishIndexRemoved(removedModel);\n\n this._data.delete(id);\n\n // Clean up tracking data structures\n const orderIndex = this._insertionOrder.indexOf(id);\n if (orderIndex !== -1) {\n this._insertionOrder.splice(orderIndex, 1);\n }\n\n if (this._accessTimes) {\n this._accessTimes.delete(id);\n }\n\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 const model = this._data.get(id);\n\n // Track access time for LRU eviction strategy\n if (model && this._accessTimes) {\n this._accessTimes.set(id, Date.now());\n }\n\n return model;\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 /**\n * SAFETY NET: Evict models when capacity is exceeded (Zone 2: Workflow orchestration)\n * Logs all evictions at WARNING level for debugging.\n * @private\n */\n private async _evictModels() {\n if (!this._maxCapacity) return;\n\n const overCapacity = this._data.size - this._maxCapacity;\n if (overCapacity <= 0) return;\n\n const toEvict = Math.min(this._evictionBatchSize, overCapacity);\n\n // Zone 2: Workflow orchestration\n this._logCapacityWarning(toEvict);\n const modelsToEvict = this._selectModelsForEviction(toEvict);\n await this._removeEvictedModels(modelsToEvict);\n this._logEvictionComplete(modelsToEvict.length);\n\n this.increment();\n }\n\n /**\n * Log capacity exceeded info (Zone 3)\n * @private\n */\n private _logCapacityWarning(toEvict: number): void {\n log.info(\n `Container capacity exceeded (${this._data.size}/${this._maxCapacity}). ` +\n `Evicting ${toEvict} models using ${this._evictionStrategy} strategy.`,\n { parentId: this._parentId }\n );\n }\n\n /**\n * Select models for eviction based on strategy (Zone 3)\n * @private\n */\n private _selectModelsForEviction(count: number): T[] {\n switch (this._evictionStrategy) {\n case \"fifo\":\n return this._selectFifoModels(count);\n case \"lru\":\n return this._selectLruModels(count);\n case \"custom\":\n return this._selectCustomModels(count);\n default:\n return this._selectFifoModels(count);\n }\n }\n\n /**\n * Select oldest models for FIFO eviction (Zone 3)\n * @private\n */\n private _selectFifoModels(count: number): T[] {\n const models: T[] = [];\n for (let i = 0; i < count && this._insertionOrder.length > 0; i++) {\n const oldestId = this._insertionOrder.shift();\n if (!oldestId) continue;\n\n const model = this._data.get(oldestId);\n if (model) {\n models.push(model);\n }\n }\n return models;\n }\n\n /**\n * Select least recently used models for LRU eviction (Zone 3)\n * @private\n */\n private _selectLruModels(count: number): T[] {\n const models: T[] = [];\n\n if (this._accessTimes) {\n const sorted = Array.from(this._accessTimes.entries())\n .sort((a, b) => a[1] - b[1])\n .slice(0, count);\n\n sorted.forEach(([id]) => {\n const model = this._data.get(id);\n if (model) {\n models.push(model);\n }\n });\n }\n\n return models;\n }\n\n /**\n * Select models using custom filter for eviction (Zone 3)\n * @private\n */\n private _selectCustomModels(count: number): T[] {\n if (this._customEvictionFilter) {\n const candidates = this._customEvictionFilter(this.data);\n return candidates.slice(0, count);\n }\n\n log.error(\n \"Custom eviction strategy specified but no customEvictionFilter provided. \" +\n \"Falling back to FIFO.\",\n { parentId: this._parentId }\n );\n\n return this._selectFifoModels(count);\n }\n\n /**\n * Remove and destroy evicted models (Zone 3)\n * @private\n */\n private async _removeEvictedModels(models: T[]): Promise<void> {\n for (const model of models) {\n log.info(\n `Evicting model: ${model.id} (type: ${model.constructor.name})`,\n {\n modelId: model.id,\n parentId: this._parentId,\n strategy: this._evictionStrategy,\n }\n );\n\n this.removeModel(model.id, true);\n\n destroyKosModel(model).catch((e) =>\n log.error(`Failed to destroy evicted model ${model.id}:`, e)\n );\n }\n }\n\n /**\n * Log eviction completion (Zone 3)\n * @private\n */\n private _logEvictionComplete(evictedCount: number): void {\n log.info(\n `Evicted ${evictedCount} models. ` +\n `Current size: ${this._data.size}/${this._maxCapacity}`,\n { parentId: this._parentId }\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","export enum KosModelState {\n CREATING = `creating`,\n CREATED = `created`,\n INITIALIZING = `initializing`,\n INITIALIZED = `initialized`,\n LOADING = `loading`,\n LOADED = `loaded`,\n ONLINE = `online`,\n READYING = `readying`,\n READY = `ready`,\n READY_FAILED = `ready_failed`,\n RESETTING = `resetting`,\n RESET = `reset`,\n OFFLINE = `offline`,\n UNLOADING = `unloading`,\n UNLOADED = `unloaded`,\n FAILED = `failed`,\n INACTIVE = \"inactive\",\n ACTIVE = \"active\",\n ACTIVATING = \"activating\",\n DEACTIVATING = \"deactivating\",\n}\n\nexport enum KosModelEvents {\n CREATE = `create`,\n INITIALIZE = `init`,\n LOAD = `load`,\n READY = `ready`,\n GO_ONLINE = `go_online`,\n GO_OFFLINE = `go_offline`,\n RESET = `go_offline`,\n UNLOAD = `unload`,\n FAILED = \"failed\",\n GO_ACTIVE = \"go_active\",\n GO_INACTIVE = \"go_inactive\",\n TIMEOUT = \"timeout\",\n}\n","import { 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 * @kosService core.utils\n *\n * @example\n * // Wait for the 'dataModel' to become ready before using it.\n * const dataModel = await whenReady(dataModel);\n * @kosApiLevel 2\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 *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const destroyKosModel = async (model: IKosDataModel) => {\n await KosCore.getInstance().whenReady();\n await KosCore.getInstance().modelManager.initiateDestroyModel(model);\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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 *\n * @kosService core.utils\n * @kosApiLevel 2\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 *\n * @kosService core.utils\n * @kosApiLevel 2\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 *\n * @kosService core.utils\n * @kosApiLevel 2\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 *\n * @kosService core.utils\n * @kosApiLevel 2\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 *\n * @kosService core.utils\n * @kosApiLevel 2\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 *\n * @kosService core.utils\n * @kosApiLevel 2\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 *\n * @kosService core.utils\n * @kosApiLevel 2\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 *\n * @kosService core.utils\n * @kosApiLevel 2\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\n/**\n * @kosService core.utils\n * @kosApiLevel 5\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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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 *\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const isKosModel =\n <T extends IKosDataModel>(type: string) =>\n (model: any): model is T =>\n Object.getPrototypeOf(model).modelTypeId === type;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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\n/**\n * An observable, read-only view of a model's activation lifecycle.\n *\n * Models that fetch lazily do so in `activate()`, so activation state — not\n * `loaded`, which tracks the `load()` lifecycle — is what tells a consumer\n * whether that fetch has settled and whether it succeeded. Exposing just this\n * lets a view react to activation without taking a dependency on the whole\n * {@link IKosModel}.\n */\nexport interface KosModelActivationState {\n /** The model's current activation state. */\n readonly activeStatus: KosModelState;\n /** Activation is in flight — nothing conclusive to render yet. */\n readonly isActivating: boolean;\n /** Activation completed; the model's activate() work is done. */\n readonly isActive: boolean;\n /** Activation threw — the model's data is absent, not empty. */\n readonly isFailed: boolean;\n}\n\n/**\n * Retrieves an observable view of a model's activation state.\n *\n * Every member is a getter, so reads happen at access time and stay tracked —\n * call this once and read its properties inside a `kosComponent` (or any MobX\n * reaction) to re-render as the model activates, succeeds, or fails.\n *\n * @param model - The KOS data model to observe.\n * @returns The activation view, or `undefined` when the model has no wrapper\n * yet (not created, or already destroyed).\n *\n * @example Distinguishing \"still loading\" from \"empty\" from \"failed\"\n * ```tsx\n * const activation = getKosModelActivationState(container);\n * if (!activation || activation.isActivating) return <Blank />;\n * if (activation.isFailed) return <LoadError />;\n * return <Versions items={container.items} />;\n * ```\n *\n * @kosService core.utils\n * @kosApiLevel 15\n */\nexport const getKosModelActivationState = (\n model: IKosDataModel | undefined\n): KosModelActivationState | undefined => {\n if (!model?.id) {\n return undefined;\n }\n const kosModel = KosCore.getInstance().modelManager.getModelById(model.id);\n if (!kosModel) {\n return undefined;\n }\n\n return {\n get activeStatus() {\n return kosModel.activeStatus;\n },\n get isActivating() {\n return kosModel.activeStatus === KosModelState.ACTIVATING;\n },\n get isActive() {\n return kosModel.activeStatus === KosModelState.ACTIVE;\n },\n get isFailed() {\n return kosModel.activeStatus === KosModelState.FAILED;\n },\n };\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 { KosLog } from \"../log\";\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 KosLog.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.model)) {\n return model.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","/* 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 { injectStateMachineSupport } from \"./fsm-injection-utils\";\nimport {\n ChildModels,\n CompanionParentModel,\n ContainerAwareSetup,\n DependencyModels,\n FutureAliases,\n FutureContainerSetup,\n FutureService,\n KosModelSymbol,\n LogConfig,\n LoggerSetup,\n MultipleFutureContainerSetup,\n OptionsRequired,\n ParentModel,\n ReloadAwareSetup,\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\n// FSM injection and initialization functions moved to fsm-injection-utils.ts\n// for better maintainability and adherence to clean architecture principles\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 modelInstance.addAll = (models: any[]) => {\n container.addAll(models);\n };\n\n modelInstance.removeAll = (ids: string[]) => {\n container.removeAll(ids);\n };\n\n modelInstance.removeAndDestroy = async (id: string) =>\n container.removeAndDestroy(id);\n\n modelInstance.removeAndDestroyAll = async (ids: string[]) =>\n container.removeAndDestroyAll(ids);\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 // The framework ALWAYS puts the parent in initialData.companionParent regardless of parentProperty\n const parentModel = initialData.companionParent;\n if (!parentModel) {\n log.warn(\n `Companion decorator configured but no parent model found in initialData.companionParent`\n );\n return;\n }\n\n // Add getCompanionParent method (available in both modes)\n modelInstance.getCompanionParent = () => parentModel;\n\n // Create immutable getter for the parent property (required for both modes)\n // This prevents accidental reassignment and ensures consistency\n Object.defineProperty(modelInstance, parentProperty, {\n get: () => parentModel,\n enumerable: true,\n configurable: true, // Allow MobX to make this observable if needed\n });\n\n // If composition mode, stop here - only getCompanionParent() and direct property access 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 injectReloadAwareSupport(modelInstance: any) {\n const setup = modelInstance[ReloadAwareSetup];\n if (!setup) return;\n\n const { reloadDependencies = [] } = setup;\n\n // Add _isReloading backing field on instance\n modelInstance._isReloading = false;\n\n // Add isReloading getter that aggregates across declared dependencies\n Object.defineProperty(modelInstance, \"isReloading\", {\n get() {\n if (this._isReloading) return true;\n for (const dep of reloadDependencies) {\n if (this[dep]?.isReloading) return true;\n }\n return false;\n },\n enumerable: true,\n configurable: true,\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 // Inject companion support immediately after construction, before any other setup\n // This ensures this.trouble is available before computed properties are accessed\n injectCompanionSupport(modelInstance, initialData);\n injectFutureServices(modelInstance);\n injectFutureContainerSupport(modelInstance);\n injectMultipleFutureContainerSupport(modelInstance);\n injectTroubleAwareSupport(modelInstance);\n injectContainerAwareSupport(modelInstance, modelId);\n injectStateMachineSupport(modelInstance);\n injectReloadAwareSupport(modelInstance);\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 * Indicates whether this model requires options to be provided during instantiation.\n * When true, the framework will throw an error if an empty or undefined options object\n * is provided when creating a dependency with DependencyResolutionPolicy.CREATE.\n * @default false\n */\n optionsRequired?: 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 * @kosService core.kos-model\n * @kosApiLevel 2\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 // Store optionsRequired flag for dependency resolution validation\n if (modelConfig.optionsRequired) {\n typedCtor.prototype[OptionsRequired] = true;\n }\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","/* eslint-disable no-param-reassign */\nimport type { ApiCallback } from \"../../../common/events\";\nimport { EventBusFunctional } from \"../../../common/events\";\nimport { DependencyLifecycle } from \"../../types\";\nimport type { BaselineDependency } from \"../../types/service-response-store\";\nimport { IKosDataModel } from \"../kosModel\";\nimport type { FlowControlOptions } from \"./kos-topic-handler-flow-control\";\nimport { SubscriptionHandlers } from \"./propKeys\";\n\n/**\n * Extended ApiCallback that includes wildcard capture data for handlers with trailing wildcards\n *\n * @kosService core.topic-handler\n * @kosApiLevel 12\n */\nexport interface ApiCallbackWithWildcard<T = string> extends ApiCallback<T> {\n /**\n * @kosApiLevel 8\n */\n wildcardCapture?: Record<string, string>;\n}\n\n/**\n * Zone 3: Parses wildcard segment from topic pattern and actual topic\n * @internal - exported for testing\n */\nexport function parseWildcardSegment(\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 * Zone 3: Checks if topic pattern has trailing wildcard\n * @internal - exported for testing\n */\nexport function checkWildcardPattern(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 *\n * @kosService core.topic-handler\n * @kosApiLevel 2\n */\nexport interface IKosTopicHandlerParams<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n> {\n /**\n * The topic or array of topics to which the handler should respond.\n */\n topic: string | string[];\n\n /**\n * A conditional function that determines whether the handler should be invoked based on the received payload and the Kos Data Model instance.\n * If not provided, the handler will always be invoked when a matching topic is received.\n *\n * @param payload - The transformed payload received from the topic.\n * @param model - The Kos Data Model instance to which the topic handler belongs.\n * @returns `true` if the handler should be invoked, `false` otherwise.\n */\n condition?: (\n payload: TransformedResponse,\n model: Model,\n raw: Response\n ) => boolean;\n\n /**\n * A transformation function that converts the raw response payload into a desired format.\n * If not provided, the payload will be used as is.\n *\n * @param payload - The raw response payload received from the topic.\n * @returns The transformed payload in the desired format.\n */\n transform?: (payload: Response) => TransformedResponse;\n\n /**\n * Indicates whether the topic handler should listen for WebSocket messages.\n * If set to `true`, the handler will be invoked when WebSocket messages with matching topics are received.\n * Default is `false`.\n */\n websocket?: boolean;\n\n /**\n * @internal\n */\n fos?: boolean;\n\n /**\n * @internal\n */\n bridge?: boolean;\n\n lifecycle?: DependencyLifecycle;\n\n /**\n * @internal\n */\n skipParse?: boolean;\n\n /**\n * @kosApiLevel 6\n */\n destinationAddress?: string;\n\n /**\n * When true, the `destinationAddress` value is used exactly as provided\n * and the transport will NOT fall back to `connId` from query parameters\n * or kosBridge. Use this when a subscription intentionally targets\n * a specific (or empty) destination regardless of the current device context.\n * @kosApiLevel 22\n */\n explicitDestination?: boolean;\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 * @kosApiLevel 11\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 * @kosApiLevel 11\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 * @kosApiLevel 11\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 * @kosApiLevel 11\n */\n filter?: (payload: Response) => boolean;\n\n /**\n * Only handle the event once, then automatically unsubscribe\n * @kosApiLevel 11\n */\n once?: boolean;\n\n /**\n * Replay the last N events to new handlers\n * @kosApiLevel 11\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 * @kosApiLevel 12\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 * @kosApiLevel 12\n */\n flow?: FlowControlOptions<Response, TransformedResponse>;\n\n /**\n * Baseline dependency configuration for baseline-delta race condition handling.\n * When specified, this handler will wait for the baseline service request to complete\n * before processing events, and will intelligently replay queued events based on\n * temporal comparison with the baseline request/response timing.\n *\n * @example\n * ```typescript\n * @kosTopicHandler({\n * topic: TOPIC_INGREDIENT_UPDATE,\n * websocket: true,\n * lifecycle: DependencyLifecycle.READY,\n * requiresBaseline: {\n * path: PATH_INGREDIENTS,\n * method: 'get',\n * replayStrategy: 'after-request'\n * }\n * })\n * handleIngredientUpdate(payload: IngredientUpdatePayload) {\n * // Framework guarantees:\n * // 1. Baseline loaded before this handler executes\n * // 2. Queued events replayed with temporal filtering\n * // 3. Only events newer than baseline are processed\n * }\n * ```\n * @kosApiLevel 15\n */\n requiresBaseline?: BaselineDependency;\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 * @kosService core.topic-handler\n * @kosApiLevel 2\n */\nexport function kosTopicHandler<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n>(params: IKosTopicHandlerParams<Response, Model, TransformedResponse>) {\n return (\n target: any,\n _propertyKey: string,\n descriptor: PropertyDescriptor\n ) => {\n const configuration = prepareHandlerConfiguration(params, descriptor);\n registerTopicHandlers(target, params.topic, configuration);\n\n if (params.replay) {\n configureReplayBehavior(params.topic, params.replay.bufferSize);\n }\n };\n}\n\n// === TYPE DEFINITIONS ===\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\n/**\n * Zone 2: Prepares handler configuration by coordinating enhancement creation\n */\nfunction prepareHandlerConfiguration<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n>(\n params: IKosTopicHandlerParams<Response, Model, TransformedResponse>,\n descriptor: PropertyDescriptor\n) {\n const {\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 explicitDestination = false,\n debounce,\n throttle,\n buffer,\n filter,\n once,\n wildcardName,\n flow,\n requiresBaseline,\n } = params;\n\n const originalHandler = descriptor.value;\n const enhancedHandler = applyFunctionalEnhancements(originalHandler, {\n debounce,\n throttle,\n buffer,\n once,\n });\n const enhancedCondition = combineFilterWithCondition(filter, condition);\n\n return {\n websocket,\n fos,\n bridge,\n handler: enhancedHandler,\n condition: enhancedCondition,\n transform,\n lifecycle,\n skipParse,\n destinationAddress,\n explicitDestination,\n wildcardName,\n flow,\n requiresBaseline,\n once,\n };\n}\n\n/**\n * Zone 2: Applies functional enhancements to handler\n *\n * @kosService core.topic-handler\n * @kosApiLevel 15\n */\nexport function applyFunctionalEnhancements<T>(\n handler: TopicHandler<T>,\n enhancements: {\n debounce?: number | { delay: number; discardIntermediate?: boolean };\n throttle?: number | { interval: number; discardIntermediate?: boolean };\n buffer?: { time: number; maxSize?: number };\n once?: boolean;\n }\n): TopicHandler<T> {\n let enhancedHandler = handler;\n\n const debounceDelay =\n typeof enhancements.debounce === \"number\"\n ? enhancements.debounce\n : enhancements.debounce?.delay;\n const throttleInterval =\n typeof enhancements.throttle === \"number\"\n ? enhancements.throttle\n : enhancements.throttle?.interval;\n\n if (debounceDelay && debounceDelay > 0) {\n enhancedHandler = createDebouncedHandler(\n enhancedHandler,\n enhancements.debounce!\n );\n } else if (throttleInterval && throttleInterval > 0) {\n enhancedHandler = createThrottledHandler(\n enhancedHandler,\n enhancements.throttle!\n );\n } else if (enhancements.buffer) {\n // Adapt TopicHandler<T> to BufferedHandler<T>\n // The buffered handler receives an array and calls the original handler for each item\n // (bound here; enhancedHandler is reassigned to the buffered wrapper below).\n const inner = enhancedHandler;\n const adaptedHandler: BufferedHandler<T> = async function (\n this: any,\n payloads: T[]\n ) {\n for (const payload of payloads) {\n await inner.call(this, payload);\n }\n };\n enhancedHandler = createBufferedHandler(\n adaptedHandler,\n enhancements.buffer\n );\n } else if (enhancements.once) {\n enhancedHandler = createOnceHandler(enhancedHandler);\n }\n\n return enhancedHandler;\n}\n\n/**\n * Zone 2: Combines filter with existing condition function\n */\nfunction combineFilterWithCondition<\n Response = any,\n Model extends IKosDataModel = any,\n TransformedResponse = Response\n>(\n filter: ((payload: Response) => boolean) | undefined,\n condition: (\n payload: TransformedResponse,\n model: Model,\n raw: Response\n ) => boolean\n): (payload: TransformedResponse, model: Model, raw: Response) => boolean {\n if (!filter) {\n return condition;\n }\n\n return (payload: TransformedResponse, model: Model, raw: Response) => {\n if (!filter(raw)) {\n return false;\n }\n return condition(payload, model, raw);\n };\n}\n\n/**\n * Zone 3: Registers handler configuration for topics\n */\nfunction registerTopicHandlers(\n target: any,\n topic: string | string[],\n handlerConfig: any\n): void {\n target[SubscriptionHandlers] = target[SubscriptionHandlers] || {};\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\n/**\n * Zone 3: Configures replay behavior for topics\n */\nfunction configureReplayBehavior(\n topic: string | string[],\n bufferSize: number\n): void {\n setupReplayHandler(topic, bufferSize);\n}\n\n// === HELPER FUNCTIONS FOR FUNCTIONAL PATTERNS ===\n\n/**\n * Zone 2: Creates debounced handler using appropriate strategy\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 strategy = determineDebounceStrategy(config);\n\n return strategy === \"discard\"\n ? createDiscardingDebouncer(originalHandler as TopicHandler<T>, delay)\n : createAccumulatingDebouncer(originalHandler as BufferedHandler<T>, delay);\n}\n\n/**\n * Zone 3: Determines which debounce strategy to use\n */\nfunction determineDebounceStrategy(\n config: number | { delay: number; discardIntermediate?: boolean }\n): \"discard\" | \"accumulate\" {\n const discardIntermediate =\n typeof config === \"object\" ? config.discardIntermediate : false;\n return discardIntermediate ? \"discard\" : \"accumulate\";\n}\n\n/**\n * Zone 3: Creates handler that discards intermediate values\n */\nfunction createDiscardingDebouncer<T>(\n originalHandler: TopicHandler<T>,\n delay: number\n): TopicHandler<T> {\n let timeoutId: NodeJS.Timeout | null = null;\n\n return function (this: any, payload: T) {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n originalHandler.call(this, payload);\n timeoutId = null;\n }, delay);\n };\n}\n\n/**\n * Zone 3: Creates handler that accumulates all values\n */\nfunction createAccumulatingDebouncer<T>(\n originalHandler: BufferedHandler<T>,\n delay: number\n): TopicHandler<T> {\n let timeoutId: NodeJS.Timeout | null = null;\n let accumulated: T[] = [];\n\n return function (this: any, payload: T) {\n accumulated.push(payload);\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n timeoutId = setTimeout(() => {\n const batch = [...accumulated];\n accumulated = [];\n originalHandler.call(this, batch);\n timeoutId = null;\n }, delay);\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","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 /**\n * Drops every edge into and out of a model. Called when the model is\n * destroyed, so its dependencies are not left pinned by a model that is\n * gone and can never release them.\n */\n removeAll(modelId: string) {\n for (const dependencyId of this._usesCache.get(modelId) ?? []) {\n const usedBy = this._usedByCache.get(dependencyId);\n if (usedBy) {\n this._usedByCache.set(\n dependencyId,\n usedBy.filter((id) => id !== modelId)\n );\n }\n }\n this._usesCache.delete(modelId);\n\n for (const dependentId of this._usedByCache.get(modelId) ?? []) {\n const uses = this._usesCache.get(dependentId);\n if (uses) {\n this._usesCache.set(\n dependentId,\n uses.filter((id) => id !== modelId)\n );\n }\n }\n this._usedByCache.delete(modelId);\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","// model-cache.ts\n\nimport { observable, runInAction } 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 runInAction(() => {\n this._modelsById.set(existing.modelId, existing);\n });\n return existing as T;\n }\n\n removeModel(modelId: string): void {\n runInAction(() => {\n this._modelsById.delete(modelId);\n this._toDelete.delete(modelId);\n });\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 runInAction(() => {\n this._modelsById.set(modelId, model!);\n });\n }\n }\n\n markForDeletion(model: IKosModel): void {\n runInAction(() => {\n this._modelsById.delete(model.modelId);\n });\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 * Suspense cache backing `useKosModel`.\n *\n * A `finished` entry never re-runs its fetcher, so it has to be evicted when\n * the model it stands for is destroyed. Otherwise the hook keeps resolving the\n * key against a model that no longer exists and the model is never rebuilt.\n *\n * It lives in core rather than beside the hook so the model manager can evict\n * on destroy without depending on the ui layer.\n */\n\nexport type ModelHookCacheEntry =\n | { status: \"pending\"; promise: Promise<unknown> }\n | { status: \"finished\"; key: string }\n | { status: \"error\"; error: unknown };\n\nconst cache = new Map<string, ModelHookCacheEntry>();\n\nexport const modelHookCache = {\n has: (key: string) => cache.has(key),\n get: (key: string) => cache.get(key),\n set: (key: string, entry: ModelHookCacheEntry) => cache.set(key, entry),\n delete: (key: string) => cache.delete(key),\n clear: () => cache.clear(),\n};\n\n/** Evicts a model's cache entry so the next render rebuilds it. */\nexport const clearModelHookCacheEntry = (modelId?: string): void => {\n if (modelId) {\n cache.delete(modelId);\n }\n};\n","/**\n * Utilities for enriching errors with model context throughout the lifecycle.\n * Provides consistent error formatting and context propagation without specific checks.\n */\n\nimport type { IKosDataModel, IKosModel } from \"../core/kosModel\";\nimport { KosLog } from \"../core/log\";\nimport { DependencyLifecycle } from \"../types/kos-dependency\";\n\n/**\n * Enhanced error class that preserves context through the model lifecycle.\n */\nexport class KosModelError extends Error {\n public readonly context: ModelErrorContext;\n public readonly originalCause?: Error;\n\n constructor(message: string, context: ModelErrorContext, cause?: Error) {\n super(message, { cause });\n this.name = \"KosModelError\";\n this.context = context;\n this.originalCause = cause;\n\n // Preserve stack trace\n if (cause?.stack) {\n this.stack = `${this.stack}\\nCaused by: ${cause.stack}`;\n }\n }\n\n /**\n * Format error with full context for logging.\n */\n toDetailedString(): string {\n const parts = [\n `KosModelError: ${this.message}`,\n ``,\n `Context:`,\n ` Model Type: ${this.context.modelType}`,\n ` Model ID: ${this.context.modelId}`,\n ];\n\n if (this.context.parentModel) {\n parts.push(\n ` Parent Model: ${this.context.parentModel.type} [${this.context.parentModel.id}]`\n );\n }\n\n if (this.context.lifecycle) {\n parts.push(` Lifecycle: ${this.context.lifecycle}`);\n }\n\n if (this.context.operation) {\n parts.push(` Operation: ${this.context.operation}`);\n }\n\n if (this.context.options && Object.keys(this.context.options).length > 0) {\n parts.push(` Options: ${JSON.stringify(this.context.options, null, 2)}`);\n }\n\n if (this.originalCause) {\n parts.push(``, `Original Error: ${this.originalCause.message}`);\n }\n\n return parts.join(\"\\n\");\n }\n}\n\n/**\n * Context information for model errors.\n */\nexport interface ModelErrorContext {\n /** Type of model involved */\n modelType: string;\n /** ID of model instance */\n modelId?: string;\n /** Parent model context if applicable */\n parentModel?: {\n type: string;\n id: string;\n };\n /** Lifecycle phase where error occurred */\n lifecycle?: DependencyLifecycle | string;\n /** Operation being performed */\n operation?: string;\n /** Options provided to the model */\n options?: Record<string, any>;\n /** Additional context-specific data */\n metadata?: Record<string, any>;\n}\n\n/**\n * Wraps an error with model context, preserving the original error as cause.\n */\nexport function enrichError(\n error: Error | unknown,\n context: ModelErrorContext\n): KosModelError {\n const originalError =\n error instanceof Error ? error : new Error(String(error));\n\n // If already a KosModelError, preserve and add context\n if (error instanceof KosModelError) {\n return new KosModelError(\n `${error.message} (enriched with additional context)`,\n { ...error.context, ...context },\n error.originalCause || originalError\n );\n }\n\n // Create new enriched error\n return new KosModelError(\n `Error in ${context.operation || \"model operation\"}: ${\n originalError.message\n }`,\n context,\n originalError\n );\n}\n\n/**\n * Safely executes an async operation with automatic error enrichment.\n */\nexport async function executeWithContext<T>(\n operation: () => Promise<T>,\n context: ModelErrorContext\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n const enrichedError = enrichError(error, context);\n KosLog.error(enrichedError.toDetailedString());\n throw enrichedError;\n }\n}\n\n/**\n * Safely executes a sync operation with automatic error enrichment.\n */\nexport function executeSyncWithContext<T>(\n operation: () => T,\n context: ModelErrorContext\n): T {\n try {\n return operation();\n } catch (error) {\n const enrichedError = enrichError(error, context);\n KosLog.error(enrichedError.toDetailedString());\n throw enrichedError;\n }\n}\n\n/**\n * Creates context for a model from its data.\n */\nexport function createModelContext(\n model: IKosModel | IKosDataModel,\n operation?: string\n): ModelErrorContext {\n const modelData = \"modelData\" in model ? model.modelData : model;\n const modelId =\n \"modelId\" in model\n ? model.modelId\n : \"id\" in modelData\n ? modelData.id\n : undefined;\n const modelType =\n \"modelTypeName\" in model\n ? model.modelTypeName\n : modelData.constructor?.name || \"unknown\";\n\n return {\n modelType,\n modelId,\n operation,\n };\n}\n\n/**\n * Logs a collection of errors with summary and details.\n */\nexport function logErrorCollection(\n errors: Array<{ error: Error; context: ModelErrorContext }>,\n summary: string\n): void {\n if (errors.length === 0) return;\n\n KosLog.error(`${summary} - ${errors.length} error(s) occurred:`);\n\n errors.forEach(({ error, context }, index) => {\n const enriched =\n error instanceof KosModelError ? error : enrichError(error, context);\n\n KosLog.error(\n ` [${index + 1}/${errors.length}] ${enriched.toDetailedString()}`\n );\n });\n}\n","/**\n * Zone 3 utility for logging errors with structured context\n */\n\nexport interface ModelInstantiationErrorContext {\n modelType: string;\n options: any;\n registryId: string;\n}\n\n/**\n * Logs a model instantiation error with structured metadata.\n *\n * @param error - The error that occurred during instantiation\n * @param context - Contextual information about the failed instantiation\n */\nexport function logModelInstantiationError(\n error: unknown,\n context: ModelInstantiationErrorContext\n): void {\n console.error(\"Model instantiation failed\", {\n modelType: context.modelType,\n options: context.options,\n registryId: context.registryId,\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n timestamp: new Date().toISOString(),\n });\n}\n","import type { DependencyLifecycle } from \"../../types\";\nimport { 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 * Lifecycle phase at which this companion should be created.\n * Extracted from the @kosCompanion decorator metadata.\n * Defaults to undefined (treated as INIT - immediate creation).\n */\n lifecycle?: DependencyLifecycle;\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","// companion-instantiator.ts\n\nimport type { DependencyLifecycle } from \"../types\";\nimport { CompanionParentModel } from \"./decorators\";\nimport 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-companion-instantiator\" });\n\n/**\n * Handles creation and lifecycle management of companion models.\n * Companions are models that extend or enhance parent models and can be\n * created at specific lifecycle phases based on decorator configuration.\n */\nexport class KosCompanionInstantiator {\n constructor(\n private registry: IKosRegistry,\n private cache: KosModelCacheHandler,\n private createModel: (\n typeId: string,\n id: string,\n options: Record<string, any>\n ) => any\n ) {}\n\n /**\n * Creates companion models for a parent model, optionally filtered by lifecycle phase.\n * Called automatically during instantiation for companions without lifecycle specified.\n * Can be called from lifecycle hooks to create lifecycle-deferred companions.\n *\n * @param model The parent model\n * @param options Options to pass to companion constructors\n * @param lifecycle Optional lifecycle filter - only create companions matching this phase\n */\n createCompanionModels(\n model: IKosModel,\n options: Record<string, any>,\n lifecycle?: DependencyLifecycle\n ) {\n const companionDefs = this.getCompanionDefinitions(model.modelTypeName);\n\n if (lifecycle !== undefined) {\n log.debug(\n `Creating ${lifecycle} lifecycle companions for ${model.modelTypeName} [${model.modelId}]`\n );\n }\n\n for (const companionDef of companionDefs) {\n const resolved = this.resolveCompanionType(\n companionDef,\n model,\n options,\n lifecycle\n );\n if (!resolved) continue;\n\n if (!this.shouldCreateCompanion(resolved.lifecycle, lifecycle)) continue;\n\n this.instantiateCompanion(resolved.type, model, options, lifecycle);\n }\n }\n\n /**\n * Get companion definitions for a parent model type\n */\n private getCompanionDefinitions(parentTypeId: string) {\n return this.registry.companionModels?.[parentTypeId] || [];\n }\n\n /**\n * Resolve companion type from definition and extract lifecycle metadata\n */\n private resolveCompanionType(\n companionDef: any,\n model: IKosModel,\n options: Record<string, any>,\n requestedLifecycle?: DependencyLifecycle\n ): { type: string; lifecycle?: DependencyLifecycle } | null {\n if (isKosCompanionTypeFactory(companionDef.type)) {\n return this.resolveFactoryCompanion(\n companionDef,\n model,\n options,\n requestedLifecycle\n );\n } else {\n return this.resolveStringCompanion(companionDef);\n }\n }\n\n /**\n * Resolve factory companion by calling factory and extracting lifecycle\n */\n private resolveFactoryCompanion(\n companionDef: any,\n model: IKosModel,\n options: Record<string, any>,\n requestedLifecycle?: DependencyLifecycle\n ): { type: string; lifecycle?: DependencyLifecycle } | null {\n const companionType = companionDef.type(model.modelData, options);\n\n if (!companionType) {\n log.debug(\n `Companion factory returned undefined for ${model.modelTypeName} at ${\n requestedLifecycle || \"INIT\"\n } phase`\n );\n return null;\n }\n\n const lifecycle = this.extractLifecycleFromType(companionType);\n return { type: companionType, lifecycle };\n }\n\n /**\n * Resolve string companion using pre-extracted lifecycle from registration\n */\n private resolveStringCompanion(companionDef: any): {\n type: string;\n lifecycle?: DependencyLifecycle;\n } {\n return {\n type: companionDef.type,\n lifecycle: companionDef.lifecycle,\n };\n }\n\n /**\n * Extract lifecycle metadata from companion model decorator\n */\n private extractLifecycleFromType(\n companionType: string\n ): DependencyLifecycle | undefined {\n const companionModelReg = this.registry.models[companionType];\n if (!companionModelReg?.class) return undefined;\n\n const companionMetadata =\n companionModelReg.class.prototype[CompanionParentModel];\n return companionMetadata?.lifecycle;\n }\n\n /**\n * Determine if companion should be created based on lifecycle filtering\n */\n private shouldCreateCompanion(\n companionLifecycle: DependencyLifecycle | undefined,\n requestedLifecycle: DependencyLifecycle | undefined\n ): boolean {\n if (requestedLifecycle !== undefined) {\n // Only create companions that match the specified lifecycle\n return companionLifecycle === requestedLifecycle;\n } else {\n // When no lifecycle filter, only create companions without lifecycle (INIT phase)\n return companionLifecycle === undefined;\n }\n }\n\n /**\n * Instantiate and attach companion to parent model\n */\n private instantiateCompanion(\n companionType: string,\n parentModel: IKosModel,\n options: Record<string, any>,\n lifecycle?: DependencyLifecycle\n ): void {\n const companionId = this.generateCompanionId(\n companionType,\n parentModel.modelId\n );\n\n if (\n this.companionAlreadyExists(\n companionId,\n companionType,\n parentModel.modelTypeName\n )\n ) {\n return;\n }\n\n const companion = this.createCompanionInstance(\n companionType,\n companionId,\n parentModel,\n options\n );\n\n if (companion) {\n this.attachCompanionToParent(companion, parentModel);\n log.debug(\n `Created ${lifecycle || \"INIT\"} companion ${companionType} for ${\n parentModel.modelTypeName\n } [${parentModel.modelId}]`\n );\n }\n }\n\n /**\n * Generate unique companion ID\n */\n private generateCompanionId(companionType: string, parentId: string): string {\n return `${companionType}-${parentId}`;\n }\n\n /**\n * Check if companion already exists in cache\n */\n private companionAlreadyExists(\n companionId: string,\n companionType: string,\n parentTypeName: string\n ): boolean {\n if (this.cache.hasModel(companionId)) {\n log.debug(\n `Companion ${companionType} already exists for ${parentTypeName}`\n );\n return true;\n }\n return false;\n }\n\n /**\n * Create companion model instance with parent context\n */\n private createCompanionInstance(\n companionType: string,\n companionId: string,\n parentModel: IKosModel,\n options: Record<string, any>\n ): IKosModel | null {\n const result = this.createModel(companionType, companionId, {\n data: options,\n companionParent: parentModel.modelData,\n kosParentId: parentModel.modelId,\n });\n\n return result?.model || null;\n }\n\n /**\n * Attach companion to parent model\n */\n private attachCompanionToParent(\n companion: IKosModel,\n parent: IKosModel\n ): void {\n companion[CompanionParentModel] = parent;\n parent.addCompanionModel(companion);\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","/**\n * Constants for KOS model lifecycle and operations\n */\n\n/**\n * Timeout in milliseconds for model lifecycle transitions.\n * Models that don't complete their transition within this time will reject.\n */\nexport const MODEL_PROMISE_TIMEOUT_MS = 5000;\n","/**\n * Zone 3 utilities for model lifecycle transitions\n */\n\nimport type { IKosModel } from \"../core/kosModel\";\nimport { KosModelEvents, KosModelState } from \"../core/lifecycle\";\n\n/**\n * Transition map type for lifecycle operations\n */\nexport type ModelPromiseResolver = (model: IKosModel) => Promise<void>;\n\n/**\n * Transitions a model to the ACTIVE state\n */\nexport const transitionToActive = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.GO_ACTIVE, KosModelState.ACTIVE);\n\n/**\n * Transitions a model to the READY state\n */\nexport const transitionToReady = (model: IKosModel): Promise<void> =>\n model.whenReady();\n\n/**\n * Transitions a model to the LOADED state\n */\nexport const transitionToLoad = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.LOAD, KosModelState.LOADED);\n\n/**\n * Transitions a model to the UNLOADED state\n */\nexport const transitionToUnload = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.UNLOAD, KosModelState.UNLOADED);\n\n/**\n * Transitions a model to the INITIALIZED state\n */\nexport const transitionToInit = (model: IKosModel): Promise<void> =>\n model.fsm.transitionTo(KosModelEvents.INITIALIZE, KosModelState.INITIALIZED);\n\n/**\n * Enum defining available lifecycle transitions\n */\nexport enum Transitions {\n ACTIVE = \"active\",\n READY = \"ready\",\n LOAD = \"load\",\n UNLOAD = \"unload\",\n INIT = \"init\",\n}\n\n/**\n * Mapping of transition types to their corresponding transition functions\n */\nexport const TransitionMap: Record<Transitions, ModelPromiseResolver> = {\n [Transitions.ACTIVE]: transitionToActive,\n [Transitions.READY]: transitionToReady,\n [Transitions.LOAD]: transitionToLoad,\n [Transitions.UNLOAD]: transitionToUnload,\n [Transitions.INIT]: transitionToInit,\n};\n","/**\n * Zone 3 utility for promise timeout and race operations\n */\n\nimport { MODEL_PROMISE_TIMEOUT_MS } from \"../constants/model-constants\";\nimport type { IKosModel } from \"../core/kosModel\";\nimport { KosLog } from \"../core/log\";\n\n/**\n * Custom error for model timeout scenarios\n */\nexport class ModelError extends Error {\n model: IKosModel;\n constructor(message: string | undefined, model: IKosModel) {\n super(message);\n this.model = model;\n }\n}\n\n/**\n * Creates a promise that rejects after a specified delay with model context.\n * Provides a cancel function to prevent rejection if the operation completes.\n *\n * @param ms - Timeout duration in milliseconds\n * @param model - The model being operated on\n * @param status - Description of the operation status (e.g., \"ACTIVE\", \"INACTIVE\")\n * @returns Object containing the timeout promise and a cancel function\n *\n * @example\n * ```typescript\n * const { promise: timeoutPromise, cancel } = rejectAfterDelay(\n * MODEL_PROMISE_TIMEOUT_MS,\n * myModel,\n * 'ACTIVE'\n * );\n *\n * Promise.race([\n * myOperation().then(() => cancel()),\n * timeoutPromise\n * ]);\n * ```\n */\nexport const 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\n/**\n * Races a promise against a timeout with automatic cleanup.\n * Useful for ensuring operations complete within a time limit.\n *\n * @param promise - The operation promise to race\n * @param timeoutMs - Timeout duration in milliseconds (defaults to MODEL_PROMISE_TIMEOUT_MS)\n * @param model - The model being operated on\n * @param status - Description of the operation\n * @returns Promise that resolves/rejects based on whichever completes first\n *\n * @example\n * ```typescript\n * await raceWithTimeout(\n * model.transitionToActive(),\n * MODEL_PROMISE_TIMEOUT_MS,\n * model,\n * 'ACTIVE'\n * );\n * ```\n */\nexport const raceWithTimeout = async <T>(\n promise: Promise<T>,\n timeoutMs: number = MODEL_PROMISE_TIMEOUT_MS,\n model: IKosModel,\n status: string\n): Promise<T> => {\n const { promise: timeoutPromise, cancel } = rejectAfterDelay(\n timeoutMs,\n model,\n status\n );\n\n try {\n const result = await Promise.race([promise, timeoutPromise]);\n cancel();\n return result as T;\n } catch (error) {\n cancel();\n throw error;\n }\n};\n","/**\n * Zone 3 type guard utilities for KOS models\n */\n\nimport { ObservableMap } from \"mobx\";\nimport { DependencyModels } from \"../core/decorators\";\nimport { IKosModelContainer } from \"../core/kos-container-model\";\nimport type { IKosDataModel } from \"../core/kosModel\";\n\n/**\n * Type guard to check if a model has a toJSON method\n */\nexport const isPrintable = (model: any): model is { toJSON: () => object } =>\n typeof model.toJSON === \"function\";\n\n/**\n * Type guard to check if an object is a KOS data model\n */\nexport const isKosDataModel = (model: any): model is IKosDataModel =>\n model[DependencyModels] !== undefined;\n\n/**\n * Type guard to check if a model is a KOS model container\n */\nexport const isKosModelContainer = (\n model: any\n): model is IKosModelContainer<any> =>\n model.revision !== undefined && model.index !== undefined;\n\n/**\n * Resolves a child attribute to its data model representation.\n * Handles various collection types and extracts KOS data models.\n *\n * @param attribute - The attribute to resolve (can be a model, container, collection, or array)\n * @returns The resolved data model(s) or undefined\n */\nexport const resolveChild = (\n attribute: any\n): IKosDataModel | IKosDataModel[] | undefined => {\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 { MODEL_PROMISE_TIMEOUT_MS } from \"../constants/model-constants\";\nimport { DependencyModels, OptionsRequired } from \"../core/decorators\";\nimport { resolveParameters } from \"../core/decorators/resolve-parameters\";\nimport { KosCore } from \"../core/kosCore\";\nimport type { IKosModel } from \"../core/kosModel\";\nimport { KosLog } from \"../core/log\";\nimport {\n DependencyLifecycle,\n DependencyResolutionPolicy,\n KosDependencyParams,\n} from \"../types/kos-dependency\";\nimport { enrichError, logErrorCollection } from \"./model-error-utils\";\nimport { TransitionMap, Transitions } from \"./model-transition-utils\";\nimport { rejectAfterDelay } from \"./promise-utils\";\n\n// Re-export for backward compatibility\nexport { TransitionMap, Transitions } from \"./model-transition-utils\";\nexport type { ModelPromiseResolver } from \"./model-transition-utils\";\nexport {\n isKosDataModel,\n isKosModelContainer,\n isPrintable,\n resolveChild,\n} from \"./model-type-guards\";\nexport { ModelError } from \"./promise-utils\";\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport interface ModelPromise {\n promise?: Promise<void>;\n modelId?: string;\n model?: IKosModel;\n type?: string;\n status?: string;\n}\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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\n const resolutionPolicy =\n dependency.resolutionPolicy || DependencyResolutionPolicy.CREATE;\n\n KosLog.debug(\n `Resolving dependent model ${dependency.modelType} with id ${dataModelId} (policy: ${resolutionPolicy})`\n );\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\n // Validate model type is registered\n const modelManager = KosCore.getInstance().modelManager;\n const modelRegistry = modelManager.registry.models[dependency.modelType];\n\n if (!modelRegistry) {\n const errorMessage = `No model registered for type ${dependency.modelType}`;\n\n KosLog.error(\n `Failed to resolve dependency for model ${model.modelId}:\n - Dependency Type: ${dependency.modelType}\n - Dependency ID: ${dataModelId}\n - Resolution Policy: ${resolutionPolicy}\n - Parent Model: ${model.modelTypeName}\n - Parent Model ID: ${model.modelId}\n - Error: ${errorMessage}`\n );\n\n if (resolutionPolicy === DependencyResolutionPolicy.CONTINUE) {\n KosLog.warn(\n `Model type not registered (policy: CONTINUE) - Model ${model.modelId} will continue without dependency ${dependency.modelType} [${dataModelId}]`\n );\n return { dependentModel: null, dataModelId, success: false };\n }\n\n throw new Error(\n `Dependency resolution failed - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}`\n );\n }\n\n // FIRST: Try to look up existing model instance\n const existingModel = modelManager.getModelById(dataModelId);\n\n if (existingModel) {\n // Verify the model type matches\n if (existingModel.modelTypeName !== dependency.modelType) {\n const errorMessage = `Model type mismatch: expected ${dependency.modelType}, found ${existingModel.modelTypeName}`;\n\n KosLog.error(\n `Failed to resolve dependency for model ${model.modelId}:\n - Dependency Type: ${dependency.modelType}\n - Dependency ID: ${dataModelId}\n - Resolution Policy: ${resolutionPolicy}\n - Parent Model: ${model.modelTypeName}\n - Parent Model ID: ${model.modelId}\n - Found Model Type: ${existingModel.modelTypeName}\n - Error: ${errorMessage}`\n );\n\n if (resolutionPolicy === DependencyResolutionPolicy.CONTINUE) {\n KosLog.warn(\n `Model type mismatch (policy: CONTINUE) - Model ${model.modelId} will continue without dependency`\n );\n return { dependentModel: null, dataModelId, success: false };\n }\n\n throw new Error(\n `Dependency resolution failed - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}`\n );\n }\n\n KosLog.debug(\n `Found existing dependent model ${dependency.modelType} with id ${dataModelId}`\n );\n\n // Return in the same format as createModelInstance\n return {\n dependentModel: { model: existingModel, data: existingModel.modelData },\n dataModelId,\n success: true,\n };\n }\n\n // Model doesn't exist - check resolution policy to decide what to do\n KosLog.debug(\n `Model ${dependency.modelType} [${dataModelId}] does not exist. Applying resolution policy: ${resolutionPolicy}`\n );\n\n // If CONTINUE policy and model doesn't exist, return null without attempting creation\n if (resolutionPolicy === DependencyResolutionPolicy.CONTINUE) {\n KosLog.warn(\n `Model ${dependency.modelType} [${dataModelId}] not found (policy: CONTINUE) - Model ${model.modelId} will continue without this dependency`\n );\n return { dependentModel: null, dataModelId, success: false };\n }\n\n // For CREATE and FAIL policies, attempt to create the model\n // Check if the target model requires options but none (or empty) were provided\n const hasOptions = Object.keys(options).length > 0;\n const modelClass = modelRegistry.class || modelRegistry.create;\n const requiresOptions = modelClass?.prototype?.[OptionsRequired] === true;\n\n if (requiresOptions && !hasOptions) {\n const errorMessage = `Model ${dependency.modelType} requires options but none were provided`;\n\n KosLog.error(\n `Failed to resolve dependency for model ${model.modelId}:\n - Dependency Type: ${dependency.modelType}\n - Dependency ID: ${dataModelId}\n - Resolution Policy: ${resolutionPolicy}\n - Parent Model: ${model.modelTypeName}\n - Parent Model ID: ${model.modelId}\n - Provided Options: ${JSON.stringify(options, null, 2)}\n - Error: ${errorMessage}\n - Model requires options but dependency declaration provides none`\n );\n\n throw new Error(\n `Dependency resolution failed - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}. Use resolutionPolicy: DependencyResolutionPolicy.CONTINUE if this dependency is optional.`\n );\n }\n\n try {\n const dependentModel =\n KosCore.getInstance().modelManager.createModelInstance(\n dependency.modelType,\n dataModelId,\n options\n );\n\n KosLog.debug(\n `Successfully created dependent model ${dependency.modelType} with id ${dataModelId}`\n );\n\n return { dependentModel, dataModelId, success: true };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n KosLog.error(\n `Failed to create dependency for model ${model.modelId}:\n - Dependency Type: ${dependency.modelType}\n - Dependency ID: ${dataModelId}\n - Resolution Policy: ${resolutionPolicy}\n - Parent Model: ${model.modelTypeName}\n - Parent Model ID: ${model.modelId}\n - Provided Options: ${JSON.stringify(options, null, 2)}\n - Error: ${errorMessage}`\n );\n\n // Only CREATE and FAIL policies reach this catch block\n // (CONTINUE policy returns earlier without attempting creation)\n if (resolutionPolicy === DependencyResolutionPolicy.FAIL) {\n throw new Error(\n `Dependency resolution failed (policy: FAIL) - Model ${model.modelId} cannot resolve dependency ${dependency.modelType} [${dataModelId}]: ${errorMessage}`\n );\n }\n\n // For CREATE policy, rethrow the original error\n throw error;\n }\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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 resolutionResult = createModelDependency(model, dependency);\n\n // Handle CONTINUE policy where dependency resolution failed\n if (!resolutionResult.success || !resolutionResult.dependentModel) {\n KosLog.debug(\n `Skipping dependency ${dependency.modelType} with id ${resolutionResult.dataModelId} - resolution failed with CONTINUE policy`\n );\n model.modelData[key] = undefined;\n return null;\n }\n\n const { dependentModel, dataModelId } = resolutionResult;\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 MODEL_PROMISE_TIMEOUT_MS,\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 const enrichedError = enrichError(err, {\n modelType: dependency.modelType,\n modelId: dataModelId,\n parentModel: {\n type: model.modelTypeName,\n id: model.modelId,\n },\n lifecycle: lifecycle,\n operation: \"dependency whenReady()\",\n });\n KosLog.error(enrichedError.toDetailedString());\n cancel();\n // Rethrow to ensure Promise.race can reject\n throw enrichedError;\n }),\n promise,\n ]);\n })\n .filter((p) => !!p);\n\n return dependenciesByLifecycle;\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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 if (!promise.model || !promise.status) {\n return Promise.resolve();\n }\n\n const { promise: timeoutPromise, cancel: timeoutCancel } =\n rejectAfterDelay(\n MODEL_PROMISE_TIMEOUT_MS,\n promise.model,\n promise.status\n );\n return Promise.race([\n promise.promise\n ?.then(() => {\n timeoutCancel();\n })\n .catch((err) => {\n const enrichedError = enrichError(err, {\n modelType: promise.type || \"unknown\",\n modelId: promise.modelId,\n parentModel: {\n type: sourceModel.modelTypeName,\n id: sourceModel.modelId,\n },\n lifecycle: sourceLifecycle,\n operation: `transition to ${target}`,\n });\n KosLog.error(enrichedError.toDetailedString());\n timeoutCancel();\n // Rethrow to ensure Promise.race can reject\n throw enrichedError;\n }),\n timeoutPromise,\n ]);\n })\n );\n const failedChildren = settledChildren.filter((p) => p.status === \"rejected\");\n\n if (failedChildren.length > 0) {\n const errors = failedChildren.map((result) => {\n const promise = childPromises[settledChildren.indexOf(result)];\n return {\n error:\n result.status === \"rejected\"\n ? result.reason\n : new Error(\"Unknown error\"),\n context: {\n modelType: promise.type || \"unknown\",\n modelId: promise.modelId,\n parentModel: {\n type: sourceModel.modelTypeName,\n id: sourceModel.modelId,\n },\n lifecycle: sourceLifecycle,\n operation: `transition to ${target}`,\n },\n };\n });\n\n logErrorCollection(\n errors,\n `Model ${sourceModel.modelId} had ${failedChildren.length} failed child model(s) on ${sourceLifecycle}`\n );\n }\n};\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\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\n// Type guards are now imported from ./model-type-guards.ts and re-exported above\n","import { isKosDataModel, isKosModelContainer } from \"../../util\";\nimport { DependencyModels } from \"../decorators\";\nimport { SubscriptionHandlers } from \"../decorators/propKeys\";\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 subscriptions: !!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 subscriptions: (() => {\n const handlers = modelData[SubscriptionHandlers] || {};\n const topics = Object.keys(handlers);\n if (topics.length === 0) return { count: 0, data: [] };\n return {\n count: topics.length,\n data: topics.map((topic) => {\n const config = handlers[topic];\n return {\n topic,\n websocket: !!config.websocket,\n ...(config.lifecycle && { lifecycle: config.lifecycle }),\n ...(config.fos && { fos: true }),\n ...(config.bridge && { bridge: true }),\n ...(config.destinationAddress && {\n destinationAddress: config.destinationAddress,\n }),\n ...(config.wildcardName && {\n wildcardName: config.wildcardName,\n }),\n ...(config.flow && { flow: true }),\n ...(config.requiresBaseline && { requiresBaseline: true }),\n };\n }),\n };\n })(),\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, activeStatus, or onlineStatus.\n * Online/offline transitions are tracked on model.onlineStatus because the\n * main FSM keeps status at READY when GO_ONLINE / GO_OFFLINE fire; reading\n * model.status for those targets would hang the transition forever.\n */\n private getTransitionStatusFor(target: KosModelState): KosModelState {\n if ([KosModelState.ACTIVE, KosModelState.INACTIVE].includes(target)) {\n return this.model.activeStatus;\n }\n if ([KosModelState.ONLINE, KosModelState.OFFLINE].includes(target)) {\n return this.model.onlineStatus;\n }\n return 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 '${\n this.model.id || \"unknown\"\n }' 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(\n `Removing ${this.registeredRoutes.length} HTTP routes for model ${\n this.model.id || \"unknown\"\n }`\n );\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(\n `Failed to remove route: ${route.method} ${route.path} (not found)`\n );\n }\n }\n\n this.logger.debug(\n `Successfully removed ${totalRemoved} routes from browser router`\n );\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","import { ReplayStrategy } from \"../../types/service-response-store\";\n\nexport interface KosOfflineQueueLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/**\n * Queued event with temporal metadata\n */\nexport interface QueuedEvent {\n /**\n * Event handler function\n */\n handler: () => void;\n\n /**\n * When this event was received at the framework (timestamp)\n * Used for baseline-delta temporal filtering\n */\n receivedAt: number;\n\n /**\n * Topic this event was received on (for debugging)\n */\n topic?: string;\n\n /**\n * Event payload (for debugging)\n */\n payload?: any;\n}\n\n/**\n * Statistics about queued events\n */\nexport interface QueueStatistics {\n /**\n * Total events in queue\n */\n total: number;\n\n /**\n * Oldest event timestamp\n */\n oldestEventAt?: number;\n\n /**\n * Newest event timestamp\n */\n newestEventAt?: number;\n\n /**\n * Events that would be replayed with AFTER_REQUEST strategy\n */\n afterRequest?: number;\n\n /**\n * Events that would be replayed with AFTER_RESPONSE strategy\n */\n afterResponse?: number;\n}\n\nexport class KosOfflineQueue {\n private queue: QueuedEvent[] = [];\n\n constructor(private log: KosOfflineQueueLogger) {}\n\n /**\n * Enqueue an event handler with temporal tracking\n *\n * @param handler - Event handler function\n * @param topic - Optional topic for debugging\n * @param payload - Optional payload for debugging\n */\n enqueue(handler: () => void, topic?: string, payload?: any): void {\n this.queue.push({\n handler,\n receivedAt: Date.now(),\n topic,\n payload,\n });\n }\n\n /**\n * Flush all queued events (original behavior for backward compatibility)\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 event of this.queue) {\n try {\n event.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 /**\n * Flush queued events with temporal filtering strategy\n * Used for baseline-delta race condition handling\n *\n * @param strategy - Replay strategy to use\n * @param baselineRequestedAt - When baseline request was sent (for AFTER_REQUEST)\n * @param baselineReceivedAt - When baseline response received (for AFTER_RESPONSE)\n */\n flushWithStrategy(\n strategy: ReplayStrategy,\n baselineRequestedAt?: number,\n baselineReceivedAt?: number\n ): void {\n if (this.queue.length === 0) return;\n\n const totalQueued = this.queue.length;\n const eventsToReplay = this.filterEventsByStrategy(\n strategy,\n baselineRequestedAt,\n baselineReceivedAt\n );\n const discarded = totalQueued - eventsToReplay.length;\n\n this.log.warn(\n `Processing ${eventsToReplay.length}/${totalQueued} offline message(s) with strategy: ${strategy}`\n );\n\n for (const event of eventsToReplay) {\n try {\n event.handler();\n } catch (e) {\n this.log.error(\n `Error while processing offline message for topic ${event.topic}:`,\n e\n );\n }\n }\n\n this.queue = [];\n this.log.info(\n `Offline queue flushed with strategy ${strategy}. Replayed: ${eventsToReplay.length}, Discarded: ${discarded}`\n );\n }\n\n /**\n * Filter events based on replay strategy\n * @private\n */\n private filterEventsByStrategy(\n strategy: ReplayStrategy,\n baselineRequestedAt?: number,\n baselineReceivedAt?: number\n ): QueuedEvent[] {\n switch (strategy) {\n case ReplayStrategy.ALL:\n return [...this.queue];\n\n case ReplayStrategy.AFTER_REQUEST:\n if (baselineRequestedAt === undefined) {\n this.log.warn(\n \"AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events\"\n );\n return [...this.queue];\n }\n return this.queue.filter(\n (event) => event.receivedAt >= baselineRequestedAt\n );\n\n case ReplayStrategy.AFTER_RESPONSE:\n if (baselineReceivedAt === undefined) {\n this.log.warn(\n \"AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events\"\n );\n return [...this.queue];\n }\n return this.queue.filter(\n (event) => event.receivedAt >= baselineReceivedAt\n );\n\n case ReplayStrategy.NONE:\n return [];\n\n default:\n this.log.warn(`Unknown replay strategy: ${strategy}, replaying all`);\n return [...this.queue];\n }\n }\n\n /**\n * Get queue statistics for monitoring\n */\n getStatistics(\n baselineRequestedAt?: number,\n baselineReceivedAt?: number\n ): QueueStatistics {\n if (this.queue.length === 0) {\n return { total: 0 };\n }\n\n const timestamps = this.queue.map((e) => e.receivedAt);\n const stats: QueueStatistics = {\n total: this.queue.length,\n oldestEventAt: Math.min(...timestamps),\n newestEventAt: Math.max(...timestamps),\n };\n\n if (baselineRequestedAt !== undefined) {\n stats.afterRequest = this.queue.filter(\n (e) => e.receivedAt >= baselineRequestedAt\n ).length;\n }\n\n if (baselineReceivedAt !== undefined) {\n stats.afterResponse = this.queue.filter(\n (e) => e.receivedAt >= baselineReceivedAt\n ).length;\n }\n\n return stats;\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 // Idempotent: drop any prior subscriptions before re-adding, so callers\n // can register() on reconnect without doubling up /kosCore/online+offline subs.\n this.dispose();\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","/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport 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","/**\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 {\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport const createMessageBody = (msg: string, body?: string) => {\n let _msg = msg;\n if (body) {\n _msg += body;\n }\n return _msg;\n};\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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};\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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};\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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};\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosBroadcastRequestParams<T extends object> {\n msg: T;\n options: KosBroadcastRequest;\n}\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosMessageResponseParams<T extends object> {\n msg: T;\n options: KosMessageOptions;\n}\n\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosHttpMessageResponseParams<T extends object> {\n msg: T;\n options: KosHttpMessageOptions;\n}\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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\n/**\n * @kosService core.fetch\n * @kosApiLevel 2\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","/**\n * Discriminator carried by every {@link TransportNotReadyError}.\n *\n * Prefer checking `error.code === TRANSPORT_NOT_READY` over `instanceof` when\n * the error may have crossed a bundle boundary (an app and the SDK can end up\n * with separate copies of the class).\n *\n * @category Service Request\n * @kosService core.fetch\n * @kosApiLevel 23\n */\nexport const TRANSPORT_NOT_READY = \"TRANSPORT_NOT_READY\";\n\n/**\n * Raised when a request's timeout budget expires while waiting for the KOS\n * transport to become ready — the socket is closed, reconnecting, or not yet\n * authorized — so the request was never sent.\n *\n * This is deliberately distinct from the `TimeoutError` `DOMException` raised\n * when the request itself times out. The two call for different reactions:\n *\n * - `TimeoutError` — the request reached the service and the service was slow.\n * Retrying later is usually reasonable.\n * - `TransportNotReadyError` — connectivity is down. Retrying the same request\n * will fail the same way until the socket comes back; surface a connectivity\n * state to the user or trigger a reconnect/reload instead.\n *\n * @example\n * ```typescript\n * try {\n * await api.get(\"/api/device/status\", { timeout: 3000 });\n * } catch (error) {\n * if (isTransportNotReadyError(error)) {\n * // websocket is down — show the offline UI\n * }\n * }\n * ```\n *\n * @category Service Request\n * @kosService core.fetch\n * @kosApiLevel 23\n */\nexport class TransportNotReadyError extends Error {\n /** Stable discriminator; see {@link TRANSPORT_NOT_READY}. */\n readonly code = TRANSPORT_NOT_READY;\n\n /**\n * The budget, in milliseconds, that expired while waiting. `undefined` when\n * the wait was cut short by a caller-supplied timeout signal rather than by\n * the request's own budget.\n */\n readonly timeout?: number;\n\n /** The URL of the request that was never sent. */\n readonly url?: string;\n\n constructor(details: { timeout?: number; url?: string } = {}) {\n super(\n `Transport not ready${\n details.timeout === undefined ? \"\" : ` after ${details.timeout}ms`\n }${details.url ? ` - url: ${details.url}` : \"\"}`\n );\n this.name = \"TransportNotReadyError\";\n this.timeout = details.timeout;\n this.url = details.url;\n }\n}\n\n/**\n * Type guard for {@link TransportNotReadyError} that works across bundle\n * boundaries by checking the `code` discriminator rather than the prototype.\n *\n * @category Service Request\n * @kosService core.fetch\n * @kosApiLevel 23\n */\nexport const isTransportNotReadyError = (\n error: unknown\n): error is TransportNotReadyError =>\n !!error && (error as TransportNotReadyError).code === TRANSPORT_NOT_READY;\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\";\nimport { TransportNotReadyError } from \"./transport-not-ready-error\";\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 *\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nexport interface KosServiceResponse<T> {\n data: T;\n status: number;\n}\n\nconst DEFAULT_WS_TIMEOUT = 30000;\n\n/**\n * The WebSocket timeout duration in milliseconds. An unparseable\n * `KOS_WS_TIMEOUT` falls back to the default rather than disabling the budget.\n */\nconst WS_TIMEOUT = (() => {\n const configured = process.env.KOS_WS_TIMEOUT\n ? parseInt(process.env.KOS_WS_TIMEOUT)\n : DEFAULT_WS_TIMEOUT;\n return Number.isNaN(configured) ? DEFAULT_WS_TIMEOUT : configured;\n})();\n\n/**\n * Resolves the timeout budget for a request.\n *\n * The budget covers the whole call — waiting for the transport to become ready\n * *and* the request itself — not just the request. A non-positive or\n * non-finite value (`0`, `Infinity`) opts out of the budget entirely and\n * restores the pre-budget behavior of queuing until the transport recovers.\n *\n * @param timeout - The caller-supplied timeout, if any.\n * @returns The budget in milliseconds, or `undefined` for no budget.\n */\nconst resolveTimeoutBudget = (timeout?: number): number | undefined => {\n const budget = timeout ?? WS_TIMEOUT;\n return Number.isFinite(budget) && budget > 0 ? budget : undefined;\n};\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 * Creates an AbortSignal that will abort after the specified timeout.\n * Falls back to manual implementation for environments without AbortSignal.timeout.\n *\n * @param ms - Timeout in milliseconds\n * @returns An AbortSignal that aborts after the timeout\n */\nconst createTimeoutSignal = (ms: number): AbortSignal => {\n if (\"timeout\" in AbortSignal) {\n return AbortSignal.timeout(ms);\n }\n // Fallback for older environments\n const controller = new AbortController();\n setTimeout(() => {\n controller.abort(\n new DOMException(`Request timed out after ${ms}ms`, \"TimeoutError\")\n );\n }, ms);\n return controller.signal;\n};\n\n/**\n * Combines multiple AbortSignals into one that aborts when any of them abort.\n * Falls back to manual implementation for environments without AbortSignal.any.\n *\n * @param signals - Array of AbortSignals to combine\n * @returns A combined AbortSignal\n */\nconst combineSignals = (signals: AbortSignal[]): AbortSignal => {\n if (\"any\" in AbortSignal) {\n return (\n AbortSignal as unknown as { any: (signals: AbortSignal[]) => AbortSignal }\n ).any(signals);\n }\n // Fallback for older environments\n const controller = new AbortController();\n for (const signal of signals) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n return controller.signal;\n }\n signal.addEventListener(\"abort\", () => controller.abort(signal.reason), {\n once: true,\n });\n }\n return controller.signal;\n};\n\n/**\n * Builds the single signal that governs a request: the caller's signal (if\n * any) combined with the timeout budget (if any).\n *\n * Always returns a signal so the request path has one code path. With no\n * budget and no caller signal the returned signal simply never aborts.\n *\n * @param budget - The timeout budget in milliseconds, or `undefined` for none.\n * @param callerSignal - The caller-supplied abort signal, if any.\n * @returns The signal covering readiness wait and request.\n */\nconst createRequestSignal = (\n budget: number | undefined,\n callerSignal?: AbortSignal\n): AbortSignal => {\n const timeoutSignal = budget ? createTimeoutSignal(budget) : undefined;\n if (timeoutSignal && callerSignal) {\n return combineSignals([callerSignal, timeoutSignal]);\n }\n return timeoutSignal ?? callerSignal ?? new AbortController().signal;\n};\n\n/**\n * True when an abort reason represents an expired timeout rather than an\n * explicit caller abort.\n */\nconst isTimeoutReason = (reason: unknown): boolean =>\n (reason as DOMException | undefined)?.name === \"TimeoutError\";\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 * The timeout is a budget for the **entire call** — waiting for the transport\n * to become ready plus the request itself — so a request issued while the\n * socket is down or reconnecting settles within the budget instead of parking\n * forever on transport readiness. If the transport becomes ready with budget\n * left, the remainder applies to the request; the clock is not restarted.\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 * @throws {TransportNotReadyError} if the budget expires before the transport\n * is ready, meaning the request was never sent.\n * @throws {DOMException} TimeoutError if the request itself times out.\n * @throws {DOMException} AbortError if the request is aborted via signal.\n */\nconst kosFetchWs = async (\n url: string,\n options?: KosFetchOptions\n): Promise<Response> => {\n const transport = KosCore.getInstance().transport;\n const requestId = uuid();\n const urlObj = new URL(url);\n const path = `${urlObj.pathname}${urlObj.search}`;\n log.debug(`path: ${path}`);\n const budget = resolveTimeoutBudget(options?.timeout);\n const messageFactory = fetchMessageFactory(options);\n\n // Create the unified abort signal (timeout + caller signal) BEFORE waiting on\n // the transport. The readiness wait is part of the budget: `whenReady()` has\n // no timeout of its own and `connectionEstablished` goes false on socket\n // close, so a signal created after the wait would never start ticking for a\n // request issued while the transport is down.\n const signal = createRequestSignal(budget, options?.signal);\n\n try {\n await transport.whenReady({ signal });\n } catch (error) {\n if (isTimeoutReason(error)) {\n log.error(\n `Transport not ready${\n budget === undefined ? \"\" : ` after ${budget}ms`\n } - request not sent - url: ${url}`\n );\n throw new TransportNotReadyError({ timeout: budget, url });\n }\n log.debug(`Request aborted while waiting for transport - url: ${url}`);\n throw error;\n }\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, reject) => {\n let unsubscribe: (() => void) | null = null;\n\n // Check if already aborted before starting\n if (signal.aborted) {\n const reason = signal.reason;\n if (reason?.name === \"TimeoutError\") {\n log.error(`Timeout occurred - url: ${url}`);\n } else {\n log.debug(`Request aborted - url: ${url}`);\n }\n reject(reason || new DOMException(\"Aborted\", \"AbortError\"));\n return;\n }\n\n // Single abort handler for both user abort and timeout\n const onAbort = () => {\n if (unsubscribe) unsubscribe();\n\n const reason = signal.reason;\n if (reason?.name === \"TimeoutError\") {\n log.error(`Timeout occurred - url: ${url}`);\n } else {\n log.debug(`Request aborted - url: ${url}`);\n }\n\n reject(reason || new DOMException(\"Aborted\", \"AbortError\"));\n };\n\n signal.addEventListener(\"abort\", onAbort, { once: true });\n\n const subscription = EventBus.subscribe(requestId, (responseMsg) => {\n // Remove abort listener on successful response\n signal.removeEventListener(\"abort\", onAbort);\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 *\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nlet BASE_URL = `kos:`;\n/**\n * KOS fetch function — WebSocket-based fetch implementation for KOS transport.\n *\n * @kosService core.fetch\n * @kosApiLevel 2\n */\nlet kosFetch = kosFetchWs;\n// Check if mocking of fetch requests is enabled.\n// Deprecated: KOS_MOCK_FETCH is a compile-time switch that bypasses the KOS\n// transport entirely. Prefer the KosMock facility (core/core/transport/mock),\n// which mocks at the transport layer with runtime control.\nif (process.env.KOS_MOCK_FETCH === `true`) {\n const PORT = process.env.KOS_PORT || \"9999\";\n kosFetch = fetch as typeof kosFetch; // 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 { KosLog } from \"../core/log\";\nimport type { KosFetchOptions, RetryConfig } from \"../types\";\nimport type { Response } from \"../types/utils/kos-fetch\";\nimport { BASE_URL, kosFetch } from \"./kos-fetch\";\nimport type { ErrorResponseContext } from \"./service-request-error\";\nimport { isTransportNotReadyError } from \"./transport-not-ready-error\";\n\nexport type { ErrorResponseContext };\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 *\n * @kosService core.service-request\n * @kosApiLevel 2\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\";\n\n/**\n * Error string returned when the transport never became ready inside the\n * request's timeout budget, so the request was never sent. Distinct from\n * `\"Request timed out\"`, which means the request was sent and the service was\n * slow.\n *\n * @kosService core.service-request\n * @kosApiLevel 23\n */\nexport const ERROR_TRANSPORT_NOT_READY = \"Transport not ready\";\ntype NonNeverKeys<T> = {\n [K in keyof T]-?: T[K] extends never | undefined ? never : K;\n}[keyof T];\n\n/**\n * @kosService core.service-request\n */\nexport type AvailableMethods<T> = Exclude<\n NonNeverKeys<T>,\n \"parameters\" | \"requestBody\"\n>;\n\n/**\n * @kosService core.service-request\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\n/**\n * @kosService core.service-request\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\n/**\n * @kosService core.service-request\n */\nexport type 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\n/**\n * @kosService core.service-request\n */\nexport type 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\n/**\n * @kosService core.service-request\n */\n/** Transport facts about a response, alongside its parsed body. */\nexport interface ResponseContext {\n status: number;\n headers: Record<string, string>;\n}\n\nexport type ServiceResponse<T> =\n | [error: string, data: null, errorContext?: ErrorResponseContext]\n | [error: null, data: T, context?: ResponseContext];\n\n/**\n * @kosService core.service-request\n */\nexport type DeepRequired<T> = {\n [K in keyof T]-?: T[K] extends object\n ? DeepRequired<T[K]>\n : T[K] extends Array<infer U>\n ? Array<DeepRequired<U>>\n : T[K];\n};\n/**\n * @kosService core.service-request\n */\nexport type ElementType<T> = T extends (infer U)[] ? U : never;\n\n/** Methods considered mutating — skipped by retry unless `retryMutations` is true */\nconst MUTATING_METHODS = new Set([\"POST\", \"PUT\", \"DELETE\", \"PATCH\"]);\n\n/** Default retry settings applied when `retry: true` or partial config */\nconst RETRY_DEFAULTS: Required<Omit<RetryConfig, \"retryOn\">> = {\n maxAttempts: 3,\n baseDelayMs: 350,\n backoffFactor: 2,\n retryMutations: false,\n};\n\n/**\n * Resolves a `retry` option into a fully-populated config or `undefined`.\n * @internal\n */\nfunction resolveRetryConfig(\n retry: boolean | RetryConfig | undefined\n):\n | (Required<Omit<RetryConfig, \"retryOn\">> & Pick<RetryConfig, \"retryOn\">)\n | undefined {\n if (!retry) return undefined;\n if (retry === true) return { ...RETRY_DEFAULTS };\n return { ...RETRY_DEFAULTS, ...retry };\n}\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(\n (key) =>\n `${encodeURIComponent(key)}=${encodeURIComponent(\n (params as any).query[key]\n )}`\n )\n .join(\"&\")\n : \"\";\n\n const fullUrl = `${resolveBaseUrl().URL}${url}${query ? `?${query}` : \"\"}`;\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\n const retryConfig = resolveRetryConfig(options?.retry);\n\n // If retry is disabled or method is mutating and retryMutations is false, single attempt\n const shouldRetry =\n retryConfig &&\n (retryConfig.retryMutations || !MUTATING_METHODS.has(fetchOptions.method));\n\n if (!shouldRetry) {\n return executeFetch(fullUrl, fetchOptions);\n }\n\n return executeFetchWithRetry(fullUrl, fetchOptions, retryConfig);\n}\n\n/**\n * The transport facts a caller may need: `dst-addr` names the client the\n * response was sent to, which is how a window learns its own address.\n * @internal\n */\nfunction responseContext(response: Response): ResponseContext {\n const headers: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return { status: response.status, headers };\n}\n\n/**\n * Executes a single fetch attempt and returns a service response tuple.\n * @internal\n */\nasync function executeFetch(fullUrl: string, fetchOptions: any): Promise<any> {\n try {\n const response = await kosFetch(fullUrl, fetchOptions);\n\n if (response.status < 200 || response.status >= 400) {\n const errorContext = await captureErrorResponseContext(response);\n return [`${response.statusText || ERROR_UNKNOWN}`, null, errorContext];\n }\n\n const payload = await response.json();\n return [null, payload.data ?? payload, responseContext(response)];\n } catch (error) {\n // Transport down — the request was never sent. Distinct from a timeout so\n // callers can react to connectivity rather than to a slow service.\n if (isTransportNotReadyError(error)) {\n log.error(`Transport not ready, request not sent: ${fullUrl}`);\n return [ERROR_TRANSPORT_NOT_READY, null];\n }\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n log.error(`Request timed out: ${fullUrl}`);\n return [\"Request timed out\", null];\n }\n if (error.name === \"AbortError\") {\n log.debug(`Request aborted: ${fullUrl}`);\n return [\"Request aborted\", null];\n }\n }\n log.error(`Unexpected error during fetch: ${error}`);\n return [error instanceof Error ? error.message : ERROR_UNKNOWN, null];\n }\n}\n\n/**\n * Executes a fetch with retry and exponential backoff.\n *\n * Retries are attempted when:\n * 1. The response has an error status (< 200 or >= 400)\n * 2. The `retryOn` predicate (if provided) returns `true` for that response\n * 3. We haven't exceeded `maxAttempts`\n *\n * Network-level errors (timeouts, aborts) are NOT retried — they indicate\n * transport problems, not transient server errors.\n *\n * @internal\n */\nasync function executeFetchWithRetry(\n fullUrl: string,\n fetchOptions: any,\n config: Required<Omit<RetryConfig, \"retryOn\">> & Pick<RetryConfig, \"retryOn\">\n): Promise<any> {\n let lastResult: any;\n\n for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {\n try {\n const response: Response = await kosFetch(fullUrl, fetchOptions);\n\n // Success — return immediately\n if (response.status >= 200 && response.status < 400) {\n const payload = await response.json();\n return [null, payload.data ?? payload, responseContext(response)];\n }\n\n // Error response — check if we should retry\n const errorContext = await captureErrorResponseContext(response);\n lastResult = [\n `${response.statusText || ERROR_UNKNOWN}`,\n null,\n errorContext,\n ];\n\n // If predicate says don't retry, stop immediately\n if (config.retryOn && !config.retryOn(response)) {\n log.debug(\n `Retry predicate returned false for ${fullUrl} (status ${response.status}), stopping`\n );\n return lastResult;\n }\n\n if (attempt < config.maxAttempts) {\n const delayMs =\n config.baseDelayMs * Math.pow(config.backoffFactor, attempt - 1);\n log.warn(\n `Request to ${fullUrl} failed (status ${response.status}), ` +\n `retrying in ${delayMs}ms (attempt ${attempt}/${config.maxAttempts})`\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n } catch (error) {\n // Network-level errors are not retried — return immediately\n if (isTransportNotReadyError(error)) {\n log.error(`Transport not ready, request not sent: ${fullUrl}`);\n return [ERROR_TRANSPORT_NOT_READY, null];\n }\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n log.error(`Request timed out: ${fullUrl}`);\n return [\"Request timed out\", null];\n }\n if (error.name === \"AbortError\") {\n log.debug(`Request aborted: ${fullUrl}`);\n return [\"Request aborted\", null];\n }\n }\n log.error(`Unexpected error during fetch: ${error}`);\n return [error instanceof Error ? error.message : ERROR_UNKNOWN, null];\n }\n }\n\n // All attempts exhausted — return last error result\n log.error(`All ${config.maxAttempts} attempts failed for ${fullUrl}`);\n return lastResult;\n}\n\n/**\n * Reads the response body and headers from an HTTP error response.\n * Best-effort: if the body cannot be parsed as JSON it falls back to text,\n * and if that fails the body is left undefined.\n * @internal\n */\nasync function captureErrorResponseContext(\n response: Response\n): Promise<ErrorResponseContext> {\n let responseBody: unknown;\n try {\n const text = await response.text();\n try {\n responseBody = JSON.parse(text);\n } catch {\n responseBody = text;\n }\n } catch {\n responseBody = undefined;\n }\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n return {\n status: response.status,\n statusText: response.statusText,\n responseBody,\n responseHeaders,\n };\n}\n\ntype RequestOptions = Omit<KosFetchOptions, \"method\" | \"body\">;\n/**\n * @kosService core.service-request\n * @kosApiLevel 2\n */\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","import {\n kosServiceRequest as baseKosServiceRequest,\n type HttpMethod,\n type IKosServiceRequestParams,\n type KosExecutionContext,\n type RequestOptions,\n} from \"../../core/core/decorators/kos-service-request\";\nimport {\n createClient,\n type ClientResponse,\n type PathsByMethod,\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\n/**\n * Request options for controlling fetch behavior\n * Includes destinationAddress, headers, timeout, and other transport options\n *\n * @example\n * ```typescript\n * const options: KosRequestOptions = {\n * destinationAddress: 'device-123',\n * headers: { 'X-Custom-Header': 'value' },\n * timeout: 5000\n * };\n * ```\n */\nexport type { RequestOptions as KosRequestOptions };\n\n/**\n * Type alias for strongly-typed execution context.\n * The context is automatically injected as the last parameter to methods\n * decorated with @kosServiceRequest (without lifecycle) or @kosFuture.\n *\n * @example With @kosServiceRequest\n * ```typescript\n * @kosServiceRequest({\n * path: PATH_DEVICE_STATUS,\n * method: 'get'\n * })\n * async refreshStatus(\n * ctx: ExecutionContext<typeof PATH_DEVICE_STATUS, 'get'>\n * ): Promise<void> {\n * const [error, response] = await ctx.$request({\n * queryParams: { includeMetadata: true }, // ← Fully typed!\n * requestOptions: {\n * destinationAddress: 'device-123',\n * timeout: 5000\n * }\n * });\n * if (error) throw new Error(error);\n * this.status = response?.status;\n * }\n * ```\n *\n * @example With @kosFuture (context-based tracker)\n * ```typescript\n * @kosFuture({ trackerPolicy: 'context' })\n * async loadData(filter: string, ctx: ExecutionContext): Promise<Data> {\n * const data = await fetchData(filter);\n * ctx.$tracker?.complete();\n * return data;\n * }\n * ```\n */\nexport type ExecutionContext<\n Path extends ApiPath = ApiPath,\n Method extends HttpMethod = \"get\"\n> = KosExecutionContext<paths, Path, Method>;\n\n/**\n * Typed decorator factory for @kosServiceRequest with KOS SDK OpenAPI types\n *\n * Provides full IntelliSense and type safety for path, query params, and body\n * based on the KOS SDK OpenAPI schema.\n *\n * @example\n * ```typescript\n * import { kosServiceRequest, PATH_DEVICE_STATUS } from '../../utils/service';\n *\n * @kosServiceRequest({\n * path: PATH_DEVICE_STATUS,\n * method: 'get',\n * lifecycle: DependencyLifecycle.LOAD,\n * queryParams: { includeMetadata: true } // ← Fully typed!\n * })\n * private onStatusLoaded(): void {\n * const response = getServiceResponse(this, PATH_DEVICE_STATUS, 'get');\n * }\n * ```\n */\nexport function kosServiceRequest<\n Path extends ApiPath,\n Method extends HttpMethod = \"get\",\n Response = any,\n TransformedResponse = Response\n>(\n params: IKosServiceRequestParams<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >\n) {\n return baseKosServiceRequest<\n paths,\n Path,\n Method,\n Response,\n TransformedResponse\n >(params);\n}\n\nexport default api;\n","import API from \"../../../models/utils/service\";\nimport { DependencyLifecycle } from \"../../types\";\nimport { ResponseRetention } from \"../../types/service-response-store\";\nimport type { ServiceResponse } from \"../../util/kos-service-request\";\nimport type { ErrorResponseContext } from \"../../util/service-request-error\";\nimport { ServiceRequestError } from \"../../util/service-request-error\";\nimport {\n ServiceRequestHandlers,\n type HttpMethod,\n type ServiceRequestMetadata,\n} from \"../decorators/kos-service-request\";\nimport { resolveParameters } from \"../decorators/resolve-parameters\";\nimport type { IKosDataModel } from \"../kosModel\";\nimport { KosLog } from \"../log\";\nimport { ServiceResponseStore } from \"./service-response-store\";\n\nconst log = KosLog.createLogger({\n name: \"kos-service-request-manager\",\n group: \"Model\",\n});\n\n// ============================================================================\n// Zone 3: Low-level helper functions\n// ============================================================================\n\n/**\n * Checks if request should execute based on condition\n * @internal\n */\nfunction shouldExecuteRequest(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): boolean {\n return !metadata.condition || metadata.condition(model);\n}\n\n/**\n * Resolves path parameters from metadata\n * @internal\n */\nfunction resolvePathFromMetadata(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): string {\n return resolveParameters({\n value: metadata.path,\n modelId: model.id,\n modelData: model,\n }) as string;\n}\n\n/**\n * Resolves path params from metadata\n * @internal\n */\nfunction resolvePathParams(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): Record<string, any> | undefined {\n if (!metadata.pathParams) return undefined;\n\n return resolveParameters({\n value:\n typeof metadata.pathParams === \"function\"\n ? metadata.pathParams(model)\n : metadata.pathParams,\n modelId: model.id,\n modelData: model,\n }) as Record<string, any> | undefined;\n}\n\n/**\n * Resolves query params from metadata\n * @internal\n */\nfunction resolveQueryParams(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): Record<string, any> | undefined {\n if (!metadata.queryParams) return undefined;\n\n return resolveParameters({\n value:\n typeof metadata.queryParams === \"function\"\n ? metadata.queryParams(model)\n : metadata.queryParams,\n modelId: model.id,\n modelData: model,\n }) as Record<string, any> | undefined;\n}\n\n/**\n * Resolves body from metadata\n * @internal\n */\nfunction resolveBodyParams(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): any {\n if (!metadata.body) return undefined;\n\n return resolveParameters({\n value:\n typeof metadata.body === \"function\"\n ? metadata.body(model)\n : metadata.body,\n modelId: model.id,\n modelData: model,\n });\n}\n\n/**\n * Resolves request options from metadata\n * @internal\n */\nfunction resolveRequestOptions(\n metadata: ServiceRequestMetadata,\n model: IKosDataModel\n): any {\n if (!metadata.requestOptions) return undefined;\n\n return typeof metadata.requestOptions === \"function\"\n ? metadata.requestOptions(model)\n : metadata.requestOptions;\n}\n\n/**\n * Normalizes HTTP method to lowercase\n * @internal\n */\nfunction normalizeHttpMethod(\n method: HttpMethod | undefined\n): \"get\" | \"post\" | \"put\" | \"delete\" {\n return (method || \"get\").toLowerCase() as \"get\" | \"post\" | \"put\" | \"delete\";\n}\n\n/**\n * Creates storage key for response store\n * @internal\n */\nfunction createStorageKey(path: string, method: HttpMethod): string {\n return `${method.toUpperCase()}:${path}`;\n}\n\n/**\n * Checks if value is missing (undefined or null)\n * @internal\n */\nfunction isValueMissing(value: any): boolean {\n return value === undefined || value === null;\n}\n\n/**\n * Validates required field and logs warning if missing\n * @internal\n */\nfunction validateRequiredField(\n value: any,\n fieldName: string,\n path: string,\n isRequired: boolean\n): void {\n if (isRequired && isValueMissing(value)) {\n log.warn(\n `Required field '${fieldName}' is missing in response for ${path}`\n );\n }\n}\n\n/**\n * Applies default value if current value is missing\n * @internal\n */\nfunction applyDefaultIfMissing(value: any, defaultValue: any): any {\n return isValueMissing(value) && defaultValue !== undefined\n ? defaultValue\n : value;\n}\n\n/**\n * Manages lifecycle-driven service requests for KOS models\n *\n * The ServiceRequestManager executes @kosServiceRequest decorated methods\n * during the appropriate lifecycle phase (INIT, LOAD, READY, ACTIVATE).\n *\n * @internal\n */\nexport class ServiceRequestManager {\n private model: IKosDataModel;\n private responseStore: ServiceResponseStore;\n private handlers: Map<DependencyLifecycle, ServiceRequestMetadata[]>;\n\n constructor(model: IKosDataModel, responseStore: ServiceResponseStore) {\n this.model = model;\n this.responseStore = responseStore;\n this.handlers = new Map();\n\n this.discoverHandlers();\n }\n\n /**\n * Discover and organize service request handlers by lifecycle phase\n */\n private discoverHandlers(): void {\n const prototype = Object.getPrototypeOf(this.model);\n const handlerMetadata = prototype[ServiceRequestHandlers] || {};\n\n // Group handlers by lifecycle phase\n Object.values(handlerMetadata).forEach((metadata: any) => {\n const lifecycle = metadata.lifecycle;\n\n if (!this.handlers.has(lifecycle)) {\n this.handlers.set(lifecycle, []);\n }\n\n this.handlers.get(lifecycle)!.push(metadata);\n });\n\n if (Object.keys(handlerMetadata).length > 0) {\n log.debug(\n `Discovered ${\n Object.keys(handlerMetadata).length\n } service request handlers for model ${this.model.id}`\n );\n }\n }\n\n /**\n * Execute all service requests for a specific lifecycle phase\n *\n * @param lifecycle - The lifecycle phase to execute\n */\n async executeForLifecycle(lifecycle: DependencyLifecycle): Promise<void> {\n const handlers = this.handlers.get(lifecycle);\n\n if (!handlers || handlers.length === 0) {\n return;\n }\n\n log.debug(\n `Executing ${handlers.length} service requests for lifecycle ${lifecycle}`\n );\n\n // Execute all handlers for this lifecycle phase\n await Promise.all(handlers.map((handler) => this.executeHandler(handler)));\n }\n\n /**\n * Zone 1: Orchestrates the entire service request flow\n */\n private async executeHandler(\n metadata: ServiceRequestMetadata\n ): Promise<void> {\n try {\n if (!this.shouldProcessRequest(metadata)) {\n return;\n }\n\n const requestContext = await this.prepareAndExecuteRequest(metadata);\n await this.processAndStoreResponse(requestContext, metadata);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n await this.handleError(error, metadata);\n }\n }\n\n /**\n * Zone 2: Validates request preconditions\n */\n private shouldProcessRequest(metadata: ServiceRequestMetadata): boolean {\n if (!shouldExecuteRequest(metadata, this.model)) {\n log.debug(`Skipping request ${metadata.path} - condition returned false`);\n return false;\n }\n return true;\n }\n\n /**\n * Zone 2: Coordinates request preparation, execution, and timing capture\n */\n private async prepareAndExecuteRequest(metadata: ServiceRequestMetadata) {\n const requestContext = this.prepareRequest(metadata);\n const timing = this.captureRequestTiming();\n const result = await this.performRequest(requestContext);\n const [error, response] = result;\n const errorContext = result[2] as ErrorResponseContext | undefined;\n const responseTiming = this.captureResponseTiming();\n\n return {\n requestContext,\n error,\n response,\n errorContext,\n requestedAt: timing.requestedAt,\n receivedAt: responseTiming.receivedAt,\n };\n }\n\n /**\n * Zone 3: Captures request timestamp\n */\n private captureRequestTiming() {\n return { requestedAt: Date.now() };\n }\n\n /**\n * Zone 3: Captures response timestamp\n */\n private captureResponseTiming() {\n return { receivedAt: Date.now() };\n }\n\n /**\n * Zone 2: Coordinates response processing and storage\n */\n private async processAndStoreResponse(\n context: {\n requestContext: {\n resolvedPath: string;\n method: \"get\" | \"post\" | \"put\" | \"delete\";\n pathParams?: Record<string, any>;\n queryParams?: Record<string, any>;\n body?: any;\n };\n error: string | null;\n errorContext?: ErrorResponseContext;\n response: any;\n requestedAt: number;\n receivedAt: number;\n },\n metadata: ServiceRequestMetadata\n ): Promise<void> {\n if (context.error) {\n await this.handleError(\n new Error(context.error),\n metadata,\n context.errorContext\n );\n return;\n }\n\n const transformedData = await this.processResponse(\n context.response,\n metadata\n );\n await this.storeAndInvokeHandler(\n transformedData,\n metadata,\n context.requestContext.resolvedPath,\n context.requestedAt,\n context.receivedAt\n );\n }\n\n /**\n * Zone 2: Prepares request parameters by coordinating parameter resolution\n * @internal\n */\n private prepareRequest(metadata: ServiceRequestMetadata) {\n const resolvedPath = resolvePathFromMetadata(metadata, this.model);\n const pathParams = resolvePathParams(metadata, this.model);\n const queryParams = resolveQueryParams(metadata, this.model);\n const body = resolveBodyParams(metadata, this.model);\n const requestOptions = resolveRequestOptions(metadata, this.model);\n const method = normalizeHttpMethod(metadata.method);\n\n return {\n resolvedPath,\n method,\n pathParams,\n queryParams,\n body,\n requestOptions,\n };\n }\n\n /**\n * Zone 3: Performs the HTTP request\n * @internal\n */\n private async performRequest(context: {\n resolvedPath: string;\n method: \"get\" | \"post\" | \"put\" | \"delete\";\n pathParams?: Record<string, any>;\n queryParams?: Record<string, any>;\n body?: any;\n requestOptions?: any;\n }): Promise<ServiceResponse<any>> {\n return await this.makeRequest(\n context.resolvedPath,\n context.method,\n {\n path: context.pathParams as any,\n query: context.queryParams as any,\n },\n context.body,\n context.requestOptions\n );\n }\n\n /**\n * Zone 2: Processes response by coordinating transformations\n * @internal\n */\n private async processResponse(\n response: any,\n metadata: ServiceRequestMetadata\n ): Promise<any> {\n let transformedData = response;\n\n // Apply custom transform function if provided\n if (metadata.transform) {\n transformedData = metadata.transform(response);\n }\n\n // Apply mappings if provided; with iterateOver they apply per item in handleIteration.\n if (\n metadata.mappings &&\n metadata.mappings.length > 0 &&\n !metadata.iterateOver\n ) {\n transformedData = this.applyMappings(transformedData, metadata);\n }\n\n // Handle array iteration and model creation\n if (metadata.iterateOver) {\n transformedData = await this.handleIteration(transformedData, metadata);\n }\n\n return transformedData;\n }\n\n /**\n * Zone 2: Stores response and invokes handler with cleanup\n * @internal\n */\n private async storeAndInvokeHandler(\n transformedData: any,\n metadata: ServiceRequestMetadata,\n resolvedPath: string,\n requestedAt: number,\n receivedAt: number\n ): Promise<void> {\n // Store response with temporal tracking\n const cacheConfig = metadata.cache || {\n retention: ResponseRetention.SINGLE,\n };\n const storageKey = createStorageKey(resolvedPath, metadata.method || \"get\");\n this.responseStore.set(\n storageKey,\n transformedData,\n cacheConfig,\n requestedAt,\n receivedAt\n );\n\n // Invoke handler with error-first parameters (error, data)\n await metadata.originalHandler.call(this.model, null, transformedData);\n\n // Trigger baseline-aware queue flush if subscription manager exists\n // This allows queued events to be replayed with temporal filtering\n this.triggerBaselineQueueFlush(resolvedPath);\n\n // Cleanup if needed\n if (this.responseStore.shouldCleanupAfterHandler(storageKey)) {\n this.responseStore.delete(storageKey);\n }\n }\n\n /**\n * Trigger queue flush for topic handlers waiting on this baseline\n * @private\n */\n private triggerBaselineQueueFlush(baselinePath: string): void {\n // Access subscription manager through model's internal components\n const subscriptionManager = (this.model as any).subscriptionManager;\n\n if (!subscriptionManager || !subscriptionManager.flushQueueForBaseline) {\n return; // No subscription manager or old version without baseline support\n }\n\n // Flush queue with baseline temporal filtering\n // The subscription manager will check all topics with baseline dependencies\n // and replay queued events using the appropriate strategy\n subscriptionManager.flushQueueForBaseline(baselinePath);\n }\n\n /**\n * Make HTTP request using existing KOS API client\n */\n private async makeRequest(\n path: string,\n method: \"get\" | \"post\" | \"put\" | \"delete\",\n params?: { path?: Record<string, string>; query?: Record<string, any> },\n body?: any,\n requestOptions?: any\n ): Promise<ServiceResponse<any>> {\n // Cast API to any to bypass strict OpenAPI typing for dynamic paths\n // This is safe because we're validating paths at runtime\n const api = API as any;\n\n switch (method) {\n case \"get\":\n return await api.get(path, params, requestOptions);\n case \"post\":\n return await api.post(path, params, body, requestOptions);\n case \"put\":\n return await api.put(path, params, body, requestOptions);\n case \"delete\":\n return await api.delete(path, params, body, requestOptions);\n default:\n return [\n `Unsupported HTTP method: ${method}`,\n null,\n ] as ServiceResponse<any>;\n }\n }\n\n /**\n * Zone 2: Applies field mappings to response data by coordinating extraction, transformation, and validation\n */\n private applyMappings(data: any, metadata: ServiceRequestMetadata): any {\n if (!metadata.mappings || metadata.mappings.length === 0) {\n return data;\n }\n\n const mapped: any = {};\n\n metadata.mappings.forEach((mapping) => {\n // Zone 3: Extract source value\n const sourceValue = this.getNestedValue(data, mapping.from);\n\n // Zone 3: Apply transformation if specified\n const transformedValue = mapping.transform\n ? this.applyTransform(sourceValue, mapping.transform)\n : sourceValue;\n\n // Zone 3: Validate required fields\n validateRequiredField(\n transformedValue,\n mapping.from,\n metadata.path,\n mapping.required || false\n );\n\n // Zone 3: Apply default value if needed\n const finalValue = applyDefaultIfMissing(\n transformedValue,\n mapping.default\n );\n\n mapped[mapping.to] = finalValue;\n });\n\n return mapped;\n }\n\n /**\n * Get nested value from object using dot notation\n */\n private getNestedValue(obj: any, path: string): any {\n return path.split(\".\").reduce((current, key) => current?.[key], obj);\n }\n\n /**\n * Apply transformation to a value\n */\n private applyTransform(\n value: any,\n transform: string | ((val: any) => any)\n ): any {\n if (typeof transform === \"function\") {\n return transform(value);\n }\n\n // Built-in transformers\n switch (transform) {\n case \"string\":\n return String(value);\n case \"number\":\n return Number(value);\n case \"boolean\":\n return Boolean(value);\n case \"date\":\n return value ? new Date(value) : undefined;\n case \"json\":\n return typeof value === \"string\" ? JSON.parse(value) : value;\n default:\n log.warn(`Unknown transformer: ${transform}`);\n return value;\n }\n }\n\n /**\n * Handle array iteration and model creation\n */\n private async handleIteration(\n data: any,\n metadata: ServiceRequestMetadata\n ): Promise<any[]> {\n if (!metadata.iterateOver) return data;\n\n // Get the array to iterate over\n const array = this.getNestedValue(data, metadata.iterateOver);\n\n if (!Array.isArray(array)) {\n log.warn(\n `iterateOver path '${metadata.iterateOver}' did not resolve to an array`\n );\n return [];\n }\n\n // If modelFactory is provided, create model instances\n if (metadata.modelFactory) {\n return array.map((item) => {\n // Apply mappings to transform item into model options\n const options =\n metadata.mappings && metadata.mappings.length > 0\n ? this.applyMappings(item, metadata)\n : item;\n\n // Extract ID using provided extractor or default to 'id' field\n const id = metadata.idExtractor\n ? metadata.idExtractor(options)\n : options.id;\n\n if (!id) {\n throw new Error(\n `Cannot create model instance: no ID found in response data. ` +\n `Provide an 'idExtractor' function or ensure response items have an 'id' field.`\n );\n }\n\n // Check if using new registration object or legacy curried function\n // Non-null assertion safe here because we're inside the if (metadata.modelFactory) block\n const factory = metadata.modelFactory!;\n if (typeof factory === \"function\") {\n // Legacy curried function: (id: string) => (options: any) => IKosDataModel\n const instanceFactory = factory(id);\n return instanceFactory(options);\n } else {\n // New registration object: Model.instance(id).options(opts).build()\n return factory.instance(id).options(options).build();\n }\n });\n }\n\n // Otherwise return mapped array items\n return array.map((item) => {\n if (metadata.mappings && metadata.mappings.length > 0) {\n return this.applyMappings(item, metadata);\n }\n return item;\n });\n }\n\n /**\n * Handle errors according to configured strategy\n */\n private async handleError(\n error: Error,\n metadata: ServiceRequestMetadata,\n errorContext?: ErrorResponseContext\n ): Promise<void> {\n const errorHandler = metadata.errorHandler || { strategy: \"throw\" };\n\n // Build a rich error for the onError callback\n const richError = errorContext\n ? new ServiceRequestError(error.message, errorContext)\n : error;\n\n // Call custom error handler if provided\n if (errorHandler.onError) {\n errorHandler.onError(richError, this.model);\n }\n\n switch (errorHandler.strategy) {\n case \"throw\":\n throw error;\n\n case \"log\":\n log.error(\n `Service request failed for ${metadata.path}:`,\n error.message\n );\n // Store default value and call handler (consistent with 'default' strategy)\n if (errorHandler.defaultValue !== undefined) {\n const storageKey = createStorageKey(\n metadata.path,\n metadata.method || \"get\"\n );\n this.responseStore.set(\n storageKey,\n errorHandler.defaultValue,\n metadata.cache || { retention: ResponseRetention.SINGLE }\n );\n await metadata.originalHandler.call(\n this.model,\n error.message,\n errorHandler.defaultValue\n );\n }\n break;\n\n case \"ignore\":\n // Silently ignore, store default value and call handler\n if (errorHandler.defaultValue !== undefined) {\n const storageKey = createStorageKey(\n metadata.path,\n metadata.method || \"get\"\n );\n this.responseStore.set(\n storageKey,\n errorHandler.defaultValue,\n metadata.cache || { retention: ResponseRetention.SINGLE }\n );\n await metadata.originalHandler.call(\n this.model,\n error.message,\n errorHandler.defaultValue\n );\n }\n break;\n\n case \"default\":\n // Store default value in response store\n if (errorHandler.defaultValue !== undefined) {\n const storageKey = createStorageKey(\n metadata.path,\n metadata.method || \"get\"\n );\n this.responseStore.set(\n storageKey,\n errorHandler.defaultValue,\n metadata.cache || { retention: ResponseRetention.SINGLE }\n );\n // Call handler with error and default value (error-first parameters)\n await metadata.originalHandler.call(\n this.model,\n error.message,\n errorHandler.defaultValue\n );\n }\n break;\n }\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>(\n eventType: string\n): 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\n const startBatchTimer = () => {\n if (batchTimer) clearTimeout(batchTimer);\n\n batchPromise = new Promise<void>((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 return {\n type,\n iterator: iterate<T>(type),\n done: false,\n };\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(item.type, item.iterator.next());\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]) =>\n [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(eventType, iterator.iterator.next());\n }\n }\n }\n } finally {\n // Clean up all iterators\n await Promise.all(iterators.map((item) => item.iterator.return()));\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 = 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\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 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 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}\n","import type { IKosDataModel } from \"../kosModel\";\nimport type { IKosTopicHandlerParams } from \"./kosTopicHandler\";\n\n/**\n * Advanced flow control options for kosTopicHandler\n *\n * @kosService core.topic-handler\n * @kosApiLevel 12\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\n/**\n * @kosService core.topic-handler\n * @kosApiLevel 12\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 *\n * @kosService core.topic-handler\n * @kosApiLevel 12\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 *\n * @kosService core.topic-handler\n * @kosApiLevel 12\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 *\n * @kosService core.topic-handler\n * @kosApiLevel 12\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 { when } from \"mobx\";\n\n/**\n * Resolves the reason an `AbortSignal` carries, falling back to a generic\n * `AbortError` for signals aborted without one.\n */\nconst abortReason = (signal: AbortSignal): unknown =>\n signal.reason ?? new DOMException(\"Aborted\", \"AbortError\");\n\n/**\n * Waits for a MobX predicate to become `true`, but gives up as soon as the\n * supplied signal aborts.\n *\n * MobX's `when()` waits forever by design. That is the right default for\n * lifecycle code, but a caller working against a deadline needs the wait to be\n * cancellable — and, more importantly, needs the underlying reaction disposed\n * when it gives up. Without disposal, every abandoned waiter leaves a live\n * reaction observing the predicate for the lifetime of the process.\n *\n * @param predicate - The reactive condition to wait for.\n * @param signal - Optional signal that cancels the wait. When omitted the wait\n * is indefinite, matching plain `when()`.\n * @returns A promise that resolves once the predicate holds.\n * @throws The signal's abort reason (a `TimeoutError` or `AbortError`\n * `DOMException` for signals created by the SDK) if it aborts first.\n *\n * @internal\n */\nexport const abortableWhen = async (\n predicate: () => boolean,\n signal?: AbortSignal\n): Promise<void> => {\n if (predicate()) {\n return;\n }\n\n if (!signal) {\n await when(predicate);\n return;\n }\n\n if (signal.aborted) {\n throw abortReason(signal);\n }\n\n const pending = when(predicate);\n let onAbort: (() => void) | undefined;\n\n try {\n await Promise.race([\n // `cancel()` below rejects this promise with MobX's WHEN_CANCELLED\n // sentinel. That rejection *is* the cancellation, never a real failure,\n // so it is swallowed here; the abort branch supplies the thrown reason.\n pending.catch(() => undefined),\n new Promise<never>((_, reject) => {\n onAbort = () => reject(abortReason(signal));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }),\n ]);\n } finally {\n if (onAbort) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n // Disposes the underlying reaction. Required on the abort path so\n // abandoned waiters do not accumulate, and harmless once the predicate has\n // already resolved.\n pending.cancel();\n }\n};\n","// Wire-frame encoding/decoding for the KosMock facility. The frame format is\n// the transport's own: `header:value` lines, a blank line, then an optional\n// JSON body (see processKosMessage). Encoders here must stay byte-compatible\n// with what BaseTransport.onMessage and kosFetchWs expect: the response-id\n// header routes the frame to the awaiting request, the `status` header must be\n// a string (kosFetchWs compares it to the literal \"200\"), and service-layer\n// consumers read a `{status, data}` envelope from the body JSON.\nimport {\n HEADER_METHOD,\n HEADER_ORDERED,\n HEADER_REQUEST_ID,\n HEADER_REQUEST_TYPE,\n HEADER_RESPONSE_ID,\n HEADER_TOPIC,\n HEADER_URL,\n HEADER_WORK_TRACKER,\n STATUS,\n} from \"../../../../common\";\nimport { processKosMessage } from \"../base-message-transport\";\n\nexport const KOS_HTTP_REQUEST_TYPE = \"kos.http.request\";\nexport const KOS_HTTP_RESPONSE_TYPE = \"kos.http.response\";\nexport const KOS_FUTURE_TYPE = \"kos.future\";\nexport const KOS_BROKER_SUBSCRIBE_TYPE = \"kos.broker.subscribe\";\nexport const KOS_BROKER_UNSUBSCRIBE_TYPE = \"kos.broker.unsubscribe\";\nexport const KOS_ADDR_ALIAS_TYPE = \"kos.addr.alias\";\n\n/** Wire header stamped on every response the mock layer generates. */\nexport const KOS_MOCKED_HEADER = \"kos-mocked\";\n/** Optional wire header naming the fixture a mocked response came from. */\nexport const KOS_MOCK_FIXTURE_HEADER = \"kos-mock-fixture\";\n/** Wire header stamped on responses a transformer modified in flight. */\nexport const KOS_MOCK_TRANSFORMED_HEADER = \"kos-mock-transformed\";\n\nconst CONTENT_TYPE_HEADER = \"content-type\";\nconst MESSAGE_SEPARATOR = \"\\n\\n\";\n\nexport interface KosMockRequestFrame {\n method: string;\n url: string;\n requestId: string;\n tracker?: string;\n ordered: boolean;\n headers: Record<string, string>;\n rawBody?: string;\n}\n\nexport interface KosMockResponseFrameInput {\n requestId: string;\n status?: number;\n data?: unknown;\n headers?: Record<string, string>;\n /** Verbatim body override — skips the `{status, data}` envelope. */\n raw?: string;\n}\n\nconst toTransportString = (\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n): string | undefined => (typeof data === \"string\" ? data : undefined);\n\n/** Frame `type` header, or undefined for non-string/unparseable data. */\nexport function peekFrameType(\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n): string | undefined {\n const text = toTransportString(data);\n if (!text) {\n return undefined;\n }\n try {\n return processKosMessage(text).headers[HEADER_REQUEST_TYPE];\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decodes an outbound `kos.http.request` frame. Returns undefined for\n * anything else (binary data, topic subscribes, FOS frames, ...).\n */\nexport function decodeRequestFrame(\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n): KosMockRequestFrame | undefined {\n const text = toTransportString(data);\n if (!text) {\n return undefined;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(text));\n } catch {\n return undefined;\n }\n if (headers[HEADER_REQUEST_TYPE] !== KOS_HTTP_REQUEST_TYPE) {\n return undefined;\n }\n const method = headers[HEADER_METHOD];\n const url = headers[HEADER_URL];\n const requestId = headers[HEADER_REQUEST_ID];\n if (!method || !url || !requestId) {\n return undefined;\n }\n return {\n method,\n url,\n requestId,\n tracker: headers[HEADER_WORK_TRACKER],\n ordered: headers[HEADER_ORDERED] === \"true\",\n headers,\n rawBody: body || undefined,\n };\n}\n\n/**\n * Decodes the topic list from a `kos.broker.subscribe`/`unsubscribe` frame.\n * Returns undefined when the frame is not a broker frame.\n */\nexport function decodeSubscribeTopics(\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n): { type: \"subscribe\" | \"unsubscribe\"; topics: string[] } | undefined {\n const text = toTransportString(data);\n if (!text) {\n return undefined;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(text));\n } catch {\n return undefined;\n }\n const frameType = headers[HEADER_REQUEST_TYPE];\n if (\n frameType !== KOS_BROKER_SUBSCRIBE_TYPE &&\n frameType !== KOS_BROKER_UNSUBSCRIBE_TYPE\n ) {\n return undefined;\n }\n let topics: string[] = [];\n try {\n const parsed = JSON.parse(body);\n if (Array.isArray(parsed)) {\n topics = parsed.filter(\n (topic): topic is string => typeof topic === \"string\"\n );\n }\n } catch {\n // A malformed broker frame still identifies as one; report no topics.\n }\n return {\n type: frameType === KOS_BROKER_SUBSCRIBE_TYPE ? \"subscribe\" : \"unsubscribe\",\n topics,\n };\n}\n\nconst assertHeaderSafe = (name: string, value: string) => {\n if (value.includes(\"\\n\")) {\n throw new Error(`KosMock frame ${name} must not contain newlines`);\n }\n};\n\nconst encodeFrame = (\n headers: Array<[string, string]>,\n body: string\n): string => {\n const lines = headers.map(([name, value]) => {\n assertHeaderSafe(name, value);\n return `${name}:${value}`;\n });\n return `${lines.join(\"\\n\")}${MESSAGE_SEPARATOR}${body}`;\n};\n\n/**\n * Re-encodes a frame from already-parsed headers and a body — used when a\n * transformer patches an inbound frame's body while preserving its headers.\n */\nexport function encodeRawFrame(\n headers: Record<string, string>,\n body: string\n): string {\n return encodeFrame(Object.entries(headers), body);\n}\n\n/**\n * Encodes an inbound HTTP response frame for a pending request. The default\n * body is the `{status, data}` envelope service consumers expect.\n */\nexport function encodeHttpResponseFrame({\n requestId,\n status = 200,\n data,\n headers = {},\n raw,\n}: KosMockResponseFrameInput): string {\n const body = raw ?? JSON.stringify({ status, data: data ?? {} });\n return encodeFrame(\n [\n [HEADER_RESPONSE_ID, requestId],\n [STATUS, `${status}`],\n [CONTENT_TYPE_HEADER, \"application/json\"],\n ...Object.entries(headers),\n [HEADER_REQUEST_TYPE, KOS_HTTP_RESPONSE_TYPE],\n ],\n body\n );\n}\n\n/** Encodes an inbound topic push frame. */\nexport function encodeTopicFrame(\n topic: string,\n body: unknown,\n headers: Record<string, string> = {}\n): string {\n return encodeFrame(\n [[HEADER_TOPIC, topic], ...Object.entries(headers)],\n typeof body === \"string\" ? body : JSON.stringify(body ?? {})\n );\n}\n\n/**\n * Encodes an inbound future push frame. Dispatches on the `type` header alone\n * — it must NOT carry topic/subscription/response-id headers or\n * BaseTransport.onMessage would route it elsewhere.\n */\nexport function encodeFutureFrame(future: unknown): string {\n return encodeFrame(\n [[HEADER_REQUEST_TYPE, KOS_FUTURE_TYPE]],\n JSON.stringify(future)\n );\n}\n","// Generic future lifecycle simulator. Emits `type:kos.future` frames through\n// the inbound transport path, so FutureContainerModel republishes them on\n// `kos.future/{tracker||id}` and the real future plumbing (progress, end\n// states, cancellation) runs unmodified. Progress is advanced by accumulated\n// interval ticks, not wall-clock reads, so simulations are deterministic under\n// fake timers.\nimport { uuid } from \"../../../util/api-request-id\";\nimport { KosLog } from \"../../log\";\nimport { encodeFutureFrame } from \"./mock-frames\";\nimport type {\n IKosMockFutureHandle,\n IKosMockFutureSimulator,\n KosMockFutureEndState,\n KosMockFutureFrame,\n KosMockFutureOptions,\n KosMockRequest,\n} from \"./mock-types\";\n\nexport interface FutureSimulatorDeps {\n emitFrame(frame: string): void;\n /** Called on the first future needing them; registers shared cancel routes. */\n ensureCancelRoutes(): void;\n}\n\nconst DEFAULT_DURATION_MS = 5000;\nconst DEFAULT_INTERVAL_MS = 250;\n\nclass KosMockFutureHandle implements IKosMockFutureHandle {\n readonly id: string;\n readonly tracker?: string;\n\n progress = 0;\n done = false;\n\n private remainingTimeMs: number;\n private elapsedMs = 0;\n private endStateValue?: KosMockFutureEndState;\n private reasonValue?: string;\n private timer?: ReturnType<typeof setInterval>;\n private started = false;\n\n private readonly durationMs: number;\n private readonly intervalMs: number;\n private readonly targetEndState: KosMockFutureEndState;\n private readonly targetReason?: string;\n private readonly clientData?: Record<string, unknown>;\n\n constructor(\n options: KosMockFutureOptions,\n private readonly emitFrame: (frame: string) => void\n ) {\n this.id = options.id ?? uuid();\n this.tracker = options.tracker;\n this.durationMs = options.durationMs ?? DEFAULT_DURATION_MS;\n this.intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;\n this.targetEndState = options.endState ?? \"SUCCESS\";\n this.targetReason = options.reason;\n this.clientData = options.clientData;\n this.remainingTimeMs = this.durationMs;\n }\n\n snapshot(): KosMockFutureFrame {\n return {\n id: this.id,\n tracker: this.tracker,\n progress: this.progress,\n remainingTimeMs: this.remainingTimeMs,\n endState: this.endStateValue,\n reason: this.reasonValue,\n clientData: this.clientData,\n };\n }\n\n start(): void {\n if (this.started || this.done) {\n return;\n }\n this.started = true;\n this.timer = setInterval(() => this.tick(), this.intervalMs);\n }\n\n private tick(): void {\n this.elapsedMs += this.intervalMs;\n if (this.elapsedMs >= this.durationMs) {\n this.complete(this.targetEndState, this.targetReason);\n } else {\n this.emitProgress(\n this.elapsedMs / this.durationMs,\n this.durationMs - this.elapsedMs\n );\n }\n }\n\n emitProgress(progress: number, remainingTimeMs?: number): void {\n if (this.done) {\n return;\n }\n this.progress = progress;\n if (remainingTimeMs !== undefined) {\n this.remainingTimeMs = remainingTimeMs;\n }\n this.emitFrame(encodeFutureFrame(this.snapshot()));\n }\n\n complete(endState: KosMockFutureEndState = \"SUCCESS\", reason?: string): void {\n if (this.done) {\n return;\n }\n this.stopTimer();\n this.done = true;\n this.endStateValue = endState;\n this.reasonValue = reason;\n this.remainingTimeMs = 0;\n if (endState === \"SUCCESS\") {\n this.progress = 1;\n }\n this.emitFrame(encodeFutureFrame(this.snapshot()));\n }\n\n cancel(): void {\n this.complete(\"CANCEL\", this.reasonValue ?? \"canceled by mock\");\n }\n\n dispose(): void {\n this.stopTimer();\n this.done = true;\n }\n\n private stopTimer(): void {\n if (this.timer !== undefined) {\n clearInterval(this.timer);\n this.timer = undefined;\n }\n }\n}\n\nexport class KosMockFutureSimulator implements IKosMockFutureSimulator {\n private readonly futures = new Map<string, KosMockFutureHandle>();\n\n constructor(private readonly deps: FutureSimulatorDeps) {}\n\n create(options: KosMockFutureOptions = {}): IKosMockFutureHandle {\n const handle = new KosMockFutureHandle(options, this.deps.emitFrame);\n this.futures.set(handle.id, handle);\n if (options.registerCancelRoute !== false) {\n this.deps.ensureCancelRoutes();\n }\n if (!options.tracker) {\n KosLog.warn(\n `KosMock future ${handle.id} has no tracker — models will not link it to their request; prefer futures.fromRequest`\n );\n }\n if (options.autoStart !== false) {\n handle.start();\n }\n return handle;\n }\n\n fromRequest(\n req: KosMockRequest,\n options: KosMockFutureOptions = {}\n ): IKosMockFutureHandle {\n return this.create({ tracker: req.tracker, ...options });\n }\n\n get(idOrTracker: string): IKosMockFutureHandle | undefined {\n const byId = this.futures.get(idOrTracker);\n if (byId) {\n return byId;\n }\n for (const handle of this.futures.values()) {\n if (handle.tracker === idOrTracker) {\n return handle;\n }\n }\n return undefined;\n }\n\n get active(): IKosMockFutureHandle[] {\n return [...this.futures.values()].filter((handle) => !handle.done);\n }\n\n clear(): void {\n this.futures.forEach((handle) => handle.dispose());\n this.futures.clear();\n }\n}\n","// Out-of-band fixture library. Two backends behind one facade:\n//\n// - browser: IndexedDB (`kos-mock-fixtures` database) — per-browser,\n// per-origin persistence with zero infrastructure.\n// - server: a `kosui fixtures serve` directory over localhost HTTP —\n// committable, shareable, never bundled into the app.\n//\n// When a server is configured it is preferred for saves and lookups; the\n// browser store is the fallback, so the console workflow is identical with\n// or without the server running.\nimport { KosLog } from \"../../log\";\nimport type { KosMockRegistry } from \"./mock-registry\";\nimport type {\n IKosMockFixtureStore,\n KosMockFixture,\n KosMockFixtureSummary,\n KosMockPlaybackHandle,\n KosMockPlaybackOptions,\n} from \"./mock-types\";\n\n/** Default `kosui fixtures serve` address (port 5676 — \"KOSM\" on a keypad). */\nexport const DEFAULT_FIXTURE_SERVER_URL = \"http://localhost:5676\";\n\nconst DB_NAME = \"kos-mock-fixtures\";\nconst STORE_NAME = \"fixtures\";\n\ninterface FixtureBackend {\n save(name: string, fixture: KosMockFixture): Promise<void>;\n load(name: string): Promise<KosMockFixture | undefined>;\n list(): Promise<Omit<KosMockFixtureSummary, \"source\">[]>;\n delete(name: string): Promise<boolean>;\n}\n\nconst summarize = (\n name: string,\n fixture: KosMockFixture\n): Omit<KosMockFixtureSummary, \"source\"> => {\n return {\n name,\n capturedAt: fixture.capturedAt,\n exchanges: fixture.exchanges.length,\n pushes: fixture.pushes.length,\n };\n};\n\n// -- browser backend (IndexedDB) ---------------------------------------------\n\nconst openDb = (): Promise<IDBDatabase> =>\n new Promise((resolve, reject) => {\n const request = indexedDB.open(DB_NAME, 1);\n request.onupgradeneeded = () => {\n if (!request.result.objectStoreNames.contains(STORE_NAME)) {\n request.result.createObjectStore(STORE_NAME);\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n\nconst withStore = async <T>(\n mode: IDBTransactionMode,\n operation: (store: IDBObjectStore) => IDBRequest<T>\n): Promise<T> => {\n const db = await openDb();\n try {\n return await new Promise<T>((resolve, reject) => {\n const request = operation(\n db.transaction(STORE_NAME, mode).objectStore(STORE_NAME)\n );\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n } finally {\n db.close();\n }\n};\n\nclass BrowserFixtureBackend implements FixtureBackend {\n private get available(): boolean {\n return typeof indexedDB !== \"undefined\";\n }\n\n async save(name: string, fixture: KosMockFixture): Promise<void> {\n if (!this.available) {\n throw new Error(\"IndexedDB is not available in this environment\");\n }\n await withStore(\"readwrite\", (store) => store.put(fixture, name));\n }\n\n async load(name: string): Promise<KosMockFixture | undefined> {\n if (!this.available) {\n return undefined;\n }\n return withStore<KosMockFixture | undefined>(\"readonly\", (store) =>\n store.get(name)\n );\n }\n\n async list(): Promise<Omit<KosMockFixtureSummary, \"source\">[]> {\n if (!this.available) {\n return [];\n }\n const [keys, values] = await Promise.all([\n withStore<IDBValidKey[]>(\"readonly\", (store) => store.getAllKeys()),\n withStore<KosMockFixture[]>(\"readonly\", (store) => store.getAll()),\n ]);\n return keys.map((key, index) => summarize(String(key), values[index]));\n }\n\n async delete(name: string): Promise<boolean> {\n if (!this.available) {\n return false;\n }\n const existing = await this.load(name);\n if (!existing) {\n return false;\n }\n await withStore(\"readwrite\", (store) => store.delete(name));\n return true;\n }\n}\n\n// -- server backend (kosui fixtures serve) -----------------------------------\n\nexport class ServerFixtureBackend implements FixtureBackend {\n constructor(private readonly baseUrl: string) {}\n\n private url(name?: string): string {\n const base = this.baseUrl.replace(/\\/$/, \"\");\n return name\n ? `${base}/fixtures/${encodeURIComponent(name)}`\n : `${base}/fixtures`;\n }\n\n async save(name: string, fixture: KosMockFixture): Promise<void> {\n const response = await fetch(this.url(name), {\n method: \"PUT\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(fixture),\n });\n if (!response.ok) {\n throw new Error(`Fixture server rejected save: ${response.status}`);\n }\n }\n\n async load(name: string): Promise<KosMockFixture | undefined> {\n const response = await fetch(this.url(name));\n if (!response.ok) {\n return undefined;\n }\n return (await response.json()) as KosMockFixture;\n }\n\n async list(): Promise<Omit<KosMockFixtureSummary, \"source\">[]> {\n const response = await fetch(this.url());\n if (!response.ok) {\n return [];\n }\n const payload = (await response.json()) as {\n fixtures: Omit<KosMockFixtureSummary, \"source\">[];\n };\n return payload.fixtures ?? [];\n }\n\n async delete(name: string): Promise<boolean> {\n const response = await fetch(this.url(name), { method: \"DELETE\" });\n return response.ok;\n }\n}\n\n// -- facade -------------------------------------------------------------------\n\nexport interface FixtureStoreDeps {\n browserBackend?: FixtureBackend;\n serverBackendFactory?: (url: string) => FixtureBackend;\n}\n\nexport function createFixtureStore(\n registry: KosMockRegistry,\n deps: FixtureStoreDeps = {}\n): IKosMockFixtureStore {\n const browser = deps.browserBackend ?? new BrowserFixtureBackend();\n const serverFactory =\n deps.serverBackendFactory ??\n ((url: string) => new ServerFixtureBackend(url));\n\n let server: FixtureBackend | undefined;\n let serverUrl: string | undefined;\n\n const resolveName = (fixture: KosMockFixture, name?: string): string => {\n const resolved = name ?? fixture.name;\n if (!resolved) {\n throw new Error(\n \"Fixture has no name — pass one: fixtures.save(fixture, {name})\"\n );\n }\n return resolved;\n };\n\n const store: IKosMockFixtureStore = {\n get serverUrl() {\n return serverUrl;\n },\n\n useServer(url) {\n if (url === undefined) {\n server = undefined;\n serverUrl = undefined;\n return;\n }\n serverUrl = url === true ? DEFAULT_FIXTURE_SERVER_URL : url;\n server = serverFactory(serverUrl);\n },\n\n async save(fixture, options = {}) {\n const name = resolveName(fixture, options.name);\n const named = { ...fixture, name };\n const target =\n options.to === \"browser\"\n ? browser\n : options.to === \"server\"\n ? server\n : server ?? browser;\n if (!target) {\n throw new Error(\n \"No fixture server configured — useServer() or save to the browser\"\n );\n }\n await target.save(name, named);\n KosLog.info(`KosMock fixture \"${name}\" saved`);\n return name;\n },\n\n saveRecording(name) {\n return store.save(registry.recorder.toFixture(), { name });\n },\n\n async load(name) {\n if (server) {\n const fromServer = await server\n .load(name)\n .catch(() => undefined as KosMockFixture | undefined);\n if (fromServer) {\n return fromServer;\n }\n }\n return browser.load(name).catch(() => undefined);\n },\n\n async list() {\n const summaries: KosMockFixtureSummary[] = [];\n if (server) {\n try {\n (await server.list()).forEach((summary) =>\n summaries.push({ ...summary, source: \"server\" })\n );\n } catch {\n KosLog.warn(`KosMock fixture server unreachable at ${serverUrl}`);\n }\n }\n try {\n (await browser.list()).forEach((summary) =>\n summaries.push({ ...summary, source: \"browser\" })\n );\n } catch {\n // IndexedDB unavailable — server results (if any) still stand.\n }\n return summaries;\n },\n\n async delete(name) {\n let deleted = false;\n if (server) {\n deleted = (await server.delete(name).catch(() => false)) || deleted;\n }\n deleted = (await browser.delete(name).catch(() => false)) || deleted;\n return deleted;\n },\n\n async import() {\n if (typeof document === \"undefined\") {\n KosLog.warn(`KosMock fixture import requires a browser environment`);\n return undefined;\n }\n return new Promise((resolve) => {\n const input = document.createElement(\"input\");\n input.type = \"file\";\n input.accept = \".json,application/json\";\n input.onchange = async () => {\n const file = input.files?.[0];\n if (!file) {\n resolve(undefined);\n return;\n }\n try {\n const fixture = JSON.parse(await file.text()) as KosMockFixture;\n const name = await store.save(fixture, {\n name: fixture.name ?? file.name.replace(/\\.json$/, \"\"),\n });\n resolve(name);\n } catch (error: any) {\n KosLog.error(`KosMock fixture import failed`, error?.message);\n resolve(undefined);\n }\n };\n input.click();\n });\n },\n\n async play(name, options?: KosMockPlaybackOptions) {\n const fixture = await store.load(name);\n if (!fixture) {\n throw new Error(\n `No fixture named \"${name}\" in the store${\n serverUrl ? ` or at ${serverUrl}` : \"\"\n }`\n );\n }\n return registry.loadFixture(fixture, options) as KosMockPlaybackHandle;\n },\n };\n\n return store;\n}\n","// Pure route-pattern matching for the KosMock facility. No transport imports —\n// keep this module trivially unit-testable.\n\nexport interface KosMockCompiledRoute {\n pattern: string;\n regex: RegExp;\n paramNames: string[];\n}\n\nconst REGEX_SPECIALS = /[.*+?^${}()|[\\]\\\\]/g;\n\nconst escapeLiteral = (segment: string) =>\n segment.replace(REGEX_SPECIALS, \"\\\\$&\");\n\n/** Strips a trailing slash so `/a/b/` and `/a/b` compare equal (root `/` kept). */\nexport const normalizePath = (path: string) =>\n path.length > 1 && path.endsWith(\"/\") ? path.slice(0, -1) : path;\n\n/**\n * Compiles a route pattern into a regex.\n *\n * Syntax:\n * - `:name` matches one path segment and captures it under `name`\n * - `*` as a non-final segment matches one segment (uncaptured)\n * - `*` as the final segment matches the rest of the path (captured as `*`)\n */\nexport function compileRoutePattern(pattern: string): KosMockCompiledRoute {\n const paramNames: string[] = [];\n const segments = normalizePath(pattern).split(\"/\");\n\n const parts = segments.map((segment, index) => {\n if (segment.startsWith(\":\") && segment.length > 1) {\n paramNames.push(segment.slice(1));\n return \"([^/]+)\";\n }\n if (segment === \"*\") {\n if (index === segments.length - 1) {\n paramNames.push(\"*\");\n return \"(.*)\";\n }\n return \"[^/]+\";\n }\n return escapeLiteral(segment);\n });\n\n return {\n pattern,\n regex: new RegExp(`^${parts.join(\"/\")}$`),\n paramNames,\n };\n}\n\n/** Returns captured params on match, undefined otherwise. */\nexport function matchRoutePattern(\n compiled: KosMockCompiledRoute,\n path: string\n): Record<string, string> | undefined {\n const result = compiled.regex.exec(normalizePath(path));\n if (!result) {\n return undefined;\n }\n const params: Record<string, string> = {};\n compiled.paramNames.forEach((name, index) => {\n params[name] = result[index + 1];\n });\n return params;\n}\n\n/** Splits a wire `url` header into pathname and decoded query params. */\nexport function splitUrl(url: string): {\n path: string;\n query: Record<string, string>;\n} {\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex === -1) {\n return { path: url, query: {} };\n }\n const path = url.slice(0, queryIndex);\n const query: Record<string, string> = {};\n for (const pair of url.slice(queryIndex + 1).split(\"&\")) {\n if (!pair) {\n continue;\n }\n const [key, value] = pair.split(\"=\");\n query[decodeURIComponent(key)] = decodeURIComponent(value || \"\");\n }\n return { path, query };\n}\n\nexport function methodMatches(\n routeMethod: string,\n requestMethod: string\n): boolean {\n return (\n routeMethod === \"*\" ||\n routeMethod.toUpperCase() === requestMethod.toUpperCase()\n );\n}\n","// Fixture playback: turns a recorded KosMockFixture back into live behavior\n// with captured timings intact.\n//\n// - Captured exchanges become routes replaying their responses in captured\n// order (per endpoint), each delayed by its captured request→response\n// latency.\n// - Multiplexed endpoints (many operations over one path) replay correctly\n// via body discriminators: a dotted path (or function) extracts the\n// operation from each request body, captured exchanges are bucketed by\n// that value, and every incoming request is served from its own bucket —\n// so calls needn't repeat the captured order. Unknown values decline.\n// - The consume policy decides what a served exchange leaves behind:\n// \"once\" retires it (a dry endpoint declines, passing through to the real\n// backend in hybrid mode — captured responses never shadow live reality\n// twice); \"repeat-last\" keeps re-serving the final response (the default\n// for standalone, where there is no backend to fall through to).\n// - Future pushes whose tracker matches a captured exchange are ANCHORED to\n// that exchange: when the replayed request comes in, its frames are\n// scheduled at the captured request→frame deltas — so a pour replayed at\n// any moment gets its progress cadence exactly as the device produced it.\n// - Everything else (topics, unmatched futures) replays on the absolute\n// captured timeline (\"scheduled\") or on `startPushes()` (\"manual\").\n//\n// Future linkage across replay: a replayed pour generates a fresh tracker,\n// so playback maintains a captured→live tracker map (populated as requests\n// are served) and rewrites trackers in response bodies and future-frame\n// bodies. Trackers are uuids — plain string substitution is collision-safe.\nimport { KosLog } from \"../../log\";\nimport { encodeTopicFrame, KOS_FUTURE_TYPE } from \"./mock-frames\";\nimport type { KosMockRegistry } from \"./mock-registry\";\nimport type {\n KosMockFixture,\n KosMockFixtureExchange,\n KosMockFixturePush,\n KosMockHandle,\n KosMockPlaybackHandle,\n KosMockPlaybackOptions,\n} from \"./mock-types\";\nimport { splitUrl } from \"./route-matcher\";\n\ntype DiscriminatorSpec = string | ((body: unknown) => unknown);\n\nconst rewriteTrackers = (\n raw: string,\n trackerMap: Map<string, string>\n): string => {\n let out = raw;\n trackerMap.forEach((liveTracker, capturedTracker) => {\n out = out.split(capturedTracker).join(liveTracker);\n });\n return out;\n};\n\n/** Discriminator value as a bucket key; errors and misses become \"undefined\". */\nconst discriminatorKey = (spec: DiscriminatorSpec, body: unknown): string => {\n try {\n if (typeof spec === \"function\") {\n return String(spec(body));\n }\n let current: unknown = body;\n for (const part of spec.split(\".\")) {\n if (current === null || typeof current !== \"object\") {\n return String(undefined);\n }\n current = (current as Record<string, unknown>)[part];\n }\n return String(current);\n } catch {\n return String(undefined);\n }\n};\n\ninterface ServeQueue {\n queue: KosMockFixtureExchange[];\n served: number;\n}\n\nexport function installFixturePlayback(\n registry: KosMockRegistry,\n fixture: KosMockFixture,\n options: KosMockPlaybackOptions = {}\n): KosMockPlaybackHandle {\n const name = options.name ?? fixture.name;\n const speed = options.speed ?? 1;\n const consume =\n options.consume ?? (registry.standalone ? \"repeat-last\" : \"once\");\n const discriminators: Record<string, DiscriminatorSpec> = {\n ...fixture.discriminators,\n ...options.discriminators,\n };\n const trackerMap = new Map<string, string>();\n const timers = new Set<ReturnType<typeof setTimeout>>();\n let stopped = false;\n\n const schedule = (delayMs: number, fire: () => void) => {\n const timer = setTimeout(() => {\n timers.delete(timer);\n fire();\n }, Math.max(0, delayMs));\n timers.add(timer);\n };\n\n const firePush = (push: KosMockFixturePush) => {\n if (push.kind === \"topic\" && push.topic) {\n registry.publishFrame(encodeTopicFrame(push.topic, push.body));\n } else if (push.kind === \"future\") {\n // Rewrite at fire time — the live tracker may only become known once\n // the replayed request has been served.\n registry.publishFrame(\n `type:${KOS_FUTURE_TYPE}\\n\\n${rewriteTrackers(push.body, trackerMap)}`\n );\n }\n };\n\n // Split pushes: futures whose tracker matches a captured exchange anchor to\n // that exchange; the rest live on the absolute timeline.\n const capturedTrackers = new Set(\n fixture.exchanges\n .map((exchange) => exchange.tracker)\n .filter((tracker): tracker is string => !!tracker)\n );\n const anchoredByTracker = new Map<string, KosMockFixturePush[]>();\n const unanchored: KosMockFixturePush[] = [];\n for (const push of fixture.pushes) {\n if (\n push.kind === \"future\" &&\n push.tracker &&\n capturedTrackers.has(push.tracker)\n ) {\n const list = anchoredByTracker.get(push.tracker) ?? [];\n list.push(push);\n anchoredByTracker.set(push.tracker, list);\n } else {\n unanchored.push(push);\n }\n }\n\n // Group captured exchanges per (method, path); each group replays in order,\n // or per discriminator bucket when one is configured for the endpoint.\n const groups = new Map<\n string,\n { method: string; path: string; queue: KosMockFixtureExchange[] }\n >();\n for (const exchange of fixture.exchanges) {\n const { path } = splitUrl(exchange.url);\n const key = `${exchange.method.toUpperCase()} ${path}`;\n const group = groups.get(key) ?? {\n method: exchange.method.toUpperCase(),\n path,\n queue: [],\n };\n group.queue.push(exchange);\n groups.set(key, group);\n }\n\n const anchorsScheduled = new Set<string>();\n const routeHandles: KosMockHandle[] = [];\n groups.forEach((group, groupKey) => {\n const spec = discriminators[groupKey];\n const wholeGroup: ServeQueue = { queue: group.queue, served: 0 };\n let buckets: Map<string, ServeQueue> | undefined;\n if (spec !== undefined) {\n buckets = new Map();\n for (const exchange of group.queue) {\n let parsedBody: unknown;\n try {\n parsedBody = exchange.requestBody\n ? JSON.parse(exchange.requestBody)\n : undefined;\n } catch {\n parsedBody = undefined;\n }\n const key = discriminatorKey(spec, parsedBody);\n const bucket = buckets.get(key) ?? { queue: [], served: 0 };\n bucket.queue.push(exchange);\n buckets.set(key, bucket);\n }\n }\n\n routeHandles.push(\n registry.route(\n group.method as never,\n group.path,\n (req) => {\n if (stopped) {\n return undefined;\n }\n let serveQueue: ServeQueue | undefined;\n if (buckets && spec !== undefined) {\n serveQueue = buckets.get(discriminatorKey(spec, req.json()));\n if (!serveQueue) {\n return undefined; // Uncaptured operation — decline.\n }\n } else {\n serveQueue = wholeGroup;\n }\n if (serveQueue.served >= serveQueue.queue.length) {\n if (consume === \"once\") {\n return undefined; // Retired — hybrid falls through to reality.\n }\n serveQueue.served = serveQueue.queue.length - 1; // repeat last\n }\n const exchange = serveQueue.queue[serveQueue.served];\n serveQueue.served += 1;\n\n if (exchange.tracker && req.tracker) {\n trackerMap.set(exchange.tracker, req.tracker);\n }\n // Anchored frames fire relative to this request, at the captured\n // request→frame deltas.\n if (exchange.tracker && !anchorsScheduled.has(exchange.tracker)) {\n anchorsScheduled.add(exchange.tracker);\n const anchored = anchoredByTracker.get(exchange.tracker) ?? [];\n anchored.forEach((push) =>\n schedule((push.tMs - exchange.tMs) / speed, () => firePush(push))\n );\n }\n return {\n status: exchange.status,\n raw: rewriteTrackers(exchange.responseBody, trackerMap),\n delayMs: options.ignoreLatency\n ? 0\n : (exchange.latencyMs ?? 0) / speed,\n };\n },\n {\n fixture: name,\n description: `fixture replay: ${group.method} ${group.path} (${\n group.queue.length\n } captured${spec !== undefined ? \", discriminated\" : \"\"})`,\n }\n )\n );\n });\n\n // Absolute timeline for unanchored pushes.\n let pushesStarted = false;\n const startPushes = () => {\n if (pushesStarted) {\n return;\n }\n pushesStarted = true;\n unanchored.forEach((push) =>\n schedule(push.tMs / speed, () => firePush(push))\n );\n };\n\n if ((options.pushes ?? \"scheduled\") === \"scheduled\") {\n startPushes();\n }\n\n KosLog.info(\n `KosMock fixture${name ? ` \"${name}\"` : \"\"} loaded: ${\n groups.size\n } routes, ${fixture.pushes.length} pushes (${\n fixture.pushes.length - unanchored.length\n } anchored), consume: ${consume}`\n );\n\n return {\n name,\n startPushes,\n stop: () => {\n stopped = true;\n routeHandles.forEach((handle) => handle.remove());\n timers.forEach((timer) => clearTimeout(timer));\n timers.clear();\n },\n };\n}\n","// Live-traffic recorder. The interceptor tees every outbound frame and every\n// inbound frame (real, mocked, or injected) through here; while recording,\n// request/response pairs become fixture \"exchanges\" (matched by request-id)\n// and topic/future frames become fixture \"pushes\" with their timeline\n// offsets. The result is a plain-JSON KosMockFixture that\n// `KosMock.loadFixture` can replay for offline testing.\nimport { KosLog } from \"../../log\";\nimport { processKosMessage } from \"../base-message-transport\";\nimport {\n decodeRequestFrame,\n KOS_FUTURE_TYPE,\n KOS_MOCKED_HEADER,\n} from \"./mock-frames\";\nimport type {\n IKosMockRecorder,\n KosMockFixture,\n KosMockFixtureExchange,\n KosMockFixturePush,\n KosMockFixtureSend,\n} from \"./mock-types\";\n\ninterface PendingRequest {\n tMs: number;\n method: string;\n url: string;\n tracker?: string;\n requestBody?: string;\n requestHeaders?: Record<string, string>;\n}\n\nexport class KosMockRecorder implements IKosMockRecorder {\n private recording = false;\n private name?: string;\n private startedAt = 0;\n private capturedAt?: string;\n private readonly pending = new Map<string, PendingRequest>();\n private exchanges: KosMockFixtureExchange[] = [];\n private pushes: KosMockFixturePush[] = [];\n private sends: KosMockFixtureSend[] = [];\n\n get isRecording(): boolean {\n return this.recording;\n }\n\n start(options: { name?: string } = {}): void {\n this.recording = true;\n this.name = options.name;\n this.startedAt = Date.now();\n this.capturedAt = new Date().toISOString();\n this.pending.clear();\n this.exchanges = [];\n this.pushes = [];\n this.sends = [];\n KosLog.info(\n `KosMock recorder started${options.name ? ` (${options.name})` : \"\"}`\n );\n }\n\n stop(): KosMockFixture {\n const fixture = this.toFixture();\n this.recording = false;\n KosLog.info(\n `KosMock recorder stopped: ${fixture.exchanges.length} exchanges, ${fixture.pushes.length} pushes, ${fixture.sends?.length ?? 0} sends`\n );\n return fixture;\n }\n\n toFixture(): KosMockFixture {\n return {\n version: 1,\n name: this.name,\n capturedAt: this.capturedAt,\n exchanges: [...this.exchanges],\n pushes: [...this.pushes],\n sends: [...this.sends],\n };\n }\n\n download(filename?: string): void {\n if (typeof document === \"undefined\") {\n KosLog.warn(`KosMock recorder download requires a browser environment`);\n return;\n }\n const fixture = this.toFixture();\n const blob = new Blob([JSON.stringify(fixture, null, 2)], {\n type: \"application/json\",\n });\n const url = URL.createObjectURL(blob);\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = filename ?? `${fixture.name ?? \"kos-mock-fixture\"}.json`;\n anchor.click();\n URL.revokeObjectURL(url);\n }\n\n private elapsed(): number {\n return Date.now() - this.startedAt;\n }\n\n /** Interceptor tap: every outbound frame. Internal. */\n noteOutbound(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n if (!this.recording) {\n return;\n }\n const frame = decodeRequestFrame(data);\n if (!frame) {\n this.noteSend(data);\n return;\n }\n this.pending.set(frame.requestId, {\n tMs: this.elapsed(),\n method: frame.method,\n url: frame.url,\n tracker: frame.tracker,\n requestBody: frame.rawBody,\n requestHeaders: frame.headers,\n });\n }\n\n /**\n * Everything else a window sends: alias registration, broker subscribes,\n * client-sent futures. What a window asked for is not recoverable from the\n * responses it got back, so it is captured rather than discarded.\n */\n private noteSend(\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n ): void {\n if (typeof data !== \"string\") {\n return;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(data));\n } catch {\n return;\n }\n this.sends.push({\n tMs: this.elapsed(),\n type: headers[\"type\"],\n headers: headers,\n ...(body ? { body } : {}),\n });\n }\n\n /** Interceptor tap: every inbound frame (real, mocked, injected). Internal. */\n noteInbound(frame: string): void {\n if (!this.recording) {\n return;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(frame));\n } catch {\n return;\n }\n\n const responseId = headers[\"response-id\"];\n if (responseId) {\n const request = this.pending.get(responseId);\n if (!request) {\n return; // Response to a request sent before recording started.\n }\n this.pending.delete(responseId);\n this.exchanges.push({\n ...request,\n status: parseInt(headers[\"status\"] ?? \"200\", 10) || 200,\n responseBody: body ?? \"\",\n responseHeaders: headers,\n latencyMs: Math.max(0, this.elapsed() - request.tMs),\n ...(headers[KOS_MOCKED_HEADER] === \"true\" ? { mocked: true } : {}),\n });\n return;\n }\n\n const topic = headers[\"subscription\"] || headers[\"topic\"];\n if (topic) {\n this.pushes.push({\n tMs: this.elapsed(),\n kind: \"topic\",\n topic,\n body: body ?? \"\",\n headers: headers,\n });\n return;\n }\n\n if (headers[\"type\"] === KOS_FUTURE_TYPE) {\n let tracker: string | undefined;\n try {\n tracker = JSON.parse(body)?.tracker;\n } catch {\n // Unparseable future body — keep the push without tracker linkage.\n }\n this.pushes.push({\n tMs: this.elapsed(),\n kind: \"future\",\n tracker,\n body: body ?? \"\",\n headers: headers,\n });\n }\n }\n}\n","// Out-of-band imperative setups. Fixtures carry data; a setup module carries\n// code — transformers, custom route handlers, config injections, observers —\n// authored against the KosMock instance and served read-only by\n// `kosui fixtures serve` from its `setups/` directory:\n//\n// // fixtures/setups/agitation-choreo.mjs\n// export default (kosMock) => {\n// const observer = kosMock.observe({ onFuture: (f) => { ... } });\n// return () => observer(); // teardown\n// };\n//\n// The default export may be sync or async and may return a teardown. Modules\n// import nothing (the KosMock instance is passed in / on window.KosMock), so\n// they load from any origin without a bundler.\nimport { KosLog } from \"../../log\";\nimport { DEFAULT_FIXTURE_SERVER_URL } from \"./mock-fixtures\";\nimport type { KosMockRegistry } from \"./mock-registry\";\nimport type {\n IKosMockSetupStore,\n KosMockSetupHandle,\n KosMockSetupModule,\n} from \"./mock-types\";\n\nexport interface SetupStoreDeps {\n /** Module loader seam — tests inject a fake; default is dynamic import. */\n loadModule?: (url: string) => Promise<{ default?: KosMockSetupModule }>;\n}\n\n// The ignore comments keep bundlers (vite/webpack) from trying to resolve a\n// runtime URL at build time.\nconst dynamicImport = (url: string) =>\n import(/* @vite-ignore */ /* webpackIgnore: true */ url);\n\nexport function createSetupStore(\n registry: KosMockRegistry,\n deps: SetupStoreDeps = {}\n): IKosMockSetupStore {\n const loadModule = deps.loadModule ?? dynamicImport;\n const activeSetups = new Map<\n string,\n { handle: KosMockSetupHandle; teardown?: () => void }\n >();\n\n const serverBase = () =>\n (registry.fixtures.serverUrl ?? DEFAULT_FIXTURE_SERVER_URL).replace(\n /\\/$/,\n \"\"\n );\n\n const resolve = (nameOrUrl: string): { name: string; url: string } => {\n if (/^https?:\\/\\//.test(nameOrUrl)) {\n const stem = nameOrUrl.split(\"/\").pop() ?? nameOrUrl;\n return { name: stem.replace(/\\.mjs$/, \"\"), url: nameOrUrl };\n }\n const name = nameOrUrl.replace(/\\.mjs$/, \"\");\n return {\n name,\n url: `${serverBase()}/setups/${encodeURIComponent(name)}.mjs`,\n };\n };\n\n const runTeardown = (name: string): boolean => {\n const entry = activeSetups.get(name);\n if (!entry) {\n return false;\n }\n activeSetups.delete(name);\n try {\n entry.teardown?.();\n } catch (error: any) {\n KosLog.error(`KosMock setup \"${name}\" teardown threw`, error?.message);\n }\n return true;\n };\n\n const store: IKosMockSetupStore = {\n async load(nameOrUrl) {\n const { name, url } = resolve(nameOrUrl);\n const module = await loadModule(url);\n const setup = module?.default;\n if (typeof setup !== \"function\") {\n throw new Error(\n `Setup module ${url} has no default-export function (see KosMockSetupModule)`\n );\n }\n // Replace semantics: unwind a previous load of the same name first.\n runTeardown(name);\n\n const result = await setup(registry);\n const handle: KosMockSetupHandle = {\n name,\n url,\n unload: () => {\n runTeardown(name);\n },\n };\n activeSetups.set(name, {\n handle,\n teardown: typeof result === \"function\" ? result : undefined,\n });\n KosLog.info(`KosMock setup \"${name}\" installed from ${url}`);\n return handle;\n },\n\n async list() {\n const response = await fetch(`${serverBase()}/setups`);\n if (!response.ok) {\n return [];\n }\n const payload = (await response.json()) as {\n setups: Array<{ name: string }>;\n };\n return payload.setups ?? [];\n },\n\n active() {\n return [...activeSetups.values()].map((entry) => entry.handle);\n },\n\n unload(name) {\n return runTeardown(name);\n },\n\n clear() {\n [...activeSetups.keys()].forEach((name) => runTeardown(name));\n },\n };\n\n return store;\n}\n","// Config-property simulation over the standard config-bean wire surface:\n//\n// read GET /api/kos/config/details/{beanId}/{depth}\n// → {status, data: {scopes, details: [{bean, scopes, schema: {paths, schema}}]}}\n// write POST /api/kos/config/{beanId} body {prop: value}\n// change WS topic /kos/config/{beanId}\n// → {changes: [{attr, currentValue, previousValue}], scopedChanges, errors}\n//\n// (Shapes per models/services/config-bean and the config-bean model's topic\n// handler. Values ride the change topic as strings.)\n//\n// `update` simulates a change by publishing the topic — pure injection, works\n// against a live device. `inject` goes further: it overlays properties (and\n// their schema nodes) that the backend does not implement yet, transforming\n// reads in flight and absorbing writes that touch only injected props.\nimport { KosLog } from \"../../log\";\nimport type { KosMockRegistry } from \"./mock-registry\";\nimport type {\n KosMockConfigFacade,\n KosMockConfigInjectionHandle,\n} from \"./mock-types\";\n\nconst asWireValue = (value: unknown): string =>\n typeof value === \"string\" ? value : JSON.stringify(value);\n\nconst configTopic = (beanId: string) => `/kos/config/${beanId}`;\n\nconst changeEnvelope = (\n props: Record<string, unknown>,\n previousValues: Record<string, unknown> = {}\n) => {\n return {\n changes: Object.entries(props).map(([attr, value]) => {\n return {\n attr,\n currentValue: asWireValue(value),\n previousValue:\n previousValues[attr] === undefined\n ? \"\"\n : asWireValue(previousValues[attr]),\n };\n }),\n scopedChanges: [],\n errors: [],\n };\n};\n\nexport function createConfigFacade(\n registry: KosMockRegistry\n): KosMockConfigFacade {\n const update: KosMockConfigFacade[\"update\"] = (\n beanId,\n props,\n options = {}\n ) => {\n registry.publishTopic(\n configTopic(beanId),\n changeEnvelope(props, options.previousValues)\n );\n };\n\n const inject: KosMockConfigFacade[\"inject\"] = (beanId, injection) => {\n const current: Record<string, unknown> = { ...injection.props };\n const schema = injection.schema ?? {};\n\n // Reads: merge injected props + schema into the details response.\n const transformerHandle = registry.transformResponse(\n \"GET\",\n `/api/kos/config/details/${beanId}/:depth`,\n (body: any) => {\n if (!body || typeof body !== \"object\") {\n return undefined;\n }\n const details = Array.isArray(body.data?.details)\n ? body.data.details\n : undefined;\n if (!details) {\n return undefined;\n }\n const detail = details[0] ?? {};\n details[0] = {\n ...detail,\n bean: { ...detail.bean, ...current },\n schema: {\n paths: [\n ...(detail.schema?.paths ?? []),\n ...Object.keys(schema).filter(\n (key) => !(detail.schema?.paths ?? []).includes(key)\n ),\n ],\n schema: { ...detail.schema?.schema, ...schema },\n },\n };\n return body;\n },\n { description: `config.inject ${beanId}` }\n );\n\n // Writes: absorb modifications that touch only injected props; anything\n // else passes through to the real backend untouched.\n const routeHandle = registry.post(\n `/api/kos/config/${beanId}`,\n (req) => {\n const requested = req.json<Record<string, unknown>>();\n if (!requested) {\n return undefined;\n }\n const keys = Object.keys(requested);\n const injectedKeys = keys.filter((key) => key in current);\n if (injectedKeys.length === 0) {\n return undefined;\n }\n if (injectedKeys.length < keys.length) {\n KosLog.warn(\n `KosMock config.inject ${beanId}: mixed write passes through; injected props will be rejected by the backend: ${injectedKeys.join(\n \", \"\n )}`\n );\n return undefined;\n }\n const previousValues = { ...current };\n Object.assign(current, requested);\n update(beanId, requested, { previousValues });\n return { data: {} };\n },\n { description: `config.inject ${beanId} writes` }\n );\n\n const handle: KosMockConfigInjectionHandle = {\n id: routeHandle.id,\n set: (props) => {\n const previousValues = { ...current };\n Object.assign(current, props);\n update(beanId, props, { previousValues });\n },\n remove: () => {\n transformerHandle.remove();\n routeHandle.remove();\n },\n enable: () => undefined,\n disable: () => {\n transformerHandle.remove();\n routeHandle.remove();\n },\n };\n return handle;\n };\n\n return { update, inject };\n}\n","// The KosMock registry: single source of truth for mock routes, topic\n// emitters, simulated futures, and scenario state. The transport interceptor\n// and the standalone socket both consult it per frame, so registrations take\n// effect on the next request — statically at startup or dynamically on a live\n// connection.\nimport { uuid } from \"../../../util/api-request-id\";\nimport { getQueryParams } from \"../../../util/get-query-params\";\nimport {\n hasKosProfile,\n resolveKosProfiles,\n} from \"../../../util/kos-config-init\";\nimport { KosLog } from \"../../log\";\nimport { KosMockFutureSimulator } from \"./future-simulator\";\nimport { createFixtureStore } from \"./mock-fixtures\";\nimport { installFixturePlayback } from \"./mock-playback\";\nimport { KosMockRecorder } from \"./mock-recorder\";\nimport { createSetupStore } from \"./mock-setups\";\nimport { processKosMessage } from \"../base-message-transport\";\nimport { createConfigFacade } from \"./mock-config\";\nimport {\n decodeRequestFrame,\n decodeSubscribeTopics,\n encodeHttpResponseFrame,\n encodeRawFrame,\n encodeTopicFrame,\n KOS_FUTURE_TYPE,\n KOS_MOCK_FIXTURE_HEADER,\n KOS_MOCK_TRANSFORMED_HEADER,\n KOS_MOCKED_HEADER,\n} from \"./mock-frames\";\nimport type {\n IKosMockControl,\n KosMockConfig,\n KosMockFixture,\n KosMockHandle,\n KosMockMethod,\n KosMockObserver,\n KosMockPlaybackHandle,\n KosMockPlaybackOptions,\n KosMockRequest,\n KosMockRequestObservation,\n KosMockResponse,\n KosMockResponseTransformer,\n KosMockRouteHandler,\n KosMockRouteInfo,\n KosMockRouteOptions,\n KosMockScenario,\n} from \"./mock-types\";\nimport {\n compileRoutePattern,\n KosMockCompiledRoute,\n matchRoutePattern,\n methodMatches,\n splitUrl,\n} from \"./route-matcher\";\n\n/** Frame delivery seam handed to the registry by a transport integration. */\nexport interface KosMockFrameIO {\n /** Injects an inbound frame through the real receive path. */\n deliver(frame: string): void;\n /** Sends the original outbound frame onward (hybrid pass-through). */\n forward(): void;\n}\n\ninterface RegisteredRoute {\n id: string;\n method: KosMockMethod;\n pattern: string;\n compiled: KosMockCompiledRoute;\n handler: KosMockRouteHandler;\n description?: string;\n once: boolean;\n enabled: boolean;\n delayMs?: number;\n fixture?: string;\n when?: (req: KosMockRequest) => boolean;\n hitCount: number;\n}\n\ninterface RegisteredTransformer {\n id: string;\n method: KosMockMethod;\n pattern: string;\n compiled: KosMockCompiledRoute;\n transform: KosMockResponseTransformer;\n description?: string;\n}\n\n/** Outbound requests kept for response correlation (transformers). */\nconst PENDING_REQUEST_CAP = 500;\n\nconst sleep = (ms: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nconst asHandler = (\n handler: KosMockRouteHandler | KosMockResponse\n): KosMockRouteHandler =>\n typeof handler === \"function\" ? handler : () => handler;\n\nexport class KosMockRegistry implements IKosMockControl {\n private routes: RegisteredRoute[] = [];\n private settings: KosMockConfig = {};\n private enabledFlag = false;\n private readonly injectors = new Set<(frame: string) => void>();\n private readonly subscribedTopicSet = new Set<string>();\n private readonly emitters = new Map<string, ReturnType<typeof setInterval>>();\n private readonly scenarioTeardowns = new Map<string, () => void>();\n private cancelRoutesRegistered = false;\n\n readonly state = new Map<string, unknown>();\n\n readonly futures = new KosMockFutureSimulator({\n emitFrame: (frame) => this.publishFrame(frame),\n ensureCancelRoutes: () => this.ensureFutureCancelRoutes(),\n });\n\n readonly recorder = new KosMockRecorder();\n\n readonly config = createConfigFacade(this);\n\n readonly fixtures = createFixtureStore(this);\n\n readonly setups = createSetupStore(this);\n\n /**\n * Internal: when set (a boot fixture is loading), the standalone socket\n * delays its open until this settles, so replayed routes exist before the\n * app's boot requests fire. Always resolves (errors are logged upstream).\n */\n bootGate?: Promise<void>;\n\n private readonly observers = new Set<KosMockObserver>();\n\n private transformers: RegisteredTransformer[] = [];\n\n private readonly pendingRequests = new Map<\n string,\n KosMockRequestObservation\n >();\n\n transformResponse(\n method: KosMockMethod,\n pattern: string,\n transform: KosMockResponseTransformer,\n options: { id?: string; description?: string } = {}\n ): KosMockHandle {\n const registered: RegisteredTransformer = {\n id: options.id ?? uuid(),\n method,\n pattern,\n compiled: compileRoutePattern(pattern),\n transform,\n description: options.description,\n };\n this.transformers.push(registered);\n const remove = () => {\n this.transformers = this.transformers.filter(\n (candidate) => candidate.id !== registered.id\n );\n };\n return {\n id: registered.id,\n remove,\n enable: () => undefined,\n disable: remove,\n };\n }\n\n /**\n * Interceptor seam: patches a matching inbound response frame through the\n * transformer chain before it reaches the app. Returns the (possibly\n * modified) frame. Internal.\n */\n transformInboundFrame(frame: string): string {\n if (this.transformers.length === 0) {\n return frame;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(frame));\n } catch {\n return frame;\n }\n const responseId = headers[\"response-id\"];\n if (!responseId) {\n return frame;\n }\n const request = this.pendingRequests.get(responseId);\n this.pendingRequests.delete(responseId);\n if (!request) {\n return frame;\n }\n\n const matching = this.transformers.filter(\n (transformer) =>\n methodMatches(transformer.method, request.method) &&\n matchRoutePattern(transformer.compiled, request.path) !== undefined\n );\n if (matching.length === 0) {\n return frame;\n }\n\n let parsed: unknown;\n try {\n parsed = body ? JSON.parse(body) : undefined;\n } catch {\n return frame; // Non-JSON body: transformers don't apply.\n }\n\n const info = {\n request,\n headers,\n status: parseInt(headers[\"status\"] ?? \"200\", 10) || 200,\n mocked: headers[KOS_MOCKED_HEADER] === \"true\",\n };\n let current = parsed;\n let changed = false;\n for (const transformer of matching) {\n try {\n const result = transformer.transform(current, info);\n if (result !== undefined) {\n current = result;\n changed = true;\n }\n } catch (error: any) {\n KosLog.error(\n `KosMock transformer for ${transformer.method} ${transformer.pattern} threw`,\n error?.message\n );\n }\n }\n if (!changed) {\n return frame;\n }\n return encodeRawFrame(\n { ...headers, [KOS_MOCK_TRANSFORMED_HEADER]: \"true\" },\n JSON.stringify(current)\n );\n }\n\n private readonly playbacks = new Set<KosMockPlaybackHandle>();\n\n observe(observer: KosMockObserver): () => void {\n this.observers.add(observer);\n return () => this.observers.delete(observer);\n }\n\n /**\n * Transport-integration tap: every outbound frame passes through here\n * (recorder + observers), independent of the enabled flag. Internal.\n */\n noteOutboundFrame(\n data: string | ArrayBufferLike | Blob | ArrayBufferView\n ): void {\n this.recorder.noteOutbound(data);\n const hasRequestObservers = [...this.observers].some(\n (observer) => observer.onRequest\n );\n if (!hasRequestObservers && this.transformers.length === 0) {\n return;\n }\n const frame = decodeRequestFrame(data);\n if (!frame) {\n return;\n }\n const { path, query } = splitUrl(frame.url);\n const observation = {\n method: frame.method,\n url: frame.url,\n path,\n query,\n requestId: frame.requestId,\n tracker: frame.tracker,\n rawBody: frame.rawBody,\n };\n if (this.transformers.length > 0) {\n // Correlation store for transformInboundFrame; capped so unanswered\n // requests can't grow it unbounded.\n if (this.pendingRequests.size >= PENDING_REQUEST_CAP) {\n const oldest = this.pendingRequests.keys().next().value;\n if (oldest !== undefined) {\n this.pendingRequests.delete(oldest);\n }\n }\n this.pendingRequests.set(frame.requestId, observation);\n }\n if (hasRequestObservers) {\n this.observers.forEach((observer) =>\n this.notifyObserver(() => observer.onRequest?.(observation))\n );\n }\n }\n\n /**\n * Transport-integration tap: every inbound frame (real, mocked, injected)\n * passes through here. Internal.\n */\n noteInboundFrame(frame: string): void {\n this.recorder.noteInbound(frame);\n if (this.observers.size === 0) {\n return;\n }\n let headers: Record<string, string>;\n let body: string;\n try {\n ({ headers, body } = processKosMessage(frame));\n } catch {\n return;\n }\n\n const responseId = headers[\"response-id\"];\n if (responseId) {\n const observation = {\n requestId: responseId,\n status: parseInt(headers[\"status\"] ?? \"200\", 10) || 200,\n mocked: headers[KOS_MOCKED_HEADER] === \"true\",\n fixture: headers[KOS_MOCK_FIXTURE_HEADER],\n body: body ?? \"\",\n headers,\n };\n this.observers.forEach((observer) =>\n this.notifyObserver(() => observer.onResponse?.(observation))\n );\n return;\n }\n\n const topic = headers[\"subscription\"] || headers[\"topic\"];\n if (topic) {\n const observation = { topic, body: body ?? \"\", headers };\n this.observers.forEach((observer) =>\n this.notifyObserver(() => observer.onTopic?.(observation))\n );\n return;\n }\n\n if (headers[\"type\"] === KOS_FUTURE_TYPE) {\n let future: unknown;\n try {\n future = JSON.parse(body);\n } catch {\n return;\n }\n this.observers.forEach((observer) =>\n this.notifyObserver(() => observer.onFuture?.(future as never))\n );\n }\n }\n\n /** An observer throwing must never disturb transport flow. */\n private notifyObserver(notify: () => void): void {\n try {\n notify();\n } catch (error: any) {\n KosLog.error(`KosMock observer threw`, error?.message);\n }\n }\n\n loadFixture(\n fixture: KosMockFixture,\n options?: KosMockPlaybackOptions\n ): KosMockPlaybackHandle {\n const inner = installFixturePlayback(this, fixture, options);\n const handle: KosMockPlaybackHandle = {\n name: inner.name,\n startPushes: inner.startPushes,\n stop: () => {\n this.playbacks.delete(handle);\n inner.stop();\n },\n };\n this.playbacks.add(handle);\n return handle;\n }\n\n // -- activation ------------------------------------------------------------\n\n get enabled(): boolean {\n return this.enabledFlag;\n }\n\n enable(): void {\n if (!this.enabledFlag) {\n this.enabledFlag = true;\n KosLog.info(`KosMock enabled`);\n }\n }\n\n disable(): void {\n if (this.enabledFlag) {\n this.enabledFlag = false;\n KosLog.info(`KosMock disabled`);\n }\n }\n\n get standalone(): boolean {\n return !!this.settings.standalone;\n }\n\n /** Internal: whether the standalone socket self-authorizes on open. */\n get authorizeOnOpen(): boolean {\n return this.settings.authorize !== false;\n }\n\n configure(config: KosMockConfig): void {\n this.settings = { ...this.settings, ...config };\n if (config.standalone) {\n this.enable();\n }\n }\n\n // -- routes ----------------------------------------------------------------\n\n route(\n method: KosMockMethod,\n pattern: string,\n handler: KosMockRouteHandler | KosMockResponse,\n options: KosMockRouteOptions = {}\n ): KosMockHandle {\n const registered: RegisteredRoute = {\n id: options.id ?? uuid(),\n method,\n pattern,\n compiled: compileRoutePattern(pattern),\n handler: asHandler(handler),\n description: options.description,\n once: !!options.once,\n enabled: options.enabled !== false,\n delayMs: options.delayMs,\n fixture: options.fixture,\n when: options.when,\n hitCount: 0,\n };\n this.routes.push(registered);\n // Registering a mock is the intent to use it.\n this.enable();\n return {\n id: registered.id,\n remove: () => this.removeRoute(registered.id),\n enable: () => this.setRouteEnabled(registered.id, true),\n disable: () => this.setRouteEnabled(registered.id, false),\n };\n }\n\n get(\n pattern: string,\n handler: KosMockRouteHandler | KosMockResponse,\n options?: KosMockRouteOptions\n ): KosMockHandle {\n return this.route(\"GET\", pattern, handler, options);\n }\n\n post(\n pattern: string,\n handler: KosMockRouteHandler | KosMockResponse,\n options?: KosMockRouteOptions\n ): KosMockHandle {\n return this.route(\"POST\", pattern, handler, options);\n }\n\n put(\n pattern: string,\n handler: KosMockRouteHandler | KosMockResponse,\n options?: KosMockRouteOptions\n ): KosMockHandle {\n return this.route(\"PUT\", pattern, handler, options);\n }\n\n del(\n pattern: string,\n handler: KosMockRouteHandler | KosMockResponse,\n options?: KosMockRouteOptions\n ): KosMockHandle {\n return this.route(\"DELETE\", pattern, handler, options);\n }\n\n private removeRoute(id: string): void {\n this.routes = this.routes.filter((route) => route.id !== id);\n }\n\n private setRouteEnabled(id: string, enabled: boolean): void {\n const route = this.routes.find((candidate) => candidate.id === id);\n if (route) {\n route.enabled = enabled;\n }\n }\n\n // -- inbound injection -----------------------------------------------------\n\n /**\n * Transport integrations register how inbound frames reach the receive\n * path. Internal — not part of IKosMockControl.\n */\n registerInjector(inject: (frame: string) => void): () => void {\n this.injectors.add(inject);\n return () => this.injectors.delete(inject);\n }\n\n publishTopic(\n topic: string,\n body: unknown,\n headers?: Record<string, string>\n ): void {\n this.publishFrame(encodeTopicFrame(topic, body, headers));\n }\n\n publishFrame(rawFrame: string): void {\n if (this.injectors.size === 0) {\n KosLog.warn(\n `KosMock.publishFrame: no active transport to deliver the frame`\n );\n return;\n }\n this.injectors.forEach((inject) => inject(rawFrame));\n }\n\n topicEmitter(\n topic: string,\n options: { intervalMs: number; body: (tick: number) => unknown }\n ): KosMockHandle {\n const id = uuid();\n let tick = 0;\n const start = () => {\n const timer = setInterval(() => {\n this.publishTopic(topic, options.body(tick));\n tick += 1;\n }, options.intervalMs);\n this.emitters.set(id, timer);\n };\n const stop = () => {\n const timer = this.emitters.get(id);\n if (timer !== undefined) {\n clearInterval(timer);\n this.emitters.delete(id);\n }\n };\n start();\n return {\n id,\n remove: stop,\n enable: () => {\n if (!this.emitters.has(id)) {\n start();\n }\n },\n disable: stop,\n };\n }\n\n // -- scenarios ---------------------------------------------------------------\n\n scenario(scenario: KosMockScenario): KosMockHandle {\n const id = `scenario:${scenario.name}:${uuid()}`;\n const teardown = scenario.setup(this);\n if (teardown) {\n this.scenarioTeardowns.set(id, teardown);\n }\n KosLog.info(`KosMock scenario \"${scenario.name}\" installed`);\n const remove = () => {\n const dispose = this.scenarioTeardowns.get(id);\n this.scenarioTeardowns.delete(id);\n dispose?.();\n };\n return { id, remove, enable: () => undefined, disable: remove };\n }\n\n // -- introspection -----------------------------------------------------------\n\n list(): KosMockRouteInfo[] {\n return this.routes.map((route) => {\n return {\n id: route.id,\n method: route.method,\n pattern: route.pattern,\n description: route.description,\n enabled: route.enabled,\n hitCount: route.hitCount,\n };\n });\n }\n\n describe() {\n return {\n enabled: this.enabled,\n standalone: this.standalone,\n routes: this.list(),\n transformers: this.transformers.map((transformer) => {\n return {\n id: transformer.id,\n method: transformer.method,\n pattern: transformer.pattern,\n description: transformer.description,\n };\n }),\n setups: this.setups.active().map((setup) => {\n return { name: setup.name, url: setup.url };\n }),\n activeFutures: this.futures.active.map((future) => future.id),\n subscribedTopics: this.subscribedTopics,\n };\n }\n\n get subscribedTopics(): string[] {\n return [...this.subscribedTopicSet];\n }\n\n clear(): void {\n this.setups.clear();\n [...this.playbacks].forEach((playback) => playback.stop());\n this.routes = [];\n this.transformers = [];\n this.pendingRequests.clear();\n this.cancelRoutesRegistered = false;\n this.emitters.forEach((timer) => clearInterval(timer));\n this.emitters.clear();\n this.scenarioTeardowns.forEach((teardown) => teardown());\n this.scenarioTeardowns.clear();\n this.futures.clear();\n this.state.clear();\n this.subscribedTopicSet.clear();\n }\n\n // -- frame handling (internal seam for transport integrations) --------------\n\n /**\n * Inspects an outbound frame. Returns true when the registry takes\n * ownership (it will deliver a response or forward asynchronously); false\n * means the caller sends the frame as usual. Internal — not part of\n * IKosMockControl.\n */\n handleOutboundFrame(\n data: string | ArrayBufferLike | Blob | ArrayBufferView,\n io: KosMockFrameIO\n ): boolean {\n if (!this.enabledFlag) {\n return false;\n }\n\n const subscription = decodeSubscribeTopics(data);\n if (subscription) {\n subscription.topics.forEach((topic) => {\n if (subscription.type === \"subscribe\") {\n this.subscribedTopicSet.add(topic);\n } else {\n this.subscribedTopicSet.delete(topic);\n }\n });\n return false;\n }\n\n const frame = decodeRequestFrame(data);\n if (!frame) {\n return false;\n }\n\n const { path, query } = splitUrl(frame.url);\n const candidates = this.routes\n .map((route) => {\n return {\n route,\n params:\n route.enabled && methodMatches(route.method, frame.method)\n ? matchRoutePattern(route.compiled, path)\n : undefined,\n };\n })\n .filter(\n (\n candidate\n ): candidate is typeof candidate & {\n params: Record<string, string>;\n } => candidate.params !== undefined\n );\n\n const policy = this.unmatchedPolicy();\n if (candidates.length === 0) {\n if (policy === \"respond404\") {\n this.deliverResponse(io, frame.requestId, {\n status: 404,\n data: { message: `KosMock: no route for ${frame.method} ${path}` },\n });\n return true;\n }\n if (policy === \"warn\") {\n KosLog.warn(`KosMock: unmatched ${frame.method} ${path}`);\n }\n return false;\n }\n\n const request: Omit<KosMockRequest, \"params\"> = {\n method: frame.method,\n url: frame.url,\n path,\n query,\n headers: frame.headers,\n requestId: frame.requestId,\n tracker: frame.tracker,\n ordered: frame.ordered,\n rawBody: frame.rawBody,\n json: <T>() => {\n if (!frame.rawBody) {\n return undefined;\n }\n try {\n return JSON.parse(frame.rawBody) as T;\n } catch {\n return undefined;\n }\n },\n };\n\n void this.resolve(request, candidates, io, policy);\n return true;\n }\n\n private async resolve(\n request: Omit<KosMockRequest, \"params\">,\n candidates: Array<{\n route: RegisteredRoute;\n params: Record<string, string>;\n }>,\n io: KosMockFrameIO,\n policy: \"passthrough\" | \"respond404\" | \"warn\"\n ): Promise<void> {\n for (const { route, params } of candidates) {\n const scopedRequest = { ...request, params };\n if (route.when) {\n let accepted = false;\n try {\n accepted = route.when(scopedRequest);\n } catch (error: any) {\n KosLog.error(\n `KosMock \\`when\\` guard for ${route.method} ${route.pattern} threw`,\n error?.message\n );\n }\n if (!accepted) {\n continue;\n }\n }\n let response: KosMockResponse | undefined;\n try {\n response = await route.handler(scopedRequest, this.context());\n } catch (error: any) {\n KosLog.error(\n `KosMock handler for ${route.method} ${route.pattern} threw`,\n error?.message\n );\n response = {\n status: 500,\n data: { message: `KosMock handler error: ${error?.message}` },\n };\n }\n if (!response) {\n continue;\n }\n const delayMs =\n response.delayMs ?? route.delayMs ?? this.settings.defaultDelayMs;\n if (delayMs) {\n await sleep(delayMs);\n }\n route.hitCount += 1;\n if (route.once) {\n this.removeRoute(route.id);\n }\n this.deliverResponse(io, request.requestId, response, route);\n return;\n }\n\n // Every candidate declined.\n if (policy === \"respond404\") {\n this.deliverResponse(io, request.requestId, {\n status: 404,\n data: {\n message: `KosMock: all routes declined ${request.method} ${request.path}`,\n },\n });\n return;\n }\n if (policy === \"warn\") {\n KosLog.warn(\n `KosMock: all routes declined ${request.method} ${request.path}`\n );\n }\n io.forward();\n }\n\n /**\n * Every mock-origin response is stamped `kos-mocked: true` (plus\n * `kos-mock-fixture` when the route belongs to a fixture) so mocked traffic\n * is detectable in devtools and on the fetch response headers.\n */\n private deliverResponse(\n io: KosMockFrameIO,\n requestId: string,\n response: KosMockResponse,\n route?: RegisteredRoute\n ): void {\n io.deliver(\n encodeHttpResponseFrame({\n requestId,\n status: response.status,\n data: response.data,\n raw: response.raw,\n headers: {\n [KOS_MOCKED_HEADER]: \"true\",\n ...(route?.fixture\n ? { [KOS_MOCK_FIXTURE_HEADER]: route.fixture }\n : {}),\n ...response.headers,\n },\n })\n );\n }\n\n private context() {\n return {\n state: this.state,\n futures: this.futures,\n publishTopic: (\n topic: string,\n body: unknown,\n headers?: Record<string, string>\n ) => this.publishTopic(topic, body, headers),\n };\n }\n\n private unmatchedPolicy(): \"passthrough\" | \"respond404\" | \"warn\" {\n return (\n this.settings.onUnmatched ??\n (this.standalone ? \"respond404\" : \"passthrough\")\n );\n }\n\n /**\n * Shared cancel routes for simulated futures. They decline unknown ids, so\n * in hybrid mode cancellation of real futures still reaches the device.\n */\n private ensureFutureCancelRoutes(): void {\n if (this.cancelRoutesRegistered) {\n return;\n }\n this.cancelRoutesRegistered = true;\n const cancelHandler: KosMockRouteHandler = (req) => {\n const future = this.futures.get(req.params.id);\n if (!future || future.done) {\n return undefined;\n }\n future.cancel();\n return { data: {} };\n };\n this.route(\"POST\", \"/api/kos/future/:id/cancel\", cancelHandler, {\n id: \"kos-mock-future-cancel\",\n description: \"KosMock simulated future cancel\",\n });\n this.route(\"DELETE\", \"/api/kos/future/:id\", cancelHandler, {\n id: \"kos-mock-future-delete\",\n description: \"KosMock simulated future delete\",\n });\n }\n}\n\nconst resolveSingleton = (): KosMockRegistry => {\n if (typeof window !== \"undefined\") {\n const existing = (window as any).KosMock;\n if (existing instanceof KosMockRegistry) {\n return existing;\n }\n const registry = new KosMockRegistry();\n (window as any).KosMock = registry;\n return registry;\n }\n return new KosMockRegistry();\n};\n\n/**\n * The singleton typed as the concrete registry — internal seam for the\n * transport interceptor and the standalone socket, which need\n * `handleOutboundFrame`/`registerInjector`.\n */\nexport const kosMockRegistry: KosMockRegistry = resolveSingleton();\n\n/**\n * The KosMock singleton — also exposed as `window.KosMock` for runtime\n * (agent/Studio/devtools) control.\n *\n * @kosService core.mock\n * @kosApiLevel 24\n */\nexport const KosMock: IKosMockControl = kosMockRegistry;\n\n// Startup activation, from a query param or a KOS profile. The query param\n// mirrors the `?host=`/`?alias=` convention; the profile form covers hosts\n// that own the URL (the SWT window), where `globalThis.getKosConfig` is the\n// only channel available. A query param wins over a profile.\n//\n// `?kosMock=standalone` / `studio.mock.standalone` boots against the loopback\n// socket; `?kosMock=on` / `studio.mock` merely arms the interceptor for hybrid\n// mocking. `?kosRecord` / `studio.mock.record` (optionally `=<name>`) starts\n// the recorder at module init — before the transport exists — so a capture\n// includes the boot exchanges (assemblies, availability, ...) that offline\n// playback needs; starting from the dev console after boot would miss them.\nconst PROFILE_MOCK = \"studio.mock\";\nconst PROFILE_MOCK_STANDALONE = \"studio.mock.standalone\";\nconst PROFILE_MOCK_RECORD = \"studio.mock.record\";\nconst PROFILE_MOCK_FIXTURE_SERVER = \"studio.mock.fixtureServer\";\nconst PROFILE_MOCK_FIXTURE = \"studio.mock.fixture\";\nconst PROFILE_MOCK_SETUP = \"studio.mock.setup\";\n\n/**\n * A profile carries its value the way the query param does: bare for a flag,\n * `name=value` when it needs one. Returns undefined when absent, \"\" when bare.\n */\nconst profileValue = (name: string): string | undefined => {\n const match = resolveKosProfiles().find(\n (profile) => profile === name || profile.startsWith(`${name}=`)\n );\n return match === undefined ? undefined : match.slice(name.length + 1);\n};\n\nif (typeof window !== \"undefined\") {\n const params = (window.location?.search ? getQueryParams() : {}) as Record<\n string,\n string | undefined\n >;\n\n const setting = (param: string, profile: string): string | undefined =>\n params[param] !== undefined ? params[param] : profileValue(profile);\n\n const mock =\n params[\"kosMock\"] !== undefined\n ? params[\"kosMock\"]\n : hasKosProfile(PROFILE_MOCK_STANDALONE)\n ? \"standalone\"\n : hasKosProfile(PROFILE_MOCK)\n ? \"on\"\n : undefined;\n const record = setting(\"kosRecord\", PROFILE_MOCK_RECORD);\n const fixtureServer = setting(\n \"kosFixtureServer\",\n PROFILE_MOCK_FIXTURE_SERVER\n );\n const fixture = setting(\"kosFixture\", PROFILE_MOCK_FIXTURE);\n const setups = setting(\"kosSetup\", PROFILE_MOCK_SETUP);\n\n if (mock === \"standalone\") {\n KosMock.configure({ standalone: true });\n } else if (mock === \"on\") {\n KosMock.enable();\n }\n if (record !== undefined) {\n KosMock.recorder.start({ name: record || undefined });\n }\n // `?kosFixtureServer` (bare = default URL) connects the out-of-band fixture\n // library; `?kosFixture=<name>` plays a fixture at boot and\n // `?kosSetup=<a,b>` installs setup modules — the standalone socket holds\n // its open until everything named here is in place.\n if (fixtureServer !== undefined) {\n KosMock.fixtures.useServer(fixtureServer || true);\n }\n const bootLoads: Promise<void>[] = [];\n if (fixture) {\n bootLoads.push(\n KosMock.fixtures\n .play(fixture)\n .then(() => undefined)\n .catch((error: any) =>\n KosLog.error(\n `KosMock: boot fixture \"${fixture}\" failed to load`,\n error?.message\n )\n )\n );\n }\n if (setups) {\n for (const name of setups.split(\",\").filter(Boolean)) {\n bootLoads.push(\n KosMock.setups\n .load(name)\n .then(() => undefined)\n .catch((error: any) =>\n KosLog.error(\n `KosMock: boot setup \"${name}\" failed to load`,\n error?.message\n )\n )\n );\n }\n }\n if (bootLoads.length > 0) {\n kosMockRegistry.bootGate = Promise.all(bootLoads).then(() => undefined);\n }\n}\n","// The always-present interception layer. BaseTransport wraps its raw socket\n// with installMockInterceptor at construction; the wrapper is inert until the\n// KosMock registry is enabled, then answers matched requests locally and lets\n// everything else through — which is what makes hybrid mocking against a live\n// device possible.\n//\n// Two wiring constraints this wrapper exists to satisfy:\n// - Both send paths (BaseTransport.send AND direct socket.socket.send calls\n// from subscription/offline-queue code) bottom out on the raw Transport's\n// send, so wrapping the raw Transport catches everything.\n// - BaseTransport.onOpen reassigns `this.socket = event.currentTarget`, so\n// open events must be re-fired with the wrapper as currentTarget or the\n// wrapper would be silently dropped after the first open.\nimport type { Transport } from \"../transport\";\nimport { KosMockRegistry, kosMockRegistry } from \"./mock-registry\";\n\nclass MockInterceptorTransport implements Transport {\n private messageHandler: ((ev: MessageEvent) => any) | null = null;\n private openHandler: ((ev: Event) => any) | null = null;\n private closeHandler: ((ev: CloseEvent) => any) | null = null;\n private errorHandler: ((ev: Event) => any) | null = null;\n private readonly unregisterInjector: () => void;\n\n constructor(\n private readonly inner: Transport,\n private readonly registry: KosMockRegistry\n ) {\n this.unregisterInjector = registry.registerInjector((frame) =>\n this.deliver(frame)\n );\n inner.onmessage = (ev) => {\n // Frames from the real socket run the transformer chain (in-flight\n // response patching), then deliver, then observe. deliver() applies\n // the same sequence to injected and mocked frames.\n if (typeof ev.data === \"string\") {\n this.deliver(ev.data);\n } else {\n this.messageHandler?.(ev);\n }\n };\n inner.onopen = () => {\n // Re-fire with the wrapper as currentTarget (see header comment).\n const ev = { currentTarget: this } as unknown as Event;\n this.openHandler?.(ev);\n };\n inner.onclose = (ev) => {\n this.unregisterInjector();\n this.closeHandler?.(ev);\n };\n inner.onerror = (ev) => this.errorHandler?.(ev);\n }\n\n /**\n * Every inbound frame's path to the app: transform → deliver → observe.\n * Observation runs last so a reacting observer's injections land AFTER the\n * frame that caused them, as a real backend's consequences would; observers\n * and the recorder see the transformed frame — what the app saw.\n */\n private deliver(frame: string): void {\n const transformed = this.registry.transformInboundFrame(frame);\n this.messageHandler?.({ data: transformed } as MessageEvent);\n this.registry.noteInboundFrame(transformed);\n }\n\n get onmessage() {\n return this.messageHandler;\n }\n set onmessage(handler: ((ev: MessageEvent) => any) | null) {\n this.messageHandler = handler;\n }\n\n get onopen() {\n return this.openHandler;\n }\n set onopen(handler: ((ev: Event) => any) | null) {\n this.openHandler = handler;\n }\n\n get onclose() {\n return this.closeHandler;\n }\n set onclose(handler: ((ev: CloseEvent) => any) | null) {\n this.closeHandler = handler;\n }\n\n get onerror() {\n return this.errorHandler;\n }\n set onerror(handler: ((ev: Event) => any) | null) {\n this.errorHandler = handler;\n }\n\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n this.registry.noteOutboundFrame(data);\n const owned = this.registry.handleOutboundFrame(data, {\n deliver: (frame) => this.deliver(frame),\n forward: () => this.inner.send(data),\n });\n if (!owned) {\n this.inner.send(data);\n }\n }\n\n close(): void {\n this.unregisterInjector();\n return this.inner.close();\n }\n\n addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void {\n this.inner.addEventListener(type, listener, options);\n }\n\n removeEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions\n ): void {\n this.inner.removeEventListener(type, listener, options);\n }\n\n dispatchEvent(event: Event): boolean {\n return this.inner.dispatchEvent(event);\n }\n}\n\n/** Wraps a raw transport with the KosMock interception layer. */\nexport function installMockInterceptor(\n inner: Transport,\n registry: KosMockRegistry = kosMockRegistry\n): Transport {\n return new MockInterceptorTransport(inner, registry);\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 { installMockInterceptor } from \"./mock/mock-interceptor\";\nimport { Transport } from \"./transport\";\nimport { WebSocketBridgeTransport } from \"./web-socket-transport-adapter\";\n\nexport enum WebSocketEvents {\n CONNECTED = `websocket.connected`,\n DISCONNECTED = `websocket.disconnected`,\n ERROR = `websocket.error`,\n MAX_RETRIES_EXCEEDED = `websocket.max_retries_exceeded`,\n RELOAD = `websocket.reload`,\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\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 // The KosMock interception layer wraps every raw transport; it is inert\n // until the registry is enabled.\n this.socket = installMockInterceptor(\n new Transport(`${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.socket.onerror = this.onError.bind(this);\n this.oldSend = this.socket.send;\n this.connectionEstablished = false;\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(event: CloseEvent) {\n const { code, reason, wasClean } = event;\n KosLog.warn(\n `WebSocket closed: code=${code}, reason=${\n reason || \"none\"\n }, wasClean=${wasClean}`\n );\n\n runInAction(() => {\n this.connectionEstablished = false;\n });\n\n // Publish disconnection event with details\n EventBus.publish(WebSocketEvents.DISCONNECTED, { code, reason, wasClean });\n\n if (this.shouldAttemptReconnection(code)) {\n this.onConnectionLost?.();\n } else {\n KosLog.info(\n `Not reconnecting due to close code ${code} (intentional close or configuration error)`\n );\n }\n }\n\n onError(ev: Event) {\n KosLog.error(`websocket error: `, ev);\n\n // Publish error event for application awareness\n // Note: onerror is typically followed by onclose, but this allows\n // faster detection of connection issues\n EventBus.publish(WebSocketEvents.ERROR, { event: ev });\n }\n\n /**\n * Determines whether to attempt reconnection based on WebSocket close code.\n * @param code - The WebSocket close code\n * @returns true if reconnection should be attempted\n */\n private shouldAttemptReconnection(code: number): boolean {\n // Close codes reference: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n switch (code) {\n case 1000: // Normal closure - server-initiated on loopback is still an outage, reconnect\n return true;\n case 1001: // Going away - server shutting down, reconnect with backoff\n return true;\n case 1002: // Protocol error - likely a bug, don't reconnect\n return false;\n case 1003: // Unsupported data - likely a bug, don't reconnect\n return false;\n case 1005: // No status received - abnormal, try to reconnect\n return true;\n case 1006: // Abnormal closure - connection dropped, reconnect\n return true;\n case 1007: // Invalid frame payload - likely a bug, don't reconnect\n return false;\n case 1008: // Policy violation - don't reconnect\n return false;\n case 1009: // Message too big - configuration issue, don't reconnect\n return false;\n case 1010: // Mandatory extension - negotiation failed, don't reconnect\n return false;\n case 1011: // Internal server error - temporary, reconnect with backoff\n return true;\n case 1012: // Service restart - reconnect with backoff\n return true;\n case 1013: // Try again later - reconnect with backoff\n return true;\n case 1014: // Bad gateway - reconnect with backoff\n return true;\n case 1015: // TLS handshake failure - configuration issue, don't reconnect\n return false;\n default:\n // For unknown codes, attempt reconnection\n return true;\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 this.oldSend.call(this.socket, data);\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._onerror = 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","// Fully-offline mode: a loopback Transport that \"opens\" without a server and\n// a BaseTransport flavor that uses it. TransportFactory selects\n// MockMessageTransport when `KosMock.standalone` is set (code or\n// `?kosMock=standalone`), so a demo app boots the complete KosCore lifecycle\n// with zero build flags and zero hardware.\n//\n// The socket itself is nearly inert: request interception already happened in\n// the interceptor wrapper (BaseTransport wraps every raw transport, this one\n// included), and in standalone mode the registry's default onUnmatched policy\n// is \"respond404\", so no request frame should ever reach this sink.\nimport { KosLog } from \"../../log\";\nimport type { Transport } from \"../transport\";\nimport { BaseTransport, TransportParams } from \"../base-message-transport\";\nimport { KOS_HTTP_REQUEST_TYPE, peekFrameType } from \"./mock-frames\";\nimport { kosMockRegistry } from \"./mock-registry\";\n\n/**\n * The frame that authorizes the transport. KosCore subscribes to this topic\n * and flips `transport.authorized`, which `whenReady()` gates on — delivering\n * it through the real receive path means standalone boot needs no\n * KOS_ALLOW_ANONYMOUS build flag. The auth handler's RELOAD side effect is\n * ignored outside the READY lifecycle state, so firing it at boot is safe.\n */\nconst LOGGED_IN_FRAME = `topic:/studioServer/auth/LOGGED_IN\\ntype:kos.broker.topic\\n\\n{}`;\n\nexport class StandaloneMockSocket implements Transport {\n onclose: ((ev: CloseEvent) => any) | null = null;\n onerror: ((ev: Event) => any) | null = null;\n onmessage: ((ev: MessageEvent) => any) | null = null;\n onopen: ((ev: Event) => any) | null = null;\n\n constructor(url: string) {\n KosLog.info(`KosMock standalone socket replacing ${url}`);\n // A macrotask, not a microtask: the open must fire after the surrounding\n // boot code has finished wiring handlers and subscriptions. When a boot\n // fixture is loading (?kosFixture=), also wait for its routes to exist —\n // otherwise the app's boot requests would 404 before the replay installs.\n setTimeout(async () => {\n await kosMockRegistry.bootGate;\n this.onopen?.({ currentTarget: this } as unknown as Event);\n if (kosMockRegistry.authorizeOnOpen) {\n this.onmessage?.({ data: LOGGED_IN_FRAME } as MessageEvent);\n }\n }, 0);\n }\n\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n // Broker subscribes and alias frames are expected and swallowed. A\n // request frame arriving here means the unmatched policy was overridden\n // to \"passthrough\" with no real socket behind it — that request will\n // hang, so say so.\n if (peekFrameType(data) === KOS_HTTP_REQUEST_TYPE) {\n KosLog.warn(\n `KosMock standalone: unmatched request reached the loopback socket and will hang — add a route or use onUnmatched: \"respond404\"`,\n String(data).split(\"\\n\", 2).join(\" \")\n );\n }\n }\n\n close(): void {\n // Nothing to close; reconnect logic never engages.\n }\n\n addEventListener(): void {\n // Not used by BaseTransport.\n }\n\n removeEventListener(): void {\n // Not used by BaseTransport.\n }\n\n dispatchEvent(): boolean {\n return true;\n }\n}\n\nexport class MockMessageTransport extends BaseTransport {\n protected RESPONSE_ID_HEADER: string;\n\n constructor({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n }: TransportParams) {\n super({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n Transport: StandaloneMockSocket,\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\";\nimport { KosMock } from \"./mock/mock-registry\";\nimport { MockMessageTransport } from \"./mock/standalone-mock-socket\";\n\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 (KosMock.standalone && !fos) {\n KosLog.warn(`Using KosMock standalone transport`);\n return new MockMessageTransport({\n host,\n port,\n protocol,\n alias,\n onConnectionEstablished,\n onConnectionLost,\n });\n }\n if (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 { action, computed, makeObservable, observable, reaction } from \"mobx\";\nimport { EventBus, EventCallback } from \"../../../common\";\n\nimport { abortableWhen } from \"../../util/abortable-when\";\nimport { getQueryParams } from \"../../util/get-query-params\";\nimport { KosLog } from \"../log\";\nimport { MessageTransport, WebSocketEvents } 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\n/**\n * Options for {@link IKosServiceTransport.whenReady}.\n *\n * @kosService core.transport\n * @kosApiLevel 23\n */\nexport interface KosTransportReadyOptions {\n /**\n * Cancels the readiness wait when it aborts. Without one the wait is\n * indefinite, which is correct for startup/lifecycle code but not for a\n * request working against a deadline.\n *\n * When the signal aborts, `whenReady` rejects with the signal's reason and\n * disposes the underlying reactive waiter.\n */\n signal?: AbortSignal;\n}\n\nexport interface KosSubscriptionParams {\n topic: string;\n callback: EventCallback;\n fos?: boolean;\n bridge?: boolean;\n destinationAddress?: string | null;\n explicitDestination?: boolean;\n}\nexport interface IKosServiceTransport {\n host: string;\n port: number;\n protocol: string;\n token?: string;\n alias?: string;\n connectionEstablished: boolean;\n authorized: boolean;\n socket?: MessageTransport;\n init(): IKosServiceTransport;\n subscribeTopic(params: KosSubscriptionParams): VoidFunction;\n whenReady(options?: KosTransportReadyOptions): Promise<IKosConnectionStatus>;\n fosSocket?: MessageTransport;\n}\n\nexport type KosCallback = (msg: IKosMessage) => void;\n\n// WebSocketEvents is imported from base-message-transport.ts\nexport { WebSocketEvents } from \"./base-message-transport\";\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 // Reconnection state (persists across BaseTransport re-creation in init())\n private reconnectAttempts = 0;\n private static readonly MAX_RECONNECT_ATTEMPTS = 10;\n private static readonly BASE_DELAY_MS = 1000;\n private static readonly MAX_DELAY_MS = 30000;\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 this.reconnectAttempts = 0;\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\n onConnectionLost: () => {\n log.error(`Connection Lost`);\n this.scheduleReconnect();\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 /**\n * Schedules a reconnect attempt using exponential backoff with jitter.\n * Counter persists across BaseTransport re-creation, so the cap actually\n * fires after MAX_RECONNECT_ATTEMPTS consecutive failures rather than\n * resetting on every new BaseTransport instance.\n */\n private scheduleReconnect() {\n if (this.reconnectAttempts >= WebSocketTransport.MAX_RECONNECT_ATTEMPTS) {\n KosLog.error(\n `Max reconnection attempts (${WebSocketTransport.MAX_RECONNECT_ATTEMPTS}) reached. Giving up.`\n );\n EventBus.publish(WebSocketEvents.MAX_RETRIES_EXCEEDED, {\n attempts: this.reconnectAttempts,\n });\n return;\n }\n\n const delay = this.calculateBackoffDelay();\n KosLog.debug(\n `Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts + 1}/${\n WebSocketTransport.MAX_RECONNECT_ATTEMPTS\n })`\n );\n\n setTimeout(() => {\n this.reconnectAttempts++;\n this.init();\n }, delay);\n }\n\n private calculateBackoffDelay(): number {\n const exponentialDelay = Math.min(\n WebSocketTransport.BASE_DELAY_MS * Math.pow(2, this.reconnectAttempts),\n WebSocketTransport.MAX_DELAY_MS\n );\n // ±25% jitter to prevent thundering herd on multi-client restarts\n const jitter = exponentialDelay * 0.25 * (Math.random() * 2 - 1);\n return Math.floor(exponentialDelay + jitter);\n }\n\n private _sendSubscriptionMessage(\n topic: string,\n type: \"subscribe\" | \"unsubscribe\",\n fos = false,\n bridge = false,\n connectionId?: string | null,\n explicitDestination = false\n ) {\n log.debug(`${type} to topic ${topic}`);\n let connId: string | null | undefined;\n if (explicitDestination) {\n connId = connectionId;\n } else {\n const params = getQueryParams();\n const connectionParam = (params as any)?.connId;\n connId =\n connectionId ??\n connectionParam ??\n (window as any)?.kosBridge?.(\"connId\");\n }\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 explicitDestination,\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 explicitDestination\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 explicitDestination\n );\n }\n };\n }\n\n /**\n * Resolves once the transport can carry requests: the socket (and the FOS\n * socket, when used) is connected and the connection is authorized.\n *\n * Pass `options.signal` to bound the wait. `connectionEstablished` flips back\n * to `false` on socket close, so an unbounded wait parks indefinitely while\n * the transport is down — callers with a deadline must supply a signal.\n *\n * @param options - See {@link KosTransportReadyOptions}.\n * @throws The signal's abort reason if it aborts before the transport is ready.\n */\n async whenReady(options?: KosTransportReadyOptions) {\n if (!this.webSocketSupported) {\n return {\n status: `not supported`,\n };\n }\n await abortableWhen(\n () =>\n !!this.socket?.connectionEstablished &&\n (!this.useFosTransport || !!this.fosSocket?.connectionEstablished) &&\n this.authorized,\n options?.signal\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 { EventBus } from \"../../../common\";\nimport * as AsyncEventBus from \"../../../common/events/async-event-bus\";\nimport { DependencyLifecycle } from \"../../types\";\nimport type { BaselineDependency } from \"../../types/service-response-store\";\nimport { ReplayStrategy } from \"../../types/service-response-store\";\n\nimport { getMessageBody } from \"../../util/kos-message-utils\";\nimport { FlowControlManager } from \"../decorators/kos-topic-handler-flow-control\";\nimport {\n checkWildcardPattern,\n parseWildcardSegment,\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 type { ServiceResponseStore } from \"./service-response-store\";\n\nexport class KosSubscriptionManager {\n private disposers: VoidFunction[] = [];\n private activatableDisposers: VoidFunction[] = [];\n private flowControllers = new Map<string, FlowControlManager>();\n private baselineDependencies = new Map<string, BaselineDependency>();\n private registeredTopics = new Set<string>();\n private onceTopics = new Set<string>();\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\n // Once topics are permanently consumed — never re-subscribe\n if (this.onceTopics.has(resolvedTopic)) {\n this.log.debug(`Skipping once topic (already fired): ${resolvedTopic}`);\n return;\n }\n\n // Skip if already subscribed to this resolved topic\n if (this.registeredTopics.has(resolvedTopic)) {\n this.log.debug(`Skipping duplicate subscription for ${resolvedTopic}`);\n return;\n }\n this.registeredTopics.add(resolvedTopic);\n\n // Track once topics so they persist across dispose cycles\n if (config.once) {\n this.onceTopics.add(resolvedTopic);\n }\n\n this.log.debug(`Resolved topic: ${topic} → ${resolvedTopic}`);\n\n // Register baseline dependency if specified\n if (config.requiresBaseline) {\n this.baselineDependencies.set(resolvedTopic, config.requiresBaseline);\n this.log.debug(\n `Registered baseline dependency for ${resolvedTopic}: ${config.requiresBaseline.path}`\n );\n }\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 // Remove activatable topics from the dedup set so they can re-register\n const subscriptions = this.modelData?.[SubscriptionHandlers] || {};\n for (const [topic, config] of Object.entries<any>(subscriptions)) {\n if (config.lifecycle === DependencyLifecycle.ACTIVATE) {\n const resolvedTopic = this.resolvePropKey(topic);\n this.registeredTopics.delete(resolvedTopic);\n }\n }\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 this.registeredTopics.clear();\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 explicitDestination: subscription.explicitDestination,\n });\n if (activatable) {\n this.activatableDisposers.push(socketSub);\n } else {\n this.disposers.push(socketSub);\n }\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 // Extract wildcard capture if applicable\n const wildcardCapture = this.extractWildcardCapture(\n resolvedTopic,\n payload,\n subscription\n );\n\n // Check baseline readiness if required\n const baselineReady = this.isBaselineReady(resolvedTopic);\n\n if (!this.model.isReady() || !baselineReady) {\n if (!baselineReady) {\n this.log.warn(\n `Baseline not ready for ${resolvedTopic}. Queuing message.`\n );\n } else {\n this.log.warn(\n `Model ${this.modelId} not ready. Queuing message for ${resolvedTopic}`\n );\n }\n\n const offlineHandler = () => {\n const body = getMessageBody(payload, subscription.skipParse);\n const data = subscription.transform(body);\n if (subscription.condition(data, this.modelData, payload)) {\n return this.callHandlerWithWildcard(\n subscription,\n data,\n wildcardCapture,\n payload\n );\n }\n return undefined;\n };\n this.offlineQueue.enqueue(offlineHandler, resolvedTopic, payload);\n } else {\n const body = getMessageBody(payload, subscription.skipParse);\n const data = subscription.transform(body);\n if (subscription.condition(data, this.modelData, payload)) {\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 return undefined;\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 || !checkWildcardPattern(resolvedTopic)) {\n return null;\n }\n\n const actualTopic = payload?.headers?.topic || \"\";\n return parseWildcardSegment(\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(\n resolvedTopic,\n config\n );\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 explicitDestination: config.explicitDestination,\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(\n eventSource\n )) {\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(\n `Failed to start flow processing for ${resolvedTopic}:`,\n error\n );\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 (\n config.condition &&\n !config.condition(processedData, this.modelData, processedData)\n ) {\n return undefined;\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 config.handler.call(\n this.modelData,\n processedData,\n processedData,\n this.modelData\n );\n this.offlineQueue.enqueue(\n offlineHandler,\n resolvedTopic,\n processedData\n );\n } else {\n // Execute the handler with flow-controlled data\n return config.handler.call(\n this.modelData,\n processedData,\n processedData,\n this.modelData\n );\n }\n } catch (error) {\n this.log.error(\n `Error in flow control handler for ${resolvedTopic}:`,\n error\n );\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 return undefined;\n };\n }\n\n private async retryHandler(\n config: any,\n data: any,\n originalError: any\n ): 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(\n `Retry attempt ${attempt}/${retryConfig.attempts} for handler`\n );\n await new Promise((resolve) =>\n setTimeout(resolve, retryConfig.backoffMs * attempt)\n );\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(\n `All retry attempts failed, throwing last error:`,\n lastError\n );\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 // ===== BASELINE-DELTA HELPERS =====\n\n /**\n * Get ServiceResponseStore from model\n * @private\n */\n private getResponseStore(): ServiceResponseStore | undefined {\n return (this.modelData as any).serviceResponses;\n }\n\n /**\n * Check if baseline is ready for a topic handler\n * @private\n */\n private isBaselineReady(topic: string): boolean {\n const baseline = this.baselineDependencies.get(topic);\n if (!baseline) return true; // No baseline required\n\n const store = this.getResponseStore();\n if (!store) {\n this.log.warn(\n `ServiceResponseStore not found for baseline check on topic: ${topic}`\n );\n return false;\n }\n\n const method = baseline.method || \"get\";\n const key = `${method.toUpperCase()}:${baseline.path}`;\n\n return store.has(key);\n }\n\n /**\n * Trigger smart queue flush with baseline temporal filtering\n * Called after baseline loads to replay queued events\n *\n * @param topic - Topic that had baseline dependency\n */\n public flushQueueForBaseline(topic: string): void {\n const baseline = this.baselineDependencies.get(topic);\n if (!baseline) {\n this.log.debug(`No baseline dependency for topic: ${topic}`);\n return;\n }\n\n const store = this.getResponseStore();\n if (!store) {\n this.log.warn(\n `ServiceResponseStore not found, falling back to standard flush`\n );\n this.offlineQueue.flush();\n return;\n }\n\n const method = baseline.method || \"get\";\n const temporal = store.getTemporalMetadataByPath(baseline.path, method);\n\n if (!temporal) {\n this.log.warn(\n `Baseline temporal metadata not found for ${baseline.path}, falling back to standard flush`\n );\n this.offlineQueue.flush();\n return;\n }\n\n const strategy = baseline.replayStrategy || ReplayStrategy.AFTER_REQUEST;\n\n this.log.info(\n `Flushing queue with strategy ${strategy} for topic: ${topic}`\n );\n this.log.debug(\n `Baseline timing - requested: ${temporal.requestedAt}, received: ${temporal.receivedAt}`\n );\n\n this.offlineQueue.flushWithStrategy(\n strategy,\n temporal.requestedAt,\n temporal.receivedAt\n );\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 { HttpRouteHandlers } from \"../decorators/kos-http-decorators\";\nimport { ServiceRequestHandlers } from \"../decorators/kos-service-request\";\nimport { ModelEffects, SubscriptionHandlers } from \"../decorators/propKeys\";\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] && modelData[HttpRouteHandlers].length > 0\n );\n}\n\nexport function hasServiceRequestHandlers(modelData: IKosDataModel): boolean {\n const prototype = Object.getPrototypeOf(modelData);\n return (\n !!prototype?.[ServiceRequestHandlers] &&\n Object.keys(prototype[ServiceRequestHandlers]).length > 0\n );\n}\n","import {\n CachedResponse,\n ResponseCacheConfig,\n ResponseRetention,\n} from \"../../types/service-response-store\";\n\n// ============================================================================\n// Zone 3: Low-level helper functions\n// ============================================================================\n\n/**\n * Checks TTL extension preconditions\n * @internal\n */\nfunction checkTTLExtensionPreconditions(config: ResponseCacheConfig): boolean {\n return (\n config.retention === ResponseRetention.TTL &&\n config.extendOnRefresh === true &&\n config.ttl !== undefined\n );\n}\n\n/**\n * Checks if response exists in cache\n * @internal\n */\nfunction hasExistingResponse(\n responses: Map<string, CachedResponse>,\n key: string\n): boolean {\n return responses.has(key);\n}\n\n/**\n * Checks if cached response has not expired\n * @internal\n */\nfunction isResponseNotExpired(cached: CachedResponse): boolean {\n return !cached.expiresAt || Date.now() < cached.expiresAt;\n}\n\n/**\n * Schedules cleanup timer for response\n * @internal\n */\nfunction scheduleCleanup(\n key: string,\n ttl: number,\n cleanupTimers: Map<string, NodeJS.Timeout>,\n deleteCallback: (key: string) => void\n): void {\n const timer = setTimeout(() => deleteCallback(key), ttl);\n cleanupTimers.set(key, timer);\n}\n\n/**\n * ServiceResponseStore manages keyed storage of service responses with flexible retention policies.\n *\n * Responses are stored by `{method}:{path}` key (e.g., 'GET:/api/ingredients')\n * and can be configured with different retention policies to control caching behavior.\n *\n * @example\n * const store = new ServiceResponseStore();\n *\n * // Store with TTL (replaces on each request)\n * store.set('GET:/api/status', statusData, {\n * retention: ResponseRetention.TTL,\n * ttl: 5 * 60 * 1000\n * });\n *\n * // Store with TTL extension (keeps existing data, extends TTL)\n * const stored = store.set('GET:/api/expensive', expensiveData, {\n * retention: ResponseRetention.TTL,\n * ttl: 5 * 60 * 1000,\n * extendOnRefresh: true\n * });\n * // stored === false if cache was extended, true if new data stored\n *\n * // Retrieve\n * const status = store.get('GET:/api/status');\n */\nexport class ServiceResponseStore {\n private responses = new Map<string, CachedResponse>();\n private retentionPolicies = new Map<string, ResponseCacheConfig>();\n private cleanupTimers = new Map<string, NodeJS.Timeout>();\n\n /**\n * Store a response with retention policy\n *\n * @param key - Storage key (typically `{method}:{path}`)\n * @param response - Response data to cache\n * @param config - Caching configuration (defaults to SINGLE retention)\n * @param requestedAt - When the request was sent (for temporal tracking)\n * @param receivedAt - When the response was received (for temporal tracking)\n * @returns true if response was stored, false if refresh extended existing TTL\n */\n set<T>(\n key: string,\n response: T,\n config: ResponseCacheConfig = { retention: ResponseRetention.SINGLE },\n requestedAt = Date.now(),\n receivedAt = Date.now()\n ): boolean {\n if (this.shouldExtendTTL(key, config)) {\n this.extendExistingTTL(key, config.ttl!);\n return false; // TTL extended\n }\n\n const cached = this.createCachedResponse(\n response,\n key,\n config,\n requestedAt,\n receivedAt\n );\n this.storeResponse(key, cached, config);\n return true; // New data stored\n }\n\n /**\n * Get response if not expired\n *\n * @param key - Storage key\n * @returns Response data or undefined if not found/expired\n */\n get<T = any>(key: string): T | undefined {\n const cached = this.responses.get(key);\n\n if (!cached) return undefined;\n\n // Check expiration\n if (cached.expiresAt && Date.now() > cached.expiresAt) {\n this.delete(key);\n return undefined;\n }\n\n return cached.data as T;\n }\n\n /**\n * Get response by path and method\n *\n * @param path - API path\n * @param method - HTTP method (defaults to 'get')\n * @returns Response data or undefined if not found/expired\n */\n getByPath<T = any>(path: string, method = \"get\"): T | undefined {\n return this.get(this.makeKey(path, method));\n }\n\n /**\n * Check if response exists and is not expired\n *\n * @param key - Storage key\n * @returns true if valid response exists\n */\n has(key: string): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Manually delete a response\n *\n * @param key - Storage key\n */\n delete(key: string): void {\n this.responses.delete(key);\n this.retentionPolicies.delete(key);\n\n const timer = this.cleanupTimers.get(key);\n if (timer) {\n clearTimeout(timer);\n this.cleanupTimers.delete(key);\n }\n }\n\n /**\n * Clear all responses for a path (all methods)\n *\n * @param path - API path to clear\n */\n clearPath(path: string): void {\n const keys = Array.from(this.responses.keys()).filter(\n (key) => this.extractPath(key) === path\n );\n\n keys.forEach((key) => this.delete(key));\n }\n\n /**\n * Clear all responses\n */\n clear(): void {\n this.cleanupTimers.forEach((timer) => clearTimeout(timer));\n this.responses.clear();\n this.retentionPolicies.clear();\n this.cleanupTimers.clear();\n }\n\n /**\n * Get count of cached responses\n */\n get size(): number {\n return this.responses.size;\n }\n\n /**\n * Check if a response should be cleaned up after handler completes\n *\n * @param key - Storage key\n * @returns true if response has IMMEDIATE retention policy\n */\n shouldCleanupAfterHandler(key: string): boolean {\n const config = this.retentionPolicies.get(key);\n return config?.retention === ResponseRetention.IMMEDIATE;\n }\n\n /**\n * Zone 2: Evaluates if TTL should be extended instead of replacing data\n */\n private shouldExtendTTL(key: string, config: ResponseCacheConfig): boolean {\n // Zone 3: Check configuration preconditions\n if (!checkTTLExtensionPreconditions(config)) {\n return false;\n }\n\n // Zone 3: Check if non-expired response exists\n if (!hasExistingResponse(this.responses, key)) {\n return false;\n }\n\n const existing = this.responses.get(key)!;\n return isResponseNotExpired(existing);\n }\n\n /**\n * Extend TTL for existing cached response\n */\n private extendExistingTTL(key: string, ttl: number): void {\n const existing = this.responses.get(key)!;\n existing.expiresAt = Date.now() + ttl;\n this.resetCleanupTimer(key, ttl);\n }\n\n /**\n * Zone 3: Reset cleanup timer for a cached response\n */\n private resetCleanupTimer(key: string, ttl: number): void {\n this.clearTimerIfExists(key);\n scheduleCleanup(key, ttl, this.cleanupTimers, (k) => this.delete(k));\n }\n\n /**\n * Clear cleanup timer if it exists\n */\n private clearTimerIfExists(key: string): void {\n const timer = this.cleanupTimers.get(key);\n if (timer) {\n clearTimeout(timer);\n this.cleanupTimers.delete(key);\n }\n }\n\n /**\n * Create cached response object with metadata\n */\n private createCachedResponse<T>(\n response: T,\n key: string,\n config: ResponseCacheConfig,\n requestedAt: number,\n receivedAt: number\n ): CachedResponse<T> {\n return {\n data: response,\n timestamp: receivedAt, // Backward compatibility\n requestedAt,\n receivedAt,\n path: this.extractPath(key),\n method: this.extractMethod(key),\n expiresAt: this.calculateExpiresAt(config),\n };\n }\n\n /**\n * Calculate expiration timestamp based on config\n */\n private calculateExpiresAt(config: ResponseCacheConfig): number | undefined {\n return config.retention === ResponseRetention.TTL && config.ttl\n ? Date.now() + config.ttl\n : undefined;\n }\n\n /**\n * Store response with retention policy\n */\n private storeResponse(\n key: string,\n cached: CachedResponse,\n config: ResponseCacheConfig\n ): void {\n this.responses.set(key, cached);\n this.retentionPolicies.set(key, config);\n this.applyRetentionPolicy(key, config);\n }\n\n /**\n * Zone 2: Configures retention policy for a stored response\n */\n private applyRetentionPolicy(key: string, config: ResponseCacheConfig): void {\n switch (config.retention) {\n case ResponseRetention.IMMEDIATE:\n // Note: IMMEDIATE cleanup is NOT done here automatically.\n // The ServiceRequestManager will call delete() after the handler completes\n // to ensure async handlers have access to the response during execution.\n // Check via shouldCleanupAfterHandler() to determine if cleanup is needed.\n break;\n\n case ResponseRetention.TTL:\n if (config.ttl) {\n // Zone 3: Schedule cleanup timer\n scheduleCleanup(key, config.ttl, this.cleanupTimers, (k) =>\n this.delete(k)\n );\n }\n break;\n\n case ResponseRetention.SINGLE:\n // Previous response for same path already handled by set()\n // No additional cleanup needed\n break;\n\n case ResponseRetention.PERMANENT:\n case ResponseRetention.MANUAL:\n // No automatic cleanup\n break;\n }\n }\n\n /**\n * Make storage key from path and method\n */\n private makeKey(path: string, method: string): string {\n return `${method.toUpperCase()}:${path}`;\n }\n\n /**\n * Extract path from storage key\n */\n private extractPath(key: string): string {\n return key.split(\":\", 2)[1] || key;\n }\n\n /**\n * Extract method from storage key\n */\n private extractMethod(key: string): string {\n return key.split(\":\", 2)[0] || \"get\";\n }\n\n /**\n * Get temporal metadata for a cached response\n * Used for baseline-delta race condition handling\n *\n * @param key - Storage key\n * @returns Temporal metadata or undefined if not found\n */\n getTemporalMetadata(\n key: string\n ): { requestedAt: number; receivedAt: number } | undefined {\n const cached = this.responses.get(key);\n if (!cached) return undefined;\n\n return {\n requestedAt: cached.requestedAt,\n receivedAt: cached.receivedAt,\n };\n }\n\n /**\n * Get temporal metadata by path and method\n *\n * @param path - API path\n * @param method - HTTP method (defaults to 'get')\n * @returns Temporal metadata or undefined if not found\n */\n getTemporalMetadataByPath(\n path: string,\n method = \"get\"\n ): { requestedAt: number; receivedAt: number } | undefined {\n return this.getTemporalMetadata(this.makeKey(path, method));\n }\n\n /**\n * Cleanup expired responses (called periodically if needed)\n */\n cleanup(): void {\n const now = Date.now();\n const expired = Array.from(this.responses.entries())\n .filter(([_, cached]) => cached.expiresAt && now > cached.expiresAt)\n .map(([key]) => key);\n\n expired.forEach((key) => this.delete(key));\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 { ServiceRequestManager } from \"./kos-service-request-manager\";\nimport { KosSubscriptionManager } from \"./kos-subscription-manager\";\nimport { createTaggedLogger } from \"./logger-utils\";\nimport {\n hasHttpRouteHandlers,\n hasModelEffects,\n hasServiceRequestHandlers,\n hasSubscriptionHandlers,\n} from \"./model-introspection-utils\";\nimport { ServiceResponseStore } from \"./service-response-store\";\n\ninterface KosModelComponents {\n fsm: KosFSMManager;\n offlineQueue: KosOfflineQueue;\n subscriptionManager?: KosSubscriptionManager;\n effectManager?: KosEffectManager;\n onlineLifecycleManager?: KosOnlineLifecycleManager;\n httpRouteManager?: KosHttpRouteManager;\n serviceResponseStore: ServiceResponseStore;\n serviceRequestManager?: ServiceRequestManager;\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 // Always create ServiceResponseStore (needed for response caching)\n const serviceResponseStore = new ServiceResponseStore();\n\n // Attach store to modelData so getServiceResponse() can access it\n (modelData as any).serviceResponses = serviceResponseStore;\n\n const components: KosModelComponents = {\n fsm,\n offlineQueue,\n serviceResponseStore,\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 if (hasServiceRequestHandlers(modelData)) {\n components.serviceRequestManager = new ServiceRequestManager(\n modelData,\n serviceResponseStore\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, initializeStateMachine } 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\";\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\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\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport interface KosCreationContext extends IKosModelLogger {\n kosContext: KosContextBean;\n [key: string]: any;\n}\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport interface IKosDataModel\n extends IKosModelLifecycle,\n IKosVisitorHost<IKosDataModel> {\n id: string;\n getDependencies?(): void;\n getChildren?: () => IKosDataModel[];\n update?: (values) => Promise<void>;\n /**\n * @kosApiLevel 5\n */\n toJSON?: () => object;\n}\n\n/**\n * @kosService core.companion\n * @kosApiLevel 2\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\n/**\n * @kosService core.container-aware\n * @kosApiLevel 2\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\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport interface ReloadAware {\n reload: () => Promise<void>;\n /**\n * @kosApiLevel 20\n */\n readonly isReloading?: boolean;\n}\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\n */\nexport interface UnloadAware {\n unload: () => Promise<void>;\n}\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\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 onlineLifecycleManager?: KosOnlineLifecycleManager;\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 private _isLoadExecuting: boolean;\n offlineQueue: KosOfflineQueue;\n subscriptionManager?: KosSubscriptionManager;\n effectManager?: KosEffectManager;\n httpRouteManager?: KosHttpRouteManager;\n onlineLifecycleManager?: KosOnlineLifecycleManager;\n serviceResponses: any; // ServiceResponseStore\n serviceRequestManager?: any; // ServiceRequestManager\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._isLoadExecuting = 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 this.serviceResponses = components.serviceResponseStore;\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 if (components.serviceRequestManager) {\n this.serviceRequestManager = components.serviceRequestManager;\n }\n makeAutoObservable(this, {\n fsm: false,\n effectManager: false,\n subscriptionManager: false,\n onlineLifecycleManager: false,\n serviceRequestManager: false,\n serviceResponses: 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 // Execute service requests for ACTIVATE lifecycle before user's activate() method\n await this.serviceRequestManager?.executeForLifecycle(\n DependencyLifecycle.ACTIVATE\n );\n\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.activate?.(context);\n\n // Initialize FSM if configured for ACTIVATE lifecycle\n this.initializeStateMachineForLifecycle(DependencyLifecycle.ACTIVATE);\n\n log.debug(\n `Model ${this.modelTypeName} with id ${this.modelId} subscribing to all topics`\n );\n this.subscriptionManager?.registerAll(DependencyLifecycle.ACTIVATE);\n\n // Create companions configured for ACTIVATE lifecycle\n this.createLifecycleCompanions(DependencyLifecycle.ACTIVATE);\n\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\n // Execute service requests for READY lifecycle before user's ready() method\n await this.serviceRequestManager?.executeForLifecycle(\n DependencyLifecycle.READY\n );\n\n const context = KosContextManager.getContext(this.modelId);\n await this.modelData?.ready?.(context);\n\n this.offlineQueue.flush();\n\n // Initialize FSM if configured for READY lifecycle\n this.initializeStateMachineForLifecycle(DependencyLifecycle.READY);\n\n this.subscriptionManager?.registerAll(DependencyLifecycle.READY);\n\n // Create companions configured for READY lifecycle\n this.createLifecycleCompanions(DependencyLifecycle.READY);\n\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 // Check if already loaded\n if (this.fsm.current === KosModelState.LOADED) {\n log.debug(`Model ${modelTypeName} with id ${modelId} already loaded`);\n return;\n }\n\n // Prevent concurrent execution\n if (this._isLoadExecuting) {\n log.debug(\n `Model ${modelTypeName} with id ${modelId} is currently executing load`\n );\n return;\n }\n\n this._isLoadExecuting = true;\n\n try {\n log.debug(`Loading model ${modelTypeName} with id ${modelId}`);\n\n await executeDependentModelLifecycle(this, DependencyLifecycle.LOAD);\n\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 // Execute service requests for LOAD lifecycle before user's load() method\n await this.serviceRequestManager?.executeForLifecycle(\n DependencyLifecycle.LOAD\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 // Initialize FSM if configured for LOAD lifecycle\n this.initializeStateMachineForLifecycle(DependencyLifecycle.LOAD);\n\n this.subscriptionManager?.registerAll(DependencyLifecycle.LOAD);\n this.httpRouteManager?.registerAll();\n this.effectManager?.setup();\n\n // Create companions configured for LOAD lifecycle\n this.createLifecycleCompanions(DependencyLifecycle.LOAD);\n } catch (e) {\n log.error(`Model ${modelId} failed to load`, e);\n throw e;\n } finally {\n this._isLoadExecuting = false;\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\n // Cleanup FSM state\n if (this.modelData) {\n const modelData = this.modelData as any;\n modelData._fsmInitialized = false;\n if (modelData._fsmConfig) {\n const stateProperty =\n modelData._fsmOptions?.stateProperty || \"currentState\";\n modelData[stateProperty] = undefined;\n }\n if (modelData.stateHistory) {\n modelData.stateHistory = [];\n }\n }\n\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 // Execute service requests for INIT lifecycle before user's init() method\n await this.serviceRequestManager?.executeForLifecycle(\n DependencyLifecycle.INIT\n );\n\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 // Initialize FSM if configured for INIT lifecycle\n this.initializeStateMachineForLifecycle(DependencyLifecycle.INIT);\n\n this.registerSubscribers(DependencyLifecycle.INIT);\n\n // Create companions configured for INIT lifecycle\n this.createLifecycleCompanions(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 /**\n * Initialize the state machine for a specific lifecycle phase.\n * Called from lifecycle hooks (init, load, ready, activate).\n * @internal\n */\n initializeStateMachineForLifecycle(lifecycle: DependencyLifecycle) {\n if (this.modelData) {\n initializeStateMachine(this.modelData, lifecycle);\n }\n }\n\n /**\n * Creates lifecycle-deferred companion models at the appropriate phase.\n * Called from lifecycle hooks (init, load, ready, activate, online).\n * @internal\n */\n private createLifecycleCompanions(lifecycle: DependencyLifecycle) {\n // Pass empty options object - companions get their data from parent\n this.modelManager.createLifecycleCompanions(this, {}, 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 // Create companions configured for ONLINE lifecycle\n this.createLifecycleCompanions(DependencyLifecycle.ONLINE);\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","// model-instantiator.ts\n\nimport type { DependencyLifecycle } from \"../types\";\nimport { enrichError } from \"../util/model-error-utils\";\nimport { logModelInstantiationError } from \"../util/error-logger\";\nimport { KosCompanionInstantiator } from \"./companion-instantiator\";\nimport { OptionsRequired } from \"./decorators/propKeys\";\nimport { KosModel, type IKosDataModel, type IKosModel } from \"./kosModel\";\nimport { KosLog } from \"./log\";\nimport type { KosModelCacheHandler } from \"./model-cache\";\nimport type { IKosRegistry } from \"./types\";\n\nconst log = KosLog.createLogger({ name: \"kos-model-instantiator\" });\n\n/**\n * Responsible for creating KOS model instances.\n * Delegates companion model creation to KosCompanionInstantiator.\n */\nexport class KosModelInstantiator {\n private companionInstantiator: KosCompanionInstantiator;\n\n constructor(\n private registry: IKosRegistry,\n private cache: KosModelCacheHandler\n ) {\n this.companionInstantiator = new KosCompanionInstantiator(\n registry,\n cache,\n this.createModelInstance.bind(this)\n );\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 const errorMessage = `No model registered for type ${typeId}`;\n log.error(errorMessage, {\n modelType: typeId,\n requestedId: id,\n providedOptions: options,\n availableModelTypes: Object.keys(this.registry.models),\n });\n throw enrichError(new Error(errorMessage), {\n modelType: typeId,\n modelId: id,\n operation: \"model instantiation - registry lookup\",\n options,\n metadata: {\n availableModelTypes: Object.keys(this.registry.models),\n },\n });\n }\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 // Validate options requirement before attempting creation\n const hasOptions = options && Object.keys(options).length > 0;\n const modelClass = modelRegistry.class || modelRegistry.create;\n const requiresOptions = modelClass?.prototype?.[OptionsRequired] === true;\n\n if (requiresOptions && !hasOptions) {\n const error = new Error(\n `Model ${typeId} requires options but none were provided`\n );\n logModelInstantiationError(error, {\n modelType: typeId,\n options,\n registryId: this.registry.alias || \"unknown\",\n });\n throw enrichError(error, {\n modelType: typeId,\n modelId,\n operation: \"model instantiation - options validation\",\n options,\n metadata: { requiresOptions: true, hasOptions: false },\n });\n }\n\n try {\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 // Create companions without lifecycle specified (defaults to INIT phase)\n this._createCompanionModels(model, options);\n } catch (error) {\n logModelInstantiationError(error, {\n modelType: typeId,\n options,\n registryId: this.registry.alias || \"unknown\",\n });\n throw enrichError(error, {\n modelType: typeId,\n modelId,\n operation: \"model instantiation\",\n options,\n });\n }\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 /**\n * Creates companion models for a parent model, optionally filtered by lifecycle phase.\n * Delegates to KosCompanionInstantiator for all companion-related logic.\n *\n * @param model The parent model\n * @param options Options to pass to companion constructors\n * @param lifecycle Optional lifecycle filter - only create companions matching this phase\n */\n createCompanionModels(\n model: IKosModel,\n options: Record<string, any>,\n lifecycle?: DependencyLifecycle\n ) {\n this.companionInstantiator.createCompanionModels(model, options, lifecycle);\n }\n\n /**\n * @deprecated Use createCompanionModels instead\n * @private\n */\n private _createCompanionModels(\n model: IKosModel,\n options: Record<string, any>\n ) {\n this.createCompanionModels(model, options);\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 {\n DependencyLifecycle,\n type BaseKosModelRegistrationBean,\n} 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 { clearModelHookCacheEntry } from \"./model/model-hook-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 this.dependencies.removeAll(model.modelId);\n clearModelHookCacheEntry(model.modelId);\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 * Creates lifecycle-deferred companion models for a parent model.\n * Used by KosModel lifecycle hooks to instantiate companions at the appropriate phase.\n *\n * @param model The parent model\n * @param options Options to pass to companion constructors\n * @param lifecycle The lifecycle phase to create companions for\n * @internal\n */\n createLifecycleCompanions(\n model: IKosModel,\n options: Record<string, any>,\n lifecycle: DependencyLifecycle\n ) {\n this.instantiator.createCompanionModels(model, options, lifecycle);\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 FAILED = `failed`,\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\n/** Logs a lifecycle step's rejection before re-throwing it. */\nconst reportFailure = async <T>(\n step: KosCoreState,\n run: () => Promise<T>\n): Promise<T> => {\n try {\n return await run();\n } catch (error) {\n // Interpolated: an Error passed as a log argument serializes to `{}`.\n const detail =\n error instanceof Error\n ? error.stack ?? `${error.name}: ${error.message}`\n : String(error);\n log.error(`KOS Core lifecycle step \"${step}\" failed. ${detail}`);\n throw error;\n }\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 // Without this, a rejected invoke leaves the machine parked in the state\n // that threw, indistinguishable from one still running.\n const failed = transition(\n `error`,\n KosCoreState.FAILED,\n action(() => {\n runInAction(() => {\n core.status = KosCoreState.FAILED;\n });\n })\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 () => reportFailure(KosCoreState.INITIALIZING, () => core.init!()),\n transition(`done`, KosCoreState.INITIALIZED),\n failed\n ),\n [KosCoreState.INITIALIZED]: state(immediate(KosCoreState.LOADING)),\n [KosCoreState.LOADING]: invoke(\n () => reportFailure(KosCoreState.LOADING, () => core.load!()),\n transition(`done`, KosCoreState.LOADED),\n failed\n ),\n [KosCoreState.LOADED]: state(\n immediate(KosCoreState.READYING),\n transition(KosCoreEvents.UNLOAD, KosCoreState.UNLOADING)\n ),\n\n [KosCoreState.READYING]: invoke(\n () => reportFailure(KosCoreState.READYING, () => core.ready!()),\n transition(\n `done`,\n KosCoreState.READY,\n action(() => {\n runInAction(() => {\n core.status = KosCoreState.READY;\n });\n })\n ),\n failed\n ),\n [KosCoreState.RELOADING]: invoke(\n () => reportFailure(KosCoreState.RELOADING, () => core.reload!()),\n transition(`done`, KosCoreState.LOADING),\n failed\n ),\n [KosCoreState.FAILED]: state(),\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 { DependencyLifecycle } from \"../types\";\nimport { CompanionParentModel } from \"./decorators\";\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 { SelfManagedReload } from \"./decorators/kos-reload-aware\";\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 isSelfManagedReload = (model: any): boolean => !!model[SelfManagedReload];\n\nconst isUnloadable = (model: any): model is UnloadAware =>\n typeof model.unload === \"function\";\nexport interface IKosCoreLifecycle {\n /**\n * Starts the lifecycle state machine. Idempotent; called by `create()` once\n * the core has a model manager.\n */\n startLifecycle(): void;\n\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 private lifecycleStarted = false;\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.DISCONNECTED, async () => {\n // Every subscription on the dead socket is gone server-side — the\n // framework's subscribe frames only bind to that specific connection.\n // Cycle every model through offline() (which disposes its @kosTopicHandler\n // subs) and dispose its lifecycle manager. No subs will survive.\n await Promise.allSettled(\n this.modelManager.models.map(async (model) => {\n try {\n await model.offline?.();\n } catch (e) {\n log.error(`model ${model.modelId} offline() threw:`, e);\n }\n model.onlineLifecycleManager?.dispose();\n })\n );\n this.fsmService.service.send(KosCoreEvents.GO_OFFLINE);\n });\n\n EventBus.subscribe(WebSocketEvents.CONNECTED, async () => {\n await this.whenReady();\n // Re-register every model's lifecycle manager and run online() so both\n // client-side EventBus entries and server-side subscribe frames are\n // recreated over the fresh WebSocket. Must run before GO_ONLINE so\n // lifecycle managers are present to receive /kosCore/online.\n await Promise.allSettled(\n this.modelManager.models.map(async (model) => {\n model.onlineLifecycleManager?.register();\n try {\n await model.online?.();\n } catch (e) {\n log.error(`model ${model.modelId} online() threw:`, e);\n }\n })\n );\n this.fsmService.service.send(KosCoreEvents.GO_ONLINE);\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 }\n\n startLifecycle() {\n if (this.lifecycleStarted) {\n return;\n }\n this.lifecycleStarted = true;\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 if (isSelfManagedReload(model.modelData)) {\n log.info(`skipping self-managed model ${model.modelId}`);\n continue;\n }\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 if (isSelfManagedReload(model.modelData)) {\n log.info(`skipping self-managed model ${model.modelId}`);\n continue;\n }\n log.warn(`reloading model ${model.modelId}`);\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 log.debug(\"KOS Transport ready. Preloading models\");\n\n if (!this.modelManager) {\n throw new Error(\n \"KOS Core reached ready() with no model manager. Its lifecycle was \" +\n \"started without a registry.\"\n );\n }\n\n const promises = this.modelManager.preloadedModels.map((model) => {\n return {\n modelId: model.modelId,\n model,\n promise: model.whenReady!(),\n };\n });\n log.debug(`Preloaded ${promises.length} models`);\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 // Extract lifecycle from companion model decorator if it's a string type\n let lifecycle: DependencyLifecycle | undefined;\n if (typeof companion === \"string\") {\n const companionModelReg = registry.models[companion];\n if (companionModelReg?.class) {\n const companionMetadata =\n companionModelReg.class.prototype[CompanionParentModel];\n lifecycle = companionMetadata?.lifecycle;\n }\n }\n registry.companionModels[key].push({ type: companion, lifecycle });\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 // ready() dereferences the model manager, so the machine cannot start\n // before it is attached.\n instance.startLifecycle();\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 // Inert until create() starts its lifecycle: callers reading isReady\n // reach here before any registry exists.\n window.KosCore = new this(data?.connectionAlias) as any;\n this._instance = window.KosCore as any;\n }\n return this._instance;\n }\n}\n","import { 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 * @kosService core.kos-model\n * @kosApiLevel 2\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 { registerExtensionPoint } from \"../core/extension\";\nimport { KosLog } from \"../core/log\";\n\n/**\n * @kosService core.utils\n * @kosApiLevel 12\n */\nexport const EXTENSION_FEATURE_FLAG_RESOLVER = \"featureFlagResolver\";\n/**\n * @kosService core.utils\n */\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>;\n/**\n * @kosService core.utils\n * @kosApiLevel 12\n */\nexport const LOADER_FEATURE_FLAG = \"kos.loader.featureFlag\";\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const KosFeatureFlags = window.KosFeatureFlags;\n","import { KosCore } from \"../core/kosCore\";\nimport { IKosDataModel } from \"../core/kosModel\";\nimport { ModelFactory } from \"../types/model\";\n\n/**\n * @kosService core.kos-model\n * @kosApiLevel 2\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","/**\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 {\n KosFetchOptions,\n Response as KosFetchResponse,\n} 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 *\n * @kosService core.service-request\n * @kosApiLevel 2\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 * Note: Native fetch is cast to this type in mock mode - not all body types are compatible.\n */\ntype FetchType = (\n url: string,\n options?: KosFetchOptions\n) => Promise<KosFetchResponse>;\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 timeout,\n signal,\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 timeout,\n signal,\n destinationAddress: destinationAddressOverride,\n });\n\n try {\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:\n | KosServiceResponse<ResponseType>\n | undefined\n | null = await response.json();\n\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(`Request timed out while deleting model`);\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(`Request was cancelled while deleting model`);\n }\n }\n throw error;\n }\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 Partial<AbortableRequest>;\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 {\n ordered,\n studio,\n fos,\n destinationAddress,\n bridge,\n timeout,\n signal,\n }: CommonParams\n) => {\n if (timeout) {\n options.timeout = timeout;\n }\n if (signal) {\n options.signal = signal;\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 signal,\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 signal,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || url;\n\n try {\n const response = await _fetch(resolvedUrl, options);\n\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined | null;\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 ?? undefined\n );\n }\n\n const configResponse: KosServiceResponse<Response[]> | undefined | null =\n await response.json();\n\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(`Request timed out while retrieving models`);\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(`Request was cancelled while retrieving models`);\n }\n }\n throw error;\n }\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 signal,\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 signal,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || url;\n log.debug(`resolvedUrl: ${resolvedUrl}`);\n try {\n const response = await _fetch(resolvedUrl, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined | null;\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 ?? undefined\n );\n }\n const configResponse: KosServiceResponse<Response> | undefined | null =\n await response.json();\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(`Request timed out while retrieving model`);\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(`Request was cancelled while retrieving model`);\n }\n }\n throw error;\n }\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 signal,\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 signal,\n destinationAddress: destinationAddressOverride,\n });\n\n const resolvedUrl = urlOverride || `${url}/${id}`;\n try {\n const response = await _fetch(resolvedUrl, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined | null;\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 ?? undefined\n );\n }\n const configResponse: KosServiceResponse<Response> | undefined | null =\n await response.json();\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(\n `Request timed out while retrieving model by ID`\n );\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(\n `Request was cancelled while retrieving model by ID`\n );\n }\n }\n throw error;\n }\n };\n\ninterface Orderable {\n ordered: boolean;\n}\n\ninterface TimeoutAware {\n timeout: number;\n}\n\ninterface AbortableRequest {\n signal: AbortSignal;\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 Partial<AbortableRequest> {\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 Partial<AbortableRequest> {\n model?: Request;\n id: string;\n urlOverride?: string;\n}\n\n/**\n * @kosService core.service-request\n * @kosApiLevel 2\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 signal,\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 signal,\n destinationAddress: destinationAddressOverride,\n });\n\n try {\n const response = await _fetch(urlOverride || url, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined | null;\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 ?? undefined\n );\n }\n const configResponse: KosServiceResponse<any> | undefined | null =\n await response.json();\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(`Request timed out while adding model`);\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(`Request was cancelled while adding model`);\n }\n }\n throw error;\n }\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 signal,\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 signal,\n destinationAddress: destinationAddressOverride,\n });\n\n try {\n const response = await _fetch(urlOverride || `${url}/${id}`, options);\n if (!response.ok) {\n let payload: KosServiceResponse<Response> | undefined | null;\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 ?? undefined\n );\n }\n const configResponse: KosServiceResponse<any> | undefined | null = // <--- KosServiceResponse<any> should be KosServiceResponse<Request>...\n await response.json();\n return configResponse ?? undefined;\n } catch (error) {\n if (error instanceof DOMException) {\n if (error.name === \"TimeoutError\") {\n throw new FetchError(`Request timed out while modifying model`);\n }\n if (error.name === \"AbortError\") {\n throw new FetchError(`Request was cancelled while modifying model`);\n }\n }\n throw error;\n }\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 *\n * @deprecated Use `@kosServiceRequest` with `createClient`, which is typed\n * from the OpenAPI paths and carries the response context.\n * @kosService core.service-request\n * @kosApiLevel 2\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: FetchType = mock ? (fetch as FetchType) : 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\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const getKosSessionKey = (): string => `kos-${_sessionKey}`;\n\n/**\n * @kosService core.utils\n * @kosApiLevel 2\n */\nexport const isLocalRefId = (id?: string): boolean =>\n !!id && !id.includes(\"VM_SERVICE\") && id.startsWith(getKosSessionKey());\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 {\n IKosBaseContainer,\n type EvictionStrategy,\n} 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\n /** SAFETY NET: Maximum capacity before eviction */\n maxCapacity?: number;\n\n /** Eviction strategy when maxCapacity is exceeded */\n evictionStrategy?: EvictionStrategy;\n\n /** Number of items to evict when capacity exceeded */\n evictionBatchSize?: number;\n\n /** Custom eviction filter for 'custom' strategy */\n customEvictionFilter?: (models: T[]) => 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\n // Capacity management fields\n private _maxCapacity?: number;\n private _evictionStrategy: EvictionStrategy;\n private _evictionBatchSize: number;\n private _insertionOrder: string[] = []; // For FIFO strategy\n private _accessTimes?: Map<string, number>; // For LRU strategy\n private _customEvictionFilter?: (models: T[]) => T[];\n\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\n // Initialize capacity management\n this._maxCapacity = options?.maxCapacity;\n this._evictionStrategy = options?.evictionStrategy || \"fifo\";\n this._evictionBatchSize =\n options?.evictionBatchSize ??\n Math.max(10, Math.ceil((options?.maxCapacity ?? 100) * 0.1));\n this._customEvictionFilter = options?.customEvictionFilter;\n\n // Initialize LRU access tracking if needed\n if (this._evictionStrategy === \"lru\" && this._maxCapacity) {\n this._accessTimes = observable.map(new Map());\n }\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\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 /**\n * Add a data object to the container (Zone 2: Workflow orchestration)\n *\n * @param model - The data object to add\n * @param defer - If true, skip incrementing revision (for batch operations)\n */\n addModel(model: T, defer?: boolean) {\n // Zone 2: High-level workflow orchestration\n const observableData = this._ensureObservable(model);\n this._cleanupExistingDisposer(model.id);\n this._persistData(observableData);\n this._trackDataMetadata(observableData);\n this._enforceCapacityLimits();\n this._configureDataMonitoring(observableData);\n\n if (!defer) {\n this.increment();\n }\n }\n\n /**\n * Ensure data is observable (Zone 3)\n * @private\n */\n private _ensureObservable(model: T): T {\n return isObservable(model) ? model : observable.object(model);\n }\n\n /**\n * Clean up existing disposer if present (Zone 3)\n * @private\n */\n private _cleanupExistingDisposer(id: string | undefined): void {\n if (!id) return;\n\n const disposer = this._disposerMap.get(id);\n if (disposer) {\n disposer();\n this._disposerMap.delete(id);\n }\n }\n\n /**\n * Persist data to container storage (Zone 3)\n * @private\n */\n private _persistData(data: T): void {\n this._data.set(data.id || \"\", data);\n }\n\n /**\n * Track data metadata for capacity management (Zone 3)\n * @private\n */\n private _trackDataMetadata(data: T): void {\n if (!this._maxCapacity) return;\n\n // Track insertion order for FIFO eviction\n this._insertionOrder.push(data.id || \"\");\n\n // Track initial access time for LRU eviction\n if (this._accessTimes) {\n this._accessTimes.set(data.id || \"\", Date.now());\n }\n }\n\n /**\n * Enforce capacity limits and trigger eviction if needed (Zone 3)\n * @private\n */\n private _enforceCapacityLimits(): void {\n if (!this._maxCapacity) return;\n\n if (this._data.size > this._maxCapacity) {\n this._evictModels();\n }\n }\n\n /**\n * Configure MobX observers for data property changes (Zone 3)\n * @private\n */\n private _configureDataMonitoring(data: T): void {\n const disposer = observe(data, (change) => {\n if (\n Object.values(this._optionsMap || {}).includes(change.name as keyof T)\n ) {\n this.increment();\n }\n });\n this._disposerMap.set(data.id || \"\", disposer);\n }\n\n removeModel(id: string) {\n this._data.delete(id);\n\n // Clean up tracking data structures\n const orderIndex = this._insertionOrder.indexOf(id);\n if (orderIndex !== -1) {\n this._insertionOrder.splice(orderIndex, 1);\n }\n\n if (this._accessTimes) {\n this._accessTimes.delete(id);\n }\n\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 const model = this._data.get(id);\n\n // Track access time for LRU eviction strategy\n if (model && this._accessTimes) {\n this._accessTimes.set(id, Date.now());\n }\n\n return model;\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 /**\n * SAFETY NET: Evict data models when capacity is exceeded (Zone 2: Workflow orchestration)\n * Logs all evictions at WARNING level for debugging.\n * Note: Data models are not destroyed (no lifecycle), only removed from container.\n * @private\n */\n private _evictModels() {\n if (!this._maxCapacity) return;\n\n const overCapacity = this._data.size - this._maxCapacity;\n if (overCapacity <= 0) return;\n\n const toEvict = Math.min(this._evictionBatchSize, overCapacity);\n\n // Zone 2: Workflow orchestration\n this._logDataCapacityWarning(toEvict);\n const idsToEvict = this._selectDataForEviction(toEvict);\n this._removeEvictedData(idsToEvict);\n this._logDataEvictionComplete(idsToEvict.length);\n }\n\n /**\n * Log capacity exceeded warning for data container (Zone 3)\n * @private\n */\n private _logDataCapacityWarning(toEvict: number): void {\n log.info(\n `Data container capacity exceeded (${this._data.size}/${this._maxCapacity}). ` +\n `Evicting ${toEvict} items using ${this._evictionStrategy} strategy. ` +\n `This may indicate missing cleanup handlers or data inconsistency.`\n );\n }\n\n /**\n * Select data for eviction based on strategy (Zone 3)\n * @private\n */\n private _selectDataForEviction(count: number): string[] {\n switch (this._evictionStrategy) {\n case \"fifo\":\n return this._selectFifoData(count);\n case \"lru\":\n return this._selectLruData(count);\n case \"custom\":\n return this._selectCustomData(count);\n default:\n return this._selectFifoData(count);\n }\n }\n\n /**\n * Select oldest data IDs for FIFO eviction (Zone 3)\n * @private\n */\n private _selectFifoData(count: number): string[] {\n const ids: string[] = [];\n for (let i = 0; i < count && this._insertionOrder.length > 0; i++) {\n const oldestId = this._insertionOrder.shift();\n if (!oldestId) continue;\n\n if (this._data.has(oldestId)) {\n ids.push(oldestId);\n }\n }\n return ids;\n }\n\n /**\n * Select least recently used data IDs for LRU eviction (Zone 3)\n * @private\n */\n private _selectLruData(count: number): string[] {\n const ids: string[] = [];\n\n if (this._accessTimes) {\n const sorted = Array.from(this._accessTimes.entries())\n .sort((a, b) => a[1] - b[1])\n .slice(0, count);\n\n sorted.forEach(([id]) => {\n if (this._data.has(id)) {\n ids.push(id);\n }\n });\n }\n\n return ids;\n }\n\n /**\n * Select data using custom filter for eviction (Zone 3)\n * @private\n */\n private _selectCustomData(count: number): string[] {\n if (this._customEvictionFilter) {\n const candidates = this._customEvictionFilter(this.data);\n return candidates.slice(0, count).map((item) => item.id);\n }\n\n log.error(\n \"Custom eviction strategy specified but no customEvictionFilter provided. \" +\n \"Falling back to FIFO.\"\n );\n\n return this._selectFifoData(count);\n }\n\n /**\n * Remove evicted data items (Zone 3)\n * @private\n */\n private _removeEvictedData(ids: string[]): void {\n ids.forEach((id) => {\n const item = this._data.get(id);\n log.info(`Evicting data item: ${id}`, {\n itemId: id,\n itemType: item ? item.constructor?.name : \"unknown\",\n strategy: this._evictionStrategy,\n });\n\n this.removeModel(id);\n });\n }\n\n /**\n * Log eviction completion for data container (Zone 3)\n * @private\n */\n private _logDataEvictionComplete(evictedCount: number): void {\n log.info(\n `Evicted ${evictedCount} data items. ` +\n `Current size: ${this._data.size}/${this._maxCapacity}`\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","/**\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/indexing\";\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 { KosLoggerFactory } from \"./core/model/kos-logger-factory\";\nexport {\n clearModelHookCacheEntry,\n modelHookCache,\n type ModelHookCacheEntry,\n} from \"./core/model/model-hook-cache\";\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"],"names":["KosWsEvents","log","once","waitFor","delay","buffer","subscriptions","request","state","id","config","params","level","DependencyLifecycle","DependencyResolutionPolicy","hasHttpRouteHandlers","logLevel","api","kosServiceRequest","ResponseRetention","ReplayStrategy","KosContainerIndexEvents","map","models","kosAction","EventBus.publish","KosModelState","KosModelEvents","kosModel","companionModels","debounce","throttle","filter","EventBusFunctional.replay","cache","Transitions","rejectAfterDelay","dependentModel","machine","action","service","EventBus.subscribe","PORT","URL","baseKosServiceRequest","API","originalSubscribe","flushed","window","WebSocketEvents","MESSAGE_SEPARATOR","Transport","Logger","KosWSTransportStatus","count","AsyncEventBus.iterate","fsm","logger","reset","KosCoreState","KosCoreEvents","onlineMachine","AuthState","EventBus.hasEventSubscriptions","EventBusState.waitForAllWithState"],"mappings":";;;AAAO,MAAM,gBAAgB;AACtB,MAAM,eAAe;AACrB,MAAM,aAAa;AACnB,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,SAA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