{"version":3,"file":"event-bus.mjs","sources":["../../../src/lib/coordination/event-bus.ts"],"sourcesContent":["/**\n * @file Coordination Event Bus\n * @module coordination/event-bus\n * @description Event bus for coordination module cross-component communication.\n *\n * Provides a typed event bus for lifecycle, state coordination, and feature bridge events.\n *\n * @author Agent 5 - PhD TypeScript Architect\n * @version 1.0.0\n */\n\n// ============================================================================\n// Event Types\n// ============================================================================\n\n/**\n * Coordination event types and their payloads.\n */\nexport interface CoordinationEvents {\n  // Lifecycle events\n  'lifecycle:phase-started': {\n    phaseId: string;\n    phaseName: string;\n    order: number;\n  };\n  'lifecycle:phase-completed': {\n    phaseId: string;\n    phaseName: string;\n    duration: number;\n  };\n  'lifecycle:library-initialized': {\n    libraryId: string;\n    duration: number;\n  };\n  'lifecycle:all-initialized': {\n    totalDuration: number;\n    libraryCount: number;\n  };\n  'lifecycle:shutdown-started': Record<string, never>;\n  'lifecycle:shutdown-completed': {\n    duration: number;\n  };\n\n  // State coordination events\n  'state:changed': {\n    sliceId: string;\n    path?: string[];\n    previousValue: unknown;\n    newValue: unknown;\n  };\n  'state:synced': {\n    ruleId: string;\n    sourceSlice: string;\n    targetSlice: string;\n  };\n\n  // Feature bridge events\n  'feature:registered': {\n    featureId: string;\n    name: string;\n    capabilities: string[];\n  };\n  'feature:loaded': {\n    featureId: string;\n    duration: number;\n  };\n  'feature:capability-invoked': {\n    featureId: string;\n    capability: string;\n    duration: number;\n    success: boolean;\n  };\n}\n\n/**\n * Event names for coordination.\n */\nexport type CoordinationEventName = keyof CoordinationEvents;\n\n/**\n * Event handler type.\n */\nexport type CoordinationEventHandler<E extends CoordinationEventName> = (\n  payload: CoordinationEvents[E]\n) => void;\n\n// ============================================================================\n// Event Bus Implementation\n// ============================================================================\n\n/**\n * Coordination event bus for typed pub/sub communication.\n */\nexport class CoordinationEventBus {\n  /** Event listeners map */\n  private readonly listeners: Map<\n    CoordinationEventName,\n    Set<CoordinationEventHandler<CoordinationEventName>>\n  > = new Map();\n\n  /** Debug mode */\n  private debug = false;\n\n  /**\n   * Enables or disables debug logging.\n   */\n  setDebug(enabled: boolean): void {\n    this.debug = enabled;\n  }\n\n  /**\n   * Subscribes to an event.\n   * @param event - Event name\n   * @param handler - Event handler\n   * @returns Unsubscribe function\n   */\n  subscribe<E extends CoordinationEventName>(\n    event: E,\n    handler: CoordinationEventHandler<E>\n  ): () => void {\n    let handlers = this.listeners.get(event);\n    if (!handlers) {\n      handlers = new Set();\n      this.listeners.set(event, handlers);\n    }\n\n    handlers.add(handler as CoordinationEventHandler<CoordinationEventName>);\n\n    return () => {\n      handlers?.delete(handler as CoordinationEventHandler<CoordinationEventName>);\n      if (handlers?.size === 0) {\n        this.listeners.delete(event);\n      }\n    };\n  }\n\n  /**\n   * Publishes an event.\n   * @param event - Event name\n   * @param payload - Event payload\n   */\n  publish<E extends CoordinationEventName>(event: E, payload: CoordinationEvents[E]): void {\n    if (this.debug) {\n      console.info(`[CoordinationEventBus] ${event}`, payload);\n    }\n\n    const handlers = this.listeners.get(event);\n    if (!handlers) return;\n\n    for (const handler of handlers) {\n      try {\n        handler(payload);\n      } catch (error) {\n        console.error(`[CoordinationEventBus] Handler error for ${event}:`, error);\n      }\n    }\n  }\n\n  /**\n   * Subscribes to an event once.\n   * @param event - Event name\n   * @param handler - Event handler\n   * @returns Unsubscribe function\n   */\n  once<E extends CoordinationEventName>(\n    event: E,\n    handler: CoordinationEventHandler<E>\n  ): () => void {\n    const unsubscribe = this.subscribe(event, (payload) => {\n      unsubscribe();\n      handler(payload);\n    });\n    return unsubscribe;\n  }\n\n  /**\n   * Removes all listeners for an event.\n   * @param event - Event name (optional, clears all if not provided)\n   */\n  clear(event?: CoordinationEventName): void {\n    if (event) {\n      this.listeners.delete(event);\n    } else {\n      this.listeners.clear();\n    }\n  }\n\n  /**\n   * Gets the number of listeners for an event.\n   * @param event - Event name\n   */\n  listenerCount(event: CoordinationEventName): number {\n    return this.listeners.get(event)?.size ?? 0;\n  }\n\n  /**\n   * Subscribes to multiple event types.\n   * @param events - Event names\n   * @param handler - Event handler\n   * @returns Array of unsubscribe functions\n   */\n  subscribeMany<E extends CoordinationEventName>(\n    events: E[],\n    handler: CoordinationEventHandler<E>\n  ): (() => void)[] {\n    return events.map((event) => this.subscribe(event, handler));\n  }\n\n  /**\n   * Request-response pattern.\n   * @param requestEvent - Request event name\n   * @param responseEvent - Response event name\n   * @param payload - Request payload\n   * @param timeout - Timeout in milliseconds\n   * @returns Promise that resolves with the response payload\n   */\n  async request<TReq extends CoordinationEventName, TRes extends CoordinationEventName>(\n    requestEvent: TReq,\n    responseEvent: TRes,\n    payload: CoordinationEvents[TReq],\n    timeout = 5000\n  ): Promise<CoordinationEvents[TRes]> {\n    return new Promise((resolve, reject) => {\n      const timer = setTimeout(() => {\n        unsubscribe();\n        reject(new Error(`Request timeout after ${timeout}ms`));\n      }, timeout);\n\n      const unsubscribe = this.once(responseEvent, (responsePayload) => {\n        clearTimeout(timer);\n        resolve(responsePayload);\n      });\n\n      this.publish(requestEvent, payload);\n    });\n  }\n\n  /**\n   * Get event bus statistics.\n   * @returns Event bus statistics\n   */\n  getStats(): {\n    totalPublished: number;\n    totalDelivered: number;\n    totalFailures: number;\n    activeSubscriptions: number;\n  } {\n    let totalSubscriptions = 0;\n    for (const handlers of this.listeners.values()) {\n      totalSubscriptions += handlers.size;\n    }\n\n    return {\n      totalPublished: 0, // Could track this with a counter if needed\n      totalDelivered: 0, // Could track this with a counter if needed\n      totalFailures: 0, // Could track this with a counter if needed\n      activeSubscriptions: totalSubscriptions,\n    };\n  }\n\n  /**\n   * Disposes the event bus.\n   */\n  dispose(): void {\n    this.listeners.clear();\n  }\n}\n\n// ============================================================================\n// Singleton Instance\n// ============================================================================\n\n/**\n * Global coordination event bus instance.\n */\nlet globalEventBus: CoordinationEventBus | null = null;\n\n/**\n * Gets the global coordination event bus.\n * @returns Coordination event bus instance\n */\nexport function getCoordinationEventBus(): CoordinationEventBus {\n  globalEventBus ??= new CoordinationEventBus();\n  return globalEventBus;\n}\n\n/**\n * Sets the global coordination event bus.\n * @param bus - Event bus instance\n */\nexport function setCoordinationEventBus(bus: CoordinationEventBus): void {\n  if (globalEventBus) {\n    globalEventBus.dispose();\n  }\n  globalEventBus = bus;\n}\n\n/**\n * Resets the global coordination event bus.\n */\nexport function resetCoordinationEventBus(): void {\n  if (globalEventBus) {\n    globalEventBus.dispose();\n    globalEventBus = null;\n  }\n}\n\n// ============================================================================\n// Convenience Functions\n// ============================================================================\n\n/**\n * Publishes an event to the global bus.\n */\nexport function publishEvent<E extends CoordinationEventName>(\n  event: E,\n  payload: CoordinationEvents[E]\n): void {\n  getCoordinationEventBus().publish(event, payload);\n}\n\n/**\n * Subscribes to an event on the global bus.\n */\nexport function subscribeToEvent<E extends CoordinationEventName>(\n  event: E,\n  handler: CoordinationEventHandler<E>\n): () => void {\n  return getCoordinationEventBus().subscribe(event, handler);\n}\n\n/**\n * Subscribes to an event once on the global bus.\n */\nexport function onceEvent<E extends CoordinationEventName>(\n  event: E,\n  handler: CoordinationEventHandler<E>\n): () => void {\n  return getCoordinationEventBus().once(event, handler);\n}\n"],"names":["CoordinationEventBus","enabled","event","handler","handlers","payload","error","unsubscribe","events","requestEvent","responseEvent","timeout","resolve","reject","timer","responsePayload","totalSubscriptions","globalEventBus","getCoordinationEventBus","setCoordinationEventBus","bus","resetCoordinationEventBus","publishEvent","subscribeToEvent"],"mappings":"AA6FO,MAAMA,EAAqB;AAAA;AAAA,EAEf,gCAGT,IAAA;AAAA;AAAA,EAGA,QAAQ;AAAA;AAAA;AAAA;AAAA,EAKhB,SAASC,GAAwB;AAC/B,SAAK,QAAQA;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,UACEC,GACAC,GACY;AACZ,QAAIC,IAAW,KAAK,UAAU,IAAIF,CAAK;AACvC,WAAKE,MACHA,wBAAe,IAAA,GACf,KAAK,UAAU,IAAIF,GAAOE,CAAQ,IAGpCA,EAAS,IAAID,CAA0D,GA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