{"version":3,"file":"dependency-injector.mjs","sources":["../../../src/lib/coordination/dependency-injector.ts"],"sourcesContent":["/**\n * @file Dependency Injection Container\n * @module coordination/dependency-injector\n * @description PhD-level IoC container with lifecycle management and type safety.\n *\n * Implements a sophisticated dependency injection system with:\n * - Type-safe service registration and resolution\n * - Singleton, scoped, and transient lifetimes\n * - Factory functions with dependency injection\n * - Hierarchical containers with inheritance\n * - Lifecycle ordering for initialization\n * - Circular dependency detection\n * - Lazy instantiation\n *\n * @author Agent 5 - PhD TypeScript Architect\n * @version 1.0.0\n */\n\nimport {\n  type ServiceId,\n  type ServiceLifecycle,\n  type ServiceContract,\n  type ServiceRegistrationOptions,\n  type ServiceFactory,\n  type DependencyContainer,\n  createServiceId,\n} from './types';\n\n// ============================================================================\n// Internal Types\n// ============================================================================\n\n/**\n * Internal service entry with resolution metadata.\n */\ninterface ServiceEntry<T = unknown> {\n  /** Service contract */\n  contract: ServiceContract<T>;\n  /** Implementation or factory */\n  implementation: T | ServiceFactory<T>;\n  /** Registration options */\n  options: ServiceRegistrationOptions;\n  /** Whether implementation is a factory */\n  isFactory: boolean;\n  /** Resolved singleton instance */\n  instance?: T;\n  /** Whether currently resolving (for circular detection) */\n  isResolving: boolean;\n  /** Resolution order for lifecycle management */\n  resolutionOrder: number;\n}\n\n/**\n * Resolution context for tracking dependencies.\n */\ninterface ResolutionContext {\n  /** Services currently being resolved */\n  resolving: Set<ServiceId>;\n  /** Scoped instances for this resolution */\n  scopedInstances: Map<ServiceId, unknown>;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Lifecycle phase order for initialization.\n */\nconst LIFECYCLE_ORDER: Record<ServiceLifecycle, number> = {\n  bootstrap: 0,\n  core: 1,\n  feature: 2,\n  ui: 3,\n  lazy: 4,\n};\n\n/**\n * Sorts services by lifecycle phase.\n */\nfunction sortByLifecycle(a: ServiceEntry, b: ServiceEntry): number {\n  const aOrder = LIFECYCLE_ORDER[a.options.lifecycle ?? 'feature'];\n  const bOrder = LIFECYCLE_ORDER[b.options.lifecycle ?? 'feature'];\n  return aOrder - bOrder;\n}\n\n// ============================================================================\n// DependencyInjectorImpl Class\n// ============================================================================\n\n/**\n * Implementation of the dependency injection container.\n *\n * @example\n * ```typescript\n * // Define a service contract\n * const LoggerContract = createServiceContract<Logger>('logger');\n *\n * // Create container and register\n * const container = new DependencyInjectorImpl();\n * container.register(LoggerContract, new ConsoleLogger());\n *\n * // Resolve service\n * const logger = container.resolve(LoggerContract);\n * logger.info('Hello, world!');\n * ```\n *\n * @example With factories\n * ```typescript\n * // Register a factory\n * container.register(\n *   DatabaseContract,\n *   (c) => new Database(c.resolve(ConfigContract)),\n *   { scope: 'singleton', lifecycle: 'bootstrap' }\n * );\n * ```\n */\nexport class DependencyInjectorImpl implements DependencyContainer {\n  /** Service registry */\n  private readonly services: Map<ServiceId, ServiceEntry> = new Map();\n\n  /** Parent container for hierarchical resolution */\n  private readonly parent: DependencyInjectorImpl | null;\n\n  /** Resolution counter for ordering */\n  private resolutionCounter = 0;\n\n  /** Disposed flag */\n  private disposed = false;\n\n  /**\n   * Creates a new dependency injector.\n   * @param parent - Optional parent container\n   */\n  constructor(parent: DependencyInjectorImpl | null = null) {\n    this.parent = parent;\n  }\n\n  // ==========================================================================\n  // Public API\n  // ==========================================================================\n\n  /**\n   * Registers a service implementation.\n   * @template T - Service type\n   * @param contract - Service contract\n   * @param implementation - Implementation or factory\n   * @param options - Registration options\n   */\n  register<T>(\n    contract: ServiceContract<T>,\n    implementation: T | ServiceFactory<T>,\n    options: ServiceRegistrationOptions = {}\n  ): void {\n    this.ensureNotDisposed();\n\n    const isFactory = typeof implementation === 'function';\n\n    // Check for conditional registration\n    if (options.condition && !options.condition()) {\n      return;\n    }\n\n    // Validate dependencies exist if specified\n    if (options.dependencies) {\n      for (const depId of options.dependencies) {\n        if (!this.hasById(depId)) {\n          console.warn(`[DI] Service ${contract.name} depends on unregistered service: ${depId}`);\n        }\n      }\n    }\n\n    const entry: ServiceEntry<T> = {\n      contract,\n      implementation,\n      options: {\n        scope: 'singleton',\n        lifecycle: 'feature',\n        ...options,\n      },\n      isFactory,\n      isResolving: false,\n      resolutionOrder: -1,\n    };\n\n    this.services.set(contract.id, entry as ServiceEntry);\n  }\n\n  /**\n   * Registers a factory function.\n   * @template T - Service type\n   * @param contract - Service contract\n   * @param factory - Factory function\n   * @param options - Registration options\n   */\n  registerFactory<T>(\n    contract: ServiceContract<T>,\n    factory: ServiceFactory<T>,\n    options: ServiceRegistrationOptions = {}\n  ): void {\n    this.register(contract, factory, options);\n  }\n\n  /**\n   * Resolves a service.\n   * @template T - Service type\n   * @param contract - Service contract\n   * @returns Resolved service instance\n   * @throws Error if service not found or circular dependency detected\n   */\n  resolve<T>(contract: ServiceContract<T>): T {\n    return this.resolveWithContext(contract, {\n      resolving: new Set(),\n      scopedInstances: new Map(),\n    });\n  }\n\n  /**\n   * Tries to resolve a service, returning undefined if not found.\n   * @template T - Service type\n   * @param contract - Service contract\n   * @returns Resolved service or undefined\n   */\n  tryResolve<T>(contract: ServiceContract<T>): T | undefined {\n    try {\n      return this.resolve(contract);\n    } catch {\n      return contract.defaultValue;\n    }\n  }\n\n  /**\n   * Checks if a service is registered.\n   * @param contract - Service contract\n   * @returns True if registered\n   */\n  has(contract: ServiceContract<unknown>): boolean {\n    return this.hasById(contract.id);\n  }\n\n  /**\n   * Checks if a service ID is registered.\n   * @param id - Service ID\n   * @returns True if registered\n   */\n  hasById(id: ServiceId): boolean {\n    if (this.services.has(id)) return true;\n    if (this.parent) return this.parent.hasById(id);\n    return false;\n  }\n\n  /**\n   * Unregisters a service.\n   * @param contract - Service contract\n   * @returns True if service was unregistered\n   */\n  unregister(contract: ServiceContract<unknown>): boolean {\n    this.ensureNotDisposed();\n    return this.services.delete(contract.id);\n  }\n\n  /**\n   * Gets all services with a specific tag.\n   * @template T - Service type\n   * @param tag - Tag to search for\n   * @returns Array of matching services\n   */\n  getByTag<T>(tag: string): T[] {\n    const results: T[] = [];\n    const context: ResolutionContext = {\n      resolving: new Set(),\n      scopedInstances: new Map(),\n    };\n\n    for (const entry of this.services.values()) {\n      if (entry.options.tags?.includes(tag) === true) {\n        try {\n          const instance = this.resolveEntry(entry, context);\n          results.push(instance as T);\n        } catch {\n          // Skip services that fail to resolve\n        }\n      }\n    }\n\n    // Include parent services\n    if (this.parent) {\n      results.push(...this.parent.getByTag<T>(tag));\n    }\n\n    return results;\n  }\n\n  /**\n   * Gets all registered service contracts.\n   * @returns Array of service contracts\n   */\n  getRegisteredContracts(): ServiceContract<unknown>[] {\n    const contracts: ServiceContract<unknown>[] = [];\n    for (const entry of this.services.values()) {\n      contracts.push(entry.contract);\n    }\n    return contracts;\n  }\n\n  /**\n   * Gets services by lifecycle phase.\n   * @param lifecycle - Lifecycle phase\n   * @returns Array of service contracts\n   */\n  getByLifecycle(lifecycle: ServiceLifecycle): ServiceContract<unknown>[] {\n    const contracts: ServiceContract<unknown>[] = [];\n    for (const entry of this.services.values()) {\n      if (entry.options.lifecycle === lifecycle) {\n        contracts.push(entry.contract);\n      }\n    }\n    return contracts;\n  }\n\n  /**\n   * Creates a child container.\n   * @returns Child container\n   */\n  createChild(): DependencyContainer {\n    return new DependencyInjectorImpl(this);\n  }\n\n  /**\n   * Creates a scoped container for request-scoped services.\n   * @returns Scoped container\n   */\n  createScope(): DependencyContainer {\n    return new DependencyInjectorImpl(this);\n  }\n\n  /**\n   * Initializes all services in lifecycle order.\n   * @returns Promise that resolves when all services are initialized\n   */\n  async initializeAll(): Promise<void> {\n    this.ensureNotDisposed();\n\n    // Sort services by lifecycle\n    const entries = Array.from(this.services.values()).sort(sortByLifecycle);\n\n    const context: ResolutionContext = {\n      resolving: new Set(),\n      scopedInstances: new Map(),\n    };\n\n    // Initialize in order\n    for (const entry of entries) {\n      if (entry.options.scope === 'singleton' && entry.instance == null) {\n        await this.resolveEntryAsync(entry, context);\n      }\n    }\n  }\n\n  /**\n   * Disposes the container and all disposable services.\n   */\n  async dispose(): Promise<void> {\n    if (this.disposed) return;\n    this.disposed = true;\n\n    // Get all singleton instances in reverse resolution order\n    const entries = Array.from(this.services.values())\n      .filter((e) => e.instance !== undefined)\n      .sort((a, b) => b.resolutionOrder - a.resolutionOrder);\n\n    // Dispose in reverse order\n    for (const entry of entries) {\n      const instance = entry.instance as { dispose?: () => void | Promise<void> };\n      if (instance != null && typeof instance.dispose === 'function') {\n        try {\n          await instance.dispose();\n        } catch (error) {\n          console.error(`[DI] Error disposing service ${entry.contract.name}:`, error);\n        }\n      }\n    }\n\n    this.services.clear();\n  }\n\n  // ==========================================================================\n  // Private Methods\n  // ==========================================================================\n\n  /**\n   * Ensures container is not disposed.\n   */\n  private ensureNotDisposed(): void {\n    if (this.disposed) {\n      throw new Error('Container has been disposed');\n    }\n  }\n\n  /**\n   * Resolves a service with context.\n   * @template T - Service type\n   * @param contract - Service contract\n   * @param context - Resolution context\n   * @returns Resolved service\n   */\n  private resolveWithContext<T>(contract: ServiceContract<T>, context: ResolutionContext): T {\n    this.ensureNotDisposed();\n\n    // Check for existing scoped instance\n    if (context.scopedInstances.has(contract.id)) {\n      return context.scopedInstances.get(contract.id) as T;\n    }\n\n    // Find service entry\n    const entry = this.services.get(contract.id) as ServiceEntry<T> | undefined;\n\n    if (!entry) {\n      // Try parent container\n      if (this.parent) {\n        return this.parent.resolveWithContext(contract, context);\n      }\n\n      // Check for default value\n      if (contract.defaultValue !== undefined) {\n        return contract.defaultValue;\n      }\n\n      throw new Error(`Service not registered: ${contract.name} (${String(contract.id)})`);\n    }\n\n    return this.resolveEntry(entry, context);\n  }\n\n  /**\n   * Resolves a service entry.\n   * @template T - Service type\n   * @param entry - Service entry\n   * @param context - Resolution context\n   * @returns Resolved service\n   */\n  private resolveEntry<T>(entry: ServiceEntry<T>, context: ResolutionContext): T {\n    // Return existing singleton\n    if (entry.options.scope === 'singleton' && entry.instance !== undefined) {\n      return entry.instance;\n    }\n\n    // Detect circular dependency\n    if (context.resolving.has(entry.contract.id)) {\n      throw new Error(`Circular dependency detected for service: ${entry.contract.name}`);\n    }\n\n    // Mark as resolving\n    context.resolving.add(entry.contract.id);\n    entry.isResolving = true;\n\n    try {\n      let instance: T;\n\n      if (entry.isFactory) {\n        // Resolve via factory\n        const factory = entry.implementation as ServiceFactory<T>;\n        const result = factory(this);\n\n        // Handle async factories\n        if (result instanceof Promise) {\n          throw new Error(\n            `Async factory used in sync resolve for: ${entry.contract.name}. Use resolveAsync instead.`\n          );\n        }\n\n        instance = result;\n      } else {\n        // Direct implementation\n        instance = entry.implementation as T;\n      }\n\n      // Store based on scope\n      switch (entry.options.scope) {\n        case 'singleton':\n          entry.instance = instance;\n          entry.resolutionOrder = this.resolutionCounter++;\n          break;\n        case 'scoped':\n          context.scopedInstances.set(entry.contract.id, instance);\n          break;\n        case 'transient':\n        default:\n          // No caching for transient\n          break;\n      }\n\n      return instance;\n    } finally {\n      context.resolving.delete(entry.contract.id);\n      entry.isResolving = false;\n    }\n  }\n\n  /**\n   * Resolves a service entry asynchronously.\n   * @template T - Service type\n   * @param entry - Service entry\n   * @param context - Resolution context\n   * @returns Promise resolving to service\n   */\n  private async resolveEntryAsync<T>(\n    entry: ServiceEntry<T>,\n    context: ResolutionContext\n  ): Promise<T> {\n    // Return existing singleton\n    if (entry.options.scope === 'singleton' && entry.instance !== undefined) {\n      return entry.instance;\n    }\n\n    // Detect circular dependency\n    if (context.resolving.has(entry.contract.id)) {\n      throw new Error(`Circular dependency detected for service: ${entry.contract.name}`);\n    }\n\n    // Mark as resolving\n    context.resolving.add(entry.contract.id);\n    entry.isResolving = true;\n\n    try {\n      let instance: T;\n\n      if (entry.isFactory) {\n        // Resolve via factory\n        const factory = entry.implementation as ServiceFactory<T>;\n        instance = await factory(this);\n      } else {\n        // Direct implementation\n        instance = entry.implementation as T;\n      }\n\n      // Store based on scope\n      switch (entry.options.scope) {\n        case 'singleton':\n          entry.instance = instance;\n          entry.resolutionOrder = this.resolutionCounter++;\n          break;\n        case 'scoped':\n          context.scopedInstances.set(entry.contract.id, instance);\n          break;\n        case 'transient':\n        default:\n          // No caching for transient\n          break;\n      }\n\n      return instance;\n    } finally {\n      context.resolving.delete(entry.contract.id);\n      entry.isResolving = false;\n    }\n  }\n}\n\n// ============================================================================\n// Service Contract Factory\n// ============================================================================\n\n/**\n * Creates a typed service contract.\n * @template T - Service interface type\n * @param name - Service name\n * @param defaultValue - Optional default implementation\n * @param lifecycle - Service lifecycle phase\n * @returns Service contract\n *\n * @example\n * ```typescript\n * interface Logger {\n *   info(message: string): void;\n *   error(message: string, error?: Error): void;\n * }\n *\n * const LoggerContract = createServiceContract<Logger>('logger', {\n *   info: (msg) => console.log(msg),\n *   error: (msg, err) => console.error(msg, err),\n * });\n * ```\n */\nexport function createServiceContract<T>(\n  name: string,\n  defaultValue?: T,\n  lifecycle?: ServiceLifecycle\n): ServiceContract<T> {\n  return {\n    id: createServiceId(name),\n    name,\n    version: '1.0.0',\n    defaultValue,\n    lifecycle,\n  };\n}\n\n// ============================================================================\n// Singleton Instance\n// ============================================================================\n\n/**\n * Global dependency injection container.\n */\nlet globalContainer: DependencyInjectorImpl | null = null;\n\n/**\n * Gets the global dependency container.\n * @returns Global container instance\n */\nexport function getGlobalContainer(): DependencyInjectorImpl {\n  globalContainer ??= new DependencyInjectorImpl();\n  return globalContainer;\n}\n\n/**\n * Sets the global dependency container.\n * @param container - Container instance\n */\nexport function setGlobalContainer(container: DependencyInjectorImpl): void {\n  if (globalContainer) {\n    void globalContainer.dispose().catch(console.error);\n  }\n  globalContainer = container;\n}\n\n/**\n * Resets the global dependency container.\n */\nexport function resetGlobalContainer(): void {\n  if (globalContainer) {\n    void globalContainer.dispose().catch(console.error);\n    globalContainer = null;\n  }\n}\n\n// ============================================================================\n// Convenience Functions\n// ============================================================================\n\n/**\n * Registers a service in the global container.\n */\nexport function registerService<T>(\n  contract: ServiceContract<T>,\n  implementation: T | ServiceFactory<T>,\n  options?: ServiceRegistrationOptions\n): void {\n  getGlobalContainer().register(contract, implementation, options);\n}\n\n/**\n * Resolves a service from the global container.\n */\nexport function resolveService<T>(contract: ServiceContract<T>): T {\n  return getGlobalContainer().resolve(contract);\n}\n\n/**\n * Tries to resolve a service from the global container.\n */\nexport function tryResolveService<T>(contract: ServiceContract<T>): T | undefined {\n  return getGlobalContainer().tryResolve(contract);\n}\n\n// ============================================================================\n// Pre-defined Service Contracts\n// ============================================================================\n\n/**\n * Logger service contract.\n */\nexport interface ILogger {\n  debug(message: string, data?: unknown): void;\n  info(message: string, data?: unknown): void;\n  warn(message: string, data?: unknown): void;\n  error(message: string, error?: Error, data?: unknown): void;\n}\n\nexport const LoggerContract = createServiceContract<ILogger>(\n  'coordination:logger',\n  {\n    debug: (msg, data) => console.info(msg, data),\n    info: (msg, data) => console.info(msg, data),\n    warn: (msg, data) => console.warn(msg, data),\n    error: (msg, err, data) => console.error(msg, err, data),\n  },\n  'bootstrap'\n);\n\n/**\n * Configuration service contract.\n */\nexport interface IConfigService {\n  get<T>(key: string): T | undefined;\n  set<T>(key: string, value: T): void;\n  has(key: string): boolean;\n  getAll(): Record<string, unknown>;\n}\n\nexport const ConfigContract = createServiceContract<IConfigService>(\n  'coordination:config',\n  undefined,\n  'bootstrap'\n);\n\n/**\n * Telemetry service contract.\n */\nexport interface ITelemetryService {\n  trackEvent(name: string, properties?: Record<string, unknown>): void;\n  trackMetric(name: string, value: number, properties?: Record<string, unknown>): void;\n  trackException(error: Error, properties?: Record<string, unknown>): void;\n  flush(): Promise<void>;\n}\n\nexport const TelemetryContract = createServiceContract<ITelemetryService>(\n  'coordination:telemetry',\n  {\n    trackEvent: () => {},\n    trackMetric: () => {},\n    trackException: () => {},\n    flush: async () => {},\n  },\n  'bootstrap'\n);\n"],"names":["LIFECYCLE_ORDER","sortByLifecycle","a","b","aOrder","bOrder","DependencyInjectorImpl","parent","contract","implementation","options","isFactory","depId","entry","factory","id","tag","results","context","instance","contracts","lifecycle","entries","e","error","result","createServiceContract","name","defaultValue","createServiceId","globalContainer","getGlobalContainer","setGlobalContainer","container","resetGlobalContainer","registerService","resolveService","tryResolveService","LoggerContract","msg","data","err","ConfigContract","TelemetryContract"],"mappings":";AAqEA,MAAMA,IAAoD;AAAA,EACxD,WAAW;AAAA,EACX,MAAM;AAAA,EACN,SAAS;AAAA,EACT,IAAI;AAAA,EACJ,MAAM;AACR;AAKA,SAASC,EAAgBC,GAAiBC,GAAyB;AACjE,QAAMC,IAASJ,EAAgBE,EAAE,QAAQ,aAAa,SAAS,GACzDG,IAASL,EAAgBG,EAAE,QAAQ,aAAa,SAAS;AAC/D,SAAOC,IAASC;AAClB;AAiCO,MAAMC,EAAsD;AAAA;AAAA,EAEhD,+BAA6C,IAAA;AAAA;AAAA,EAG7C;AAAA;AAAA,EAGT,oBAAoB;AAAA;AAAA,EAGpB,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA,EAMnB,YAAYC,IAAwC,MAAM;AACxD,SAAK,SAASA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,SACEC,GACAC,GACAC,IAAsC,CAAA,GAChC;AACN,SAAK,kBAAA;AAEL,UAAMC,IAAY,OAAOF,KAAmB;AAG5C,QAAIC,EAAQ,aAAa,CAACA,EAAQ;AAChC;AAIF,QAAIA,EAAQ;AACV,iBAAWE,KAASF,EAAQ;AAC1B,QAAK,KAAK,QAAQE,CAAK,KACrB,QAAQ,KAAK,gBAAgBJ,EAAS,IAAI,qCAAqCI,CAAK,EAAE;AAK5F,UAAMC,IAAyB;AAAA,MAC7B,UAAAL;AAAA,MACA,gBAAAC;AAAA,MACA,SAAS;AAAA,QACP,OAAO;AAAA,QACP,WAAW;AAAA,QACX,GAAGC;AAAA,MAAA;AAAA,MAEL,WAAAC;AAAA,MACA,aAAa;AAAA,MACb,iBAAiB;AAAA,IAAA;AAGnB,SAAK,SAAS,IAAIH,EAAS,IAAIK,CAAqB;AAAA,EACtD;AAAA;AAAA;AAAA;AAAA;AAAA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