@plyaz/core 1.5.21 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/domain/base/BaseFrontendDomainService.d.ts +21 -0
- package/dist/domain/base/BaseFrontendDomainService.d.ts.map +1 -1
- package/dist/domain/example/FrontendExampleDomainService.d.ts.map +1 -1
- package/dist/entry-backend.js +68 -12
- package/dist/entry-backend.js.map +1 -1
- package/dist/entry-backend.mjs +68 -12
- package/dist/entry-backend.mjs.map +1 -1
- package/dist/entry-frontend-browser.js +68 -12
- package/dist/entry-frontend-browser.js.map +1 -1
- package/dist/entry-frontend-browser.mjs +68 -12
- package/dist/entry-frontend-browser.mjs.map +1 -1
- package/dist/entry-frontend.js +68 -12
- package/dist/entry-frontend.js.map +1 -1
- package/dist/entry-frontend.mjs +68 -12
- package/dist/entry-frontend.mjs.map +1 -1
- package/dist/index.js +68 -12
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +68 -12
- package/dist/index.mjs.map +1 -1
- package/dist/init/CoreInitializer.d.ts +8 -0
- package/dist/init/CoreInitializer.d.ts.map +1 -1
- package/dist/init/nestjs/index.js +18 -1
- package/dist/init/nestjs/index.js.map +1 -1
- package/dist/init/nestjs/index.mjs +18 -1
- package/dist/init/nestjs/index.mjs.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/common/id.ts","../../../src/events/CoreEventManager.ts","../../../src/services/ApiClientService.ts","../../../src/base/observability/BaseAdapter.ts","../../../src/base/observability/LoggerAdapter.ts","../../../src/base/observability/ObservabilityService.ts","../../../src/config/dependencies.ts","../../../src/init/ServiceRegistry.ts","../../../src/utils/runtime.ts","../../../src/init/CoreInitializer.ts","../../../src/services/DbService.ts","../../../src/init/nestjs/CoreModule.ts"],"names":["PackageLogger","logger","ERROR_CODES","CorePackageError","DbService","BACKEND_RUNTIMES","FRONTEND_RUNTIMES","CORE_EVENTS"],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,YAAA,CAAA;AAAA,QAIZ,MAAA,EAAQ,CAAC,YAAY;AAAA;AACvB,KACF;AAEA,IAAA,OAAO;AAAA,MACL,MAAA,EAAQ,WAAA;AAAA,MACR,MAAA,EAAQ,IAAA;AAAA,MACR,OAAA,EAAS,OAAA,CAAQ,OAAA,IAAW,EAAC;AAAA,MAC7B,SAAA;AAAA,MACA,OAAA,EAAS,CAAC,SAAA,EAAW,UAAA,EAAY,YAAY;AAAA,KAC/C;AAAA,EACF;AACF","file":"index.mjs","sourcesContent":["/**\n * ID Generation Utilities\n *\n * Provides consistent ID generation across the application.\n * Uses globalThis.crypto when available, with a fallback for environments without it.\n *\n * @fileoverview ID generation utility functions\n */\n\n// Constants for ID generation\nconst RANDOM_ID_RADIX = 36;\nconst RANDOM_ID_SLICE_START = 2;\nconst SHORT_ID_LENGTH = 8;\nconst HEX_RADIX = 16;\nconst HEX_SLICE_START = 2;\nconst HEX_SLICE_END = 18;\nconst SPAN_ID_LENGTH = 16;\n\n/**\n * Generate a UUID v4 string.\n * Uses crypto.randomUUID when available, otherwise falls back to a timestamp-based ID.\n *\n * @returns A UUID v4 string or fallback ID\n *\n * @example\n * ```typescript\n * const id = generateId();\n * // => 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' (crypto available)\n * // => '1701475200000-x7k9m2' (fallback)\n * ```\n */\nexport function generateId(): string {\n const cryptoApi = globalThis.crypto as { randomUUID?: () => string } | undefined;\n if (cryptoApi?.randomUUID) {\n return cryptoApi.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(RANDOM_ID_RADIX).slice(RANDOM_ID_SLICE_START)}`;\n}\n\n/**\n * Generate a short random ID (8 characters).\n * Useful for correlation IDs, short references, etc.\n *\n * @returns A short random string\n *\n * @example\n * ```typescript\n * const shortId = generateShortId();\n * // => 'x7k9m2ab'\n * ```\n */\nexport function generateShortId(): string {\n const cryptoApi = globalThis.crypto as { randomUUID?: () => string } | undefined;\n if (cryptoApi?.randomUUID) {\n return cryptoApi.randomUUID().replace(/-/g, '').slice(0, SHORT_ID_LENGTH);\n }\n return Math.random()\n .toString(RANDOM_ID_RADIX)\n .slice(RANDOM_ID_SLICE_START, RANDOM_ID_SLICE_START + SHORT_ID_LENGTH);\n}\n\n/**\n * Generate a correlation ID for tracing.\n * Format: timestamp-randomString\n *\n * @returns A correlation ID string\n *\n * @example\n * ```typescript\n * const correlationId = generateCorrelationId();\n * // => '1701475200000-x7k9m2'\n * ```\n */\nexport function generateCorrelationId(): string {\n return `${Date.now()}-${generateShortId()}`;\n}\n\n/**\n * Generate a trace ID for distributed tracing (32 hex characters / 128 bits).\n *\n * @returns A 32-character hex string\n *\n * @example\n * ```typescript\n * const traceId = generateTraceId();\n * // => 'a1b2c3d4e5f67890abcdef1234567890'\n * ```\n */\nexport function generateTraceId(): string {\n const cryptoApi = globalThis.crypto as { randomUUID?: () => string } | undefined;\n if (cryptoApi?.randomUUID) {\n // Use two UUIDs without dashes to get 64 hex chars, take first 32\n return cryptoApi.randomUUID().replace(/-/g, '');\n }\n // Fallback: concatenate two random hex strings\n return (\n Math.random().toString(HEX_RADIX).substring(HEX_SLICE_START, HEX_SLICE_END) +\n Math.random().toString(HEX_RADIX).substring(HEX_SLICE_START, HEX_SLICE_END)\n );\n}\n\n/**\n * Generate a span ID for distributed tracing (16 hex characters / 64 bits).\n *\n * @returns A 16-character hex string\n *\n * @example\n * ```typescript\n * const spanId = generateSpanId();\n * // => 'a1b2c3d4e5f67890'\n * ```\n */\nexport function generateSpanId(): string {\n const cryptoApi = globalThis.crypto as { randomUUID?: () => string } | undefined;\n if (cryptoApi?.randomUUID) {\n // Use UUID without dashes, take first 16 chars\n return cryptoApi.randomUUID().replace(/-/g, '').substring(0, SPAN_ID_LENGTH);\n }\n // Fallback: random hex string\n return Math.random().toString(HEX_RADIX).substring(HEX_SLICE_START, HEX_SLICE_END);\n}\n\n/**\n * ID generation utilities object for convenient access.\n */\nexport const IdUtils = {\n generate: generateId,\n generateShort: generateShortId,\n generateCorrelation: generateCorrelationId,\n generateTraceId,\n generateSpanId,\n} as const;\n","/**\n * Core Event Manager\n *\n * Type-safe event system for the Plyaz ecosystem.\n * Services emit events → Store, API cache, and UI subscribe independently.\n *\n * @example\n * ```typescript\n * import { CoreEventManager, CORE_EVENTS } from '@plyaz/core/events';\n *\n * // Type-safe emission (using CORE_EVENTS constants)\n * CoreEventManager.emit(CORE_EVENTS.API.REQUEST_ERROR, {\n * method: 'GET',\n * url: '/api/users',\n * requestId: '123',\n * error: new Error('Failed'),\n * duration: 500,\n * });\n *\n * // Type-safe subscription\n * CoreEventManager.on(CORE_EVENTS.AUTH.LOGIN, (event) => {\n * console.log(event.data.userId); // Typed!\n * });\n *\n * // Custom events (with generic type)\n * CoreEventManager.emit<MyPayload>('custom:event', { custom: 'data' });\n * ```\n */\n\nimport { EventEmitter } from 'events';\nimport type { CoreEventPayloadMap, CoreEventScopeType, CoreEvent } from '@plyaz/types/core';\nimport { generateCorrelationId } from '../utils/common';\n\n/**\n * Core Event Manager\n *\n * Features:\n * - Type-safe event emission and subscription via CORE_EVENTS constants\n * - Scope-based event filtering\n * - Wildcard subscriptions\n * - Auto cleanup on dispose\n * - Correlation IDs for tracing\n *\n * @example\n * ```typescript\n * import { CoreEventManager, CORE_EVENTS } from '@plyaz/core/events';\n *\n * // Type-safe with CORE_EVENTS\n * CoreEventManager.emit(CORE_EVENTS.AUTH.LOGIN, {\n * userId: '123',\n * method: 'email',\n * });\n *\n * CoreEventManager.on(CORE_EVENTS.AUTH.LOGIN, (event) => {\n * console.log(event.data.userId); // Typed as string!\n * });\n *\n * // Custom events with explicit type\n * interface MyPayload { custom: string }\n * CoreEventManager.emit<MyPayload>('custom:event', { custom: 'data' });\n * ```\n */\n\n// Constants\nconst MAX_EVENT_LISTENERS = 100;\n\nclass CoreEventManagerClass {\n private emitter = new EventEmitter();\n private subscriptions = new Map<string, Set<(event: CoreEvent<unknown, string>) => void>>();\n\n constructor() {\n // Increase max listeners for large apps\n this.emitter.setMaxListeners(MAX_EVENT_LISTENERS);\n }\n\n /**\n * Emit an event\n *\n * @param eventType - Event type from CORE_EVENTS or custom string\n * @param data - Event payload (type-safe when using CORE_EVENTS)\n *\n * @example\n * ```typescript\n * // Type-safe with CORE_EVENTS\n * CoreEventManager.emit(CORE_EVENTS.AUTH.LOGIN, { userId: '123', method: 'email' });\n *\n * // Custom event\n * CoreEventManager.emit<MyPayload>('custom:event', { custom: 'data' });\n * ```\n */\n emit<T extends keyof CoreEventPayloadMap>(eventType: T, data: CoreEventPayloadMap[T]): boolean;\n emit<TData = unknown>(eventType: string, data?: TData): boolean;\n emit<TData = unknown>(eventType: string, data?: TData): boolean {\n const [scope] = eventType.split(':');\n const event: CoreEvent<TData, string> = {\n type: eventType,\n scope: scope ?? 'system',\n timestamp: Date.now(),\n correlationId: this.getCorrelationId(),\n data: data as TData,\n };\n\n // Emit to specific listeners\n this.emitter.emit(eventType, event);\n\n // Emit to wildcard listeners\n this.emitter.emit('*', event);\n\n return true;\n }\n\n /**\n * Subscribe to an event\n *\n * @param eventType - Event type from CORE_EVENTS or custom string\n * @param handler - Event handler (type-safe when using CORE_EVENTS)\n * @returns Unsubscribe function\n *\n * @example\n * ```typescript\n * // Type-safe with CORE_EVENTS\n * const unsub = CoreEventManager.on(CORE_EVENTS.AUTH.LOGIN, (event) => {\n * console.log(event.data.userId); // Typed!\n * });\n *\n * // Custom event\n * CoreEventManager.on<MyPayload>('custom:event', (event) => {\n * console.log(event.data.custom);\n * });\n * ```\n */\n on<T extends keyof CoreEventPayloadMap>(\n eventType: T,\n handler: (event: CoreEvent<CoreEventPayloadMap[T], CoreEventScopeType>) => void\n ): () => void;\n on<TData = unknown, TScope extends string = string>(\n eventType: string,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): () => void;\n on<TData = unknown, TScope extends string = string>(\n eventType: string,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): () => void {\n this.emitter.on(eventType, handler as (event: CoreEvent<unknown, string>) => void);\n\n // Track for cleanup\n if (!this.subscriptions.has(eventType)) {\n this.subscriptions.set(eventType, new Set());\n }\n this.subscriptions.get(eventType)!.add(handler as (event: CoreEvent<unknown, string>) => void);\n\n // Return unsubscribe function\n return () => {\n this.emitter.off(eventType, handler as (event: CoreEvent<unknown, string>) => void);\n this.subscriptions\n .get(eventType)\n ?.delete(handler as (event: CoreEvent<unknown, string>) => void);\n };\n }\n\n /**\n * Subscribe once to an event\n *\n * @param eventType - Event type from CORE_EVENTS or custom string\n * @param handler - Event handler\n * @returns Unsubscribe function\n */\n once<T extends keyof CoreEventPayloadMap>(\n eventType: T,\n handler: (event: CoreEvent<CoreEventPayloadMap[T], CoreEventScopeType>) => void\n ): () => void;\n once<TData = unknown, TScope extends string = string>(\n eventType: string,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): () => void;\n once<TData = unknown, TScope extends string = string>(\n eventType: string,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): () => void {\n const wrappedHandler = (event: CoreEvent<TData, TScope>): void => {\n handler(event);\n this.emitter.off(eventType, wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n this.subscriptions\n .get(eventType)\n ?.delete(wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n };\n\n this.emitter.on(eventType, wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n\n // Track for cleanup\n if (!this.subscriptions.has(eventType)) {\n this.subscriptions.set(eventType, new Set());\n }\n this.subscriptions\n .get(eventType)!\n .add(wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n\n // Return unsubscribe function\n return () => {\n this.emitter.off(eventType, wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n this.subscriptions\n .get(eventType)\n ?.delete(wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n };\n }\n\n /**\n * Subscribe to all events in a scope\n *\n * @param scope - Event scope to listen to (e.g., CoreEventScope.AUTH)\n * @param handler - Event handler\n * @returns Unsubscribe function\n *\n * @example\n * ```typescript\n * CoreEventManager.onScope(CoreEventScope.AUTH, (event) => {\n * // Handles auth:login, auth:logout, auth:tokenRefresh, etc.\n * console.log(`Auth event: ${event.type}`, event.data);\n * });\n * ```\n */\n onScope<TScope extends string = string, TData = unknown>(\n scope: TScope,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): () => void {\n const wrappedHandler = (event: CoreEvent<TData, TScope>): void => {\n if (event.scope === scope) {\n handler(event);\n }\n };\n return this.on('*', wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n }\n\n /**\n * Remove a specific handler from an event\n *\n * @param eventType - Event type\n * @param handler - Handler to remove\n */\n off<TData = unknown, TScope extends string = string>(\n eventType: string,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): void {\n this.emitter.off(eventType, handler as (event: CoreEvent<unknown, string>) => void);\n this.subscriptions\n .get(eventType)\n ?.delete(handler as (event: CoreEvent<unknown, string>) => void);\n }\n\n /**\n * Dispose all subscriptions\n */\n dispose(): void {\n this.subscriptions.forEach((handlers, eventType) => {\n handlers.forEach(handler => this.emitter.off(eventType, handler));\n });\n this.subscriptions.clear();\n this.emitter.removeAllListeners();\n }\n\n /**\n * Generate correlation ID for event tracing\n */\n private getCorrelationId(): string {\n return generateCorrelationId();\n }\n}\n\n// Singleton export\nexport const CoreEventManager = new CoreEventManagerClass();\n","/**\n * API Client Singleton Service (@plyaz/core)\n * Manages the API client with environment-specific configurations and intelligent defaults\n *\n * The app reads process.env and constructs ApiClientOptions, then passes to this service.\n * Service never touches process.env directly - all env reading happens in the app layer.\n *\n * @module services/ApiClientService\n */\n\n// Imports from @plyaz/api (dependency)\nimport { createApiClient, mergeConfigs, setDefaultApiClient } from '@plyaz/api/frontend';\nimport type { ApiClientWithEvents, ApiClientOptions, ApiConfig } from '@plyaz/types/api';\nimport { type ClientEventManager, type EndpointsList, ApiPackageError } from '@plyaz/api/frontend';\nimport { PRODUCTION_CONFIG, STAGING_CONFIG, DEVELOPMENT_CONFIG } from '@plyaz/config';\nimport {\n API_ERROR_CODES,\n PACKAGE_STATUS_CODES,\n OPERATIONS,\n ERROR_CODES,\n ERROR_CATEGORY,\n HTTP_STATUS,\n CORE_EVENTS,\n} from '@plyaz/types';\nimport type { CoreApiRequestErrorPayload, CoreApiEnvironmentConfig } from '@plyaz/types/core';\nimport { CoreEventManager } from '../events/CoreEventManager';\nimport { generateRequestId } from '@plyaz/errors';\nimport type { ResponseError } from 'fetchff';\n// Note: Root store is injected by Core.initialize(), not created here\n\n/**\n * Minimum retry attempts recommended for production environments\n *\n * Production services should have sufficient retries to handle transient failures\n * while maintaining acceptable response times for end users.\n *\n * @constant\n * @default 3\n */\nconst MIN_RETRY_ATTEMPTS_PRODUCTION = 3;\n\n/**\n * Get configuration based on environment\n *\n * Returns environment-specific defaults that will be merged with user configuration.\n * Each environment has optimized settings for its use case:\n *\n * - **Production**: Aggressive retries (5), encryption required, telemetry enabled\n * - **Staging**: Mirrors production for accurate pre-deployment testing\n * - **Development/Test**: Conservative retries (1), encryption optional, full debug mode\n *\n * These defaults come from `@plyaz/config` and can be overridden via the `apiConfig` parameter.\n *\n * @param env - Environment name determining which defaults to apply\n * @returns Environment-specific configuration from @plyaz/config\n *\n * @example\n * ```typescript\n * const prodDefaults = getConfigForEnvironment('production');\n * // Returns PRODUCTION_CONFIG with aggressive retries, encryption, etc.\n *\n * const devDefaults = getConfigForEnvironment('development');\n * // Returns DEVELOPMENT_CONFIG with conservative retries, no encryption\n * ```\n *\n * @see {@link CoreApiEnvironmentConfig.env} - Environment types\n * @internal\n */\nfunction getConfigForEnvironment(env: CoreApiEnvironmentConfig['env']): Partial<ApiConfig> {\n switch (env) {\n case 'production':\n return PRODUCTION_CONFIG as Partial<ApiConfig>;\n case 'staging':\n return STAGING_CONFIG as Partial<ApiConfig>;\n case 'development':\n case 'test':\n default:\n return DEVELOPMENT_CONFIG as Partial<ApiConfig>;\n }\n}\n\n/**\n * Validate base URL requirement\n *\n * Ensures that a baseURL is provided in the configuration. The baseURL is mandatory\n * for all API clients as it defines where requests should be sent.\n *\n * @param mergedConfig - Merged configuration after applying all defaults\n * @param errors - Error array to append validation errors to\n *\n * @example\n * ```typescript\n * const errors: string[] = [];\n * validateBaseURL(mergedConfig, errors);\n *\n * if (errors.length > 0) {\n * // baseURL is missing\n * }\n * ```\n *\n * @internal\n */\nfunction validateBaseURL(mergedConfig: ApiClientOptions, errors: string[]): void {\n if (!mergedConfig.baseURL) {\n errors.push('baseURL is required in API configuration (apiConfig parameter)');\n }\n}\n\n/**\n * Validate production encryption configuration\n *\n * Production environments MUST have encryption properly configured to protect sensitive data.\n * This function validates that:\n * - If encryption is enabled, an encryption key MUST be provided\n * - If encryption is disabled, a security warning is issued\n *\n * **Why encryption is required in production**:\n * - Compliance: GDPR, CCPA, PIPL, HIPAA regulations require data protection\n * - Security: Protects PII, payment info, health data, crypto wallet addresses\n * - 50+ sensitive field patterns: email, SSN, card numbers, API keys, etc.\n *\n * @param mergedConfig - Merged configuration after applying all defaults\n * @param errors - Error array to append critical validation errors to\n * @param warnings - Warning array to append non-critical warnings to\n *\n * @example\n * ```typescript\n * const errors: string[] = [];\n * const warnings: string[] = [];\n *\n * validateProductionEncryption(mergedConfig, errors, warnings);\n *\n * // If encryption enabled but no key:\n * // errors = ['encryption.key is REQUIRED when encryption is enabled in production...']\n *\n * // If encryption disabled:\n * // warnings = ['[SECURITY WARNING] Encryption is disabled in production...']\n * ```\n *\n * @internal\n */\nfunction validateProductionEncryption(\n mergedConfig: ApiClientOptions,\n errors: string[],\n warnings: string[]\n): void {\n if (mergedConfig.encryption?.enabled) {\n if (!mergedConfig.encryption?.key) {\n errors.push(\n 'encryption.key is REQUIRED when encryption is enabled in production. ' +\n 'Pass it in apiConfig: { encryption: { key: { id: \"prod-key-v1\", key: process.env.ENCRYPTION_KEY!, algorithm: \"AES-GCM\", format: \"raw\" } } }'\n );\n }\n } else {\n warnings.push(\n '[SECURITY WARNING] Encryption is disabled in production. ' +\n 'This is not recommended for handling sensitive data (PII, payment info, etc.).'\n );\n }\n}\n\n/**\n * Validate production performance settings\n *\n * Validates production configuration for optimal performance, reliability, and monitoring:\n * - **Network-aware features**: Adapts to varying network conditions for better UX\n * - **Telemetry**: Required for production monitoring and alerting\n * - **Retry attempts**: Minimum 3 retries recommended for reliability\n *\n * These are warnings (not errors) as they don't prevent the client from working,\n * but indicate suboptimal production configuration.\n *\n * @param mergedConfig - Merged configuration after applying all defaults\n * @param warnings - Warning array to append performance warnings to\n *\n * @example\n * ```typescript\n * const warnings: string[] = [];\n * validateProductionPerformance(mergedConfig, warnings);\n *\n * // Possible warnings:\n * // - '[PERFORMANCE WARNING] networkAware is disabled in production...'\n * // - '[MONITORING WARNING] telemetry is disabled in production...'\n * // - '[RELIABILITY WARNING] Only 1 retry attempts configured...'\n * ```\n *\n * @internal\n */\nfunction validateProductionPerformance(mergedConfig: ApiClientOptions, warnings: string[]): void {\n if (!mergedConfig.networkAware?.enabled) {\n warnings.push(\n '[PERFORMANCE WARNING] networkAware is disabled in production. ' +\n 'Enable it for better user experience on varying network conditions.'\n );\n }\n\n if (!mergedConfig.tracking?.telemetry) {\n warnings.push(\n '[MONITORING WARNING] telemetry is disabled in production. ' +\n 'Enable it for production monitoring and alerting.'\n );\n }\n\n if (\n mergedConfig.retry &&\n mergedConfig.retry.attempts !== undefined &&\n mergedConfig.retry.attempts < MIN_RETRY_ATTEMPTS_PRODUCTION\n ) {\n warnings.push(\n `[RELIABILITY WARNING] Only ${mergedConfig.retry.attempts} retry attempts configured. ` +\n 'Consider increasing to 3-5 for better reliability in production.'\n );\n }\n}\n\n/**\n * Validate staging encryption configuration\n *\n * Staging environments should mirror production configuration for accurate pre-deployment testing.\n * This function validates:\n * - If encryption is enabled, an encryption key MUST be provided (same as production)\n * - If encryption is disabled, issues a warning (staging should match production)\n * - Telemetry should be enabled to test monitoring before production\n *\n * **Why staging should mirror production**:\n * - Catches configuration issues before they reach production\n * - Tests encryption/decryption with real-world-like data\n * - Validates monitoring and alerting pipelines\n *\n * @param mergedConfig - Merged configuration after applying all defaults\n * @param errors - Error array to append critical validation errors to\n * @param warnings - Warning array to append configuration warnings to\n *\n * @example\n * ```typescript\n * const errors: string[] = [];\n * const warnings: string[] = [];\n *\n * validateStagingEncryption(mergedConfig, errors, warnings);\n *\n * // If encryption enabled but no key:\n * // errors = ['encryption.key is REQUIRED in staging (aligned with production)...']\n *\n * // If encryption or telemetry disabled:\n * // warnings = ['[SECURITY WARNING] Encryption is disabled in staging...']\n * ```\n *\n * @internal\n */\nfunction validateStagingEncryption(\n mergedConfig: ApiClientOptions,\n errors: string[],\n warnings: string[]\n): void {\n if (mergedConfig.encryption?.enabled) {\n if (!mergedConfig.encryption?.key) {\n errors.push(\n 'encryption.key is REQUIRED in staging (aligned with production). ' +\n 'Pass it in apiConfig: { encryption: { key: { id: \"staging-key-v1\", key: process.env.ENCRYPTION_KEY!, algorithm: \"AES-GCM\", format: \"raw\" } } }'\n );\n }\n } else {\n warnings.push(\n '[SECURITY WARNING] Encryption is disabled in staging. ' +\n 'Staging should mirror production for accurate testing.'\n );\n }\n\n if (!mergedConfig.tracking?.telemetry) {\n warnings.push(\n '[MONITORING WARNING] telemetry is disabled in staging. ' +\n 'Enable it to test monitoring before production deployment.'\n );\n }\n}\n\n/**\n * Validate development encryption configuration\n *\n * Development environments have more relaxed requirements to facilitate rapid development:\n * - Encryption is OPTIONAL (enabled flag can be true, but key is not required)\n * - When encryption is enabled without a key, issues an informational warning\n *\n * **Why encryption is optional in development**:\n * - Faster iteration without needing to manage encryption keys\n * - Easier debugging of request/response payloads\n * - Test data typically doesn't contain real sensitive information\n *\n * @param mergedConfig - Merged configuration after applying all defaults\n * @param warnings - Warning array to append informational messages to\n *\n * @example\n * ```typescript\n * const warnings: string[] = [];\n * validateDevelopmentEncryption(mergedConfig, warnings);\n *\n * // If encryption enabled without key:\n * // warnings = ['[DEV INFO] Encryption is enabled but no key provided...']\n * ```\n *\n * @internal\n */\nfunction validateDevelopmentEncryption(mergedConfig: ApiClientOptions, warnings: string[]): void {\n if (mergedConfig.encryption?.enabled && !mergedConfig.encryption?.key) {\n warnings.push(\n '[DEV INFO] Encryption is enabled but no key provided in apiConfig. ' +\n 'Encryption will be skipped in development (this is normal).'\n );\n }\n}\n\n/**\n * Map environment metadata to API configuration structure\n *\n * Converts environment-level metadata from `CoreApiEnvironmentConfig` into `ApiConfig` format\n * that can be merged with other configurations. Currently maps:\n *\n * - **apiKey**: Converted to static header `X-API-Key`\n * - **rateLimit**: Reserved for future use (not currently mapped)\n *\n * **Note**: This mapping is applied AFTER environment defaults but BEFORE user-provided\n * apiConfig, giving it medium priority in the configuration merge hierarchy.\n *\n * @param envConfig - Environment configuration containing metadata\n * @param envDefaults - Environment-specific defaults from @plyaz/config\n * @returns Partial API configuration with mapped environment metadata\n *\n * @example\n * ```typescript\n * const envConfig = { env: 'production', apiKey: 'my-api-key' };\n * const envDefaults = PRODUCTION_CONFIG;\n *\n * const mapped = mapEnvironmentMetadata(envConfig, envDefaults);\n * // Returns: { headers: { static: { 'X-API-Key': 'my-api-key' } } }\n * ```\n *\n * @see {@link CoreApiEnvironmentConfig} - Environment configuration interface\n * @internal\n */\nfunction mapEnvironmentMetadata(\n envConfig: CoreApiEnvironmentConfig,\n envDefaults: Partial<ApiConfig>\n): Partial<ApiConfig> {\n const mapped: Partial<ApiConfig> = {};\n\n // Add API key to headers if provided\n if (envConfig.apiKey) {\n // Extract existing static headers if headers is an object with static property\n const existingStatic =\n envDefaults.headers &&\n typeof envDefaults.headers === 'object' &&\n 'static' in envDefaults.headers &&\n typeof envDefaults.headers.static === 'object'\n ? envDefaults.headers.static\n : {};\n\n mapped.headers = {\n static: { ...(existingStatic ?? {}), 'X-API-Key': envConfig.apiKey },\n };\n }\n\n // Note: rateLimit from envConfig is not mapped to ApiConfig\n // Rate limiting is typically handled at the server/API gateway level\n // If needed in the future, it should be added to ApiConfig interface first\n\n return mapped;\n}\n\n/**\n * Apply default client setting to @plyaz/api services and hooks\n *\n * Conditionally calls `setDefaultApiClient()` based on the `setAsDefault` flag in environment config.\n * When enabled, all services and hooks from @plyaz/api will automatically use this client instance\n * without needing to pass it explicitly via `ServiceOptions.apiClient`.\n *\n * **Default behavior**: If `setAsDefault` is not specified, it defaults to `true`.\n *\n * **Use cases**:\n * - `true` (default): Single API client for the entire application (recommended for most apps)\n * - `false`: Multiple API clients (main API, analytics API, etc.) or testing scenarios\n *\n * @param client - The API client instance to set as default\n * @param envConfig - Environment configuration containing the setAsDefault flag\n *\n * @example\n * ```typescript\n * const client = await createApiClient(config);\n * const envConfig = { env: 'production', setAsDefault: true };\n *\n * applyDefaultClientSetting(client, envConfig);\n * // Now all @plyaz/api services use this client automatically\n *\n * const campaigns = await fetchCampaigns({ page: 1 });\n * // No need to pass apiClient - uses the default\n * ```\n *\n * @example\n * ```typescript\n * // Multiple clients scenario\n * const mainClient = await createApiClient(mainConfig);\n * const analyticsClient = await createApiClient(analyticsConfig);\n *\n * applyDefaultClientSetting(mainClient, { env: 'production', setAsDefault: true });\n * applyDefaultClientSetting(analyticsClient, { env: 'production', setAsDefault: false });\n *\n * // Main API uses default\n * const campaigns = await fetchCampaigns({ page: 1 });\n *\n * // Analytics API must be passed explicitly\n * const analytics = await fetchAnalytics(\n * { date: '2025-10-16' },\n * { apiClient: analyticsClient }\n * );\n * ```\n *\n * @see {@link CoreApiEnvironmentConfig.setAsDefault} - Flag documentation\n * @see {@link ServiceOptions.apiClient} - How to override the default client\n * @internal\n */\nfunction applyDefaultClientSetting(\n client: ApiClientWithEvents<ClientEventManager, EndpointsList>,\n envConfig: CoreApiEnvironmentConfig\n): void {\n const shouldSetAsDefault = envConfig.setAsDefault !== false;\n if (shouldSetAsDefault) {\n setDefaultApiClient(client);\n }\n}\n\n/**\n * Validate environment configuration for production readiness.\n * Ensures critical settings are properly configured based on environment.\n *\n * @param envConfig - Environment configuration\n * @param mergedConfig - Merged configuration after applying all defaults\n * @throws {ApiPackageError} If validation fails\n */\nfunction validateEnvironmentConfig(\n envConfig: CoreApiEnvironmentConfig,\n mergedConfig: ApiClientOptions\n): void {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n // Validate required base URL\n validateBaseURL(mergedConfig, errors);\n\n // Environment-specific validation\n if (envConfig.env === 'production') {\n validateProductionEncryption(mergedConfig, errors, warnings);\n validateProductionPerformance(mergedConfig, warnings);\n } else if (envConfig.env === 'staging') {\n validateStagingEncryption(mergedConfig, errors, warnings);\n } else if (envConfig.env === 'development') {\n validateDevelopmentEncryption(mergedConfig, warnings);\n }\n\n // Log warnings (intentional console usage for config validation)\n if (warnings.length > 0) {\n globalThis.console.warn('[ApiClientService] Configuration warnings:', warnings);\n }\n\n // Throw if there are errors\n if (errors.length > 0) {\n throw new ApiPackageError(\n 'service.validation.failed',\n PACKAGE_STATUS_CODES.INVALID_CONFIGURATION,\n API_ERROR_CODES.CONFIG_VALIDATION_FAILED,\n {\n context: {\n operation: OPERATIONS.VALIDATION,\n // Ensure error details conform to ErrorDetail shape (include errorCode)\n errors: errors.map(err => ({\n field: 'config',\n message: err,\n errorCode: String(API_ERROR_CODES.CONFIG_VALIDATION_FAILED),\n })),\n i18n: {\n errors: errors.join('; '),\n warnings: warnings.join('; '),\n },\n },\n }\n );\n }\n}\n\n/**\n * API Client Singleton Service\n * Manages API client instance lifecycle with environment-specific configurations\n *\n * @example\n * ```typescript\n * // In your app initialization (Next.js, React, etc.)\n * import { ApiClientService } from '@plyaz/core';\n *\n * // Environment metadata\n * const envConfig = {\n * env: process.env.NODE_ENV as 'production',\n * apiKey: process.env.API_KEY,\n * };\n *\n * // API configuration with event handlers\n * await ApiClientService.init(envConfig, {\n * baseURL: process.env.API_URL!,\n * encryption: {\n * key: {\n * id: 'prod-key-v1',\n * key: process.env.ENCRYPTION_KEY!,\n * algorithm: 'AES-GCM'\n * }\n * },\n * clientEvents: {\n * onRequestStart: (event) => apiStore.trackRequest(event),\n * },\n * });\n *\n * // Later, anywhere in your app\n * const client = ApiClientService.getClient();\n * ```\n */\nexport class ApiClientService {\n private static instance: ApiClientWithEvents<ClientEventManager, EndpointsList> | null = null;\n private static isInitializing = false;\n private static initPromise: Promise<void> | null = null;\n\n /**\n * Initialize the API client with environment config and API options\n *\n * @param envConfig - Environment metadata (env, apiKey)\n * @param apiConfig - API configuration (baseURL, encryption, timeout, event handlers, etc.)\n * @returns Promise that resolves to the initialized client\n */\n static async init(\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n ): Promise<ApiClientWithEvents<ClientEventManager, EndpointsList>> {\n // If already initialized, return existing instance\n if (this.instance) {\n globalThis.console.warn(\n '[ApiClientService] Client already initialized. Returning existing instance.'\n );\n return this.instance;\n }\n\n // If currently initializing, wait for that to complete\n if (this.isInitializing && this.initPromise) {\n await this.initPromise;\n return this.instance!;\n }\n\n // Start initialization\n this.isInitializing = true;\n this.initPromise = this.createClient(envConfig, apiConfig);\n\n try {\n await this.initPromise;\n return this.instance!;\n } finally {\n this.isInitializing = false;\n this.initPromise = null;\n }\n }\n\n /**\n * Internal initialization logic\n * Merges environment-specific defaults with API configuration\n *\n * Merge Priority (lowest to highest):\n * 1. Environment defaults (PRODUCTION_CONFIG / STAGING_CONFIG / DEVELOPMENT_CONFIG)\n * 2. Environment metadata (envConfig - apiKey)\n * 3. API configuration (apiConfig - baseURL, encryption, timeout, etc.)\n */\n // eslint-disable-next-line max-lines-per-function, complexity\n private static async createClient(\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n ): Promise<void> {\n try {\n // Step 1: Get environment-specific defaults based on env\n const envDefaults = getConfigForEnvironment(envConfig.env);\n\n // Step 2: Build config from envConfig (environment metadata only)\n const envMetadataMapped = mapEnvironmentMetadata(envConfig, envDefaults);\n\n // Step 3: Create onError handler to emit errors to Core\n const coreErrorHandler = async (\n error: ResponseError<unknown, unknown, unknown, unknown>\n // eslint-disable-next-line complexity\n ): Promise<void> => {\n const requestId = generateRequestId();\n const method = error.config?.method ?? 'UNKNOWN';\n const url = error.config?.url ?? 'unknown';\n\n // CRITICAL: Emit error event to Core\n // Core will handle updating the appropriate store based on runtime context:\n // - Backend: In-memory store (ServerErrorMiddleware)\n // - Frontend: Zustand store (useRootStore)\n try {\n // API returns ErrorResponse (array of error details)\n const errorDetails = Array.isArray(error.response?.data) ? error.response.data : [];\n\n // If no error details from API, create a fallback error\n if (errorDetails.length === 0) {\n const serializedError = {\n id: requestId,\n code: ERROR_CODES.CORE_API_CLIENT_REQUEST_FAILED,\n message: error.message ?? 'API request failed',\n status: error.status,\n category: ERROR_CATEGORY.Network,\n timestamp: new Date().toISOString(),\n isRetryable: error.status ? error.status >= HTTP_STATUS.INTERNAL_SERVER_ERROR : false,\n source: 'api-client',\n dismissed: false,\n context: {\n method,\n url,\n requestId,\n },\n };\n\n // Emit single error to Core\n CoreEventManager.emit(CORE_EVENTS.SYSTEM.ERROR, { errors: [serializedError] });\n } else {\n // Convert ErrorResponse (API error details array) to SerializedError[]\n const serializedErrors = errorDetails.map(\n (detail: Record<string, unknown>, index: number) => ({\n id: `${requestId}-${index}`,\n code: (detail.errorCode as string) ?? ERROR_CODES.CORE_API_CLIENT_REQUEST_FAILED,\n message: (detail.message as string) ?? error.message ?? 'API request failed',\n status: error.status,\n category: ERROR_CATEGORY.Network,\n timestamp: new Date().toISOString(),\n isRetryable: error.status\n ? error.status >= HTTP_STATUS.INTERNAL_SERVER_ERROR\n : false,\n source: 'api-client',\n dismissed: false,\n context: {\n method,\n url,\n requestId,\n field: detail.field as string | undefined,\n valueGiven: detail.valueGiven,\n allowedValues: detail.allowedValues,\n constraints: detail.constraints,\n },\n })\n );\n\n // Emit array of errors to Core\n CoreEventManager.emit(CORE_EVENTS.SYSTEM.ERROR, { errors: serializedErrors });\n }\n } catch (e) {\n // If event emission fails, log but don't break the error flow\n console.error('[ApiClientService] Failed to emit error event:', e);\n }\n\n // Also emit API-specific error event for logging, monitoring, etc.\n ApiClientService.emitApiError(error, {\n method,\n url,\n requestId,\n status: error.status,\n duration: 0,\n });\n };\n\n // Step 4: Merge with priority: envDefaults → envMetadata → apiConfig → coreErrorHandler\n const userOnError = apiConfig?.onError;\n const combinedOnError = userOnError\n ? Array.isArray(userOnError)\n ? [...userOnError, coreErrorHandler]\n : [userOnError, coreErrorHandler]\n : coreErrorHandler;\n\n const mergedOptions = mergeConfigs(\n envDefaults, // Environment defaults (lowest priority)\n envMetadataMapped, // Environment metadata (medium priority)\n { ...(apiConfig ?? {}), onError: combinedOnError } // API configuration + core error handler\n ) as ApiClientOptions;\n\n // Step 5: Validate the merged configuration\n validateEnvironmentConfig(envConfig, mergedOptions);\n\n // Step 6: Create the client instance with merged configuration\n this.instance = await createApiClient(mergedOptions);\n\n // Step 6: Set as default client for @plyaz/api services and hooks (if enabled)\n applyDefaultClientSetting(this.instance, envConfig);\n } catch (error) {\n throw new ApiPackageError(\n 'service.initialization.failed',\n PACKAGE_STATUS_CODES.INITIALIZATION_FAILED,\n API_ERROR_CODES.CLIENT_INITIALIZATION_FAILED,\n {\n cause: error instanceof Error ? error : undefined,\n context: {\n operation: OPERATIONS.INITIALIZATION,\n originalError: error instanceof Error ? error.message : String(error),\n i18n: {\n error: error instanceof Error ? error.message : String(error),\n },\n },\n }\n );\n }\n }\n\n /**\n * Get the initialized client instance\n *\n * @throws {ApiPackageError} If client not initialized\n */\n static getClient(): ApiClientWithEvents<ClientEventManager, EndpointsList> {\n if (!this.instance) {\n throw new ApiPackageError(\n 'service.not_initialized',\n PACKAGE_STATUS_CODES.INITIALIZATION_FAILED,\n API_ERROR_CODES.CLIENT_INITIALIZATION_FAILED,\n {\n context: {\n operation: OPERATIONS.INITIALIZATION,\n i18n: {\n hint: 'Call ApiClientService.init(envConfig, apiConfig) before accessing the client',\n },\n },\n }\n );\n }\n return this.instance;\n }\n\n /**\n * Check if client is initialized\n */\n static isInitialized(): boolean {\n return this.instance !== null;\n }\n\n /**\n * Reinitialize with new config and options\n */\n static async reinitialize(\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n ): Promise<ApiClientWithEvents<ClientEventManager, EndpointsList>> {\n this.dispose();\n return this.init(envConfig, apiConfig);\n }\n\n /**\n * Dispose of the client instance\n */\n static dispose(): void {\n if (this.instance && 'dispose' in this.instance) {\n this.instance.dispose?.();\n }\n this.instance = null;\n this.isInitializing = false;\n this.initPromise = null;\n }\n\n /**\n * Emits an API error event via CoreEventManager.\n * Called when API operations fail to integrate with global error handling.\n *\n * **CRITICAL**: This event emission triggers automatic error state updates.\n * The global error store MUST subscribe to CORE_EVENTS.API.REQUEST_ERROR to:\n * 1. Capture all API errors automatically\n * 2. Update global error state for UI display\n * 3. Ensure individual domain stores remain error-free (only domain data)\n *\n * This is the unified error hook that:\n * - On frontend: Emits event that global error store subscribes to\n * - On backend: Emits event for logging/monitoring (can be configured to rethrow)\n *\n * @param error - The error that occurred\n * @param options - Additional context for the error\n * @param options.method - HTTP method (GET, POST, etc.)\n * @param options.url - Request URL\n * @param options.requestId - Unique request identifier\n * @param options.status - HTTP status code (if available)\n * @param options.duration - Request duration in ms\n * @param options.rethrow - Whether to rethrow the error after emitting (default: false)\n *\n * @example\n * ```typescript\n * // Global error store setup (in @plyaz/store)\n * CoreEventManager.on(CORE_EVENTS.API.REQUEST_ERROR, (payload) => {\n * errorStore.setError({\n * message: payload.error.message,\n * status: payload.status,\n * url: payload.url,\n * requestId: payload.requestId,\n * });\n * });\n *\n * // Frontend usage - emit to store\n * ApiClientService.emitApiError(error, {\n * method: 'GET',\n * url: '/api/users',\n * requestId: '123',\n * duration: 500,\n * });\n *\n * // Backend usage - emit and rethrow\n * ApiClientService.emitApiError(error, {\n * method: 'POST',\n * url: '/api/orders',\n * requestId: '456',\n * duration: 1200,\n * rethrow: true,\n * });\n * ```\n */\n static emitApiError(\n error: unknown,\n options: {\n method: string;\n url: string;\n requestId: string;\n status?: number;\n duration: number;\n rethrow?: boolean;\n }\n ): void {\n const payload: CoreApiRequestErrorPayload = {\n method: options.method,\n url: options.url,\n requestId: options.requestId,\n status: options.status,\n error,\n duration: options.duration,\n };\n\n CoreEventManager.emit(CORE_EVENTS.API.REQUEST_ERROR, payload);\n\n // Optionally rethrow for backend error propagation\n if (options.rethrow && error instanceof Error) {\n throw error;\n }\n }\n\n /**\n * Create a dedicated API client instance (NOT the singleton)\n *\n * Use this when you need an isolated client with its own configuration\n * that doesn't affect or get affected by the shared singleton instance.\n *\n * @param envConfig - Environment metadata (env, apiKey)\n * @param apiConfig - API configuration (baseURL, encryption, timeout, etc.)\n * @returns Promise that resolves to a new dedicated client instance\n *\n * @example\n * ```typescript\n * // Create a dedicated client for feature flags service\n * const flagsClient = await ApiClientService.createInstance(\n * { env: 'production' },\n * {\n * baseURL: 'https://flags.example.com',\n * timeout: 5000,\n * }\n * );\n *\n * // This client is independent from ApiClientService.getClient()\n * flagsClient.updateConfig({ timeout: 3000 }); // Only affects this instance\n * ```\n */\n static async createInstance(\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n ): Promise<ApiClientWithEvents<ClientEventManager, EndpointsList>> {\n try {\n // Step 1: Get environment-specific defaults based on env\n const envDefaults = getConfigForEnvironment(envConfig.env);\n\n // Step 2: Build config from envConfig (environment metadata only)\n const envMetadataMapped = mapEnvironmentMetadata(envConfig, envDefaults);\n\n // Step 3: Merge with priority: envDefaults → envMetadata → apiConfig\n const mergedOptions = mergeConfigs(\n envDefaults,\n envMetadataMapped,\n apiConfig ?? {}\n ) as ApiClientOptions;\n\n // Step 4: Validate the merged configuration\n validateEnvironmentConfig(envConfig, mergedOptions);\n\n // Step 5: Create a NEW client instance (not stored as singleton)\n const dedicatedClient = await createApiClient(mergedOptions);\n\n // Note: Do NOT call applyDefaultClientSetting - this is a dedicated instance\n // that should not become the default client for @plyaz/api services\n\n return dedicatedClient;\n } catch (error) {\n throw new ApiPackageError(\n 'service.instance_creation.failed',\n PACKAGE_STATUS_CODES.INITIALIZATION_FAILED,\n API_ERROR_CODES.CLIENT_INITIALIZATION_FAILED,\n {\n cause: error instanceof Error ? error : undefined,\n context: {\n operation: OPERATIONS.INITIALIZATION,\n originalError: error instanceof Error ? error.message : String(error),\n i18n: {\n error: error instanceof Error ? error.message : String(error),\n },\n },\n }\n );\n }\n }\n}\n\n// Export convenience helpers\nexport const getApiClient = (): ApiClientWithEvents<ClientEventManager, EndpointsList> =>\n ApiClientService.getClient();\n\nexport const initApiClient = (\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n): Promise<ApiClientWithEvents<ClientEventManager, EndpointsList>> =>\n ApiClientService.init(envConfig, apiConfig);\n\nexport const createApiClientInstance = (\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n): Promise<ApiClientWithEvents<ClientEventManager, EndpointsList>> =>\n ApiClientService.createInstance(envConfig, apiConfig);\n","/**\n * Base Observability Adapter\n *\n * Abstract base class for all observability adapters.\n * Provides common functionality and enforces the adapter interface.\n *\n * @module base/observability\n */\n\nimport { PackageLogger } from '@plyaz/logger';\nimport type {\n ObservabilityAdapter,\n ObservabilityAdapterConfig,\n ObservabilityProvider,\n Metric,\n SpanOptions,\n Span,\n LogEntry,\n ObservabilityEvent,\n SpanContext,\n} from '@plyaz/types/observability';\nimport { generateTraceId, generateSpanId } from '@/utils/common';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Abstract Base Adapter\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Abstract base class for observability adapters.\n *\n * Provides common functionality:\n * - Initialization lifecycle\n * - Default tag management\n * - Error handling\n * - Logging\n *\n * Subclasses must implement provider-specific methods.\n */\nexport abstract class BaseAdapter implements ObservabilityAdapter {\n abstract readonly provider: ObservabilityProvider;\n abstract readonly name: string;\n\n protected _isInitialized = false;\n protected _config: ObservabilityAdapterConfig | null = null;\n protected readonly logger: PackageLogger;\n\n constructor() {\n this.logger = new PackageLogger({\n packageName: 'core',\n service: 'ObservabilityAdapter',\n });\n }\n\n get isInitialized(): boolean {\n return this._isInitialized;\n }\n\n get config(): ObservabilityAdapterConfig | null {\n return this._config;\n }\n\n // ─── Lifecycle ─────────────────────────────────────────────────────────────\n\n async initialize(config: ObservabilityAdapterConfig): Promise<void> {\n if (this._isInitialized) {\n this.logger.warn(`${this.name} already initialized`);\n return;\n }\n\n this._config = config;\n\n if (config.enabled === false) {\n this.logger.info(`${this.name} disabled by configuration`);\n return;\n }\n\n await this.doInitialize(config);\n this._isInitialized = true;\n this.logger.info(`${this.name} initialized`, {\n provider: this.provider,\n serviceName: config.serviceName,\n environment: config.environment,\n });\n }\n\n async shutdown(): Promise<void> {\n if (!this._isInitialized) {\n return;\n }\n\n await this.flush();\n await this.doShutdown();\n this._isInitialized = false;\n this.logger.info(`${this.name} shut down`);\n }\n\n async isHealthy(): Promise<boolean> {\n if (!this._isInitialized) {\n return false;\n }\n return this.doHealthCheck();\n }\n\n // ─── Abstract Methods (Provider-specific) ──────────────────────────────────\n\n protected abstract doInitialize(config: ObservabilityAdapterConfig): Promise<void>;\n protected abstract doShutdown(): Promise<void>;\n protected abstract doHealthCheck(): Promise<boolean>;\n\n // ─── Metrics ───────────────────────────────────────────────────────────────\n\n async recordMetric(metric: Metric): Promise<void> {\n if (!this._isInitialized || this._config?.enabled === false) {\n return;\n }\n\n const metricWithDefaults = this.applyDefaultTags(metric);\n await this.doRecordMetric(metricWithDefaults);\n }\n\n async incrementCounter(\n name: string,\n value: number = 1,\n tags?: Record<string, string>\n ): Promise<void> {\n await this.recordMetric({\n type: 'counter',\n name,\n value,\n tags: { ...this._config?.defaultTags, ...tags },\n });\n }\n\n async setGauge(name: string, value: number, tags?: Record<string, string>): Promise<void> {\n await this.recordMetric({\n type: 'gauge',\n name,\n value,\n tags: { ...this._config?.defaultTags, ...tags },\n });\n }\n\n async recordHistogram(name: string, value: number, tags?: Record<string, string>): Promise<void> {\n await this.recordMetric({\n type: 'histogram',\n name,\n value,\n tags: { ...this._config?.defaultTags, ...tags },\n });\n }\n\n protected abstract doRecordMetric(metric: Metric): Promise<void>;\n\n // ─── Tracing ───────────────────────────────────────────────────────────────\n\n startSpan(options: SpanOptions): Span {\n if (!this._isInitialized || this._config?.enabled === false) {\n return this.createNoopSpan(options);\n }\n\n // Apply sampling\n if (this._config?.samplingRate !== undefined && this._config.samplingRate < 1) {\n if (Math.random() > this._config.samplingRate) {\n return this.createNoopSpan(options);\n }\n }\n\n return this.doStartSpan(options);\n }\n\n getActiveSpan(): Span | null {\n if (!this._isInitialized) {\n return null;\n }\n return this.doGetActiveSpan();\n }\n\n async withSpan<T>(options: SpanOptions, fn: (span: Span) => Promise<T>): Promise<T> {\n const span = this.startSpan(options);\n try {\n const result = await fn(span);\n span.setStatus('ok');\n return result;\n } catch (error) {\n span.setStatus('error', error instanceof Error ? error.message : String(error));\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n }\n\n protected abstract doStartSpan(options: SpanOptions): Span;\n protected abstract doGetActiveSpan(): Span | null;\n\n // ─── Logging ───────────────────────────────────────────────────────────────\n\n async log(entry: LogEntry): Promise<void> {\n if (!this._isInitialized || this._config?.enabled === false) {\n return;\n }\n\n const entryWithDefaults = {\n ...entry,\n timestamp: entry.timestamp ?? Date.now(),\n service: entry.service ?? this._config?.serviceName,\n };\n\n await this.doLog(entryWithDefaults);\n }\n\n protected abstract doLog(entry: LogEntry): Promise<void>;\n\n // ─── Events ────────────────────────────────────────────────────────────────\n\n async sendEvent(event: ObservabilityEvent): Promise<void> {\n if (!this._isInitialized || this._config?.enabled === false) {\n return;\n }\n\n const eventWithDefaults = {\n ...event,\n timestamp: event.timestamp ?? Date.now(),\n tags: { ...this._config?.defaultTags, ...event.tags },\n };\n\n await this.doSendEvent(eventWithDefaults);\n }\n\n protected abstract doSendEvent(event: ObservabilityEvent): Promise<void>;\n\n // ─── Flush ─────────────────────────────────────────────────────────────────\n\n async flush(): Promise<void> {\n if (!this._isInitialized) {\n return;\n }\n await this.doFlush();\n }\n\n protected abstract doFlush(): Promise<void>;\n\n // ─── Helpers ───────────────────────────────────────────────────────────────\n\n /**\n * Apply default tags to a metric\n */\n protected applyDefaultTags(metric: Metric): Metric {\n if (!this._config?.defaultTags) {\n return metric;\n }\n\n return {\n ...metric,\n tags: {\n ...this._config.defaultTags,\n ...metric.tags,\n },\n };\n }\n\n /**\n * Create a no-op span (for disabled/sampled-out traces)\n */\n // eslint-disable-next-line no-unused-vars\n protected createNoopSpan(_options: SpanOptions): Span {\n const context: SpanContext = {\n traceId: generateTraceId(),\n spanId: generateSpanId(),\n };\n\n return {\n context,\n setAttribute: () => {},\n setAttributes: () => {},\n addEvent: () => {},\n setStatus: () => {},\n end: () => {},\n recordException: () => {},\n };\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// No-Op Adapter\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * No-op adapter that does nothing.\n * Use when observability is disabled.\n */\nexport class NoopAdapter extends BaseAdapter {\n readonly provider = 'noop' as const;\n readonly name = 'NoopAdapter';\n\n protected async doInitialize(): Promise<void> {}\n protected async doShutdown(): Promise<void> {}\n protected async doHealthCheck(): Promise<boolean> {\n return true;\n }\n protected async doRecordMetric(): Promise<void> {}\n protected doStartSpan(options: SpanOptions): Span {\n return this.createNoopSpan(options);\n }\n protected doGetActiveSpan(): Span | null {\n return null;\n }\n protected async doLog(): Promise<void> {}\n protected async doSendEvent(): Promise<void> {}\n protected async doFlush(): Promise<void> {}\n}\n","/**\n * Logger Adapter\n *\n * Uses @plyaz/logger for observability output.\n * Can be used standalone OR alongside other adapters (Datadog, Grafana)\n * to always have console/file logging regardless of external providers.\n *\n * @example Standalone usage\n * ```typescript\n * const logger = new LoggerAdapter();\n * await logger.initialize({ serviceName: 'my-service' });\n * ```\n *\n * @example As console fallback with Datadog\n * ```typescript\n * const observability = new ObservabilityService({\n * mode: 'parallel',\n * adapters: [datadogAdapter, loggerAdapter], // Both receive all events\n * });\n * ```\n *\n * @module base/observability\n */\n\nimport { PackageLogger } from '@plyaz/logger';\nimport type {\n ObservabilityAdapterConfig,\n Metric,\n SpanOptions,\n Span,\n LogEntry,\n ObservabilityEvent,\n SpanContext,\n SpanAttributes,\n SpanEvent,\n SpanStatus,\n ConsoleAdapterConfig,\n} from '@plyaz/types/observability';\nimport { generateTraceId, generateSpanId } from '@/utils/common';\nimport { BaseAdapter } from './BaseAdapter';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Logger Adapter\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Logger adapter that uses @plyaz/logger for output.\n *\n * This adapter integrates observability with the existing logging infrastructure,\n * providing structured logging for metrics, spans, and events through PackageLogger.\n *\n * Use this adapter:\n * - As standalone for development/debugging\n * - Alongside Datadog/Grafana to always have local console output\n * - As a fallback in priority mode when external providers fail\n */\nexport class LoggerAdapter extends BaseAdapter {\n readonly provider = 'console' as const;\n readonly name = 'LoggerAdapter';\n\n private observabilityLogger!: PackageLogger;\n private logMetrics = true;\n private logSpans = true;\n private logEvents = true;\n\n protected async doInitialize(config: ObservabilityAdapterConfig): Promise<void> {\n const consoleConfig = config as ConsoleAdapterConfig;\n\n // Create dedicated logger for observability output\n this.observabilityLogger = new PackageLogger({\n packageName: 'observability',\n service: config.serviceName ?? 'LoggerAdapter',\n environment: config.environment as 'development' | 'staging' | 'production' | undefined,\n minLevel: consoleConfig.logLevel ?? 'debug',\n });\n\n // All logging enabled by default\n this.logMetrics = true;\n this.logSpans = true;\n this.logEvents = true;\n }\n\n protected async doShutdown(): Promise<void> {\n // Logger doesn't need explicit shutdown\n }\n\n protected async doHealthCheck(): Promise<boolean> {\n return true;\n }\n\n protected async doRecordMetric(metric: Metric): Promise<void> {\n if (!this.logMetrics) return;\n\n this.observabilityLogger.debug(`[METRIC] ${metric.type}:${metric.name}`, {\n metricType: metric.type,\n metricName: metric.name,\n value: 'value' in metric ? metric.value : undefined,\n unit: metric.unit,\n tags: metric.tags,\n });\n }\n\n protected doStartSpan(options: SpanOptions): Span {\n const context: SpanContext = {\n traceId: generateTraceId(),\n spanId: generateSpanId(),\n parentSpanId: options.parentContext?.spanId,\n };\n\n const startTime = options.startTime ?? Date.now();\n\n if (this.logSpans) {\n this.observabilityLogger.debug(`[SPAN START] ${options.name}`, {\n traceId: context.traceId,\n spanId: context.spanId,\n parentSpanId: context.parentSpanId,\n kind: options.kind,\n attributes: options.attributes,\n });\n }\n\n const events: SpanEvent[] = [];\n let attributes: SpanAttributes = { ...options.attributes };\n let status: SpanStatus = 'unset';\n let statusMessage: string | undefined;\n\n const logSpans = this.logSpans;\n const logger = this.observabilityLogger;\n\n return {\n context,\n setAttribute: (key, value) => {\n attributes[key] = value;\n },\n setAttributes: attrs => {\n attributes = { ...attributes, ...attrs };\n },\n addEvent: event => {\n events.push(event);\n if (logSpans) {\n logger.debug(`[SPAN EVENT] ${options.name}: ${event.name}`, {\n traceId: context.traceId,\n spanId: context.spanId,\n eventAttributes: event.attributes,\n });\n }\n },\n setStatus: (s, message) => {\n status = s;\n statusMessage = message;\n },\n end: endTime => {\n const duration = (endTime ?? Date.now()) - startTime;\n if (logSpans) {\n const logMethod = status === 'error' ? 'warn' : 'debug';\n logger[logMethod](`[SPAN END] ${options.name}`, {\n traceId: context.traceId,\n spanId: context.spanId,\n durationMs: duration,\n status,\n statusMessage,\n attributes,\n eventCount: events.length,\n });\n }\n },\n recordException: error => {\n if (logSpans) {\n logger.error(`[SPAN ERROR] ${options.name}`, {\n traceId: context.traceId,\n spanId: context.spanId,\n error: error.message,\n stack: error.stack,\n });\n }\n },\n };\n }\n\n protected doGetActiveSpan(): Span | null {\n return null; // Logger adapter doesn't track active spans\n }\n\n protected async doLog(entry: LogEntry): Promise<void> {\n const meta = {\n service: entry.service,\n traceId: entry.traceId,\n spanId: entry.spanId,\n ...entry.context,\n };\n\n // Map observability log levels to logger methods\n switch (entry.level) {\n case 'debug':\n this.observabilityLogger.debug(entry.message, meta);\n break;\n case 'info':\n this.observabilityLogger.info(entry.message, meta);\n break;\n case 'warn':\n this.observabilityLogger.warn(entry.message, meta);\n break;\n case 'error':\n this.observabilityLogger.error(entry.message, meta);\n break;\n case 'fatal':\n this.observabilityLogger.fatal(entry.message, meta);\n break;\n }\n }\n\n protected async doSendEvent(event: ObservabilityEvent): Promise<void> {\n if (!this.logEvents) return;\n\n this.observabilityLogger.info(`[EVENT] ${event.name}`, {\n eventName: event.name,\n properties: event.properties,\n tags: event.tags,\n });\n }\n\n protected async doFlush(): Promise<void> {\n // Logger handles its own buffering/flushing\n }\n}\n","/**\n * Observability Service\n *\n * Injectable service for observability (metrics, tracing, logging).\n * Works like CacheManager, DatabaseService, and ApiClient - can be injected into domain services.\n *\n * Adapters are initialized separately with their own configs.\n * This service only orchestrates - it doesn't know about adapter-specific configs.\n *\n * @module base/observability\n */\n\nimport { PackageLogger } from '@plyaz/logger';\nimport { CorePackageError } from '@plyaz/errors';\nimport { ERROR_CODES } from '@plyaz/types/errors';\nimport type {\n ObservabilityAdapter,\n ObservabilityAdapterConfig,\n Metric,\n SpanOptions,\n Span,\n LogEntry,\n ObservabilityEvent,\n OperationContext,\n MonitoringOperationResult,\n AdapterWithPriority,\n AdapterEntry,\n ObservabilityServiceConfig,\n ObservabilityServiceInterface,\n} from '@plyaz/types/observability';\nimport { OBSERVABILITY_METRICS } from '@plyaz/types/observability';\nimport { NoopAdapter } from './BaseAdapter';\nimport { LoggerAdapter } from './LoggerAdapter';\n\n// Default timeout for adapter operations (5 seconds)\nconst DEFAULT_ADAPTER_TIMEOUT_MS = 5000;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Observability Service Implementation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * ObservabilityService - Main observability service that implements ObservabilityAdapter.\n *\n * This service orchestrates multiple adapters and can be injected into domain services.\n * Logger adapter is always included by default for console output.\n *\n * ```typescript\n * // 1. Initialize adapters separately\n * const datadogAdapter = new DatadogAdapter();\n * await datadogAdapter.initialize({ apiKey: '...', serviceName: 'my-service' });\n *\n * // 2. Create service - logger is auto-added by default\n * const observability = new ObservabilityService();\n * await observability.initialize({\n * mode: 'parallel',\n * adapters: [datadogAdapter], // Logger added automatically\n * serviceName: 'my-service',\n * });\n *\n * // 3. Use in domain services (implements ObservabilityAdapter)\n * await observability.incrementCounter('api.requests', 1);\n * ```\n */\nexport class ObservabilityService implements ObservabilityAdapter, ObservabilityServiceInterface {\n readonly provider = 'custom' as const;\n readonly name = 'ObservabilityService';\n\n private _isInitialized = false;\n private _config: ObservabilityServiceConfig | null = null;\n private readonly logger: PackageLogger;\n private readonly adapterEntries: AdapterEntry[] = [];\n private mode: 'single' | 'parallel' | 'priority' = 'parallel';\n private readonly noopAdapter = new NoopAdapter();\n private loggerAdapter: LoggerAdapter | null = null;\n\n constructor() {\n this.logger = new PackageLogger({\n packageName: 'core',\n service: 'ObservabilityService',\n });\n }\n\n get isInitialized(): boolean {\n return this._isInitialized;\n }\n\n /**\n * Check if service has at least one working adapter\n */\n get isReady(): boolean {\n return this.adapterEntries.some(e => e.adapter.isInitialized);\n }\n\n /**\n * Get all adapters (for compatibility)\n */\n private get adapters(): ObservabilityAdapter[] {\n return this.adapterEntries.map(e => e.adapter);\n }\n\n /**\n * Get initialized adapter entries\n */\n private get initializedEntries(): AdapterEntry[] {\n return this.adapterEntries.filter(e => e.adapter.isInitialized);\n }\n\n /**\n * Get primary (non-failover) initialized adapters\n */\n private get primaryEntries(): AdapterEntry[] {\n return this.initializedEntries.filter(e => !e.failover);\n }\n\n /**\n * Get failover initialized adapters\n */\n private get failoverEntries(): AdapterEntry[] {\n return this.initializedEntries.filter(e => e.failover);\n }\n\n // ─── Lifecycle ─────────────────────────────────────────────────────────────\n\n /**\n * Check if input is an adapter with priority config\n */\n private isAdapterWithPriority(\n input: ObservabilityAdapter | AdapterWithPriority\n ): input is AdapterWithPriority {\n return (\n 'adapter' in input &&\n typeof (input as AdapterWithPriority).adapter?.isInitialized === 'boolean'\n );\n }\n\n /**\n * Normalize adapter input to adapter with priority and failover config\n */\n private normalizeAdapter(\n input: ObservabilityAdapter | AdapterWithPriority,\n defaultPriority: number\n ): { adapter: ObservabilityAdapter; priority: number; failover: boolean } {\n if (this.isAdapterWithPriority(input)) {\n return {\n adapter: input.adapter,\n priority: input.priority ?? defaultPriority,\n failover: input.failover ?? false,\n };\n }\n return { adapter: input, priority: defaultPriority, failover: false };\n }\n\n /**\n * Initialize the observability service.\n * Logger adapter is always added by default unless explicitly disabled.\n * Adapters are sorted by priority (higher = first), with failover adapters after primary.\n */\n async initialize(config: ObservabilityAdapterConfig & ObservabilityServiceConfig): Promise<void> {\n if (this._isInitialized) {\n this.logger.warn('ObservabilityService already initialized');\n return;\n }\n\n this._config = config;\n this.mode = config.mode ?? 'parallel';\n\n // Collect adapters with priorities\n const entries: AdapterEntry[] = [];\n\n // Add provided adapters\n if (config.adapter) {\n entries.push(this.normalizeAdapter(config.adapter, 0));\n }\n if (config.adapters) {\n config.adapters.forEach((a, index) => {\n // Default priority decreases with array position for stable sorting\n entries.push(this.normalizeAdapter(a, -index));\n });\n }\n\n // Always add logger adapter by default (for console output)\n // Unless there's already a console/logger adapter\n const hasLoggerAdapter = entries.some(\n e => e.adapter.provider === 'console' || e.adapter.name === 'LoggerAdapter'\n );\n if (!hasLoggerAdapter) {\n this.loggerAdapter = new LoggerAdapter();\n await this.loggerAdapter.initialize({\n enabled: config.enabled !== false,\n serviceName: config.serviceName,\n environment: config.environment,\n defaultTags: config.defaultTags,\n });\n // Logger is a failover by default with lowest priority\n entries.push({ adapter: this.loggerAdapter, priority: -1000, failover: true });\n }\n\n // Sort: primary adapters first (by priority desc), then failover adapters (by priority desc)\n entries.sort((a, b) => {\n // Primary adapters come before failover\n if (a.failover !== b.failover) {\n return a.failover ? 1 : -1;\n }\n // Within same category, sort by priority (higher first)\n return b.priority - a.priority;\n });\n\n // Store sorted entries\n this.adapterEntries.push(...entries);\n\n this._isInitialized = true;\n\n this.logger.debug('ObservabilityService initialized', {\n mode: this.mode,\n adapterCount: this.adapterEntries.length,\n primaryCount: this.primaryEntries.length,\n failoverCount: this.failoverEntries.length,\n adapters: this.adapterEntries.map(e => ({\n name: e.adapter.name,\n provider: e.adapter.provider,\n priority: e.priority,\n failover: e.failover,\n initialized: e.adapter.isInitialized,\n })),\n });\n }\n\n async shutdown(): Promise<void> {\n await Promise.all(this.adapters.map(adapter => adapter.shutdown()));\n this._isInitialized = false;\n this.logger.info('ObservabilityService shut down');\n }\n\n async isHealthy(): Promise<boolean> {\n if (this.adapters.length === 0) {\n return false;\n }\n\n const results = await Promise.all(\n this.adapters.map(adapter => adapter.isHealthy().catch(() => false))\n );\n\n // For parallel mode, all must be healthy; for priority/single, at least one\n return this.mode === 'parallel' ? results.every(Boolean) : results.some(Boolean);\n }\n\n async flush(): Promise<void> {\n await this.executeOnAdapters('flush', adapter => adapter.flush());\n }\n\n // ─── Execute on Adapters ───────────────────────────────────────────────────\n\n private get config(): ObservabilityServiceConfig {\n return this._config ?? {};\n }\n\n private async executeOnAdapters<T>(\n operation: string,\n fn: (adapter: ObservabilityAdapter) => Promise<T>\n ): Promise<void> {\n const entries = this.initializedEntries;\n if (entries.length === 0) {\n return;\n }\n\n const timeout = this.config.adapterTimeout ?? DEFAULT_ADAPTER_TIMEOUT_MS;\n\n switch (this.mode) {\n case 'parallel':\n await this.executeParallelWithFailover(operation, fn, timeout);\n break;\n case 'priority':\n await this.executePriorityWithFailover(operation, fn, timeout);\n break;\n case 'single':\n default:\n await this.executeSingle(operation, entries[0].adapter, fn, timeout);\n break;\n }\n }\n\n private async executeSingle<T>(\n operation: string,\n adapter: ObservabilityAdapter,\n fn: (adapter: ObservabilityAdapter) => Promise<T>,\n timeout: number\n ): Promise<void> {\n try {\n await this.withTimeout(fn(adapter), timeout);\n } catch (error) {\n this.logger.error(`${operation} failed on ${adapter.name}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n /**\n * Execute on primary adapters in parallel.\n * If all primary adapters fail, execute on failover adapters.\n */\n // eslint-disable-next-line complexity\n private async executeParallelWithFailover<T>(\n operation: string,\n fn: (adapter: ObservabilityAdapter) => Promise<T>,\n timeout: number\n ): Promise<void> {\n const primary = this.primaryEntries;\n const failover = this.failoverEntries;\n\n // Execute on primary adapters\n if (primary.length > 0) {\n const results = await Promise.allSettled(\n primary.map(e => this.withTimeout(fn(e.adapter), timeout))\n );\n\n const errors = results\n .map((r, i) =>\n r.status === 'rejected' ? { adapter: primary[i].adapter.name, error: r.reason } : null\n )\n .filter(Boolean);\n\n const allFailed = errors.length === primary.length;\n\n if (errors.length > 0 && !allFailed) {\n this.logger.warn(`${operation} failed on some primary adapters`, { errors });\n }\n\n // If all primary adapters failed, use failover\n if (allFailed && failover.length > 0) {\n this.logger.warn(`${operation} failed on all primary adapters, using failover`, { errors });\n await this.executeParallel(\n operation,\n failover.map(e => e.adapter),\n fn,\n timeout\n );\n return;\n }\n\n if (this.config.failOnAnyError && errors.length > 0) {\n throw new CorePackageError(\n `${operation} failed on adapters: ${errors.map(e => e?.adapter).join(', ')}`,\n ERROR_CODES.CORE_OPERATION_FAILED\n );\n }\n } else if (failover.length > 0) {\n // No primary adapters, use failover directly\n await this.executeParallel(\n operation,\n failover.map(e => e.adapter),\n fn,\n timeout\n );\n }\n }\n\n private async executeParallel<T>(\n operation: string,\n adapters: ObservabilityAdapter[],\n fn: (adapter: ObservabilityAdapter) => Promise<T>,\n timeout: number\n ): Promise<void> {\n const results = await Promise.allSettled(\n adapters.map(adapter => this.withTimeout(fn(adapter), timeout))\n );\n\n const errors = results\n .map((r, i) =>\n r.status === 'rejected' ? { adapter: adapters[i].name, error: r.reason } : null\n )\n .filter(Boolean);\n\n if (errors.length > 0) {\n this.logger.warn(`${operation} failed on some adapters`, { errors });\n }\n }\n\n /**\n * Execute on primary adapters in priority order.\n * If all primary adapters fail, try failover adapters.\n */\n // eslint-disable-next-line complexity\n private async executePriorityWithFailover<T>(\n operation: string,\n fn: (adapter: ObservabilityAdapter) => Promise<T>,\n timeout: number\n ): Promise<void> {\n const primary = this.primaryEntries;\n const failover = this.failoverEntries;\n\n // Try primary adapters first\n for (const entry of primary) {\n try {\n await this.withTimeout(fn(entry.adapter), timeout);\n return; // Success - stop trying\n } catch (error) {\n const errorName = error instanceof Error ? error.name : 'Error';\n const shouldFallback =\n !this.config.fallbackOnErrors || this.config.fallbackOnErrors.includes(errorName);\n\n if (shouldFallback) {\n this.logger.warn(`${operation} failed on ${entry.adapter.name}, trying next`, {\n error: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n throw error;\n }\n }\n\n // All primary failed, try failover adapters\n for (const entry of failover) {\n try {\n await this.withTimeout(fn(entry.adapter), timeout);\n return; // Success\n } catch (error) {\n this.logger.warn(`${operation} failed on failover ${entry.adapter.name}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n // Continue to next failover adapter\n }\n }\n\n this.logger.error(`${operation} failed on all adapters (primary and failover)`);\n }\n\n private async withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\n return Promise.race([\n promise,\n new Promise<T>((_, reject) =>\n setTimeout(() => reject(new Error(`Operation timed out after ${timeoutMs}ms`)), timeoutMs)\n ),\n ]);\n }\n\n // ─── Metrics ───────────────────────────────────────────────────────────────\n\n async recordMetric(metric: Metric): Promise<void> {\n await this.executeOnAdapters('recordMetric', adapter => adapter.recordMetric(metric));\n }\n\n async incrementCounter(\n name: string,\n value: number = 1,\n tags?: Record<string, string>\n ): Promise<void> {\n await this.executeOnAdapters('incrementCounter', adapter =>\n adapter.incrementCounter(name, value, tags)\n );\n }\n\n async setGauge(name: string, value: number, tags?: Record<string, string>): Promise<void> {\n await this.executeOnAdapters('setGauge', adapter => adapter.setGauge(name, value, tags));\n }\n\n async recordHistogram(name: string, value: number, tags?: Record<string, string>): Promise<void> {\n await this.executeOnAdapters('recordHistogram', adapter =>\n adapter.recordHistogram(name, value, tags)\n );\n }\n\n // ─── Tracing ───────────────────────────────────────────────────────────────\n\n startSpan(options: SpanOptions): Span {\n // For tracing, use first initialized adapter\n const entry = this.initializedEntries[0];\n return entry?.adapter.startSpan(options) ?? this.noopAdapter.startSpan(options);\n }\n\n async withSpan<T>(options: SpanOptions, fn: (span: Span) => Promise<T>): Promise<T> {\n const entry = this.initializedEntries[0];\n if (!entry) {\n return fn(this.noopAdapter.startSpan(options));\n }\n return entry.adapter.withSpan(options, fn);\n }\n\n getActiveSpan(): Span | null {\n const entry = this.initializedEntries[0];\n return entry?.adapter.getActiveSpan() ?? null;\n }\n\n // ─── Logging ───────────────────────────────────────────────────────────────\n\n async log(entry: LogEntry): Promise<void> {\n await this.executeOnAdapters('log', adapter => adapter.log(entry));\n }\n\n // ─── Events ────────────────────────────────────────────────────────────────\n\n async sendEvent(event: ObservabilityEvent): Promise<void> {\n await this.executeOnAdapters('sendEvent', adapter => adapter.sendEvent(event));\n }\n\n // ─── Service Operation Tracking ────────────────────────────────────────────\n\n /**\n * Track a service operation with automatic metrics and tracing.\n *\n * @example\n * ```typescript\n * const { result, metrics } = await observability.trackOperation(\n * {\n * serviceName: 'UserService',\n * operation: 'create',\n * entityType: 'user',\n * startTime: Date.now(),\n * },\n * async () => {\n * return await this.repository.create(userData);\n * }\n * );\n * ```\n */\n // eslint-disable-next-line complexity\n async trackOperation<T>(\n context: OperationContext,\n operation: () => Promise<T>\n ): Promise<{ result: T; metrics: MonitoringOperationResult }> {\n const startTime = context.startTime ?? Date.now();\n\n // Start span\n const span = this.startSpan({\n name: `${context.serviceName}.${context.operation}`,\n attributes: {\n 'service.name': context.serviceName,\n 'operation.name': context.operation,\n ...(context.entityType && { 'entity.type': context.entityType }),\n ...(context.entityId && { 'entity.id': context.entityId }),\n ...context.attributes,\n },\n parentContext: context.parentContext,\n });\n\n // Increment operation counter\n await this.incrementCounter(OBSERVABILITY_METRICS.SERVICE_OPERATION_COUNT, 1, {\n service: context.serviceName,\n operation: context.operation,\n ...(context.entityType && { entity_type: context.entityType }),\n });\n\n try {\n const result = await operation();\n const duration = Date.now() - startTime;\n\n span.setStatus('ok');\n\n await this.recordHistogram(OBSERVABILITY_METRICS.SERVICE_OPERATION_DURATION, duration, {\n service: context.serviceName,\n operation: context.operation,\n status: 'success',\n });\n\n return {\n result,\n metrics: { success: true, duration, data: result },\n };\n } catch (error) {\n const duration = Date.now() - startTime;\n\n span.setStatus('error', error instanceof Error ? error.message : String(error));\n if (error instanceof Error) {\n span.recordException(error);\n }\n\n await this.incrementCounter(OBSERVABILITY_METRICS.SERVICE_OPERATION_ERROR, 1, {\n service: context.serviceName,\n operation: context.operation,\n error_type: error instanceof Error ? error.name : 'UnknownError',\n });\n\n await this.recordHistogram(OBSERVABILITY_METRICS.SERVICE_OPERATION_DURATION, duration, {\n service: context.serviceName,\n operation: context.operation,\n status: 'error',\n });\n\n throw error;\n } finally {\n span.end();\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Factory Function\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Create an ObservabilityService with pre-initialized adapters.\n *\n * @example\n * ```typescript\n * // Initialize adapters first\n * const datadogAdapter = new DatadogAdapter();\n * await datadogAdapter.initialize({ apiKey: '...', serviceName: 'my-service' });\n *\n * // Create and initialize service (logger auto-added)\n * const observability = await createObservabilityService({\n * mode: 'parallel',\n * adapters: [datadogAdapter],\n * serviceName: 'my-service',\n * });\n *\n * // Priority mode (fallback chain)\n * const observability = await createObservabilityService({\n * mode: 'priority',\n * adapters: [datadogAdapter, grafanaAdapter],\n * serviceName: 'my-service',\n * });\n * ```\n */\nexport async function createObservabilityService(\n config: ObservabilityServiceConfig & { serviceName?: string; environment?: string } = {}\n): Promise<ObservabilityService> {\n const service = new ObservabilityService();\n await service.initialize(config);\n return service;\n}\n","/**\n * Core Dependencies Configuration\n *\n * Similar to @plyaz/api's setGlobalConfig pattern.\n * Backend services are registered here by entry points, not imported directly.\n *\n * IMPORTANT: This file must NOT import from backend service files (DbService, CacheService, etc.)\n * as that would cause the bundler to include backend dependencies in the frontend bundle.\n *\n * @example\n * ```typescript\n * // entry-backend.ts\n * import { setCoreDependencies } from './config/dependencies';\n * import { DbService } from './services/DbService';\n * import { CacheService } from './services/CacheService';\n *\n * setCoreDependencies({\n * DbService,\n * CacheService,\n * StorageService,\n * NotificationService,\n * });\n *\n * // entry-frontend.ts\n * // Don't call setCoreDependencies - no backend deps loaded\n * ```\n */\n\nimport type {\n CoreDbServiceStatic,\n CoreCacheServiceStatic,\n CoreStorageServiceStatic,\n CoreNotificationServiceStatic,\n CoreServerErrorMiddlewareStatic,\n} from '@plyaz/types/core';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Dependencies Container\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface CoreDependencies {\n DbService?: CoreDbServiceStatic;\n CacheService?: CoreCacheServiceStatic;\n StorageService?: CoreStorageServiceStatic;\n NotificationService?: CoreNotificationServiceStatic;\n ServerErrorMiddleware?: CoreServerErrorMiddlewareStatic;\n}\n\n// Global dependencies container\nlet _dependencies: CoreDependencies = {};\n\n/**\n * Set core dependencies (called by entry points)\n *\n * @example\n * ```typescript\n * // entry-backend.ts\n * import { DbService } from './services/DbService';\n * import { CacheService } from './services/CacheService';\n *\n * setCoreDependencies({\n * DbService,\n * CacheService,\n * });\n * ```\n */\nexport function setCoreDependencies(deps: CoreDependencies): void {\n _dependencies = { ..._dependencies, ...deps };\n}\n\n/**\n * Get core dependencies\n */\nexport function getCoreDependencies(): CoreDependencies {\n return _dependencies;\n}\n\n/**\n * Check if a dependency is available\n */\nexport function hasCoreDependency(key: keyof CoreDependencies): boolean {\n return _dependencies[key] !== undefined;\n}\n\n/**\n * Get a specific dependency\n */\nexport function getCoreDependency<K extends keyof CoreDependencies>(\n key: K\n): CoreDependencies[K] | undefined {\n return _dependencies[key];\n}\n\n/**\n * Clear all dependencies (useful for testing)\n */\nexport function clearCoreDependencies(): void {\n _dependencies = {};\n}\n","// This eslint disable is an edge-case as we need to ensure that we're able to load CoreInitializer regardless if FE, BE or specific frameworks\n/**\n * Service Registry - Frontend Service Auto-Initialization\n *\n * Provides a generic, scalable pattern for initializing domain services.\n * Services implement the InitializableDomainService interface and are\n * initialized automatically without hardcoded switch statements.\n *\n * @example\n * ```typescript\n * import { ServiceRegistry } from '@plyaz/core';\n * import { FeatureFlagDomainService } from '@plyaz/core/frontend';\n * import { ExampleDomainService } from '@plyaz/core/domain';\n *\n * // Initialize services\n * await ServiceRegistry.initialize({\n * apiClient: { baseURL: '/api' },\n * services: [\n * { service: FeatureFlagDomainService, config: { enabled: true } },\n * { service: ExampleDomainService, config: { enabled: true, useRealApi: false } },\n * ],\n * });\n *\n * // Access services by key\n * const flags = ServiceRegistry.get('featureFlags');\n * const isEnabled = await flags.isEnabled('my-flag');\n *\n * // Or get with type safety\n * const example = ServiceRegistry.get<ExampleDomainService>('example');\n * ```\n */\n\nimport { CorePackageError } from '@plyaz/errors';\nimport { ERROR_CODES, BACKEND_RUNTIMES, FRONTEND_RUNTIMES } from '@plyaz/types';\nimport { PackageLogger } from '@plyaz/logger';\nimport type { ApiClientOptions } from '@plyaz/types/api';\nimport type { RootStoreSlice } from '@plyaz/types/store';\nimport type {\n CoreDomainServiceInstance,\n CoreServiceCreateOptions,\n CoreServiceEntry,\n CoreServiceInitConfig,\n CoreServiceRegistryConfig,\n CoreCacheConfig,\n CoreObservabilityConfig,\n CoreRuntimeEnvironment,\n CoreDbServiceConfig,\n CoreStorageConfig,\n CoreNotificationConfig,\n // Service instance types (from @plyaz/types, not backend modules)\n CoreDbServiceInstance,\n CoreCacheManagerInstance,\n CoreStorageServiceInstance,\n CoreNotificationServiceInstance,\n} from '@plyaz/types/core';\nimport type { ObservabilityAdapter } from '@plyaz/types/observability';\nimport { createObservabilityService } from '../base/observability';\nimport { ApiClientService } from '../services/ApiClientService';\nimport { getCoreDependency } from '../config/dependencies';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal Types\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface PendingService {\n entry: CoreServiceEntry;\n initWhen: CoreServiceInitConfig['initWhen'];\n}\n\ninterface ServiceMetadata {\n entry: CoreServiceEntry;\n isSingleton: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Service Registry\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Service Registry\n *\n * Manages frontend domain service instances with auto-initialization.\n * Supports immediate, lazy, and conditional initialization.\n *\n * Key features:\n * - Generic: No switch statements, services implement common interface\n * - Scalable: Add new services without modifying registry code\n * - Flexible: Immediate, lazy, or conditional initialization\n * - Type-safe: Get services with proper typing\n */\nexport class ServiceRegistry {\n private static readonly logger = new PackageLogger({\n packageName: 'core',\n service: 'ServiceRegistry',\n });\n\n /** Initialized singleton service instances by key */\n private static _services = new Map<string, CoreDomainServiceInstance>();\n\n /** Pending services for lazy initialization */\n private static _pending = new Map<string, PendingService>();\n\n /** Service metadata (config, singleton flag) by key */\n private static _metadata = new Map<string, ServiceMetadata>();\n\n /** Global environment */\n private static _environment: 'production' | 'staging' | 'development' | 'test' = 'development';\n\n /** Runtime environment (node, browser, bun, etc.) */\n private static _runtime: CoreRuntimeEnvironment = 'node';\n\n /** Global API client options */\n private static _apiClientOptions: ApiClientOptions | null = null;\n\n /** Global database config */\n private static _dbConfig: Partial<CoreDbServiceConfig> | null = null;\n\n /** Global cache config */\n private static _cacheConfig: CoreCacheConfig | null = null;\n\n /** Global observability config */\n private static _observabilityConfig: CoreObservabilityConfig | null = null;\n\n /** Global observability adapter instance */\n private static _observabilityInstance: ObservabilityAdapter | null = null;\n\n /** Global storage config */\n private static _storageConfig: CoreStorageConfig | null = null;\n\n /** Global notifications config */\n private static _notificationsConfig: CoreNotificationConfig | null = null;\n\n /** Store registry interface from Core (type-safe) */\n private static _storeRegistry: {\n getStore<K extends keyof RootStoreSlice>(key: K): RootStoreSlice[K] | undefined;\n } | null = null;\n\n /** Initialization promises (for concurrent access during lazy init) */\n private static _initPromises = new Map<string, Promise<CoreDomainServiceInstance>>();\n\n // ─────────────────────────────────────────────────────────────────────────\n // Initialization\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Initialize the service registry with the provided configuration.\n *\n * @param config - Registry configuration with services to initialize\n *\n * @example\n * ```typescript\n * await ServiceRegistry.initialize({\n * apiClient: { baseURL: '/api' },\n * services: [\n * { service: FeatureFlagDomainService, config: { enabled: true } },\n * { service: ExampleDomainService, config: { enabled: true, initWhen: 'lazy' } },\n * ],\n * });\n * ```\n */\n // eslint-disable-next-line complexity\n static async initialize(config: CoreServiceRegistryConfig): Promise<void> {\n ServiceRegistry._environment = config.environment ?? 'development';\n ServiceRegistry._runtime = config.runtime ?? 'node';\n ServiceRegistry._apiClientOptions = config.apiClient ?? null;\n ServiceRegistry._dbConfig = config.db ?? null;\n ServiceRegistry._cacheConfig = config.cache ?? null;\n ServiceRegistry._observabilityConfig = config.observability ?? null;\n ServiceRegistry._storageConfig = config.storage ?? null;\n ServiceRegistry._notificationsConfig = config.notifications ?? null;\n ServiceRegistry._storeRegistry = config.stores ?? null;\n\n const immediatePromises: Promise<void>[] = [];\n\n for (const entry of config.services) {\n const serviceKey = entry.service.serviceKey;\n const initWhen = entry.config.initWhen ?? 'immediate';\n const enabled = entry.config.enabled !== false;\n const isSingleton = entry.config.singleton !== false; // Default: true\n\n // Store metadata for all services (even disabled)\n ServiceRegistry._metadata.set(serviceKey, { entry, isSingleton });\n\n // Skip disabled services\n if (!enabled) {\n ServiceRegistry.logger.debug(`Service ${serviceKey} is disabled, skipping`);\n continue;\n }\n\n // Handle initialization timing\n if (initWhen === 'immediate' && isSingleton) {\n // Only auto-initialize singletons\n immediatePromises.push(\n ServiceRegistry.initializeService(entry).then(() => {\n ServiceRegistry.logger.debug(`Service ${serviceKey} initialized (singleton)`);\n })\n );\n } else if (isSingleton) {\n // Store for lazy/conditional initialization\n ServiceRegistry._pending.set(serviceKey, { entry, initWhen });\n ServiceRegistry.logger.debug(\n `Service ${serviceKey} registered for ${initWhen} initialization`\n );\n } else {\n // Non-singleton: just store metadata, create on demand via create()\n ServiceRegistry.logger.debug(\n `Service ${serviceKey} registered (non-singleton, use create())`\n );\n }\n }\n\n // Wait for all immediate initializations\n await Promise.all(immediatePromises);\n\n const initializedKeys = [...ServiceRegistry._services.keys()];\n const pendingKeys = [...ServiceRegistry._pending.keys()];\n const nonSingletonKeys = [...ServiceRegistry._metadata.entries()]\n .filter(([, meta]) => !meta.isSingleton)\n .map(([key]) => key);\n\n ServiceRegistry.logger.info('Service registry initialized', {\n initialized: initializedKeys,\n pending: pendingKeys,\n nonSingleton: nonSingletonKeys,\n });\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Service Access\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Get a singleton service instance by key (synchronous).\n * Throws if the service is not initialized or is non-singleton.\n *\n * @param key - Service key (e.g., 'featureFlags', 'example')\n * @returns The service instance\n * @throws CorePackageError if service not found, not initialized, or non-singleton\n *\n * @example\n * ```typescript\n * const flags = ServiceRegistry.get<FeatureFlagDomainService>('featureFlags');\n * const isEnabled = await flags.isEnabled('my-flag');\n * ```\n */\n static get<T extends CoreDomainServiceInstance = CoreDomainServiceInstance>(key: string): T {\n const service = ServiceRegistry._services.get(key);\n if (service) {\n return service as T;\n }\n\n // Check if non-singleton (must use create())\n const metadata = ServiceRegistry._metadata.get(key);\n if (metadata && !metadata.isSingleton) {\n throw new CorePackageError(\n `Service '${key}' is configured as non-singleton. ` +\n `Use await ServiceRegistry.create('${key}') to create a new instance.`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n // Check if pending lazy initialization\n const pending = ServiceRegistry._pending.get(key);\n if (pending) {\n throw new CorePackageError(\n `Service '${key}' is configured for lazy initialization. ` +\n `Use await ServiceRegistry.getAsync('${key}') instead.`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n throw new CorePackageError(\n `Service '${key}' not found. Register it in ServiceRegistry.initialize()`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n /**\n * Create a new instance of a service.\n * Use this for non-singleton services or when you need a fresh instance.\n *\n * Note: The caller is responsible for disposing the returned instance.\n *\n * @param key - Service key\n * @param configOverrides - Optional config overrides for this instance\n * @returns Promise resolving to a new service instance\n *\n * @example\n * ```typescript\n * // Non-singleton service - always creates new instance\n * const instance1 = await ServiceRegistry.create<WorkerService>('worker');\n * const instance2 = await ServiceRegistry.create<WorkerService>('worker');\n * instance1 !== instance2; // true\n *\n * // With config overrides\n * const customWorker = await ServiceRegistry.create<WorkerService>('worker', {\n * apiClient: { baseURL: 'https://custom-api.com' },\n * });\n *\n * // Don't forget to dispose when done!\n * instance1.dispose();\n * instance2.dispose();\n * ```\n */\n static async create<T extends CoreDomainServiceInstance = CoreDomainServiceInstance>(\n key: string,\n configOverrides?: Partial<CoreServiceInitConfig>\n ): Promise<T> {\n const metadata = ServiceRegistry._metadata.get(key);\n if (!metadata) {\n throw new CorePackageError(\n `Service '${key}' not found. Register it in ServiceRegistry.initialize()`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n // Merge config with overrides\n const mergedEntry: CoreServiceEntry = {\n service: metadata.entry.service,\n config: { ...metadata.entry.config, ...configOverrides },\n };\n\n // Create new instance (don't store in registry)\n return ServiceRegistry.initializeService(mergedEntry, false) as Promise<T>;\n }\n\n /**\n * Get a service instance by key with async initialization if needed.\n * Use this for lazy-initialized services.\n *\n * @param key - Service key\n * @returns Promise resolving to the service instance\n *\n * @example\n * ```typescript\n * const example = await ServiceRegistry.getAsync<ExampleDomainService>('example');\n * const entities = await example.getAll();\n * ```\n */\n static async getAsync<T extends CoreDomainServiceInstance = CoreDomainServiceInstance>(\n key: string\n ): Promise<T> {\n // Return immediately if already initialized\n const existing = ServiceRegistry._services.get(key);\n if (existing) {\n return existing as T;\n }\n\n // Check for in-progress initialization\n const inProgress = ServiceRegistry._initPromises.get(key);\n if (inProgress) {\n return (await inProgress) as T;\n }\n\n // Check if pending lazy initialization\n const pending = ServiceRegistry._pending.get(key);\n if (pending) {\n // Handle conditional initialization\n if (typeof pending.initWhen === 'function') {\n const shouldInit = await pending.initWhen();\n if (!shouldInit) {\n throw new CorePackageError(\n `Service '${key}' initialization condition returned false`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n }\n\n // Initialize and return\n const service = await ServiceRegistry.initializeService(pending.entry);\n ServiceRegistry._pending.delete(key);\n return service as T;\n }\n\n throw new CorePackageError(\n `Service '${key}' not found. Register it in ServiceRegistry.initialize()`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n /**\n * Check if a service is registered (either initialized or pending).\n *\n * @param key - Service key\n */\n static has(key: string): boolean {\n return ServiceRegistry._services.has(key) || ServiceRegistry._pending.has(key);\n }\n\n /**\n * Check if a service is initialized and ready.\n *\n * @param key - Service key\n */\n static isInitialized(key: string): boolean {\n return ServiceRegistry._services.has(key);\n }\n\n /**\n * Get all initialized service keys.\n */\n static getInitializedKeys(): string[] {\n return [...ServiceRegistry._services.keys()];\n }\n\n /**\n * Get all pending (lazy) service keys.\n */\n static getPendingKeys(): string[] {\n return [...ServiceRegistry._pending.keys()];\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Internal: Service Initialization\n // ─────────────────────────────────────────────────────────────────────────\n\n /** Build API client options and instance for service */\n // eslint-disable-next-line complexity\n private static async buildApiClientOptions(\n config: CoreServiceInitConfig,\n entry: CoreServiceEntry\n ): Promise<{ dedicated: boolean; options?: ApiClientOptions; instance?: unknown } | undefined> {\n const dedicatedApiClient = config.dedicatedApiClient;\n const isDedicated = dedicatedApiClient === true || typeof dedicatedApiClient === 'object';\n const serviceKey = entry.service.serviceKey;\n\n const options: ApiClientOptions | undefined = isDedicated\n ? typeof dedicatedApiClient === 'object'\n ? { ...ServiceRegistry._apiClientOptions, ...dedicatedApiClient }\n : (ServiceRegistry._apiClientOptions ?? undefined)\n : (ServiceRegistry._apiClientOptions ?? undefined);\n\n if (!options) {\n return undefined;\n }\n\n // Get or create API client instance\n let apiInstance: unknown;\n if (isDedicated && options) {\n // Create dedicated API client instance for this service\n try {\n // Use the global environment from initialization\n const envConfig = {\n env: ServiceRegistry._environment,\n setAsDefault: false, // Dedicated instances should not become default\n };\n apiInstance = await ApiClientService.createInstance(envConfig, options);\n ServiceRegistry.logger.debug(\n `Created dedicated API client instance for service '${serviceKey}'`,\n {\n environment: ServiceRegistry._environment,\n }\n );\n } catch (error) {\n ServiceRegistry.logger.warn(\n `Failed to create dedicated API client for service '${serviceKey}'`,\n {\n error: error instanceof Error ? error.message : String(error),\n }\n );\n }\n } else {\n // Use global shared API client\n try {\n apiInstance = ApiClientService.getClient();\n } catch {\n ServiceRegistry.logger.debug(\n `Global API client not initialized, service '${serviceKey}' will not have API`\n );\n }\n }\n\n return {\n dedicated: isDedicated,\n options,\n instance: apiInstance,\n };\n }\n\n /** Build DB config and instance for service with runtime validation */\n // eslint-disable-next-line complexity\n private static async buildDbConfig(\n config: CoreServiceInitConfig,\n entry: CoreServiceEntry\n ): Promise<\n | {\n dedicated: boolean;\n config?: Partial<CoreDbServiceConfig>;\n instance?: CoreDbServiceInstance;\n }\n | undefined\n > {\n const dedicatedDb = config.dedicatedDb;\n const isDedicated = dedicatedDb === true || typeof dedicatedDb === 'object';\n const serviceKey = entry.service.serviceKey;\n\n // Runtime validation: DB should only be injected for backend services\n const isBackendRuntime = BACKEND_RUNTIMES.includes(ServiceRegistry._runtime);\n\n if ((isDedicated || ServiceRegistry._dbConfig) && !isBackendRuntime) {\n ServiceRegistry.logger.warn(\n `Service '${serviceKey}' is requesting database injection in '${ServiceRegistry._runtime}' runtime. ` +\n `Database is only available in backend runtimes (${BACKEND_RUNTIMES.join(', ')}). ` +\n `This service will not have database access.`\n );\n return undefined; // Skip DB injection for non-backend runtimes\n }\n\n const dbConfig: Partial<CoreDbServiceConfig> | undefined = isDedicated\n ? typeof dedicatedDb === 'object'\n ? { ...ServiceRegistry._dbConfig, ...dedicatedDb }\n : (ServiceRegistry._dbConfig ?? undefined)\n : (ServiceRegistry._dbConfig ?? undefined);\n\n if (!dbConfig) {\n return undefined;\n }\n\n const DbService = getCoreDependency('DbService');\n if (!DbService) {\n ServiceRegistry.logger.debug(\n `DbService not registered, service '${serviceKey}' will not have DB`\n );\n return undefined;\n }\n\n // Get or create DB instance\n let dbInstance: CoreDbServiceInstance | undefined;\n if (isDedicated && dbConfig) {\n // Create dedicated database instance for this service\n try {\n dbInstance = await DbService.createInstance?.(dbConfig as CoreDbServiceConfig);\n ServiceRegistry.logger.debug(\n `Created dedicated database instance for service '${serviceKey}'`\n );\n } catch (error) {\n ServiceRegistry.logger.warn(\n `Failed to create dedicated database instance for service '${serviceKey}'`,\n {\n error: error instanceof Error ? error.message : String(error),\n }\n );\n }\n } else {\n // Use global shared database\n try {\n dbInstance = DbService.getInstance();\n } catch {\n ServiceRegistry.logger.debug(\n `Global DB not initialized, service '${serviceKey}' will not have DB`\n );\n }\n }\n\n return {\n dedicated: isDedicated,\n config: dbConfig,\n instance: dbInstance,\n };\n }\n\n /** Build cache config and instance for service with runtime validation */\n // eslint-disable-next-line complexity\n private static async buildCacheConfig(\n config: CoreServiceInitConfig,\n entry: CoreServiceEntry\n ): Promise<\n | { dedicated: boolean; config?: CoreCacheConfig; instance?: CoreCacheManagerInstance }\n | undefined\n > {\n const dedicatedCache = config.dedicatedCache;\n const isDedicated = dedicatedCache === true || typeof dedicatedCache === 'object';\n const serviceKey = entry.service.serviceKey;\n\n const cacheConfig: CoreCacheConfig | undefined = isDedicated\n ? typeof dedicatedCache === 'object'\n ? ({ ...ServiceRegistry._cacheConfig, ...dedicatedCache } as CoreCacheConfig)\n : (ServiceRegistry._cacheConfig ?? undefined)\n : (ServiceRegistry._cacheConfig ?? undefined);\n\n if (!cacheConfig) {\n return undefined;\n }\n\n // Runtime validation: Cache on frontend is not supported (CacheManager uses ioredis which requires Node.js)\n const isFrontendRuntime = FRONTEND_RUNTIMES.includes(ServiceRegistry._runtime);\n\n if (isFrontendRuntime) {\n ServiceRegistry.logger.debug(\n `Service '${serviceKey}' skipping cache (frontend runtime - use Zustand store + react-query instead)`\n );\n return undefined;\n }\n\n const CacheService = getCoreDependency('CacheService');\n if (!CacheService) {\n ServiceRegistry.logger.debug(\n `CacheService not registered, service '${serviceKey}' will not have cache`\n );\n return undefined;\n }\n\n // Backend-only: Get cache manager instance from CacheService\n let cacheInstance: CoreCacheManagerInstance | undefined;\n try {\n cacheInstance = CacheService.getInstance().getCacheManager();\n if (isDedicated) {\n ServiceRegistry.logger.debug(\n `Using shared cache for service '${serviceKey}' (dedicated cache not implemented via DI)`,\n { strategy: cacheConfig.strategy }\n );\n }\n } catch {\n ServiceRegistry.logger.debug(\n `Global cache not initialized, service '${serviceKey}' will not have cache`\n );\n }\n\n return {\n dedicated: isDedicated,\n config: cacheConfig,\n instance: cacheInstance,\n };\n }\n\n /** Build observability config and instance for service */\n // eslint-disable-next-line complexity\n private static buildObservabilityConfig(\n config: CoreServiceInitConfig,\n // eslint-disable-next-line no-unused-vars\n _entry: CoreServiceEntry\n ):\n | { dedicated: boolean; config?: CoreObservabilityConfig; instance?: ObservabilityAdapter }\n | undefined {\n const dedicatedObservability = config.dedicatedObservability;\n const isDedicated =\n dedicatedObservability === true || typeof dedicatedObservability === 'object';\n\n const observabilityConfig: CoreObservabilityConfig | undefined = isDedicated\n ? typeof dedicatedObservability === 'object'\n ? ({\n ...ServiceRegistry._observabilityConfig,\n ...dedicatedObservability,\n } as CoreObservabilityConfig)\n : (ServiceRegistry._observabilityConfig ?? undefined)\n : (ServiceRegistry._observabilityConfig ?? undefined);\n\n if (!observabilityConfig) {\n return undefined;\n }\n\n // Instance will be set async if dedicated\n return {\n dedicated: isDedicated,\n config: observabilityConfig,\n instance: isDedicated ? undefined : (ServiceRegistry._observabilityInstance ?? undefined),\n };\n }\n\n /** Build storage config and instance for service with runtime validation (backend-only) */\n // eslint-disable-next-line complexity\n private static async buildStorageConfig(\n config: CoreServiceInitConfig,\n entry: CoreServiceEntry\n ): Promise<\n | { dedicated: boolean; config?: CoreStorageConfig; instance?: CoreStorageServiceInstance }\n | undefined\n > {\n const dedicatedStorage = config.dedicatedStorage;\n const isDedicated = dedicatedStorage === true || typeof dedicatedStorage === 'object';\n const serviceKey = entry.service.serviceKey;\n\n // Runtime validation: Storage is backend-only\n const isBackendRuntime = BACKEND_RUNTIMES.includes(ServiceRegistry._runtime);\n\n if ((isDedicated || ServiceRegistry._storageConfig) && !isBackendRuntime) {\n ServiceRegistry.logger.warn(\n `Service '${serviceKey}' is requesting storage injection in '${ServiceRegistry._runtime}' runtime. ` +\n `Storage is only available in backend runtimes (${BACKEND_RUNTIMES.join(', ')}). ` +\n `This service will not have storage access.`\n );\n return undefined;\n }\n\n const storageConfig: CoreStorageConfig | undefined = isDedicated\n ? typeof dedicatedStorage === 'object'\n ? { ...ServiceRegistry._storageConfig, ...dedicatedStorage }\n : (ServiceRegistry._storageConfig ?? undefined)\n : (ServiceRegistry._storageConfig ?? undefined);\n\n if (!storageConfig) {\n return undefined;\n }\n\n const StorageService = getCoreDependency('StorageService');\n if (!StorageService) {\n ServiceRegistry.logger.debug(\n `StorageService not registered, service '${serviceKey}' will not have storage`\n );\n return undefined;\n }\n\n // Get or create storage instance\n let storageInstance: CoreStorageServiceInstance | undefined;\n if (isDedicated && storageConfig) {\n try {\n storageInstance = await StorageService.createInstance?.(storageConfig);\n ServiceRegistry.logger.debug(\n `Created dedicated storage instance for service '${serviceKey}'`\n );\n } catch (error) {\n ServiceRegistry.logger.warn(\n `Failed to create dedicated storage instance for service '${serviceKey}'`,\n { error: error instanceof Error ? error.message : String(error) }\n );\n }\n } else {\n try {\n storageInstance = StorageService.getInstance();\n } catch {\n ServiceRegistry.logger.debug(\n `Global storage not initialized, service '${serviceKey}' will not have storage`\n );\n }\n }\n\n return {\n dedicated: isDedicated,\n config: storageConfig,\n instance: storageInstance,\n };\n }\n\n /** Build notifications config and instance for service with runtime validation (backend-only) */\n // eslint-disable-next-line complexity\n private static async buildNotificationsConfig(\n config: CoreServiceInitConfig,\n entry: CoreServiceEntry\n ): Promise<\n | {\n dedicated: boolean;\n config?: CoreNotificationConfig;\n instance?: CoreNotificationServiceInstance;\n }\n | undefined\n > {\n const dedicatedNotifications = config.dedicatedNotifications;\n const isDedicated =\n dedicatedNotifications === true || typeof dedicatedNotifications === 'object';\n const serviceKey = entry.service.serviceKey;\n\n // Runtime validation: Notifications is backend-only\n const isBackendRuntime = BACKEND_RUNTIMES.includes(ServiceRegistry._runtime);\n\n if ((isDedicated || ServiceRegistry._notificationsConfig) && !isBackendRuntime) {\n ServiceRegistry.logger.warn(\n `Service '${serviceKey}' is requesting notifications injection in '${ServiceRegistry._runtime}' runtime. ` +\n `Notifications is only available in backend runtimes (${BACKEND_RUNTIMES.join(', ')}). ` +\n `This service will not have notifications access.`\n );\n return undefined;\n }\n\n const notificationsConfig: CoreNotificationConfig | undefined = isDedicated\n ? typeof dedicatedNotifications === 'object'\n ? { ...ServiceRegistry._notificationsConfig, ...dedicatedNotifications }\n : (ServiceRegistry._notificationsConfig ?? undefined)\n : (ServiceRegistry._notificationsConfig ?? undefined);\n\n if (!notificationsConfig) {\n return undefined;\n }\n\n const NotificationService = getCoreDependency('NotificationService');\n if (!NotificationService) {\n ServiceRegistry.logger.debug(\n `NotificationService not registered, service '${serviceKey}' will not have notifications`\n );\n return undefined;\n }\n\n // Get or create notifications instance\n let notificationsInstance: CoreNotificationServiceInstance | undefined;\n if (isDedicated && notificationsConfig) {\n try {\n notificationsInstance = await NotificationService.createInstance?.(notificationsConfig);\n ServiceRegistry.logger.debug(\n `Created dedicated notifications instance for service '${serviceKey}'`\n );\n } catch (error) {\n ServiceRegistry.logger.warn(\n `Failed to create dedicated notifications instance for service '${serviceKey}'`,\n { error: error instanceof Error ? error.message : String(error) }\n );\n }\n } else {\n try {\n notificationsInstance = NotificationService.getInstance();\n } catch {\n ServiceRegistry.logger.debug(\n `Global notifications not initialized, service '${serviceKey}' will not have notifications`\n );\n }\n }\n\n return {\n dedicated: isDedicated,\n config: notificationsConfig,\n instance: notificationsInstance,\n };\n }\n\n /**\n * Create a dedicated ObservabilityService instance for a service.\n * Uses the same adapter pattern as global observability but with service-specific config.\n */\n private static async createDedicatedObservability(\n serviceKey: string,\n config: CoreObservabilityConfig\n ): Promise<ObservabilityAdapter | undefined> {\n // Skip if explicitly disabled\n if (config.enabled === false) {\n return undefined;\n }\n\n try {\n // createObservabilityService auto-adds LoggerAdapter as failover\n const dedicatedService = await createObservabilityService({\n mode: config.mode ?? 'parallel',\n serviceName: `${config.serviceName ?? 'service'}-${serviceKey}`,\n environment: config.environment,\n adapters: config.adapters,\n });\n\n ServiceRegistry.logger.debug(\n `Created dedicated ObservabilityService for service '${serviceKey}'`\n );\n\n return dedicatedService;\n } catch (err) {\n ServiceRegistry.logger.warn(\n `Failed to create dedicated observability for '${serviceKey}', falling back to global`,\n { error: err instanceof Error ? err.message : String(err) }\n );\n return ServiceRegistry._observabilityInstance ?? undefined;\n }\n }\n\n /**\n * Set the global observability adapter instance.\n * Called by Core.initialize() after creating the adapter.\n */\n static setObservabilityInstance(instance: ObservabilityAdapter): void {\n ServiceRegistry._observabilityInstance = instance;\n ServiceRegistry.logger.debug('Global observability instance set');\n }\n\n /**\n * Get the global observability adapter instance.\n */\n static getObservabilityInstance(): ObservabilityAdapter | null {\n return ServiceRegistry._observabilityInstance;\n }\n\n /**\n * Initialize a single service from an entry.\n * Uses the service class's static create() method.\n * Merges per-service config with global config.\n */\n private static async initializeService(\n entry: CoreServiceEntry,\n storeSingleton = true\n ): Promise<CoreDomainServiceInstance> {\n const { service: ServiceClass, config } = entry;\n const serviceKey = ServiceClass.serviceKey;\n const isSingleton = config.singleton !== false;\n\n // For singletons, check for concurrent initialization\n if (storeSingleton && isSingleton) {\n const existingPromise = ServiceRegistry._initPromises.get(serviceKey);\n if (existingPromise) return existingPromise;\n }\n\n const initPromise = ServiceRegistry.doInitializeService(entry, { isSingleton, storeSingleton });\n\n if (storeSingleton && isSingleton) {\n ServiceRegistry._initPromises.set(serviceKey, initPromise);\n }\n\n return initPromise;\n }\n\n /** Build stores for service injection */\n private static buildStoresForService(\n config: CoreServiceInitConfig\n ): Partial<RootStoreSlice> | undefined {\n const allKeys = new Set<keyof RootStoreSlice>();\n\n // Add primary store\n if (config.store) {\n allKeys.add(config.store);\n }\n\n // Add read stores\n if (config.readStores) {\n config.readStores.forEach(key => allKeys.add(key));\n }\n\n if (allKeys.size === 0) {\n return undefined;\n }\n\n if (!ServiceRegistry._storeRegistry) {\n ServiceRegistry.logger.warn('Store registry not initialized, cannot inject stores');\n return undefined;\n }\n\n const stores: Partial<RootStoreSlice> = {};\n for (const key of allKeys) {\n const store = ServiceRegistry._storeRegistry.getStore(key);\n if (store) {\n (stores as Record<keyof RootStoreSlice, unknown>)[key] = store;\n ServiceRegistry.logger.debug(`Injected store '${key}' into service`);\n } else {\n ServiceRegistry.logger.warn(`Store '${key}' requested but not found in registry`);\n }\n }\n\n return Object.keys(stores).length > 0 ? stores : undefined;\n }\n\n /** Perform the actual service initialization */\n // eslint-disable-next-line complexity\n private static async doInitializeService(\n entry: CoreServiceEntry,\n options: { isSingleton: boolean; storeSingleton: boolean }\n ): Promise<CoreDomainServiceInstance> {\n const { service: serviceClass, config } = entry;\n const serviceKey = serviceClass.serviceKey;\n const { isSingleton, storeSingleton } = options;\n\n try {\n ServiceRegistry.logger.debug(`Initializing service: ${serviceKey}`);\n\n // Build dependencies (async operations) with runtime validation\n const apiClient = await ServiceRegistry.buildApiClientOptions(config, entry);\n const db = await ServiceRegistry.buildDbConfig(config, entry);\n const cache = await ServiceRegistry.buildCacheConfig(config, entry);\n const observability = ServiceRegistry.buildObservabilityConfig(config, entry);\n const storage = await ServiceRegistry.buildStorageConfig(config, entry);\n const notifications = await ServiceRegistry.buildNotificationsConfig(config, entry);\n const stores = ServiceRegistry.buildStoresForService(config);\n\n // Create dedicated observability instance if requested\n let observabilityInstance = observability?.instance;\n if (observability?.dedicated && observability.config) {\n observabilityInstance = await ServiceRegistry.createDedicatedObservability(\n serviceKey,\n observability.config\n );\n }\n\n const createOptions: CoreServiceCreateOptions = {\n apiClient,\n db,\n cache,\n observability: observability\n ? { ...observability, instance: observabilityInstance }\n : undefined,\n storage,\n notifications,\n injected: {\n ...(stores ? { stores } : {}),\n cache: cache?.instance,\n db: db?.instance,\n api: apiClient?.instance,\n observability: observabilityInstance,\n storage: storage?.instance,\n notifications: notifications?.instance,\n },\n isSingleton,\n };\n\n ServiceRegistry.logger.debug(`Service ${serviceKey} config:`, {\n apiClientDedicated: createOptions.apiClient?.dedicated,\n dbDedicated: createOptions.db?.dedicated,\n observabilityDedicated: createOptions.observability?.dedicated,\n storageDedicated: createOptions.storage?.dedicated,\n notificationsDedicated: createOptions.notifications?.dedicated,\n injected: {\n hasCache: !!createOptions.injected?.cache,\n hasDb: !!createOptions.injected?.db,\n hasApi: !!createOptions.injected?.api,\n hasObservability: !!createOptions.injected?.observability,\n hasStorage: !!createOptions.injected?.storage,\n hasNotifications: !!createOptions.injected?.notifications,\n hasStores: !!createOptions.injected?.stores,\n },\n });\n\n const instance = await serviceClass.create(config, createOptions);\n\n if (storeSingleton && isSingleton) {\n ServiceRegistry._services.set(serviceKey, instance);\n ServiceRegistry.logger.info(`Service initialized: ${serviceKey} (singleton)`);\n } else {\n ServiceRegistry.logger.info(`Service created: ${serviceKey} (instance)`);\n }\n\n return instance;\n } catch (error) {\n ServiceRegistry.logger.error(`Failed to initialize service: ${serviceKey}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n if (storeSingleton && isSingleton) {\n ServiceRegistry._initPromises.delete(serviceKey);\n }\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Disposal\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Dispose a specific service by key.\n *\n * @param key - Service key to dispose\n */\n static dispose(key: string): void {\n const service = ServiceRegistry._services.get(key);\n if (service) {\n service.dispose();\n ServiceRegistry._services.delete(key);\n ServiceRegistry.logger.info(`Service disposed: ${key}`);\n }\n ServiceRegistry._pending.delete(key);\n }\n\n /**\n * Dispose all services and clear the registry.\n */\n static disposeAll(): void {\n // Dispose all initialized services\n for (const [key, service] of ServiceRegistry._services) {\n try {\n service.dispose();\n ServiceRegistry.logger.debug(`Disposed service: ${key}`);\n } catch (error) {\n ServiceRegistry.logger.error(`Error disposing service: ${key}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Clear all state\n ServiceRegistry._services.clear();\n ServiceRegistry._pending.clear();\n ServiceRegistry._metadata.clear();\n ServiceRegistry._initPromises.clear();\n ServiceRegistry._apiClientOptions = null;\n ServiceRegistry._dbConfig = null;\n ServiceRegistry._cacheConfig = null;\n ServiceRegistry._observabilityConfig = null;\n ServiceRegistry._observabilityInstance = null;\n ServiceRegistry._storageConfig = null;\n ServiceRegistry._notificationsConfig = null;\n\n ServiceRegistry.logger.info('Service registry disposed');\n }\n\n /**\n * Check if a service is configured as singleton.\n *\n * @param key - Service key\n * @returns true if singleton (default), false if non-singleton\n */\n static isSingleton(key: string): boolean {\n const metadata = ServiceRegistry._metadata.get(key);\n return metadata?.isSingleton ?? true;\n }\n\n /**\n * Get all non-singleton service keys.\n * These services must be created via `create()` method.\n */\n static getNonSingletonKeys(): string[] {\n return [...ServiceRegistry._metadata.entries()]\n .filter(([, meta]) => !meta.isSingleton)\n .map(([key]) => key);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Dynamic Registration\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Register a new service dynamically after initialization.\n *\n * @param entry - Service entry to register\n * @param initNow - Whether to initialize immediately (default: true)\n *\n * @example\n * ```typescript\n * // Register and initialize immediately\n * await ServiceRegistry.register({\n * service: NewDomainService,\n * config: { enabled: true },\n * });\n *\n * // Register for lazy initialization\n * ServiceRegistry.register({\n * service: LazyService,\n * config: { enabled: true, initWhen: 'lazy' },\n * }, false);\n * ```\n */\n static async register(entry: CoreServiceEntry, initNow = true): Promise<void> {\n const serviceKey = entry.service.serviceKey;\n\n // Check if already registered\n if (ServiceRegistry._services.has(serviceKey) || ServiceRegistry._pending.has(serviceKey)) {\n ServiceRegistry.logger.warn(`Service '${serviceKey}' is already registered`);\n return;\n }\n\n const initWhen = entry.config.initWhen ?? 'immediate';\n\n if (initNow && initWhen === 'immediate') {\n await ServiceRegistry.initializeService(entry);\n } else {\n ServiceRegistry._pending.set(serviceKey, { entry, initWhen });\n ServiceRegistry.logger.debug(\n `Service ${serviceKey} registered for ${initWhen} initialization`\n );\n }\n }\n\n /**\n * Unregister a service (dispose if initialized).\n *\n * @param key - Service key to unregister\n */\n static unregister(key: string): void {\n ServiceRegistry.dispose(key);\n }\n}\n","/**\n * Runtime Detection Utilities\n *\n * Utilities for detecting the current JavaScript runtime environment.\n */\n\nimport type { CoreRuntimeEnvironment } from '@plyaz/types/core';\nimport { PackageLogger } from '@plyaz/logger';\n\nconst logger = new PackageLogger({ packageName: 'core', service: 'Runtime' });\n\n/**\n * Check if a module is available via require.resolve\n */\nfunction isModuleAvailable(moduleName: string): boolean {\n const nodeRequire = globalThis.require;\n if (!nodeRequire) return false;\n\n const resolveModule = nodeRequire.resolve;\n if (!resolveModule) return false;\n\n try {\n resolveModule(moduleName);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Check for alternative runtimes (Deno, Bun) */\nfunction detectAltRuntime(): CoreRuntimeEnvironment | null {\n if (typeof globalThis.Deno !== 'undefined') return 'deno';\n if (typeof globalThis.Bun !== 'undefined') return 'bun';\n return null;\n}\n\n/** Check for edge runtime */\nfunction detectEdgeRuntime(): CoreRuntimeEnvironment | null {\n if (typeof globalThis.EdgeRuntime !== 'undefined') return 'edge';\n const isEdgeLike =\n typeof globalThis.caches !== 'undefined' &&\n typeof globalThis.Request !== 'undefined' &&\n typeof process === 'undefined';\n return isEdgeLike ? 'edge' : null;\n}\n\n/** Check for browser environment */\nfunction detectBrowser(): CoreRuntimeEnvironment | null {\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n return 'browser';\n }\n return null;\n}\n\n/** Check for Node.js framework */\nfunction detectNodeFramework(): CoreRuntimeEnvironment {\n // Check for Nuxt (SSR)\n if (process.env.__NUXT__ || process.env.NUXT_APP) return 'nuxt';\n // Check for Next.js (SSR)\n if (process.env.__NEXT_PRIVATE_ORIGIN || process.env.NEXT_RUNTIME) return 'nextjs';\n // Check for NestJS via module detection\n if (isModuleAvailable('@nestjs/core')) return 'nestjs';\n // Check for Express via module detection\n if (isModuleAvailable('express')) return 'express';\n return 'node';\n}\n\n/**\n * Detect the current runtime environment\n */\nexport function detectRuntime(): CoreRuntimeEnvironment {\n // Check alternative runtimes first\n const altRuntime = detectAltRuntime();\n if (altRuntime) return altRuntime;\n\n // Check for edge runtime\n const edgeRuntime = detectEdgeRuntime();\n if (edgeRuntime) return edgeRuntime;\n\n // Check for browser\n const browser = detectBrowser();\n if (browser) return browser;\n\n // Server-side detection (Node.js based)\n if (typeof process !== 'undefined' && process.versions?.node) {\n return detectNodeFramework();\n }\n\n return 'unknown';\n}\n\n/**\n * Load environment variables from a .env file\n */\nexport async function loadEnvFile(envPath: string, verbose?: boolean): Promise<void> {\n try {\n const dotenv = await import('dotenv');\n const result = dotenv.config({ path: envPath });\n\n if (result.error) {\n logger.warn(`Failed to load env file: ${result.error.message}`);\n } else if (verbose) {\n logger.info(`Loaded env from: ${envPath}`);\n }\n } catch {\n logger.warn('dotenv not available, skipping .env file loading');\n }\n}\n","// This eslint disable is an edge-case as we need to ensure that we're able to load CoreInitializer regardless if FE, BE or specific frameworks\n/**\n * CoreInitializer - Unified initialization for @plyaz/core\n *\n * Provides a single entry point to initialize all core services with\n * environment-aware configuration. Works across all JavaScript runtimes.\n *\n * @example Backend with full config\n * ```typescript\n * import { Core } from '@plyaz/core';\n *\n * await Core.initialize({\n * envPath: '.env',\n * db: { adapter: 'drizzle' },\n * api: {\n * env: 'production',\n * baseURL: 'https://api.example.com',\n * },\n * });\n *\n * // Access services\n * const db = Core.db;\n * const api = Core.api;\n * ```\n *\n * @example Frontend (Nuxt/Next.js)\n * ```typescript\n * import { Core } from '@plyaz/core';\n *\n * await Core.initialize({\n * skipDb: true,\n * api: { baseURL: 'https://api.example.com' },\n * });\n *\n * const api = Core.api;\n * ```\n *\n * @example NestJS with DI\n * ```typescript\n * // app.module.ts\n * import { CoreModule } from '@plyaz/core/adapters';\n * import { FeatureFlagModule } from '@plyaz/core/backend/featureFlags';\n *\n * @Module({\n * imports: [\n * CoreModule.forRoot({ envPath: '.env', db: { adapter: 'drizzle' } }),\n * FeatureFlagModule.forRoot({ provider: 'database' }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n\nimport { PackageLogger } from '@plyaz/logger';\nimport { ApiClientService } from '../services/ApiClientService';\nimport { CoreEventManager } from '../events/CoreEventManager';\nimport { ServiceRegistry } from './ServiceRegistry';\nimport type {\n CoreRuntimeEnvironment,\n CoreRuntimeContext,\n CoreEnvVars,\n CoreAppEnvironment,\n CoreAppContext,\n CoreApiInitOptions,\n CoreServiceRuntime,\n CoreInitOptions as BaseCoreInitOptions,\n CoreServicesResultBase,\n CoreServiceEntry,\n CoreDomainServiceInstance,\n CoreSystemErrorPayload,\n CoreFeatureFlagInitConfig,\n CoreErrorHandlerInitConfig,\n CoreCacheConfig,\n CoreObservabilityConfig,\n CoreDbServiceConfig,\n CoreStorageConfig,\n CoreNotificationConfig,\n // Service instance types (from @plyaz/types, not backend modules)\n CoreDbServiceInstance,\n CoreCacheServiceInstance,\n CoreStorageServiceInstance,\n CoreNotificationServiceInstance,\n} from '@plyaz/types/core';\nimport type { ObservabilityAdapter } from '@plyaz/types/observability';\nimport { ObservabilityService } from '../base/observability/ObservabilityService';\nimport { LoggerAdapter } from '../base/observability/LoggerAdapter';\nimport type { FeatureFlagValue, FeatureFlagStoreSlice } from '@plyaz/types/features';\nimport { ERROR_CODES, BACKEND_RUNTIMES, FRONTEND_RUNTIMES } from '@plyaz/types';\nimport { BaseError, CorePackageError, initializeErrorSystem } from '@plyaz/errors';\n// Core error handling (frontend-safe)\nimport {\n initializeGlobalErrorHandler,\n setEventEmitter,\n clearEventEmitter,\n} from '@plyaz/errors/middleware';\n// ServerErrorMiddleware is backend-only, import dynamically where needed\nimport type { ErrorStoreActions, GlobalErrorHandler } from '@plyaz/types/errors';\nimport { detectRuntime, loadEnvFile } from '../utils/runtime';\nimport {\n createStandaloneFeatureFlagStore,\n useRootStore,\n STORE_KEYS,\n type StoreKey,\n} from '@plyaz/store';\nimport { CORE_EVENTS, type CoreEvent } from '@plyaz/types/core';\nimport type { RootStoreSlice } from '@plyaz/types/store';\nimport type { StoreApi } from 'zustand/vanilla';\nimport { getCoreDependency } from '../config/dependencies';\n\n// Constants\nconst DEFAULT_MAX_ERRORS = 100;\n\n/**\n * Core initialization options with specific types for this package\n */\nexport interface CoreInitOptions\n extends Omit<\n BaseCoreInitOptions<\n Partial<CoreDbServiceConfig>,\n CoreApiInitOptions,\n CoreCacheConfig,\n CoreStorageConfig,\n CoreNotificationConfig\n >,\n 'observability' | 'skipObservability'\n > {\n /** Observability configuration */\n observability?: CoreObservabilityConfig;\n /** Skip observability initialization */\n skipObservability?: boolean;\n /**\n * Global error handler configuration.\n * Auto-initializes by default to catch all uncaught errors.\n * Set `enabled: false` to disable if you want to use your own error handling.\n *\n * @example\n * ```typescript\n * await Core.initialize({\n * errorHandler: {\n * enabled: true,\n * logToConsole: true,\n * maxErrors: 200,\n * filter: (error) => error instanceof MyError,\n * },\n * });\n * ```\n */\n errorHandler?: CoreErrorHandlerInitConfig;\n\n /** Feature flags configuration */\n featureFlags?: CoreFeatureFlagInitConfig;\n\n /**\n * Domain services to auto-initialize (frontend pattern).\n * Uses ServiceRegistry for automatic initialization.\n *\n * @example\n * ```typescript\n * await Core.initialize({\n * services: [\n * { service: FeatureFlagDomainService, config: { enabled: true } },\n * { service: ExampleDomainService, config: { enabled: true, useRealApi: true } },\n * ],\n * });\n *\n * // Access via ServiceRegistry\n * const flags = ServiceRegistry.get<FeatureFlagDomainService>('featureFlags');\n * ```\n */\n services?: CoreServiceEntry[];\n}\n\n/**\n * Core initialization result with specific types for this package\n */\nexport type CoreServicesResult = CoreServicesResultBase<\n CoreDbServiceInstance,\n typeof ApiClientService,\n CoreCacheServiceInstance,\n ObservabilityAdapter,\n CoreStorageServiceInstance,\n CoreNotificationServiceInstance\n>;\n\n// Domain store keys are automatically derived from STORE_KEYS\n// Excluding global stores (error, featureFlags) which are read-only by default\n\n/**\n * Function type for getting core domain services.\n * Used by entry points to inject runtime-appropriate services.\n *\n * @internal This is injected by entry points, not used directly.\n */\nexport type GetCoreDomainServicesFn = (isFrontend: boolean) => Promise<CoreServiceEntry[]>;\n\n/**\n * Injected function to get core domain services.\n * Set by entry points (entry-backend.ts) before Core.initialize().\n * Frontend entries don't set this - they just don't load default services.\n */\nlet _getCoreDomainServices: GetCoreDomainServicesFn | null = null;\n\n/**\n * Set the function to get core domain services.\n * Called by entry-backend.ts to inject the backend-aware service loader.\n *\n * @internal Used by entry points only.\n */\nexport function setGetCoreDomainServices(fn: GetCoreDomainServicesFn): void {\n _getCoreDomainServices = fn;\n}\n\nexport class Core {\n private static initialized = false;\n private static _coreServices: CoreServicesResult = {\n db: null,\n api: null,\n cache: null,\n observability: null,\n storage: null,\n notifications: null,\n env: {},\n runtime: 'unknown',\n appContext: 'webapp',\n };\n\n /**\n * Logger for Core initialization (created lazily)\n */\n private static _logger: PackageLogger | null = null;\n\n /**\n * Get or create the Core logger\n */\n private static get logger(): PackageLogger {\n Core._logger ??= new PackageLogger({\n packageName: 'core',\n service: 'Core',\n });\n return Core._logger;\n }\n\n /**\n * Log a message during initialization.\n * Uses PackageLogger, respects verbose flag.\n */\n private static log(message: string, verbose?: boolean, data?: Record<string, unknown>): void {\n if (!verbose) return;\n if (data) {\n Core.logger.info(message, data);\n } else {\n Core.logger.info(message);\n }\n }\n\n /**\n * Log a debug message during initialization.\n */\n private static logDebug(\n message: string,\n verbose?: boolean,\n data?: Record<string, unknown>\n ): void {\n if (!verbose) return;\n if (data) {\n Core.logger.debug(message, data);\n } else {\n Core.logger.debug(message);\n }\n }\n\n /**\n * Observability configuration\n */\n private static _observabilityConfig: CoreObservabilityConfig = {};\n\n /**\n * Global error handler instance\n */\n private static _errorHandler: GlobalErrorHandler | null = null;\n\n /**\n * Error handler configuration\n */\n private static _errorConfig: CoreErrorHandlerInitConfig = {};\n\n /**\n * HTTP error handler/middleware based on runtime.\n * Auto-created during initialization.\n */\n private static _httpErrorHandler: unknown = null;\n\n /**\n * Event listener cleanup functions\n */\n private static _eventCleanupFns: (() => void)[] = [];\n\n /**\n * Feature flag configuration\n */\n private static _flagConfig: CoreFeatureFlagInitConfig = {};\n\n /**\n * Root store instance (contains errors, feature flags, and all other slices)\n * Initialized during Core.initialize() - frontend uses React hook store, backend uses vanilla store\n * All store access should go through Core.rootStore - no separate stores needed\n */\n private static _rootStore: StoreApi<RootStoreSlice> | null = null;\n\n /**\n * Setup environment and context\n */\n private static async setupEnvironment(options: CoreInitOptions): Promise<CoreAppEnvironment> {\n const { envPath, environment, appContext, env, verbose } = options;\n\n Core._coreServices.appContext = appContext ?? 'webapp';\n Core.log(`App context: ${Core._coreServices.appContext}`, verbose);\n\n const globalEnvironment: CoreAppEnvironment =\n environment ?? (process.env.NODE_ENV as CoreAppEnvironment) ?? 'development';\n Core.log(`Global environment: ${globalEnvironment}`, verbose);\n\n Core._coreServices.runtime = detectRuntime();\n Core.log(`Detected runtime: ${Core._coreServices.runtime}`, verbose);\n\n if (envPath) await loadEnvFile(envPath, verbose);\n Core._coreServices.env = { ...process.env, ...env };\n\n return globalEnvironment;\n }\n\n /**\n * Initialize a service with error handling\n */\n private static async initService<T>(\n name: string,\n init: () => Promise<T>,\n verbose?: boolean\n ): Promise<T | undefined> {\n try {\n return await init();\n } catch (error) {\n Core.logger.error(`Failed to initialize ${name}`, { error: (error as Error).message });\n if (verbose) Core.logger.error('Full error', { error });\n return undefined;\n }\n }\n\n /** Initialize error handler if enabled */\n private static async initErrorHandlerIfEnabled(options: CoreInitOptions): Promise<void> {\n const { errorHandler: config, verbose } = options;\n if (config?.enabled === false) {\n Core.log('Global error handler disabled by configuration', verbose);\n return;\n }\n await Core.initService(\n 'error handler',\n async () => {\n await Core.initializeErrorHandler(config, verbose);\n Core.subscribeToErrorEvents(verbose);\n },\n verbose\n );\n }\n\n /** Initialize API client if not skipped */\n private static async initApiIfEnabled(\n options: CoreInitOptions,\n env: CoreAppEnvironment\n ): Promise<void> {\n const { api: apiConfig, skipApi, verbose } = options;\n if (skipApi) return;\n\n await Core.initService(\n 'API client',\n async () => {\n await Core.initializeApi(apiConfig, env, verbose);\n Core._coreServices.api = ApiClientService;\n Core.log('API client service initialized', verbose);\n },\n verbose\n );\n Core._coreServices.api = ApiClientService;\n }\n\n /** Initialize cache service if not skipped (backend-only due to ioredis dependency) */\n private static async initCacheIfEnabled(options: CoreInitOptions): Promise<void> {\n const { cache: cacheConfig, skipCache, verbose } = options;\n if (skipCache) {\n Core.log('Cache service skipped (skipCache: true)', verbose);\n return;\n }\n\n // Skip cache initialization if no config provided\n if (!cacheConfig) {\n Core.log('Cache service skipped (no config provided)', verbose);\n return;\n }\n\n // Skip on frontend runtimes (CacheService pulls in ioredis which requires Node.js)\n if (Core.isFrontend) {\n Core.log('Cache service skipped (frontend runtime detected)', verbose);\n return;\n }\n\n await Core.initService(\n 'cache',\n async () => {\n await Core.initializeCache(cacheConfig as CoreCacheConfig, verbose);\n const CacheService = getCoreDependency('CacheService');\n if (CacheService) {\n Core._coreServices.cache = CacheService.getInstance();\n Core.log('Cache service initialized', verbose);\n }\n },\n verbose\n );\n }\n\n /** Initialize observability if not skipped */\n private static async initObservabilityIfEnabled(\n options: CoreInitOptions,\n globalEnvironment: CoreAppEnvironment\n ): Promise<void> {\n const { observability: observabilityConfig, skipObservability, verbose } = options;\n if (skipObservability) {\n Core.log('Observability service skipped (skipObservability: true)', verbose);\n return;\n }\n\n // Always use ObservabilityService - it adds LoggerAdapter by default\n const config = observabilityConfig ?? { enabled: true };\n\n await Core.initService(\n 'observability',\n async () => {\n await Core.initializeObservability(config, verbose, globalEnvironment);\n Core.log('Observability service initialized', verbose);\n },\n verbose\n );\n }\n\n /** Initialize storage service if not skipped (backend-only) */\n private static async initStorageIfEnabled(options: CoreInitOptions): Promise<void> {\n const { storage: storageConfig, skipStorage, verbose } = options;\n\n // Skip if explicitly disabled\n if (skipStorage) {\n Core.log('Storage service skipped (skipStorage: true)', verbose);\n return;\n }\n\n // Skip if no config provided\n if (!storageConfig) {\n Core.log('Storage service skipped (no config provided)', verbose);\n return;\n }\n\n // Skip on frontend runtimes (storage is backend-only)\n if (Core.isFrontend) {\n Core.log('Storage service skipped (frontend runtime detected)', verbose);\n return;\n }\n\n await Core.initService(\n 'storage',\n async () => {\n const StorageService = getCoreDependency('StorageService');\n if (!StorageService) {\n Core.log('Storage service skipped (dependency not registered)', verbose);\n return;\n }\n await StorageService.initialize(storageConfig);\n Core._coreServices.storage = StorageService.getInstance();\n Core.log('Storage service initialized', verbose);\n },\n verbose\n );\n }\n\n /** Initialize notifications service if not skipped (backend-only) */\n private static async initNotificationsIfEnabled(options: CoreInitOptions): Promise<void> {\n const { notifications: notificationsConfig, skipNotifications, verbose } = options;\n\n // Skip if explicitly disabled\n if (skipNotifications) {\n Core.log('Notifications service skipped (skipNotifications: true)', verbose);\n return;\n }\n\n // Skip if no config provided\n if (!notificationsConfig) {\n Core.log('Notifications service skipped (no config provided)', verbose);\n return;\n }\n\n // Skip on frontend runtimes (notifications is backend-only)\n if (Core.isFrontend) {\n Core.log('Notifications service skipped (frontend runtime detected)', verbose);\n return;\n }\n\n await Core.initService(\n 'notifications',\n async () => {\n const NotificationService = getCoreDependency('NotificationService');\n if (!NotificationService) {\n Core.log('Notifications service skipped (dependency not registered)', verbose);\n return;\n }\n await NotificationService.initialize(notificationsConfig);\n Core._coreServices.notifications = NotificationService.getInstance();\n Core.log('Notifications service initialized', verbose);\n },\n verbose\n );\n }\n\n /**\n * Initialize domain services\n *\n * Loads core domain services using the injected loader (if available),\n * then merges with any user-provided services.\n * User-provided service configs override core defaults.\n *\n * Note: Frontend entries don't inject a loader, so they only use user-provided services.\n */\n private static async initDomainServicesIfConfigured(\n options: CoreInitOptions,\n globalEnvironment: CoreAppEnvironment\n ): Promise<void> {\n const { api: apiConfig, services: userServices, verbose } = options;\n const runtime = Core._coreServices.runtime;\n\n // Load core services using injected loader (backend sets this, frontend doesn't)\n const coreDomainServices = _getCoreDomainServices\n ? await _getCoreDomainServices(Core.isFrontend)\n : [];\n\n // Merge core services with user-provided services\n // User services can override core service configs by using the same service class\n const coreServiceKeys = new Set(coreDomainServices.map(s => s.service.serviceKey));\n const userOverrides = (userServices ?? []).filter(s =>\n coreServiceKeys.has(s.service.serviceKey)\n );\n const additionalUserServices = (userServices ?? []).filter(\n s => !coreServiceKeys.has(s.service.serviceKey)\n );\n\n // Build merged services: core (with overrides applied) + additional user services\n const mergedServices: CoreServiceEntry[] = coreDomainServices\n .map(coreService => {\n const override = userOverrides.find(\n u => u.service.serviceKey === coreService.service.serviceKey\n );\n return override\n ? { ...coreService, config: { ...coreService.config, ...override.config } }\n : coreService;\n })\n .concat(additionalUserServices);\n\n // Skip if somehow no services\n if (mergedServices.length === 0) return;\n\n await Core.initService(\n 'domain services',\n async () => {\n Core.log('Initializing domain services via ServiceRegistry...', verbose);\n Core.logDebug('Core services', verbose, {\n services: coreDomainServices.map(s => s.service.serviceKey),\n });\n if (userServices?.length) {\n Core.logDebug('User services', verbose, {\n services: userServices.map(s => s.service.serviceKey),\n });\n }\n await ServiceRegistry.initialize({\n environment: globalEnvironment,\n runtime,\n apiClient: apiConfig ? { baseURL: apiConfig.baseURL, ...apiConfig } : undefined,\n services: mergedServices,\n stores: {\n // Returns specific slice from namespaced root store (type-safe)\n getStore: <K extends keyof RootStoreSlice>(key: K): RootStoreSlice[K] | undefined =>\n Core.getDomainStore(key),\n },\n });\n Core.log('Domain services initialized', verbose, {\n keys: ServiceRegistry.getInitializedKeys(),\n });\n },\n verbose\n );\n }\n\n /**\n * Initialize all core services\n */\n\n static async initialize(options: CoreInitOptions = {}): Promise<CoreServicesResult> {\n if (Core.initialized) {\n Core.log('Already initialized, returning existing services', options.verbose);\n return Core._coreServices;\n }\n\n const { db: dbConfig, featureFlags: featureFlagsConfig, skipDb, verbose } = options;\n const globalEnvironment = await Core.setupEnvironment(options);\n\n await Core.initErrorHandlerIfEnabled(options);\n\n if (!Core.shouldSkipDbService(skipDb, verbose)) {\n const db = await Core.initService(\n 'database',\n () => Core.initializeDb(dbConfig, verbose),\n verbose\n );\n Core._coreServices.db = db ?? null;\n }\n\n await Core.initApiIfEnabled(options, globalEnvironment);\n\n await Core.initCacheIfEnabled(options);\n\n await Core.initObservabilityIfEnabled(options, globalEnvironment);\n\n await Core.initStorageIfEnabled(options);\n\n await Core.initNotificationsIfEnabled(options);\n\n if (featureFlagsConfig?.enabled !== false) {\n await Core.initService(\n 'feature flags',\n () => Core.initializeFeatureFlags(featureFlagsConfig, verbose),\n verbose\n );\n }\n\n await Core.initDomainServicesIfConfigured(options, globalEnvironment);\n\n Core.initialized = true;\n Core.log('Initialization complete', verbose);\n return Core._coreServices;\n }\n\n /**\n * Get initialized domain service keys\n * Use Core.getService(key) or ServiceRegistry.get(key) to access individual services.\n *\n * @example\n * ```typescript\n * const keys = Core.serviceKeys;\n * const exampleService = Core.getService('example');\n * ```\n */\n static get serviceKeys(): string[] {\n return ServiceRegistry.getInitializedKeys();\n }\n\n /**\n * All stores - unified access to ALL slices from single root store\n * All stores (global + domain) are slices of ONE Zustand store instance.\n *\n * **Auto-generated from STORE_KEYS** - No manual registration needed!\n *\n * **Benefits:**\n * - ✅ Access without hooks (store.getState())\n * - ✅ Cross-slice subscriptions work automatically\n * - ✅ Single source of truth\n * - ✅ Automatically scales with new stores\n *\n * @example\n * const errorStore = Core.stores.error; // Global slice\n * const flagsStore = Core.stores.featureFlags; // Global slice\n * const exampleStore = Core.stores.example; // Domain slice\n */\n static get stores(): Record<StoreKey, RootStoreSlice | undefined> {\n const rootState = Core._rootStore?.getState();\n\n // Dynamically generate store accessors from STORE_KEYS\n return Object.values(STORE_KEYS).reduce(\n (acc, key) => {\n Object.defineProperty(acc, key, {\n get: () => rootState,\n enumerable: true,\n });\n return acc;\n },\n {} as Record<StoreKey, RootStoreSlice | undefined>\n );\n }\n\n /**\n * Get a specific store slice by key (for ServiceRegistry injection).\n * Returns the actual slice from the namespaced root store.\n *\n * @param key - Store key (type-safe: 'example' | 'errors' | 'featureFlags')\n * @returns Specific store slice or undefined\n *\n * @example\n * ```typescript\n * const exampleSlice = Core.getDomainStore('example'); // ✅ Returns ExampleFrontendStoreSlice\n * const errorSlice = Core.getDomainStore('errors'); // ✅ Returns ErrorStoreSlice\n * const invalid = Core.getDomainStore('invalid'); // ❌ TypeScript error!\n * ```\n */\n static getDomainStore<K extends keyof RootStoreSlice>(key: K): RootStoreSlice[K] | undefined;\n static getDomainStore<T = RootStoreSlice>(): T | undefined;\n static getDomainStore<K extends keyof RootStoreSlice>(\n key?: K\n ): RootStoreSlice[K] | RootStoreSlice | undefined {\n const rootState = Core._rootStore?.getState();\n if (!rootState) return undefined;\n\n // If no key provided, return entire root store\n if (!key) return rootState;\n\n // Return specific slice from namespaced store (type-safe)\n return rootState[key];\n }\n\n /**\n * Event manager for subscribing to domain events\n * @example Core.events.on('example:created', handler)\n */\n static get events(): typeof CoreEventManager {\n return CoreEventManager;\n }\n\n /**\n * Get database service instance\n * @throws Error if not initialized\n */\n static get db(): CoreDbServiceInstance {\n if (!Core._coreServices.db) {\n throw new CorePackageError(\n 'Database service not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.db;\n }\n\n /**\n * Get API client service\n */\n static get api(): typeof ApiClientService {\n if (!Core._coreServices.api) {\n throw new CorePackageError(\n 'API client service not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.api;\n }\n\n /**\n * Get cache service instance (backend-only)\n * @throws Error if not initialized\n */\n static get cache(): CoreCacheServiceInstance {\n if (!Core._coreServices.cache) {\n throw new CorePackageError(\n 'Cache service not initialized. Call Core.initialize() with cache config first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.cache;\n }\n\n /**\n * Get observability adapter instance\n * @throws Error if not initialized\n *\n * @example\n * ```typescript\n * // Record a metric\n * await Core.observability.recordMetric({\n * type: 'counter',\n * name: 'api.requests',\n * value: 1,\n * tags: { endpoint: '/users' },\n * });\n *\n * // Start a span\n * const span = Core.observability.startSpan({ name: 'processOrder' });\n * try {\n * // ... do work\n * span.setStatus('ok');\n * } catch (e) {\n * span.recordException(e);\n * span.setStatus('error');\n * } finally {\n * span.end();\n * }\n * ```\n */\n static get observability(): ObservabilityAdapter {\n if (!Core._coreServices.observability) {\n throw new CorePackageError(\n 'Observability service not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.observability;\n }\n\n /**\n * Check if observability is initialized\n */\n static get isObservabilityInitialized(): boolean {\n return Core._coreServices.observability !== null;\n }\n\n /**\n * Get observability configuration\n */\n static get observabilityConfig(): CoreObservabilityConfig {\n return Core._observabilityConfig;\n }\n\n /**\n * Get storage service instance (backend-only)\n * @throws Error if not initialized\n *\n * @example\n * ```typescript\n * const storage = Core.storage.getStorage();\n * await storage.uploadFile({ file, filename: 'doc.pdf' });\n * ```\n */\n static get storage(): CoreStorageServiceInstance {\n if (!Core._coreServices.storage) {\n throw new CorePackageError(\n 'Storage service not initialized. Call Core.initialize() with storage config first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.storage;\n }\n\n /**\n * Check if storage is initialized\n */\n static get isStorageInitialized(): boolean {\n return Core._coreServices.storage !== null;\n }\n\n /**\n * Get notifications service instance (backend-only)\n * @throws Error if not initialized\n *\n * @example\n * ```typescript\n * const notifications = Core.notifications.getNotifications();\n * await notifications.sendEmail({ to: 'user@example.com', templateId: 'welcome' });\n * ```\n */\n static get notifications(): CoreNotificationServiceInstance {\n if (!Core._coreServices.notifications) {\n throw new CorePackageError(\n 'Notifications service not initialized. Call Core.initialize() with notifications config first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.notifications;\n }\n\n /**\n * Check if notifications is initialized\n */\n static get isNotificationsInitialized(): boolean {\n return Core._coreServices.notifications !== null;\n }\n\n /**\n * Get root store (contains all slices: errors, feature flags, etc.)\n * Use this to access the full store state and all slice actions globally.\n *\n * @example\n * ```typescript\n * // Access error actions\n * const state = Core.rootStore.getState();\n * state.addError({ ... });\n *\n * // Access flags\n * console.log(state.flags);\n *\n * // Subscribe to store changes\n * Core.rootStore.subscribe((state) => {\n * console.log('Errors:', state.errors);\n * console.log('Flags:', state.flags);\n * });\n * ```\n */\n static get rootStore(): StoreApi<RootStoreSlice> {\n if (!Core._rootStore) {\n throw new CorePackageError(\n 'Root store not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._rootStore;\n }\n\n /**\n * Get global error store actions.\n * Provides access to the error store for querying and managing errors.\n *\n * @example\n * ```typescript\n * // Get all errors\n * const allErrors = useErrorStore.getState().errors;\n *\n * // Clear all errors\n * Core.errors.clearErrors();\n *\n * // Dismiss an error\n * Core.errors.dismissError(errorId);\n * ```\n */\n static get errors(): ErrorStoreActions {\n if (!Core._errorHandler) {\n throw new CorePackageError(\n 'Error handler not initialized. Call Core.initialize() first or set errorHandler.enabled: true.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._errorHandler.getStore();\n }\n\n /**\n * Get feature flags store\n * Provides synchronous access to feature flag values from the store.\n *\n * @example\n * ```typescript\n * // Check if a flag is enabled\n * const isEnabled = Core.flags.isEnabled('NEW_FEATURE');\n *\n * // Get a flag value\n * const provider = Core.flags.getValue<string>('PAYMENT_PROVIDER');\n *\n * // Refresh flags from source\n * await Core.flags.refresh();\n * ```\n */\n static get flags(): FeatureFlagStoreSlice {\n if (!Core._rootStore) {\n throw new CorePackageError(\n 'Root store not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n // Return the feature flag slice from root store\n // Root store state includes all flag methods (isEnabled, getValue, refresh, etc.)\n return Core._rootStore.getState() as unknown as FeatureFlagStoreSlice;\n }\n\n /**\n * Check if error handler is initialized\n */\n static get isErrorHandlerInitialized(): boolean {\n return Core._errorHandler !== null;\n }\n\n /**\n * Get the HTTP error handler/middleware based on runtime.\n * Returns different types based on detected runtime:\n *\n * - **Express**: Error handler middleware function\n * ```typescript\n * app.use(Core.httpErrorHandler);\n * ```\n *\n * - **NestJS**: Exception filter class\n * ```typescript\n * app.useGlobalFilters(new (Core.httpErrorHandler)());\n * ```\n *\n * - **Next.js**: Object with App Router and Pages Router handlers\n * ```typescript\n * // App Router\n * export const GET = Core.httpErrorHandler.withErrorHandler(handler);\n * // Pages Router\n * export default Core.httpErrorHandler.createNextApiErrorHandler()(handler);\n * ```\n *\n * - **Node.js/Bun/Deno**: Object with handleError and createMiddleware\n * ```typescript\n * Core.httpErrorHandler.handleError(error, req, res);\n * ```\n *\n * - **Browser**: null (no HTTP handler needed)\n *\n * @returns The HTTP error handler for the current runtime\n */\n static get httpErrorHandler(): unknown {\n return Core._httpErrorHandler;\n }\n\n /**\n * Check if feature flags are initialized\n */\n static get isFlagsInitialized(): boolean {\n return Core._rootStore?.getState()?.featureFlags?.isInitialized ?? false;\n }\n\n /**\n * Get error handler configuration\n */\n static get errorConfig(): CoreErrorHandlerInitConfig {\n return Core._errorConfig;\n }\n\n /**\n * Get feature flag configuration\n */\n static get flagConfig(): CoreFeatureFlagInitConfig {\n return Core._flagConfig;\n }\n\n /**\n * Get loaded environment variables\n */\n static get env(): CoreEnvVars {\n return Core._coreServices.env;\n }\n\n /**\n * Get detected runtime environment\n */\n static get runtime(): CoreRuntimeEnvironment {\n return Core._coreServices.runtime;\n }\n\n /**\n * Get current app context\n */\n static get appContext(): CoreAppContext {\n return Core._coreServices.appContext;\n }\n\n /**\n * Check if Core is initialized\n */\n static get isInitialized(): boolean {\n return Core.initialized;\n }\n\n /**\n * Check if running on a backend runtime\n */\n static get isBackend(): boolean {\n return BACKEND_RUNTIMES.includes(Core._coreServices.runtime);\n }\n\n /**\n * Check if running on a frontend runtime\n */\n static get isFrontend(): boolean {\n return FRONTEND_RUNTIMES.includes(Core._coreServices.runtime);\n }\n\n /**\n * Get runtime context (backend, frontend, or universal)\n * Universal means the runtime can be either (SSR frameworks like Next.js, Nuxt, Edge)\n */\n static getRuntimeContext(): CoreRuntimeContext {\n if (BACKEND_RUNTIMES.includes(Core._coreServices.runtime)) {\n return 'backend';\n }\n if (FRONTEND_RUNTIMES.includes(Core._coreServices.runtime)) {\n return 'frontend';\n }\n return 'universal';\n }\n\n /**\n * Assert that the current runtime matches the expected runtime(s)\n * Throws an error if the runtime doesn't match\n *\n * @param expected - Expected runtime(s) to check against\n * @param serviceName - Name of the service for error message\n * @throws CorePackageError if runtime doesn't match\n *\n * @example\n * ```typescript\n * // Assert backend-only\n * Core.assertRuntime('backend', 'DatabaseService');\n *\n * // Assert multiple runtimes\n * Core.assertRuntime(['backend', 'universal'], 'CacheService');\n * ```\n */\n static assertRuntime(\n expected: CoreServiceRuntime | readonly CoreServiceRuntime[],\n serviceName: string\n ): void {\n const runtimes = Array.isArray(expected) ? expected : [expected];\n const currentContext = Core.getRuntimeContext();\n\n // Check if current context matches any of the expected runtimes\n const isAllowed = runtimes.some(runtime => {\n if (runtime === 'universal') return true;\n if (runtime === currentContext) return true;\n // Universal context (SSR) can run both frontend and backend code\n if (currentContext === 'universal') return true;\n return false;\n });\n\n if (!isAllowed) {\n throw new CorePackageError(\n `${serviceName} cannot run in ${currentContext} runtime. ` +\n `Allowed runtimes: ${runtimes.join(', ')}. ` +\n `Current runtime: ${Core._coreServices.runtime}`,\n ERROR_CODES.FEATURE_NOT_SUPPORTED\n );\n }\n }\n\n /**\n * Check if a service runtime is compatible with current runtime\n * Returns true/false instead of throwing\n *\n * @param expected - Expected runtime(s) to check against\n */\n static isRuntimeCompatible(\n expected: CoreServiceRuntime | readonly CoreServiceRuntime[]\n ): boolean {\n const runtimes = Array.isArray(expected) ? expected : [expected];\n const currentContext = Core.getRuntimeContext();\n\n return runtimes.some(runtime => {\n if (runtime === 'universal') return true;\n if (runtime === currentContext) return true;\n if (currentContext === 'universal') return true;\n return false;\n });\n }\n\n /**\n * Get a registered domain service by key.\n * Convenience method that wraps ServiceRegistry.get().\n *\n * @param key - Service key (e.g., 'featureFlags', 'example')\n * @returns The service instance\n *\n * @example\n * ```typescript\n * const flags = Core.getService<FeatureFlagDomainService>('featureFlags');\n * const isEnabled = await flags.isEnabled('my-flag');\n * ```\n */\n static getService<T extends CoreDomainServiceInstance = CoreDomainServiceInstance>(\n key: string\n ): T {\n return ServiceRegistry.get<T>(key);\n }\n\n /**\n * Get a registered domain service by key with async initialization if needed.\n * Convenience method that wraps ServiceRegistry.getAsync().\n *\n * @param key - Service key\n * @returns Promise resolving to the service instance\n */\n static async getServiceAsync<T extends CoreDomainServiceInstance = CoreDomainServiceInstance>(\n key: string\n ): Promise<T> {\n return ServiceRegistry.getAsync<T>(key);\n }\n\n /**\n * Check if a domain service is registered.\n */\n static hasService(key: string): boolean {\n return ServiceRegistry.has(key);\n }\n\n /**\n * Reset Core (useful for testing)\n */\n // eslint-disable-next-line complexity\n static async reset(): Promise<void> {\n // Close database\n if (Core._coreServices.db) {\n await Core._coreServices.db.getDatabase()?.close?.();\n }\n\n // Dispose cache\n if (Core._coreServices.cache) {\n const CacheService = getCoreDependency('CacheService');\n CacheService?.reset?.();\n }\n\n // Dispose observability\n if (Core._coreServices.observability) {\n await Core._coreServices.observability.shutdown();\n }\n Core._observabilityConfig = {};\n\n // Dispose storage\n if (Core._coreServices.storage) {\n await Core._coreServices.storage.close();\n const StorageService = getCoreDependency('StorageService');\n await StorageService?.reset?.();\n }\n\n // Dispose notifications\n if (Core._coreServices.notifications) {\n await Core._coreServices.notifications.close();\n const NotificationService = getCoreDependency('NotificationService');\n await NotificationService?.reset?.();\n }\n\n // Dispose error handler\n if (Core._errorHandler) {\n Core._errorHandler.destroy();\n Core._errorHandler = null;\n clearEventEmitter(); // Clean up CoreEventManager integration\n }\n Core._errorConfig = {};\n Core._httpErrorHandler = null;\n\n // Cleanup event listeners\n for (const cleanup of Core._eventCleanupFns) {\n cleanup();\n }\n Core._eventCleanupFns = [];\n\n // Dispose feature flags slice from root store\n if (Core._rootStore) {\n const state = Core._rootStore.getState();\n if (state.featureFlags?.dispose) {\n state.featureFlags.dispose();\n }\n Core._rootStore = null;\n }\n Core._flagConfig = {};\n\n // Dispose all registered services via ServiceRegistry\n ServiceRegistry.disposeAll();\n\n // Dispose event manager\n CoreEventManager.dispose();\n\n Core._coreServices = {\n db: null,\n api: null,\n cache: null,\n observability: null,\n storage: null,\n notifications: null,\n env: {},\n runtime: 'unknown',\n appContext: 'webapp',\n };\n Core.initialized = false;\n }\n\n /**\n * Determines whether to skip DbService initialization.\n *\n * DbService is backend-only and should never be initialized on frontend runtimes.\n * This method:\n * - Returns true (skip) if skipDb was explicitly set to true\n * - Returns true (skip) if running on frontend, with a warning\n * - Warns if someone explicitly tried to init DbService on frontend (skipDb: false)\n *\n * @param skipDb - User-provided skipDb option\n * @param verbose - Enable verbose logging\n * @returns true if DbService should be skipped\n */\n private static shouldSkipDbService(skipDb: boolean | undefined, verbose?: boolean): boolean {\n // User explicitly requested to skip\n if (skipDb === true) {\n Core.log('Database service skipped (skipDb: true)', verbose);\n return true;\n }\n\n // Check if running on frontend\n const isFrontend = Core.isFrontend;\n\n if (isFrontend) {\n // User explicitly tried to init DbService on frontend (skipDb: false)\n if (skipDb === false) {\n Core.logger.warn(\n 'DbService cannot be initialized on frontend runtime. ' +\n 'DbService is backend-only and requires Node.js. ' +\n 'Use API calls from frontend instead. Skipping database initialization.'\n );\n } else if (verbose) {\n // skipDb was undefined (default) - just log that we're skipping\n Core.log(\n 'Database service skipped (frontend runtime detected). ' +\n 'DbService is only available on backend.',\n verbose\n );\n }\n return true;\n }\n\n // Backend or universal runtime - don't skip\n return false;\n }\n\n /**\n * Initialize database service\n * Config validation is handled by DbService\n */\n private static async initializeDb(\n config?: Partial<CoreDbServiceConfig>,\n verbose?: boolean\n ): Promise<CoreDbServiceInstance> {\n Core.log(`Initializing database with adapter: ${config?.adapter ?? 'drizzle'}`, verbose);\n\n const DbService = getCoreDependency('DbService');\n if (!DbService) {\n throw new CorePackageError(\n 'DbService not available. Ensure setCoreDependencies() was called in entry-backend.ts',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return DbService.initialize({\n adapter: 'drizzle',\n ...config,\n } as CoreDbServiceConfig);\n }\n\n /**\n * Initialize API client service\n * Config validation is handled by ApiClientService\n */\n private static async initializeApi(\n config?: CoreApiInitOptions,\n globalEnvironment?: CoreAppEnvironment,\n verbose?: boolean\n ): Promise<void> {\n const { env: apiEnv, setAsDefault, ...apiClientOptions } = config ?? {};\n const resolvedEnv = apiEnv ?? globalEnvironment ?? 'development';\n\n Core.log(`Initializing API client for environment: ${resolvedEnv}`, verbose);\n\n await ApiClientService.init(\n {\n env: resolvedEnv,\n setAsDefault: setAsDefault ?? true,\n },\n apiClientOptions\n );\n }\n\n /**\n * Initialize cache service (backend-only)\n * Config validation is handled by CacheService\n */\n private static async initializeCache(config: CoreCacheConfig, verbose?: boolean): Promise<void> {\n Core.log(`Initializing cache with strategy: ${config.strategy}`, verbose);\n\n const CacheService = getCoreDependency('CacheService');\n if (!CacheService) {\n throw new CorePackageError(\n 'CacheService not available. Ensure setCoreDependencies() was called in entry-backend.ts',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n await CacheService.initialize(config);\n }\n\n /**\n * Initialize observability service based on config.\n * Always includes LoggerAdapter as failover for console output.\n */\n private static async initializeObservability(\n config: CoreObservabilityConfig,\n verbose?: boolean,\n environment?: CoreAppEnvironment\n ): Promise<void> {\n Core.log(`Initializing observability with provider: ${config.provider ?? 'auto'}`, verbose);\n\n // Use environment from config or passed parameter\n const env = config.environment ?? environment ?? 'development';\n Core._observabilityConfig = { ...config, environment: env };\n\n // Collect adapters with priorities\n const adapters: { adapter: ObservabilityAdapter; priority: number; failover?: boolean }[] = [];\n\n // Always add LoggerAdapter as failover for console output\n const loggerAdapter = new LoggerAdapter();\n await loggerAdapter.initialize({\n enabled: config.enabled !== false,\n serviceName: config.serviceName,\n environment: env,\n defaultTags: config.defaultTags,\n });\n adapters.push({ adapter: loggerAdapter, priority: -100, failover: true });\n\n // TODO: Add DatadogAdapter when configured (high priority, primary)\n // if (config.provider === 'datadog' || config.datadog) {\n // const datadogAdapter = new DatadogAdapter();\n // await datadogAdapter.initialize({\n // ...config,\n // ...config.datadog,\n // environment: env,\n // });\n // adapters.push({ adapter: datadogAdapter, priority: 100, failover: false });\n // }\n\n // Create ObservabilityService with all adapters\n const observability = new ObservabilityService();\n await observability.initialize({\n mode: config.mode ?? 'parallel',\n adapters,\n enabled: config.enabled,\n serviceName: config.serviceName,\n environment: env,\n defaultTags: config.defaultTags,\n samplingRate: config.samplingRate,\n flushInterval: config.flushInterval,\n adapterTimeout: config.flushInterval,\n });\n\n Core.log(\n `ObservabilityService initialized with ${adapters.length} adapters (env: ${env})`,\n verbose\n );\n\n Core._coreServices.observability = observability;\n // Set on ServiceRegistry for injection\n ServiceRegistry.setObservabilityInstance(observability);\n }\n\n /**\n * Initialize global error handler\n */\n /** Create and initialize root store (includes error store + all other slices) */\n private static async initializeRootStore(\n config?: CoreErrorHandlerInitConfig,\n verbose?: boolean\n ): Promise<void> {\n const isFrontend = typeof window !== 'undefined';\n\n if (isFrontend) {\n Core.log('Using frontend root store (Zustand)', verbose);\n // Frontend: use the React hook store's vanilla store API\n Core._rootStore = useRootStore as unknown as StoreApi<RootStoreSlice>;\n } else {\n Core.log('Creating backend composite store (in-memory)', verbose);\n const ServerErrorMiddleware = getCoreDependency('ServerErrorMiddleware');\n if (!ServerErrorMiddleware) {\n throw new CorePackageError(\n 'ServerErrorMiddleware not available. Ensure setCoreDependencies() was called in entry-backend.ts',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n // Backend: create in-memory error store + feature flag store (NOT Zustand)\n const backendErrorStore = ServerErrorMiddleware.createErrorStore({\n maxErrors: config?.maxErrors ?? DEFAULT_MAX_ERRORS,\n onErrorAdded: config?.onError as ((error: unknown) => void) | undefined,\n });\n\n // Create standalone feature flag store for backend\n const backendFlagStore = createStandaloneFeatureFlagStore();\n\n // Combine error + feature flag stores to match RootStoreSlice interface\n const compositeStore = {\n // Error store methods\n ...backendErrorStore,\n // Feature flag store methods\n ...backendFlagStore,\n };\n\n // Wrap backend composite store to match root store interface (getState() pattern)\n Core._rootStore = {\n getState: () => compositeStore,\n subscribe: () => () => {}, // No-op for backend\n destroy: () => {\n backendErrorStore.reset();\n backendFlagStore.dispose?.();\n },\n } as unknown as StoreApi<RootStoreSlice>;\n }\n }\n\n /** Get error store actions from root store */\n private static getErrorStoreActions(): ErrorStoreActions {\n if (!Core._rootStore) {\n throw new CorePackageError(\n 'Root store not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._rootStore.getState().errors;\n }\n\n /** Build global error handler config */\n // eslint-disable-next-line complexity\n private static buildErrorHandlerConfig(\n config?: CoreErrorHandlerInitConfig\n ): Parameters<typeof initializeGlobalErrorHandler>[1] {\n return {\n source: config?.source ?? 'global',\n maxErrors: config?.maxErrors ?? DEFAULT_MAX_ERRORS,\n filter: config?.filter,\n onError: config?.onError,\n logToConsole: config?.logToConsole ?? false,\n };\n }\n\n // eslint-disable-next-line complexity\n private static async initializeErrorHandler(\n config?: CoreErrorHandlerInitConfig,\n verbose?: boolean\n ): Promise<void> {\n if (config?.enabled === false) {\n Core.log('Error handler disabled by configuration', verbose);\n return;\n }\n\n Core._errorConfig = config ?? {};\n Core.log('Initializing global error handler...', verbose);\n\n // Initialize error system (translations, catalogs)\n // This is safe to call multiple times - it checks if already initialized\n initializeErrorSystem({\n defaultLocale: Core._errorConfig.localization?.defaultLocale,\n fallbackLocale: Core._errorConfig.localization?.fallbackLocale,\n additionalCatalogs: Core._errorConfig.localization?.additionalCatalogs,\n replaceBuiltIn: Core._errorConfig.localization?.replaceBuiltIn,\n });\n\n // Initialize root store (contains error store + all slices)\n await Core.initializeRootStore(Core._errorConfig, verbose);\n\n // Wire up CoreEventManager for automatic error event emission\n // This allows errors captured by the global handler to emit events\n setEventEmitter(CoreEventManager.emit.bind(CoreEventManager));\n\n const errorStore = Core.getErrorStoreActions();\n Core._errorHandler = initializeGlobalErrorHandler(\n errorStore,\n Core.buildErrorHandlerConfig(Core._errorConfig)\n );\n\n // Subscribe to SYSTEM.ERROR events from ApiClientService and other sources\n // Core handles updating the appropriate store based on runtime context\n const errorEventCleanup = CoreEventManager.on(\n CORE_EVENTS.SYSTEM.ERROR,\n (event: CoreEvent<CoreSystemErrorPayload>) => {\n if (!Core._rootStore) return;\n\n try {\n const { errors } = event.data;\n if (errors && errors.length > 0) {\n // Update the appropriate store based on runtime\n // Frontend: Zustand store, Backend: In-memory store (both via root store)\n Core._rootStore.getState().errors.addErrors(errors);\n Core.log(`Added ${errors.length} error(s) to store`, verbose);\n }\n } catch (e) {\n Core.logger.error('Failed to handle error event', { error: e });\n }\n }\n );\n\n // Store cleanup function\n Core._eventCleanupFns.push(errorEventCleanup);\n\n Core.log('Global error handler initialized with CoreEventManager integration', verbose);\n\n // Auto-create HTTP error handler based on runtime (unless disabled)\n if (Core._errorConfig.httpHandler !== false) {\n await Core.createHttpErrorHandler(Core._errorConfig, verbose);\n }\n }\n\n /**\n * Create HTTP error handler based on detected runtime.\n * Stores the handler in Core._httpErrorHandler for access via Core.httpErrorHandler\n */\n // eslint-disable-next-line complexity\n private static async createHttpErrorHandler(\n config?: CoreErrorHandlerInitConfig,\n verbose?: boolean\n ): Promise<void> {\n const runtime = Core._coreServices.runtime;\n const isProduction = Core._coreServices.env.NODE_ENV === 'production';\n\n // Skip for browser runtime (no HTTP error handler needed)\n if (runtime === 'browser') {\n Core._httpErrorHandler = null;\n Core.log('Skipping HTTP handler for browser runtime', verbose);\n return;\n }\n\n const ServerErrorMiddleware = getCoreDependency('ServerErrorMiddleware');\n if (!ServerErrorMiddleware) {\n Core.log('Skipping HTTP handler (ServerErrorMiddleware not registered)', verbose);\n return;\n }\n\n // Build common config for all HTTP handlers\n const httpConfig = {\n source: runtime,\n includeStack: config?.includeStack ?? !isProduction,\n logErrors: config?.logger ?? config?.logToConsole ?? true,\n errorHandler: Core._errorHandler ?? undefined,\n };\n\n switch (runtime) {\n case 'express':\n Core._httpErrorHandler = ServerErrorMiddleware.createHttpErrorHandler(httpConfig);\n Core.log('Created Express error handler middleware', verbose);\n break;\n\n case 'nestjs':\n Core._httpErrorHandler = ServerErrorMiddleware.createNestJsExceptionFilter(httpConfig);\n Core.log('Created NestJS exception filter', verbose);\n break;\n\n case 'nextjs':\n // For Next.js, provide both App Router and Pages Router handlers\n Core._httpErrorHandler = {\n /** For App Router: export const GET = withErrorHandler(handler) */\n withErrorHandler: <T>(handler: T, overrideConfig = {}) =>\n ServerErrorMiddleware.withErrorHandler(\n handler as Parameters<typeof ServerErrorMiddleware.withErrorHandler>[0],\n { ...httpConfig, ...overrideConfig }\n ),\n /** For Pages Router: export default createNextApiErrorHandler()(handler) */\n createNextApiErrorHandler: (overrideConfig = {}) =>\n ServerErrorMiddleware.createNextApiErrorHandler({ ...httpConfig, ...overrideConfig }),\n };\n Core.log('Created Next.js error handlers', verbose);\n break;\n\n case 'node':\n case 'bun':\n case 'deno':\n // Generic Node.js handler\n Core._httpErrorHandler = {\n /** Handle error: handleNodeError(error, req, res) */\n handleError: (error: unknown, req: unknown, res: unknown) =>\n ServerErrorMiddleware.handleNodeError(\n error,\n req as Parameters<typeof ServerErrorMiddleware.handleNodeError>[1],\n // eslint-disable-next-line no-magic-numbers -- Type parameter index for handleNodeError\n res as Parameters<typeof ServerErrorMiddleware.handleNodeError>[2],\n httpConfig\n ),\n /** Create middleware for use with native http */\n createMiddleware: () => ServerErrorMiddleware.createHttpErrorHandler(httpConfig),\n };\n Core.log(`Created ${runtime} error handler`, verbose);\n break;\n\n default:\n // For unknown runtimes, provide generic handler\n Core._httpErrorHandler = ServerErrorMiddleware.createHttpErrorHandler(httpConfig);\n Core.log(`Created generic HTTP error handler for ${runtime}`, verbose);\n }\n }\n\n /**\n * Subscribe to CoreEventManager error events\n * Forwards system, entity, API, validation, database, and auth errors to the global error handler.\n *\n * Note: Database errors (DATABASE.ERROR) are only subscribed on backend runtimes since\n * DbService is backend-only (skipDb: true on frontend).\n */\n private static subscribeToErrorEvents(verbose?: boolean): void {\n if (!Core._errorHandler) {\n return;\n }\n\n Core.log('Subscribing to error events...', verbose);\n\n // Subscribe to system errors (universal)\n const cleanupSystemError = CoreEventManager.on(CORE_EVENTS.SYSTEM.ERROR, event => {\n if (Core._errorHandler && event.data?.errors?.length) {\n // Capture each error in the array\n for (const err of event.data.errors) {\n Core._errorHandler.captureError(err, 'system');\n }\n }\n });\n\n // Subscribe to entity errors (universal)\n const cleanupEntityError = CoreEventManager.on(CORE_EVENTS.ENTITY.ERROR, event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'entity');\n }\n });\n\n // Subscribe to API errors (universal)\n const cleanupApiError = CoreEventManager.on(CORE_EVENTS.API.REQUEST_ERROR, event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'api');\n }\n });\n\n // Subscribe to validation errors (universal)\n const cleanupValidationError = CoreEventManager.on(CORE_EVENTS.VALIDATION.FAILED, event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'validation');\n }\n });\n\n // Subscribe to auth errors (universal - can happen on both frontend and backend)\n const cleanupAuthUnauthorized = CoreEventManager.on(CORE_EVENTS.AUTH.UNAUTHORIZED, event => {\n if (Core._errorHandler && event.data?.error) {\n Core._errorHandler.captureError(event.data.error, 'auth');\n }\n });\n\n const cleanupAuthSessionExpired = CoreEventManager.on(\n CORE_EVENTS.AUTH.SESSION_EXPIRED,\n event => {\n if (Core._errorHandler && event.data?.error) {\n Core._errorHandler.captureError(event.data.error, 'auth');\n }\n }\n );\n\n // Store universal cleanup functions\n Core._eventCleanupFns.push(\n cleanupSystemError,\n cleanupEntityError,\n cleanupApiError,\n cleanupValidationError,\n cleanupAuthUnauthorized,\n cleanupAuthSessionExpired\n );\n\n // Subscribe to database errors (backend-only)\n // Database events only fire when DbService is initialized (skipDb: false)\n if (Core.isRuntimeCompatible('backend')) {\n const cleanupDatabaseError = CoreEventManager.on(CORE_EVENTS.DATABASE.ERROR, event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'database');\n }\n });\n Core._eventCleanupFns.push(cleanupDatabaseError);\n\n // Subscribe to storage errors (backend-only)\n const cleanupStorageError = CoreEventManager.on(CORE_EVENTS.STORAGE.ERROR, event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'storage');\n }\n });\n Core._eventCleanupFns.push(cleanupStorageError);\n\n // Subscribe to notification errors (backend-only)\n const cleanupNotificationError = CoreEventManager.on(\n CORE_EVENTS.NOTIFICATION.ERROR,\n event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'notification');\n }\n }\n );\n Core._eventCleanupFns.push(cleanupNotificationError);\n\n Core.log('Subscribed to backend error events (database, storage, notification)', verbose);\n }\n\n const eventTypes = ['system', 'entity', 'api', 'validation', 'auth'];\n if (Core.isRuntimeCompatible('backend')) {\n eventTypes.push('database', 'storage', 'notification');\n }\n Core.log(`Subscribed to error events: ${eventTypes.join(', ')}`, verbose);\n }\n\n /** Handle fetch flags error and return empty flags */\n private static handleFetchFlagsError(\n error: unknown,\n config?: CoreFeatureFlagInitConfig,\n verbose?: boolean\n ): Record<string, FeatureFlagValue> {\n if (verbose) Core.logger.error('Failed to fetch feature flags', { error });\n\n // If already a package error, use as-is; otherwise wrap it\n const packageError =\n error instanceof BaseError\n ? (error as CorePackageError)\n : new CorePackageError(\n error instanceof Error ? error.message : String(error),\n ERROR_CODES.CORE_FEATURE_FLAG_PROVIDER_ERROR,\n { cause: error instanceof Error ? error : undefined }\n );\n config?.onError?.(packageError);\n return {};\n }\n\n /** Create fetch flags function */\n private static createFetchFlagsFn(\n config?: CoreFeatureFlagInitConfig,\n verbose?: boolean\n ): () => Promise<Record<string, FeatureFlagValue>> {\n // eslint-disable-next-line complexity\n return async () => {\n try {\n const client = ApiClientService.getClient();\n const endpoint = config?.apiEndpoint ?? '/feature-flags';\n const response = await client.get<{ flags: Record<string, FeatureFlagValue> }>(endpoint);\n\n if (!response.isSuccess) {\n throw new CorePackageError(\n response.error?.message ?? 'Failed to fetch feature flags',\n ERROR_CODES.CORE_FEATURE_FLAG_PROVIDER_ERROR\n );\n }\n\n return response.data?.flags ?? {};\n } catch (error) {\n return Core.handleFetchFlagsError(error, config, verbose);\n }\n };\n }\n\n /**\n * Initialize feature flags slice within root store\n */\n\n private static async initializeFeatureFlags(\n config?: CoreFeatureFlagInitConfig,\n verbose?: boolean\n ): Promise<void> {\n if (config?.enabled === false) {\n Core.log('Feature flags disabled by configuration', verbose);\n return;\n }\n\n if (!Core._rootStore) {\n throw new CorePackageError(\n 'Root store not initialized. Call Core.initializeErrorHandler() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n Core._flagConfig = config ?? {};\n Core.log('Initializing feature flags from root store...', verbose);\n\n // Initialize the feature flag slice within the root store\n const state = Core._rootStore.getState();\n await state.featureFlags.initialize({\n defaults: Core._flagConfig.defaults,\n polling: Core._flagConfig.polling,\n fetchFn: Core.createFetchFlagsFn(Core._flagConfig, verbose),\n onFlagChange: Core._flagConfig.onFlagChange,\n onError: Core._flagConfig.onError,\n });\n\n Core.log('Feature flags initialized', verbose);\n }\n}\n\n// Export for convenience (excluding server-only services - use backend entry for those)\n// Note: CacheService and DEFAULT_ENCRYPTION_FIELDS are only exported from entry-backend.ts\nexport { ApiClientService };\n","/**\n * DbService - Singleton Database Connection Manager\n *\n * @description Manages database connections for the entire application using a singleton pattern.\n * This service wraps @plyaz/db and provides a centralized way to initialize and access\n * the database across all domains (feature flags, users, campaigns, backoffice, etc.).\n *\n * **Architecture:**\n * - Uses `createDatabaseService()` from @plyaz/db which builds an adapter chain\n * - Supports Drizzle (direct PostgreSQL), Supabase (REST API), or raw SQL adapters\n * - Extension layers: Encryption → SoftDelete → Caching → Audit → ReadReplica\n *\n * **Adapter Configuration:**\n * - **Drizzle**: Requires `connectionString` (PostgreSQL URL)\n * - **Supabase**: Requires `supabaseUrl`, `supabaseServiceKey`, `supabaseAnonKey`\n * - **SQL**: Requires `connectionString`\n *\n * **Required Environment Variables (Drizzle with Supabase):**\n * - DATABASE_URL: PostgreSQL connection string (from Supabase Dashboard > Database > URI)\n *\n * **Required Environment Variables (Supabase REST API):**\n * - SUPABASE_URL: Your Supabase project URL\n * - SUPABASE_SERVICE_ROLE_KEY: Service role key for admin operations\n * - SUPABASE_ANON_PUBLIC_KEY: Anonymous key for public operations\n *\n * @example Using with Core.initialize() (Recommended)\n * ```typescript\n * import { Core } from '@plyaz/core';\n *\n * // Core.initialize() handles loading env and passing to DbService\n * await Core.initialize({\n * envPath: '.env',\n * db: {\n * adapter: 'sql',\n * cache: { enabled: true, ttl: 60 },\n * },\n * });\n *\n * // Access via Core.db\n * const db = Core.db.getDatabase();\n * const result = await db.list('users', { pagination: { limit: 10, offset: 0 } });\n * ```\n *\n * @example Direct Usage (requires explicit config)\n * ```typescript\n * // Direct usage requires explicit connectionString\n * await DbService.initialize({\n * adapter: 'drizzle',\n * drizzle: {\n * connectionString: 'postgresql://user:pass@localhost:5432/db',\n * poolSize: 20,\n * },\n * });\n * ```\n *\n * @example With Extensions\n * ```typescript\n * await Core.initialize({\n * envPath: '.env',\n * db: {\n * adapter: 'drizzle',\n * softDelete: {\n * enabled: true,\n * field: 'deleted_at',\n * excludeTables: ['audit_logs', 'feature_flag_evaluations'],\n * },\n * cache: {\n * enabled: true,\n * provider: 'memory',\n * ttl: 300,\n * },\n * audit: {\n * enabled: true,\n * retentionDays: 90,\n * },\n * },\n * });\n * ```\n *\n * @example Using with BaseRepository\n * ```typescript\n * import { BaseRepository } from '@plyaz/db';\n * import { DbService } from '@plyaz/core';\n *\n * class UserRepository extends BaseRepository<User> {\n * constructor() {\n * super(DbService.getInstance().getDatabase(), 'users');\n * }\n * }\n * ```\n *\n * @module services\n */\n\nimport { createDatabaseService } from '@plyaz/db';\nimport { DatabasePackageError } from '@plyaz/errors';\nimport {\n type DatabaseServiceInterface,\n type DatabaseServiceConfig,\n type DrizzleConfig,\n type SupabaseConfig,\n type SqlConfig,\n type Transaction,\n} from '@plyaz/types/db';\nimport { DATABASE_ERROR_CODES } from '@plyaz/types/errors';\nimport { CORE_EVENTS, type CoreDatabaseErrorPayload } from '@plyaz/types/core';\nimport { CoreEventManager } from '../events/CoreEventManager';\n\n/**\n * Default fields to encrypt per table\n * Contains sensitive PII and financial data that should be encrypted at rest\n *\n * @see docs/db-schemas/dbdiagram_schema.dbml for field definitions\n */\nexport const DEFAULT_ENCRYPTION_FIELDS: Record<string, string[]> = {\n // User PII\n users: ['password_hash', 'phone_number', 'date_of_birth'],\n\n // KYC sensitive data\n 'backoffice.kyc_submissions': ['tax_id', 'address_line1', 'address_line2'],\n\n // Connected accounts OAuth tokens\n connected_accounts: ['access_token_encrypted', 'refresh_token_encrypted', 'wallet_address'],\n\n // Payment payout accounts\n user_payout_accounts: ['provider_account_id', 'account_holder_name'],\n\n // Sessions\n sessions: ['token'],\n};\n\n// Re-export DbServiceConfig from @plyaz/types/core\nexport type { CoreDbServiceConfig } from '@plyaz/types/core';\n\n// Local alias for internal use\nimport type {\n CoreDbServiceConfig as DbServiceConfig,\n CoreDbServiceInstance,\n} from '@plyaz/types/core';\n\n/**\n * Default configuration for DbService\n *\n * **Adapter Selection Guide:**\n *\n * | Adapter | Connection | Auto-Register | RLS | Use Case |\n * |-------------|------------------|---------------|----------|-----------------------------------|\n * | `'sql'` | PostgreSQL URL | ✓ Yes | Bypassed | **Recommended** for backend |\n * | `'supabase'`| Supabase API | ✓ Yes | Enforced | Frontend / RLS-required scenarios |\n * | `'drizzle'` | PostgreSQL URL | ✓ Yes* | Bypassed | Type-safe ORM (with PgTable schemas) |\n *\n * *Drizzle supports dual-mode: uses PgTable schemas if registered, falls back to raw SQL otherwise.\n *\n * **Recommended:** Use `'sql'` adapter for backend services with Supabase PostgreSQL.\n * Direct PostgreSQL connection = best performance, bypasses RLS for full backend access.\n */\n// Database configuration constants\nconst DEFAULT_CACHE_TTL_SECONDS = 300; // 5 minutes\nconst DEFAULT_AUDIT_RETENTION_DAYS = 180; // GDPR/SOX compliance (6 months minimum)\nconst DEFAULT_POOL_SIZE = 10;\n\nconst DEFAULT_CONFIG: Partial<DbServiceConfig> = {\n adapter: 'sql',\n cache: {\n enabled: true,\n provider: 'memory',\n ttl: DEFAULT_CACHE_TTL_SECONDS,\n },\n softDelete: {\n enabled: true,\n field: 'deleted_at',\n excludeTables: [\n 'audit_logs',\n 'audit.audit_logs',\n 'audit.feature_flag_evaluations',\n 'feature_flag_evaluations',\n 'notification_events',\n 'payments_activity',\n 'campaign_analytics',\n 'admin_actions',\n 'backoffice.admin_actions',\n ],\n },\n audit: {\n enabled: true, // Enabled by default for compliance\n retentionDays: DEFAULT_AUDIT_RETENTION_DAYS,\n excludeFields: ['password_hash', 'api_key_hash', 'token_hash'],\n excludeTables: ['audit_logs', 'audit.audit_logs'], // Don't audit the audit table itself\n schema: 'audit', // Use dedicated audit schema\n usePartitionedTables: true, // Use daily partitioned tables (audit_log_yyyy_mm_dd)\n },\n // NOTE: Encryption requires key from environment or DbService.initialize()\n // Enable via: DbService.initialize({ encryption: { enabled: true, key: process.env.ENCRYPTION_KEY!, fields: DEFAULT_ENCRYPTION_FIELDS } })\n};\n\n/**\n * Complete table registry from database migrations\n * Maps logical table names to their ID columns\n *\n * @see docs/db-schemas/migrations/ for schema definitions\n * @see docs/db-schemas/dbdiagram_schema.dbml for full schema\n */\n/**\n * TABLE_REGISTRY - Custom ID Column and Schema Registry\n *\n * ONLY register tables with:\n * 1. Custom ID columns (anything other than 'id')\n * 2. Custom database schemas (anything other than 'public')\n *\n * Tables with standard 'id' column in 'public' schema do NOT need registration.\n * You can also override ID column and schema per-query using OperationConfig.\n *\n * Schema can be defined in the table key or in the config object (or both):\n * - 'schema.table': { idColumn: 'key' } ← Schema in key only\n * - 'schema.table': { idColumn: 'key', schema: 'schema' } ← Redundant but allowed\n * - 'schema.table': {} ← Empty config, schema in key\n * - 'table': { idColumn: 'key', schema: 'schema' } ← Schema in config only\n *\n * @example\n * ```typescript\n * // Using registry\n * await db.get('feature_flags', 'my-flag-key'); // Uses 'key' column from registry\n *\n * // Per-query override\n * await db.get('custom_table', 'some-key', { idColumn: 'custom_id' });\n *\n * // Schema override\n * await db.get('logs', '123', { schema: 'logging' });\n * ```\n */\nexport const TABLE_REGISTRY: Record<string, { idColumn?: string; schema?: string }> = {\n // Migration 008: Feature Flags (custom ID column 'key')\n feature_flags: { idColumn: 'key' },\n\n // Test Feature Flags (custom ID column 'key')\n test_feature_flags: { idColumn: 'key' },\n\n // Migration 010: Universal Analytics (custom ID column 'user_id')\n user_analytics_summary: { idColumn: 'user_id' },\n};\n\n/**\n * DbService - Singleton Database Connection Manager\n *\n * Provides centralized database connection management for all domains.\n * Uses @plyaz/db under the hood with configurable adapters and extensions.\n */\nexport class DbService implements CoreDbServiceInstance {\n private static instance: DbService | null = null;\n private databaseService: DatabaseServiceInterface | null = null;\n private namedAdapters: Map<string, DatabaseServiceInterface> = new Map();\n private config: DbServiceConfig | null = null;\n private initialized = false;\n\n private constructor() {}\n\n /**\n * Emits a database error event via CoreEventManager.\n * Called when database operations fail to integrate with global error handling.\n *\n * @param error - The error that occurred\n * @param operation - The operation that failed (e.g., 'transaction', 'query', 'healthCheck')\n * @param table - Optional table name involved in the operation\n * @param query - Optional query string that failed\n * @param recoverable - Whether the error is recoverable (default: false)\n */\n private emitDatabaseError(\n error: unknown,\n operation: string,\n options?: {\n table?: string;\n query?: string;\n recoverable?: boolean;\n }\n ): void {\n const payload: CoreDatabaseErrorPayload = {\n error,\n operation,\n table: options?.table,\n query: options?.query,\n recoverable: options?.recoverable ?? false,\n };\n CoreEventManager.emit(CORE_EVENTS.DATABASE.ERROR, payload);\n }\n\n /**\n * Gets the singleton instance of DbService\n *\n * @returns {DbService} The singleton instance\n */\n static getInstance(): DbService {\n DbService.instance ??= new DbService();\n return DbService.instance;\n }\n\n /**\n * Checks if the database service has been initialized\n *\n * @returns {boolean} True if initialized\n */\n static isInitialized(): boolean {\n return DbService.instance?.initialized ?? false;\n }\n\n /**\n * Resets the database service by closing connections and clearing the singleton instance\n *\n * @description Properly closes the database connection and clears the singleton.\n * Useful for testing or when you need to reinitialize with different configuration.\n *\n * @example\n * ```typescript\n * await DbService.reset();\n * await DbService.initialize({ adapter: 'sql', ... });\n * ```\n */\n static async reset(): Promise<void> {\n if (DbService.instance) {\n try {\n await DbService.instance.databaseService?.close?.();\n } catch {\n // Ignore close errors (pool might already be closed)\n }\n DbService.instance = null;\n }\n }\n\n /**\n * Initializes the database connection\n *\n * @description Sets up the database connection using the provided configuration\n * or environment variables. This method is idempotent - calling it multiple\n * times won't create additional connections.\n *\n * **Environment Variables:**\n * - `DATABASE_URL` - PostgreSQL connection string (for sql/drizzle adapters)\n * - `ENCRYPTION_KEY` - 32-byte encryption key for field encryption (optional)\n * - `SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY`, `SUPABASE_ANON_PUBLIC_KEY` - For supabase adapter\n *\n * **Encryption:** If `ENCRYPTION_KEY` env is set, encryption is auto-enabled\n * using `DEFAULT_ENCRYPTION_FIELDS`. Override via config.encryption.\n *\n * @param {DbServiceConfig} [config] - Optional configuration\n * @returns {Promise<DbService>} The initialized DbService instance\n * @throws {DatabasePackageError} When configuration is invalid or connection fails\n *\n * @example\n * ```typescript\n * // Minimal - uses DATABASE_URL env, auto-enables encryption if ENCRYPTION_KEY set\n * await DbService.initialize();\n *\n * // With explicit encryption\n * await DbService.initialize({\n * adapter: 'sql',\n * encryption: {\n * enabled: true,\n * key: 'your-32-byte-encryption-key-here!!',\n * fields: DEFAULT_ENCRYPTION_FIELDS,\n * },\n * });\n *\n * // Or via Core.initialize() with env:\n * await Core.initialize({\n * env: { ENCRYPTION_KEY: '...' },\n * db: { adapter: 'sql' },\n * });\n * ```\n */\n /** Build encryption config from user config */\n private static buildEncryptionConfig(config?: DbServiceConfig): DbServiceConfig['encryption'] {\n const encryption = config?.encryption;\n if (!encryption?.key) return undefined;\n\n return {\n enabled: encryption.enabled ?? true,\n key: encryption.key,\n fields: encryption.fields ?? DEFAULT_ENCRYPTION_FIELDS,\n algorithm: encryption.algorithm ?? 'aes-256-gcm',\n };\n }\n\n /** Merge user config with defaults */\n private static mergeConfig(config?: DbServiceConfig): DbServiceConfig {\n return {\n ...DEFAULT_CONFIG,\n ...config,\n softDelete: { ...DEFAULT_CONFIG.softDelete, ...config?.softDelete },\n cache: { ...DEFAULT_CONFIG.cache, ...config?.cache },\n audit: { ...DEFAULT_CONFIG.audit, ...config?.audit },\n encryption: DbService.buildEncryptionConfig(config),\n } as DbServiceConfig;\n }\n\n /** Initialize named adapters */\n private async initializeNamedAdapters(mergedConfig: DbServiceConfig): Promise<void> {\n if (!mergedConfig.adapters) return;\n\n for (const [name, adapterConfig] of Object.entries(mergedConfig.adapters)) {\n const namedDbConfig = this.buildDatabaseConfig({\n ...mergedConfig,\n adapter: adapterConfig.adapter,\n drizzle: adapterConfig.drizzle,\n supabase: adapterConfig.supabase,\n sql: adapterConfig.sql,\n });\n\n const namedService = await createDatabaseService(namedDbConfig);\n this.namedAdapters.set(name, namedService);\n }\n }\n\n static async initialize(config?: DbServiceConfig): Promise<DbService> {\n const instance = DbService.getInstance();\n\n if (instance.initialized) {\n return instance;\n }\n\n const mergedConfig = DbService.mergeConfig(config);\n instance.config = mergedConfig;\n\n const dbConfig = instance.buildDatabaseConfig(mergedConfig);\n instance.databaseService = await createDatabaseService(dbConfig);\n\n await instance.initializeNamedAdapters(mergedConfig);\n\n instance.initialized = true;\n return instance;\n }\n\n /**\n * Builds the DatabaseServiceConfig based on the adapter type\n * @private\n */\n\n /** Builds adapter-specific config based on adapter type */\n private buildAdapterConfig(\n adapter: string,\n config: DbServiceConfig\n ): DrizzleConfig | SupabaseConfig | SqlConfig {\n const builders: Record<string, () => DrizzleConfig | SupabaseConfig | SqlConfig> = {\n drizzle: () => this.buildDrizzleConfig(config),\n supabase: () => this.buildSupabaseConfig(config),\n sql: () => this.buildSqlConfig(config),\n };\n\n const builder = builders[adapter];\n if (!builder) {\n throw new DatabasePackageError(\n `Unsupported adapter type: ${adapter}`,\n DATABASE_ERROR_CODES.CONFIG_REQUIRED\n );\n }\n return builder();\n }\n\n /** Builds soft delete extension config */\n private buildSoftDeleteExtension(\n config: DbServiceConfig\n ): DatabaseServiceConfig['softDelete'] | undefined {\n if (!config.softDelete?.enabled) return undefined;\n return {\n enabled: true,\n field: config.softDelete.field ?? 'deleted_at',\n excludeTables: config.softDelete.excludeTables,\n };\n }\n\n /** Builds cache extension config */\n private buildCacheExtension(config: DbServiceConfig): DatabaseServiceConfig['cache'] | undefined {\n if (!config.cache?.enabled) return undefined;\n return {\n enabled: true,\n ttl: config.cache.ttl ?? DEFAULT_CACHE_TTL_SECONDS,\n provider: config.cache.provider ?? 'memory',\n invalidation: config.cache.invalidation ?? 'write',\n };\n }\n\n /** Builds audit extension config */\n private buildAuditExtension(config: DbServiceConfig): DatabaseServiceConfig['audit'] | undefined {\n if (!config.audit?.enabled) return undefined;\n return {\n enabled: true,\n retentionDays: config.audit.retentionDays ?? DEFAULT_AUDIT_RETENTION_DAYS,\n excludeFields: config.audit.excludeFields,\n excludeTables: config.audit.excludeTables,\n schema: config.audit.schema ?? 'audit',\n usePartitionedTables: config.audit.usePartitionedTables ?? true,\n };\n }\n\n /** Builds encryption extension config */\n private buildEncryptionExtension(\n config: DbServiceConfig\n ): DatabaseServiceConfig['encryption'] | undefined {\n if (!config.encryption?.enabled || !config.encryption.key) return undefined;\n return {\n enabled: true,\n key: config.encryption.key,\n fields: config.encryption.fields ?? {},\n algorithm: config.encryption.algorithm,\n };\n }\n\n private buildDatabaseConfig(config: DbServiceConfig): DatabaseServiceConfig {\n const adapter = config.adapter ?? 'drizzle';\n\n const dbConfig: DatabaseServiceConfig = {\n adapter: adapter as DatabaseServiceConfig['adapter'],\n config: this.buildAdapterConfig(adapter, config),\n };\n\n // Apply extensions\n const softDelete = this.buildSoftDeleteExtension(config);\n const cache = this.buildCacheExtension(config);\n const audit = this.buildAuditExtension(config);\n const encryption = this.buildEncryptionExtension(config);\n\n if (softDelete) dbConfig.softDelete = softDelete;\n if (cache) dbConfig.cache = cache;\n if (audit) dbConfig.audit = audit;\n if (encryption) dbConfig.encryption = encryption;\n\n return dbConfig;\n }\n\n /**\n * Builds Drizzle adapter configuration\n * @private\n */\n private buildDrizzleConfig(config: DbServiceConfig): DrizzleConfig {\n // Get connection string from config (Core.initialize() passes env values)\n const connectionString = config.drizzle?.connectionString;\n\n if (!connectionString) {\n throw new DatabasePackageError(\n 'Drizzle adapter requires a PostgreSQL connection string. ' +\n 'Provide `drizzle.connectionString` in config or use Core.initialize() with DATABASE_URL in env. ' +\n 'For Supabase, find this in Dashboard > Database > Connection string (URI).',\n DATABASE_ERROR_CODES.CONFIG_REQUIRED\n );\n }\n\n // Build table ID column mappings from TABLE_REGISTRY\n const tableIdColumns = this.buildTableIdColumns();\n\n return {\n connectionString,\n poolSize: config.drizzle?.poolSize ?? DEFAULT_POOL_SIZE,\n ssl: config.drizzle?.ssl,\n schema: config.drizzle?.schema, // Pass through schema configuration\n tableIdColumns,\n };\n }\n\n /**\n * Builds Supabase adapter configuration\n * @private\n */\n // eslint-disable-next-line complexity\n private buildSupabaseConfig(config: DbServiceConfig): SupabaseConfig {\n // Get Supabase config (Core.initialize() passes env values)\n const supabaseUrl = config.supabase?.supabaseUrl;\n const supabaseServiceKey = config.supabase?.supabaseServiceKey;\n const supabaseAnonKey = config.supabase?.supabaseAnonKey;\n\n if (!supabaseUrl || !supabaseServiceKey) {\n throw new DatabasePackageError(\n 'Supabase adapter requires supabaseUrl and supabaseServiceKey. ' +\n 'Provide in config or use Core.initialize() with SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY in env.',\n DATABASE_ERROR_CODES.CONFIG_REQUIRED\n );\n }\n\n if (!supabaseAnonKey) {\n throw new DatabasePackageError(\n 'Supabase adapter requires supabaseAnonKey. ' +\n 'Provide in config or use Core.initialize() with SUPABASE_ANON_PUBLIC_KEY in env.',\n DATABASE_ERROR_CODES.CONFIG_REQUIRED\n );\n }\n\n // Build table ID column mappings from TABLE_REGISTRY\n const tableIdColumns = this.buildTableIdColumns();\n\n return {\n supabaseUrl,\n supabaseServiceKey,\n supabaseAnonKey,\n schema: config.supabase?.schema ?? 'public',\n tableIdColumns,\n };\n }\n\n /**\n * Builds SQL adapter configuration\n * @private\n */\n private buildSqlConfig(config: DbServiceConfig): SqlConfig {\n // Get connection string from config (Core.initialize() passes env values)\n const connectionString = config.sql?.connectionString;\n\n if (!connectionString) {\n throw new DatabasePackageError(\n 'SQL adapter requires a connection string. ' +\n 'Provide `sql.connectionString` in config or use Core.initialize() with DATABASE_URL in env.',\n DATABASE_ERROR_CODES.CONFIG_REQUIRED\n );\n }\n\n // Build table ID column mappings from TABLE_REGISTRY\n const tableIdColumns = this.buildTableIdColumns();\n\n return {\n connectionString,\n dialect: config.sql?.dialect ?? 'postgresql',\n schema: config.sql?.schema, // Pass through schema configuration\n tableIdColumns,\n };\n }\n\n /**\n * Builds table ID column mappings from TABLE_REGISTRY\n * @private\n * @returns Record of table names to ID column names\n */\n // eslint-disable-next-line complexity\n private buildTableIdColumns(): Record<string, string> {\n const tableIdColumns: Record<string, string> = {};\n const baseNameConflicts = new Set<string>();\n const baseNameMappings = new Map<string, string>();\n\n // First pass: identify base name conflicts\n // e.g., if we have both 'public.users' and 'backoffice.users',\n // we can't map 'users' → one ID column\n for (const tableName of Object.keys(TABLE_REGISTRY)) {\n if (tableName.includes('.')) {\n const baseName = tableName.split('.').pop()!;\n if (baseNameMappings.has(baseName) || TABLE_REGISTRY[baseName]) {\n baseNameConflicts.add(baseName);\n } else {\n baseNameMappings.set(baseName, tableName);\n }\n }\n }\n\n // Second pass: build ID column mappings\n for (const [tableName, config] of Object.entries(TABLE_REGISTRY)) {\n const idColumn = config.idColumn ?? 'id';\n\n // Only include non-standard ID columns (not 'id')\n if (idColumn === 'id') continue;\n\n // Always map the full table name (with or without schema)\n tableIdColumns[tableName] = idColumn;\n\n // If the table name includes a schema (e.g., 'backoffice.flagged_content'),\n // also map the base name (e.g., 'flagged_content') for convenience\n // unless there's a conflict with another schema's table\n if (!tableName.includes('.')) continue;\n\n const baseName = tableName.split('.').pop()!;\n if (!baseNameConflicts.has(baseName)) {\n tableIdColumns[baseName] = idColumn;\n }\n }\n\n return tableIdColumns;\n }\n\n /**\n * Gets the initialized database service instance\n *\n * @param {string} [adapterName] - Optional named adapter to use instead of default\n * @returns {DatabaseServiceInterface} The database service instance\n * @throws {DatabasePackageError} When database is not initialized or named adapter not found\n */\n getDatabase(adapterName?: string): DatabaseServiceInterface {\n if (adapterName) {\n const namedAdapter = this.namedAdapters.get(adapterName);\n if (!namedAdapter) {\n throw new DatabasePackageError(\n `Named adapter '${adapterName}' not found. Available adapters: ${Array.from(this.namedAdapters.keys()).join(', ')}`,\n DATABASE_ERROR_CODES.INIT_FAILED\n );\n }\n return namedAdapter;\n }\n\n if (!this.databaseService) {\n throw new DatabasePackageError(\n 'Database not initialized. Call DbService.initialize() first.',\n DATABASE_ERROR_CODES.INIT_FAILED\n );\n }\n return this.databaseService;\n }\n\n /**\n * Gets a named adapter by name\n *\n * @param {string} name - The name of the adapter\n * @returns {DatabaseServiceInterface} The named adapter instance\n * @throws {DatabasePackageError} When adapter not found\n */\n getAdapter(name: string): DatabaseServiceInterface {\n return this.getDatabase(name);\n }\n\n /**\n * Lists all available named adapters\n *\n * @returns {string[]} Array of adapter names\n */\n getAvailableAdapters(): string[] {\n return ['default', ...Array.from(this.namedAdapters.keys())];\n }\n\n /**\n * Executes a database transaction with automatic rollback on failure\n *\n * @template T The return type of the transaction callback\n * @param {Function} callback - Function that receives transaction object\n * @returns {Promise<T>} The result of the transaction callback\n * @throws {DatabasePackageError} When transaction fails\n */\n async transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T> {\n const db = this.getDatabase();\n const result = await db.transaction(callback);\n\n if (!result.success) {\n const errorMessage = result.error?.message ?? 'Transaction failed';\n const error = new DatabasePackageError(errorMessage, DATABASE_ERROR_CODES.TRANSACTION_FAILED);\n // Emit database error event for global error handling\n this.emitDatabaseError(error, 'transaction', { recoverable: true });\n throw error;\n }\n\n if (result.value === undefined || result.value === null) {\n const error = new DatabasePackageError(\n 'Transaction returned no value',\n DATABASE_ERROR_CODES.INVALID_RESULT\n );\n this.emitDatabaseError(error, 'transaction', { recoverable: false });\n throw error;\n }\n\n return result.value;\n }\n\n /**\n * Sets audit context for subsequent operations\n *\n * @param context - Audit context (userId, requestId, etc.)\n */\n async setAuditContext(context: {\n userId?: string;\n requestId?: string;\n ipAddress?: string;\n userAgent?: string;\n }): Promise<void> {\n const db = this.getDatabase();\n await db.setAuditContext(context);\n }\n\n /**\n * Performs a health check on the database connection\n *\n * @returns Health check result\n */\n async healthCheck(): Promise<{ isHealthy: boolean; responseTime?: number; error?: string }> {\n try {\n const db = this.getDatabase();\n const result = await db.healthCheck();\n\n if (result.success && result.value) {\n return {\n isHealthy: result.value.isHealthy,\n responseTime: result.value.responseTime,\n };\n }\n\n // Health check failed - emit error event\n const errorMessage = result.error?.message ?? 'Health check failed';\n this.emitDatabaseError(\n new DatabasePackageError(errorMessage, DATABASE_ERROR_CODES.CONNECTION_ERROR),\n 'healthCheck',\n { recoverable: true }\n );\n\n return {\n isHealthy: false,\n error: errorMessage,\n };\n } catch (error) {\n // Exception during health check - emit error event\n this.emitDatabaseError(error, 'healthCheck', { recoverable: true });\n\n return {\n isHealthy: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n }\n\n /**\n * Gets the table registry with all known tables and their ID columns\n *\n * @returns The complete table registry\n */\n static getTableRegistry(): typeof TABLE_REGISTRY {\n return TABLE_REGISTRY;\n }\n\n /**\n * Gets ID column for a specific table\n *\n * @param tableName - Name of the table\n * @returns ID column name or 'id' as default\n */\n static getTableIdColumn(tableName: string): string {\n return TABLE_REGISTRY[tableName]?.idColumn ?? 'id';\n }\n\n /**\n * Reinitializes the database connection with new config\n *\n * @param {DbServiceConfig} [config] - New configuration\n * @returns {Promise<DbService>} The reinitialized DbService instance\n */\n static async reinitialize(config?: DbServiceConfig): Promise<DbService> {\n const instance = DbService.getInstance();\n await instance.close();\n instance.initialized = false;\n return DbService.initialize(config);\n }\n\n /**\n * Closes the database connection and cleans up resources\n */\n async close(): Promise<void> {\n this.databaseService = null;\n this.initialized = false;\n this.config = null;\n }\n\n /**\n * Gets the current configuration\n *\n * @returns {DbServiceConfig | null} Current config or null if not initialized\n */\n getConfig(): DbServiceConfig | null {\n return this.config;\n }\n\n /**\n * Gets the current adapter type\n *\n * @returns The adapter type or null if not initialized\n */\n getAdapterType(): 'drizzle' | 'supabase' | 'sql' | null {\n return this.config?.adapter ?? null;\n }\n\n /**\n * Creates a dedicated database service instance (NOT the singleton)\n *\n * Use this when you need an isolated database connection with its own configuration\n * that doesn't affect or get affected by the shared singleton instance.\n *\n * @param config - Database service configuration\n * @returns Promise that resolves to a new dedicated DbService instance\n *\n * @example\n * ```typescript\n * // Create a dedicated instance for analytics database\n * const analyticsDb = await DbService.createInstance({\n * adapter: 'sql',\n * sql: { connectionString: process.env.ANALYTICS_DB_URL },\n * cache: { enabled: false }, // No caching for analytics\n * });\n *\n * // This instance is independent from DbService.getInstance()\n * const data = await analyticsDb.getDatabase().list('events');\n *\n * // Clean up when done\n * await analyticsDb.close();\n * ```\n */\n // eslint-disable-next-line complexity\n static async createInstance(config: DbServiceConfig): Promise<DbService> {\n // Create a new instance (not the singleton)\n const dedicatedInstance = new DbService();\n\n // Build encryption config if key provided\n const encryptionKey = config.encryption?.key;\n const encryptionConfig = encryptionKey\n ? {\n enabled: config.encryption?.enabled ?? true,\n key: encryptionKey,\n fields: config.encryption?.fields ?? DEFAULT_ENCRYPTION_FIELDS,\n algorithm: config.encryption?.algorithm ?? ('aes-256-gcm' as const),\n }\n : undefined;\n\n const mergedConfig = {\n ...DEFAULT_CONFIG,\n ...config,\n // Deep merge extensions\n softDelete: { ...DEFAULT_CONFIG.softDelete, ...config.softDelete },\n cache: { ...DEFAULT_CONFIG.cache, ...config.cache },\n audit: { ...DEFAULT_CONFIG.audit, ...config.audit },\n // Encryption only if key is available\n encryption: encryptionConfig,\n } as DbServiceConfig;\n\n dedicatedInstance.config = mergedConfig;\n\n // Build adapter configuration based on adapter type\n const dbConfig = dedicatedInstance.buildDatabaseConfig(mergedConfig);\n\n dedicatedInstance.databaseService = await createDatabaseService(dbConfig);\n\n // Initialize named adapters if configured\n if (mergedConfig.adapters) {\n for (const [name, adapterConfig] of Object.entries(mergedConfig.adapters)) {\n const namedDbConfig = dedicatedInstance.buildDatabaseConfig({\n ...mergedConfig,\n adapter: adapterConfig.adapter,\n drizzle: adapterConfig.drizzle,\n supabase: adapterConfig.supabase,\n sql: adapterConfig.sql,\n });\n\n const namedService = await createDatabaseService(namedDbConfig);\n dedicatedInstance.namedAdapters.set(name, namedService);\n }\n }\n\n dedicatedInstance.initialized = true;\n\n return dedicatedInstance;\n }\n}\n\n/** Type alias for DbService instance (use for type-only imports to avoid bundling) */\nexport type DbServiceInstance = DbService;\n","/**\n * NestJS Module for @plyaz/core\n *\n * Provides dependency injection integration for NestJS applications.\n *\n * @example\n * ```typescript\n * // app.module.ts\n * import { CoreModule } from '@plyaz/core/nestjs';\n *\n * @Module({\n * imports: [\n * CoreModule.forRoot({\n * envPath: '.env',\n * db: { adapter: 'sql' },\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example Async configuration\n * ```typescript\n * CoreModule.forRootAsync({\n * imports: [ConfigModule],\n * useFactory: (config: ConfigService) => ({\n * db: {\n * adapter: 'sql',\n * sql: { connectionString: config.get('DATABASE_URL') },\n * },\n * }),\n * inject: [ConfigService],\n * })\n * ```\n */\n\nimport type { DynamicModule, Provider } from '@nestjs/common';\nimport { Core, type CoreInitOptions } from '../CoreInitializer';\nimport { DbService } from '../../services/DbService';\nimport type { CoreNestJsCoreModuleAsyncOptions } from '@plyaz/types/core';\n\n/**\n * Injection tokens for Core services\n */\nexport const CORE_OPTIONS = Symbol('CORE_OPTIONS');\nexport const DB_SERVICE = Symbol('DB_SERVICE');\n\n/**\n * Async configuration options for CoreModule\n * Uses CoreInitOptions for type safety with Core.initialize()\n */\ntype CoreModuleAsyncOptions = CoreNestJsCoreModuleAsyncOptions;\n\n/**\n * CoreModule - NestJS DI module for @plyaz/core\n */\nexport class CoreModule {\n /**\n * Register CoreModule with static configuration\n */\n static forRoot(options: CoreInitOptions = {}): DynamicModule {\n const providers: Provider[] = [\n {\n provide: CORE_OPTIONS,\n useValue: options,\n },\n {\n provide: DbService,\n useFactory: async () => {\n await Core.initialize(options);\n return Core.db;\n },\n },\n {\n provide: DB_SERVICE,\n useFactory: async () => {\n await Core.initialize(options);\n return Core.db;\n },\n },\n ];\n\n return {\n module: CoreModule,\n global: true,\n providers,\n exports: [DbService, DB_SERVICE, CORE_OPTIONS],\n };\n }\n\n /**\n * Register CoreModule with async configuration\n */\n static forRootAsync(options: CoreModuleAsyncOptions): DynamicModule {\n const providers: Provider[] = [\n {\n provide: CORE_OPTIONS,\n useFactory: options.useFactory,\n inject: options.inject ?? [],\n },\n {\n provide: DbService,\n useFactory: async (coreOptions: CoreInitOptions) => {\n await Core.initialize(coreOptions);\n return Core.db;\n },\n inject: [CORE_OPTIONS],\n },\n {\n provide: DB_SERVICE,\n useFactory: async (coreOptions: CoreInitOptions) => {\n await Core.initialize(coreOptions);\n return Core.db;\n },\n inject: [CORE_OPTIONS],\n },\n ];\n\n return {\n module: CoreModule,\n global: true,\n imports: options.imports ?? [],\n providers,\n exports: [DbService, DB_SERVICE, CORE_OPTIONS],\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/common/id.ts","../../../src/events/CoreEventManager.ts","../../../src/services/ApiClientService.ts","../../../src/base/observability/BaseAdapter.ts","../../../src/base/observability/LoggerAdapter.ts","../../../src/base/observability/ObservabilityService.ts","../../../src/config/dependencies.ts","../../../src/init/ServiceRegistry.ts","../../../src/utils/runtime.ts","../../../src/init/CoreInitializer.ts","../../../src/services/DbService.ts","../../../src/init/nestjs/CoreModule.ts"],"names":["PackageLogger","logger","ERROR_CODES","CorePackageError","DbService","BACKEND_RUNTIMES","FRONTEND_RUNTIMES","CORE_EVENTS"],"mappings":";;;;;;;;;;;;;;;;;;AAUA,IAAM,eAAA,GAAkB,EAAA;AACxB,IAAM,qBAAA,GAAwB,CAAA;AAC9B,IAAM,eAAA,GAAkB,CAAA;AACxB,IAAM,SAAA,GAAY,EAAA;AAClB,IAAM,eAAA,GAAkB,CAAA;AACxB,IAAM,aAAA,GAAgB,EAAA;AACtB,IAAM,cAAA,GAAiB,EAAA;AAmChB,SAAS,eAAA,GAA0B;AACxC,EAAA,MAAM,YAAY,UAAA,CAAW,MAAA;AAC7B,EAAA,IAAI,WAAW,UAAA,EAAY;AACzB,IAAA,OAAO,SAAA,CAAU,YAAW,CAAE,OAAA,CAAQ,MAAM,EAAE,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,eAAe,CAAA;AAAA,EAC1E;AACA,EAAA,OAAO,IAAA,CAAK,QAAO,CAChB,QAAA,CAAS,eAAe,CAAA,CACxB,KAAA,CAAM,qBAAA,EAAuB,qBAAA,GAAwB,eAAe,CAAA;AACzE;AARgB,MAAA,CAAA,eAAA,EAAA,iBAAA,CAAA;AAsBT,SAAS,qBAAA,GAA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SAAA,EAAW,UAAA,EAAY,YAAY;AAAA,KAC/C;AAAA,EACF;AACF","file":"index.mjs","sourcesContent":["/**\n * ID Generation Utilities\n *\n * Provides consistent ID generation across the application.\n * Uses globalThis.crypto when available, with a fallback for environments without it.\n *\n * @fileoverview ID generation utility functions\n */\n\n// Constants for ID generation\nconst RANDOM_ID_RADIX = 36;\nconst RANDOM_ID_SLICE_START = 2;\nconst SHORT_ID_LENGTH = 8;\nconst HEX_RADIX = 16;\nconst HEX_SLICE_START = 2;\nconst HEX_SLICE_END = 18;\nconst SPAN_ID_LENGTH = 16;\n\n/**\n * Generate a UUID v4 string.\n * Uses crypto.randomUUID when available, otherwise falls back to a timestamp-based ID.\n *\n * @returns A UUID v4 string or fallback ID\n *\n * @example\n * ```typescript\n * const id = generateId();\n * // => 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' (crypto available)\n * // => '1701475200000-x7k9m2' (fallback)\n * ```\n */\nexport function generateId(): string {\n const cryptoApi = globalThis.crypto as { randomUUID?: () => string } | undefined;\n if (cryptoApi?.randomUUID) {\n return cryptoApi.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(RANDOM_ID_RADIX).slice(RANDOM_ID_SLICE_START)}`;\n}\n\n/**\n * Generate a short random ID (8 characters).\n * Useful for correlation IDs, short references, etc.\n *\n * @returns A short random string\n *\n * @example\n * ```typescript\n * const shortId = generateShortId();\n * // => 'x7k9m2ab'\n * ```\n */\nexport function generateShortId(): string {\n const cryptoApi = globalThis.crypto as { randomUUID?: () => string } | undefined;\n if (cryptoApi?.randomUUID) {\n return cryptoApi.randomUUID().replace(/-/g, '').slice(0, SHORT_ID_LENGTH);\n }\n return Math.random()\n .toString(RANDOM_ID_RADIX)\n .slice(RANDOM_ID_SLICE_START, RANDOM_ID_SLICE_START + SHORT_ID_LENGTH);\n}\n\n/**\n * Generate a correlation ID for tracing.\n * Format: timestamp-randomString\n *\n * @returns A correlation ID string\n *\n * @example\n * ```typescript\n * const correlationId = generateCorrelationId();\n * // => '1701475200000-x7k9m2'\n * ```\n */\nexport function generateCorrelationId(): string {\n return `${Date.now()}-${generateShortId()}`;\n}\n\n/**\n * Generate a trace ID for distributed tracing (32 hex characters / 128 bits).\n *\n * @returns A 32-character hex string\n *\n * @example\n * ```typescript\n * const traceId = generateTraceId();\n * // => 'a1b2c3d4e5f67890abcdef1234567890'\n * ```\n */\nexport function generateTraceId(): string {\n const cryptoApi = globalThis.crypto as { randomUUID?: () => string } | undefined;\n if (cryptoApi?.randomUUID) {\n // Use two UUIDs without dashes to get 64 hex chars, take first 32\n return cryptoApi.randomUUID().replace(/-/g, '');\n }\n // Fallback: concatenate two random hex strings\n return (\n Math.random().toString(HEX_RADIX).substring(HEX_SLICE_START, HEX_SLICE_END) +\n Math.random().toString(HEX_RADIX).substring(HEX_SLICE_START, HEX_SLICE_END)\n );\n}\n\n/**\n * Generate a span ID for distributed tracing (16 hex characters / 64 bits).\n *\n * @returns A 16-character hex string\n *\n * @example\n * ```typescript\n * const spanId = generateSpanId();\n * // => 'a1b2c3d4e5f67890'\n * ```\n */\nexport function generateSpanId(): string {\n const cryptoApi = globalThis.crypto as { randomUUID?: () => string } | undefined;\n if (cryptoApi?.randomUUID) {\n // Use UUID without dashes, take first 16 chars\n return cryptoApi.randomUUID().replace(/-/g, '').substring(0, SPAN_ID_LENGTH);\n }\n // Fallback: random hex string\n return Math.random().toString(HEX_RADIX).substring(HEX_SLICE_START, HEX_SLICE_END);\n}\n\n/**\n * ID generation utilities object for convenient access.\n */\nexport const IdUtils = {\n generate: generateId,\n generateShort: generateShortId,\n generateCorrelation: generateCorrelationId,\n generateTraceId,\n generateSpanId,\n} as const;\n","/**\n * Core Event Manager\n *\n * Type-safe event system for the Plyaz ecosystem.\n * Services emit events → Store, API cache, and UI subscribe independently.\n *\n * @example\n * ```typescript\n * import { CoreEventManager, CORE_EVENTS } from '@plyaz/core/events';\n *\n * // Type-safe emission (using CORE_EVENTS constants)\n * CoreEventManager.emit(CORE_EVENTS.API.REQUEST_ERROR, {\n * method: 'GET',\n * url: '/api/users',\n * requestId: '123',\n * error: new Error('Failed'),\n * duration: 500,\n * });\n *\n * // Type-safe subscription\n * CoreEventManager.on(CORE_EVENTS.AUTH.LOGIN, (event) => {\n * console.log(event.data.userId); // Typed!\n * });\n *\n * // Custom events (with generic type)\n * CoreEventManager.emit<MyPayload>('custom:event', { custom: 'data' });\n * ```\n */\n\nimport { EventEmitter } from 'events';\nimport type { CoreEventPayloadMap, CoreEventScopeType, CoreEvent } from '@plyaz/types/core';\nimport { generateCorrelationId } from '../utils/common';\n\n/**\n * Core Event Manager\n *\n * Features:\n * - Type-safe event emission and subscription via CORE_EVENTS constants\n * - Scope-based event filtering\n * - Wildcard subscriptions\n * - Auto cleanup on dispose\n * - Correlation IDs for tracing\n *\n * @example\n * ```typescript\n * import { CoreEventManager, CORE_EVENTS } from '@plyaz/core/events';\n *\n * // Type-safe with CORE_EVENTS\n * CoreEventManager.emit(CORE_EVENTS.AUTH.LOGIN, {\n * userId: '123',\n * method: 'email',\n * });\n *\n * CoreEventManager.on(CORE_EVENTS.AUTH.LOGIN, (event) => {\n * console.log(event.data.userId); // Typed as string!\n * });\n *\n * // Custom events with explicit type\n * interface MyPayload { custom: string }\n * CoreEventManager.emit<MyPayload>('custom:event', { custom: 'data' });\n * ```\n */\n\n// Constants\nconst MAX_EVENT_LISTENERS = 100;\n\nclass CoreEventManagerClass {\n private emitter = new EventEmitter();\n private subscriptions = new Map<string, Set<(event: CoreEvent<unknown, string>) => void>>();\n\n constructor() {\n // Increase max listeners for large apps\n this.emitter.setMaxListeners(MAX_EVENT_LISTENERS);\n }\n\n /**\n * Emit an event\n *\n * @param eventType - Event type from CORE_EVENTS or custom string\n * @param data - Event payload (type-safe when using CORE_EVENTS)\n *\n * @example\n * ```typescript\n * // Type-safe with CORE_EVENTS\n * CoreEventManager.emit(CORE_EVENTS.AUTH.LOGIN, { userId: '123', method: 'email' });\n *\n * // Custom event\n * CoreEventManager.emit<MyPayload>('custom:event', { custom: 'data' });\n * ```\n */\n emit<T extends keyof CoreEventPayloadMap>(eventType: T, data: CoreEventPayloadMap[T]): boolean;\n emit<TData = unknown>(eventType: string, data?: TData): boolean;\n emit<TData = unknown>(eventType: string, data?: TData): boolean {\n const [scope] = eventType.split(':');\n const event: CoreEvent<TData, string> = {\n type: eventType,\n scope: scope ?? 'system',\n timestamp: Date.now(),\n correlationId: this.getCorrelationId(),\n data: data as TData,\n };\n\n // Emit to specific listeners\n this.emitter.emit(eventType, event);\n\n // Emit to wildcard listeners\n this.emitter.emit('*', event);\n\n return true;\n }\n\n /**\n * Subscribe to an event\n *\n * @param eventType - Event type from CORE_EVENTS or custom string\n * @param handler - Event handler (type-safe when using CORE_EVENTS)\n * @returns Unsubscribe function\n *\n * @example\n * ```typescript\n * // Type-safe with CORE_EVENTS\n * const unsub = CoreEventManager.on(CORE_EVENTS.AUTH.LOGIN, (event) => {\n * console.log(event.data.userId); // Typed!\n * });\n *\n * // Custom event\n * CoreEventManager.on<MyPayload>('custom:event', (event) => {\n * console.log(event.data.custom);\n * });\n * ```\n */\n on<T extends keyof CoreEventPayloadMap>(\n eventType: T,\n handler: (event: CoreEvent<CoreEventPayloadMap[T], CoreEventScopeType>) => void\n ): () => void;\n on<TData = unknown, TScope extends string = string>(\n eventType: string,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): () => void;\n on<TData = unknown, TScope extends string = string>(\n eventType: string,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): () => void {\n this.emitter.on(eventType, handler as (event: CoreEvent<unknown, string>) => void);\n\n // Track for cleanup\n if (!this.subscriptions.has(eventType)) {\n this.subscriptions.set(eventType, new Set());\n }\n this.subscriptions.get(eventType)!.add(handler as (event: CoreEvent<unknown, string>) => void);\n\n // Return unsubscribe function\n return () => {\n this.emitter.off(eventType, handler as (event: CoreEvent<unknown, string>) => void);\n this.subscriptions\n .get(eventType)\n ?.delete(handler as (event: CoreEvent<unknown, string>) => void);\n };\n }\n\n /**\n * Subscribe once to an event\n *\n * @param eventType - Event type from CORE_EVENTS or custom string\n * @param handler - Event handler\n * @returns Unsubscribe function\n */\n once<T extends keyof CoreEventPayloadMap>(\n eventType: T,\n handler: (event: CoreEvent<CoreEventPayloadMap[T], CoreEventScopeType>) => void\n ): () => void;\n once<TData = unknown, TScope extends string = string>(\n eventType: string,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): () => void;\n once<TData = unknown, TScope extends string = string>(\n eventType: string,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): () => void {\n const wrappedHandler = (event: CoreEvent<TData, TScope>): void => {\n handler(event);\n this.emitter.off(eventType, wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n this.subscriptions\n .get(eventType)\n ?.delete(wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n };\n\n this.emitter.on(eventType, wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n\n // Track for cleanup\n if (!this.subscriptions.has(eventType)) {\n this.subscriptions.set(eventType, new Set());\n }\n this.subscriptions\n .get(eventType)!\n .add(wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n\n // Return unsubscribe function\n return () => {\n this.emitter.off(eventType, wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n this.subscriptions\n .get(eventType)\n ?.delete(wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n };\n }\n\n /**\n * Subscribe to all events in a scope\n *\n * @param scope - Event scope to listen to (e.g., CoreEventScope.AUTH)\n * @param handler - Event handler\n * @returns Unsubscribe function\n *\n * @example\n * ```typescript\n * CoreEventManager.onScope(CoreEventScope.AUTH, (event) => {\n * // Handles auth:login, auth:logout, auth:tokenRefresh, etc.\n * console.log(`Auth event: ${event.type}`, event.data);\n * });\n * ```\n */\n onScope<TScope extends string = string, TData = unknown>(\n scope: TScope,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): () => void {\n const wrappedHandler = (event: CoreEvent<TData, TScope>): void => {\n if (event.scope === scope) {\n handler(event);\n }\n };\n return this.on('*', wrappedHandler as (event: CoreEvent<unknown, string>) => void);\n }\n\n /**\n * Remove a specific handler from an event\n *\n * @param eventType - Event type\n * @param handler - Handler to remove\n */\n off<TData = unknown, TScope extends string = string>(\n eventType: string,\n handler: (event: CoreEvent<TData, TScope>) => void\n ): void {\n this.emitter.off(eventType, handler as (event: CoreEvent<unknown, string>) => void);\n this.subscriptions\n .get(eventType)\n ?.delete(handler as (event: CoreEvent<unknown, string>) => void);\n }\n\n /**\n * Dispose all subscriptions\n */\n dispose(): void {\n this.subscriptions.forEach((handlers, eventType) => {\n handlers.forEach(handler => this.emitter.off(eventType, handler));\n });\n this.subscriptions.clear();\n this.emitter.removeAllListeners();\n }\n\n /**\n * Generate correlation ID for event tracing\n */\n private getCorrelationId(): string {\n return generateCorrelationId();\n }\n}\n\n// Singleton export\nexport const CoreEventManager = new CoreEventManagerClass();\n","/**\n * API Client Singleton Service (@plyaz/core)\n * Manages the API client with environment-specific configurations and intelligent defaults\n *\n * The app reads process.env and constructs ApiClientOptions, then passes to this service.\n * Service never touches process.env directly - all env reading happens in the app layer.\n *\n * @module services/ApiClientService\n */\n\n// Imports from @plyaz/api (dependency)\nimport { createApiClient, mergeConfigs, setDefaultApiClient } from '@plyaz/api/frontend';\nimport type { ApiClientWithEvents, ApiClientOptions, ApiConfig } from '@plyaz/types/api';\nimport { type ClientEventManager, type EndpointsList, ApiPackageError } from '@plyaz/api/frontend';\nimport { PRODUCTION_CONFIG, STAGING_CONFIG, DEVELOPMENT_CONFIG } from '@plyaz/config';\nimport {\n API_ERROR_CODES,\n PACKAGE_STATUS_CODES,\n OPERATIONS,\n ERROR_CODES,\n ERROR_CATEGORY,\n HTTP_STATUS,\n CORE_EVENTS,\n} from '@plyaz/types';\nimport type { CoreApiRequestErrorPayload, CoreApiEnvironmentConfig } from '@plyaz/types/core';\nimport { CoreEventManager } from '../events/CoreEventManager';\nimport { generateRequestId } from '@plyaz/errors';\nimport type { ResponseError } from 'fetchff';\n// Note: Root store is injected by Core.initialize(), not created here\n\n/**\n * Minimum retry attempts recommended for production environments\n *\n * Production services should have sufficient retries to handle transient failures\n * while maintaining acceptable response times for end users.\n *\n * @constant\n * @default 3\n */\nconst MIN_RETRY_ATTEMPTS_PRODUCTION = 3;\n\n/**\n * Get configuration based on environment\n *\n * Returns environment-specific defaults that will be merged with user configuration.\n * Each environment has optimized settings for its use case:\n *\n * - **Production**: Aggressive retries (5), encryption required, telemetry enabled\n * - **Staging**: Mirrors production for accurate pre-deployment testing\n * - **Development/Test**: Conservative retries (1), encryption optional, full debug mode\n *\n * These defaults come from `@plyaz/config` and can be overridden via the `apiConfig` parameter.\n *\n * @param env - Environment name determining which defaults to apply\n * @returns Environment-specific configuration from @plyaz/config\n *\n * @example\n * ```typescript\n * const prodDefaults = getConfigForEnvironment('production');\n * // Returns PRODUCTION_CONFIG with aggressive retries, encryption, etc.\n *\n * const devDefaults = getConfigForEnvironment('development');\n * // Returns DEVELOPMENT_CONFIG with conservative retries, no encryption\n * ```\n *\n * @see {@link CoreApiEnvironmentConfig.env} - Environment types\n * @internal\n */\nfunction getConfigForEnvironment(env: CoreApiEnvironmentConfig['env']): Partial<ApiConfig> {\n switch (env) {\n case 'production':\n return PRODUCTION_CONFIG as Partial<ApiConfig>;\n case 'staging':\n return STAGING_CONFIG as Partial<ApiConfig>;\n case 'development':\n case 'test':\n default:\n return DEVELOPMENT_CONFIG as Partial<ApiConfig>;\n }\n}\n\n/**\n * Validate base URL requirement\n *\n * Ensures that a baseURL is provided in the configuration. The baseURL is mandatory\n * for all API clients as it defines where requests should be sent.\n *\n * @param mergedConfig - Merged configuration after applying all defaults\n * @param errors - Error array to append validation errors to\n *\n * @example\n * ```typescript\n * const errors: string[] = [];\n * validateBaseURL(mergedConfig, errors);\n *\n * if (errors.length > 0) {\n * // baseURL is missing\n * }\n * ```\n *\n * @internal\n */\nfunction validateBaseURL(mergedConfig: ApiClientOptions, errors: string[]): void {\n if (!mergedConfig.baseURL) {\n errors.push('baseURL is required in API configuration (apiConfig parameter)');\n }\n}\n\n/**\n * Validate production encryption configuration\n *\n * Production environments MUST have encryption properly configured to protect sensitive data.\n * This function validates that:\n * - If encryption is enabled, an encryption key MUST be provided\n * - If encryption is disabled, a security warning is issued\n *\n * **Why encryption is required in production**:\n * - Compliance: GDPR, CCPA, PIPL, HIPAA regulations require data protection\n * - Security: Protects PII, payment info, health data, crypto wallet addresses\n * - 50+ sensitive field patterns: email, SSN, card numbers, API keys, etc.\n *\n * @param mergedConfig - Merged configuration after applying all defaults\n * @param errors - Error array to append critical validation errors to\n * @param warnings - Warning array to append non-critical warnings to\n *\n * @example\n * ```typescript\n * const errors: string[] = [];\n * const warnings: string[] = [];\n *\n * validateProductionEncryption(mergedConfig, errors, warnings);\n *\n * // If encryption enabled but no key:\n * // errors = ['encryption.key is REQUIRED when encryption is enabled in production...']\n *\n * // If encryption disabled:\n * // warnings = ['[SECURITY WARNING] Encryption is disabled in production...']\n * ```\n *\n * @internal\n */\nfunction validateProductionEncryption(\n mergedConfig: ApiClientOptions,\n errors: string[],\n warnings: string[]\n): void {\n if (mergedConfig.encryption?.enabled) {\n if (!mergedConfig.encryption?.key) {\n errors.push(\n 'encryption.key is REQUIRED when encryption is enabled in production. ' +\n 'Pass it in apiConfig: { encryption: { key: { id: \"prod-key-v1\", key: process.env.ENCRYPTION_KEY!, algorithm: \"AES-GCM\", format: \"raw\" } } }'\n );\n }\n } else {\n warnings.push(\n '[SECURITY WARNING] Encryption is disabled in production. ' +\n 'This is not recommended for handling sensitive data (PII, payment info, etc.).'\n );\n }\n}\n\n/**\n * Validate production performance settings\n *\n * Validates production configuration for optimal performance, reliability, and monitoring:\n * - **Network-aware features**: Adapts to varying network conditions for better UX\n * - **Telemetry**: Required for production monitoring and alerting\n * - **Retry attempts**: Minimum 3 retries recommended for reliability\n *\n * These are warnings (not errors) as they don't prevent the client from working,\n * but indicate suboptimal production configuration.\n *\n * @param mergedConfig - Merged configuration after applying all defaults\n * @param warnings - Warning array to append performance warnings to\n *\n * @example\n * ```typescript\n * const warnings: string[] = [];\n * validateProductionPerformance(mergedConfig, warnings);\n *\n * // Possible warnings:\n * // - '[PERFORMANCE WARNING] networkAware is disabled in production...'\n * // - '[MONITORING WARNING] telemetry is disabled in production...'\n * // - '[RELIABILITY WARNING] Only 1 retry attempts configured...'\n * ```\n *\n * @internal\n */\nfunction validateProductionPerformance(mergedConfig: ApiClientOptions, warnings: string[]): void {\n if (!mergedConfig.networkAware?.enabled) {\n warnings.push(\n '[PERFORMANCE WARNING] networkAware is disabled in production. ' +\n 'Enable it for better user experience on varying network conditions.'\n );\n }\n\n if (!mergedConfig.tracking?.telemetry) {\n warnings.push(\n '[MONITORING WARNING] telemetry is disabled in production. ' +\n 'Enable it for production monitoring and alerting.'\n );\n }\n\n if (\n mergedConfig.retry &&\n mergedConfig.retry.attempts !== undefined &&\n mergedConfig.retry.attempts < MIN_RETRY_ATTEMPTS_PRODUCTION\n ) {\n warnings.push(\n `[RELIABILITY WARNING] Only ${mergedConfig.retry.attempts} retry attempts configured. ` +\n 'Consider increasing to 3-5 for better reliability in production.'\n );\n }\n}\n\n/**\n * Validate staging encryption configuration\n *\n * Staging environments should mirror production configuration for accurate pre-deployment testing.\n * This function validates:\n * - If encryption is enabled, an encryption key MUST be provided (same as production)\n * - If encryption is disabled, issues a warning (staging should match production)\n * - Telemetry should be enabled to test monitoring before production\n *\n * **Why staging should mirror production**:\n * - Catches configuration issues before they reach production\n * - Tests encryption/decryption with real-world-like data\n * - Validates monitoring and alerting pipelines\n *\n * @param mergedConfig - Merged configuration after applying all defaults\n * @param errors - Error array to append critical validation errors to\n * @param warnings - Warning array to append configuration warnings to\n *\n * @example\n * ```typescript\n * const errors: string[] = [];\n * const warnings: string[] = [];\n *\n * validateStagingEncryption(mergedConfig, errors, warnings);\n *\n * // If encryption enabled but no key:\n * // errors = ['encryption.key is REQUIRED in staging (aligned with production)...']\n *\n * // If encryption or telemetry disabled:\n * // warnings = ['[SECURITY WARNING] Encryption is disabled in staging...']\n * ```\n *\n * @internal\n */\nfunction validateStagingEncryption(\n mergedConfig: ApiClientOptions,\n errors: string[],\n warnings: string[]\n): void {\n if (mergedConfig.encryption?.enabled) {\n if (!mergedConfig.encryption?.key) {\n errors.push(\n 'encryption.key is REQUIRED in staging (aligned with production). ' +\n 'Pass it in apiConfig: { encryption: { key: { id: \"staging-key-v1\", key: process.env.ENCRYPTION_KEY!, algorithm: \"AES-GCM\", format: \"raw\" } } }'\n );\n }\n } else {\n warnings.push(\n '[SECURITY WARNING] Encryption is disabled in staging. ' +\n 'Staging should mirror production for accurate testing.'\n );\n }\n\n if (!mergedConfig.tracking?.telemetry) {\n warnings.push(\n '[MONITORING WARNING] telemetry is disabled in staging. ' +\n 'Enable it to test monitoring before production deployment.'\n );\n }\n}\n\n/**\n * Validate development encryption configuration\n *\n * Development environments have more relaxed requirements to facilitate rapid development:\n * - Encryption is OPTIONAL (enabled flag can be true, but key is not required)\n * - When encryption is enabled without a key, issues an informational warning\n *\n * **Why encryption is optional in development**:\n * - Faster iteration without needing to manage encryption keys\n * - Easier debugging of request/response payloads\n * - Test data typically doesn't contain real sensitive information\n *\n * @param mergedConfig - Merged configuration after applying all defaults\n * @param warnings - Warning array to append informational messages to\n *\n * @example\n * ```typescript\n * const warnings: string[] = [];\n * validateDevelopmentEncryption(mergedConfig, warnings);\n *\n * // If encryption enabled without key:\n * // warnings = ['[DEV INFO] Encryption is enabled but no key provided...']\n * ```\n *\n * @internal\n */\nfunction validateDevelopmentEncryption(mergedConfig: ApiClientOptions, warnings: string[]): void {\n if (mergedConfig.encryption?.enabled && !mergedConfig.encryption?.key) {\n warnings.push(\n '[DEV INFO] Encryption is enabled but no key provided in apiConfig. ' +\n 'Encryption will be skipped in development (this is normal).'\n );\n }\n}\n\n/**\n * Map environment metadata to API configuration structure\n *\n * Converts environment-level metadata from `CoreApiEnvironmentConfig` into `ApiConfig` format\n * that can be merged with other configurations. Currently maps:\n *\n * - **apiKey**: Converted to static header `X-API-Key`\n * - **rateLimit**: Reserved for future use (not currently mapped)\n *\n * **Note**: This mapping is applied AFTER environment defaults but BEFORE user-provided\n * apiConfig, giving it medium priority in the configuration merge hierarchy.\n *\n * @param envConfig - Environment configuration containing metadata\n * @param envDefaults - Environment-specific defaults from @plyaz/config\n * @returns Partial API configuration with mapped environment metadata\n *\n * @example\n * ```typescript\n * const envConfig = { env: 'production', apiKey: 'my-api-key' };\n * const envDefaults = PRODUCTION_CONFIG;\n *\n * const mapped = mapEnvironmentMetadata(envConfig, envDefaults);\n * // Returns: { headers: { static: { 'X-API-Key': 'my-api-key' } } }\n * ```\n *\n * @see {@link CoreApiEnvironmentConfig} - Environment configuration interface\n * @internal\n */\nfunction mapEnvironmentMetadata(\n envConfig: CoreApiEnvironmentConfig,\n envDefaults: Partial<ApiConfig>\n): Partial<ApiConfig> {\n const mapped: Partial<ApiConfig> = {};\n\n // Add API key to headers if provided\n if (envConfig.apiKey) {\n // Extract existing static headers if headers is an object with static property\n const existingStatic =\n envDefaults.headers &&\n typeof envDefaults.headers === 'object' &&\n 'static' in envDefaults.headers &&\n typeof envDefaults.headers.static === 'object'\n ? envDefaults.headers.static\n : {};\n\n mapped.headers = {\n static: { ...(existingStatic ?? {}), 'X-API-Key': envConfig.apiKey },\n };\n }\n\n // Note: rateLimit from envConfig is not mapped to ApiConfig\n // Rate limiting is typically handled at the server/API gateway level\n // If needed in the future, it should be added to ApiConfig interface first\n\n return mapped;\n}\n\n/**\n * Apply default client setting to @plyaz/api services and hooks\n *\n * Conditionally calls `setDefaultApiClient()` based on the `setAsDefault` flag in environment config.\n * When enabled, all services and hooks from @plyaz/api will automatically use this client instance\n * without needing to pass it explicitly via `ServiceOptions.apiClient`.\n *\n * **Default behavior**: If `setAsDefault` is not specified, it defaults to `true`.\n *\n * **Use cases**:\n * - `true` (default): Single API client for the entire application (recommended for most apps)\n * - `false`: Multiple API clients (main API, analytics API, etc.) or testing scenarios\n *\n * @param client - The API client instance to set as default\n * @param envConfig - Environment configuration containing the setAsDefault flag\n *\n * @example\n * ```typescript\n * const client = await createApiClient(config);\n * const envConfig = { env: 'production', setAsDefault: true };\n *\n * applyDefaultClientSetting(client, envConfig);\n * // Now all @plyaz/api services use this client automatically\n *\n * const campaigns = await fetchCampaigns({ page: 1 });\n * // No need to pass apiClient - uses the default\n * ```\n *\n * @example\n * ```typescript\n * // Multiple clients scenario\n * const mainClient = await createApiClient(mainConfig);\n * const analyticsClient = await createApiClient(analyticsConfig);\n *\n * applyDefaultClientSetting(mainClient, { env: 'production', setAsDefault: true });\n * applyDefaultClientSetting(analyticsClient, { env: 'production', setAsDefault: false });\n *\n * // Main API uses default\n * const campaigns = await fetchCampaigns({ page: 1 });\n *\n * // Analytics API must be passed explicitly\n * const analytics = await fetchAnalytics(\n * { date: '2025-10-16' },\n * { apiClient: analyticsClient }\n * );\n * ```\n *\n * @see {@link CoreApiEnvironmentConfig.setAsDefault} - Flag documentation\n * @see {@link ServiceOptions.apiClient} - How to override the default client\n * @internal\n */\nfunction applyDefaultClientSetting(\n client: ApiClientWithEvents<ClientEventManager, EndpointsList>,\n envConfig: CoreApiEnvironmentConfig\n): void {\n const shouldSetAsDefault = envConfig.setAsDefault !== false;\n if (shouldSetAsDefault) {\n setDefaultApiClient(client);\n }\n}\n\n/**\n * Validate environment configuration for production readiness.\n * Ensures critical settings are properly configured based on environment.\n *\n * @param envConfig - Environment configuration\n * @param mergedConfig - Merged configuration after applying all defaults\n * @throws {ApiPackageError} If validation fails\n */\nfunction validateEnvironmentConfig(\n envConfig: CoreApiEnvironmentConfig,\n mergedConfig: ApiClientOptions\n): void {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n // Validate required base URL\n validateBaseURL(mergedConfig, errors);\n\n // Environment-specific validation\n if (envConfig.env === 'production') {\n validateProductionEncryption(mergedConfig, errors, warnings);\n validateProductionPerformance(mergedConfig, warnings);\n } else if (envConfig.env === 'staging') {\n validateStagingEncryption(mergedConfig, errors, warnings);\n } else if (envConfig.env === 'development') {\n validateDevelopmentEncryption(mergedConfig, warnings);\n }\n\n // Log warnings (intentional console usage for config validation)\n if (warnings.length > 0) {\n globalThis.console.warn('[ApiClientService] Configuration warnings:', warnings);\n }\n\n // Throw if there are errors\n if (errors.length > 0) {\n throw new ApiPackageError(\n 'service.validation.failed',\n PACKAGE_STATUS_CODES.INVALID_CONFIGURATION,\n API_ERROR_CODES.CONFIG_VALIDATION_FAILED,\n {\n context: {\n operation: OPERATIONS.VALIDATION,\n // Ensure error details conform to ErrorDetail shape (include errorCode)\n errors: errors.map(err => ({\n field: 'config',\n message: err,\n errorCode: String(API_ERROR_CODES.CONFIG_VALIDATION_FAILED),\n })),\n i18n: {\n errors: errors.join('; '),\n warnings: warnings.join('; '),\n },\n },\n }\n );\n }\n}\n\n/**\n * API Client Singleton Service\n * Manages API client instance lifecycle with environment-specific configurations\n *\n * @example\n * ```typescript\n * // In your app initialization (Next.js, React, etc.)\n * import { ApiClientService } from '@plyaz/core';\n *\n * // Environment metadata\n * const envConfig = {\n * env: process.env.NODE_ENV as 'production',\n * apiKey: process.env.API_KEY,\n * };\n *\n * // API configuration with event handlers\n * await ApiClientService.init(envConfig, {\n * baseURL: process.env.API_URL!,\n * encryption: {\n * key: {\n * id: 'prod-key-v1',\n * key: process.env.ENCRYPTION_KEY!,\n * algorithm: 'AES-GCM'\n * }\n * },\n * clientEvents: {\n * onRequestStart: (event) => apiStore.trackRequest(event),\n * },\n * });\n *\n * // Later, anywhere in your app\n * const client = ApiClientService.getClient();\n * ```\n */\nexport class ApiClientService {\n private static instance: ApiClientWithEvents<ClientEventManager, EndpointsList> | null = null;\n private static isInitializing = false;\n private static initPromise: Promise<void> | null = null;\n\n /**\n * Initialize the API client with environment config and API options\n *\n * @param envConfig - Environment metadata (env, apiKey)\n * @param apiConfig - API configuration (baseURL, encryption, timeout, event handlers, etc.)\n * @returns Promise that resolves to the initialized client\n */\n static async init(\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n ): Promise<ApiClientWithEvents<ClientEventManager, EndpointsList>> {\n // If already initialized, return existing instance\n if (this.instance) {\n globalThis.console.warn(\n '[ApiClientService] Client already initialized. Returning existing instance.'\n );\n return this.instance;\n }\n\n // If currently initializing, wait for that to complete\n if (this.isInitializing && this.initPromise) {\n await this.initPromise;\n return this.instance!;\n }\n\n // Start initialization\n this.isInitializing = true;\n this.initPromise = this.createClient(envConfig, apiConfig);\n\n try {\n await this.initPromise;\n return this.instance!;\n } finally {\n this.isInitializing = false;\n this.initPromise = null;\n }\n }\n\n /**\n * Internal initialization logic\n * Merges environment-specific defaults with API configuration\n *\n * Merge Priority (lowest to highest):\n * 1. Environment defaults (PRODUCTION_CONFIG / STAGING_CONFIG / DEVELOPMENT_CONFIG)\n * 2. Environment metadata (envConfig - apiKey)\n * 3. API configuration (apiConfig - baseURL, encryption, timeout, etc.)\n */\n // eslint-disable-next-line max-lines-per-function, complexity\n private static async createClient(\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n ): Promise<void> {\n try {\n // Step 1: Get environment-specific defaults based on env\n const envDefaults = getConfigForEnvironment(envConfig.env);\n\n // Step 2: Build config from envConfig (environment metadata only)\n const envMetadataMapped = mapEnvironmentMetadata(envConfig, envDefaults);\n\n // Step 3: Create onError handler to emit errors to Core\n const coreErrorHandler = async (\n error: ResponseError<unknown, unknown, unknown, unknown>\n // eslint-disable-next-line complexity\n ): Promise<void> => {\n const requestId = generateRequestId();\n const method = error.config?.method ?? 'UNKNOWN';\n const url = error.config?.url ?? 'unknown';\n\n // CRITICAL: Emit error event to Core\n // Core will handle updating the appropriate store based on runtime context:\n // - Backend: In-memory store (ServerErrorMiddleware)\n // - Frontend: Zustand store (useRootStore)\n try {\n // API returns ErrorResponse (array of error details)\n const errorDetails = Array.isArray(error.response?.data) ? error.response.data : [];\n\n // If no error details from API, create a fallback error\n if (errorDetails.length === 0) {\n const serializedError = {\n id: requestId,\n code: ERROR_CODES.CORE_API_CLIENT_REQUEST_FAILED,\n message: error.message ?? 'API request failed',\n status: error.status,\n category: ERROR_CATEGORY.Network,\n timestamp: new Date().toISOString(),\n isRetryable: error.status ? error.status >= HTTP_STATUS.INTERNAL_SERVER_ERROR : false,\n source: 'api-client',\n dismissed: false,\n context: {\n method,\n url,\n requestId,\n },\n };\n\n // Emit single error to Core\n CoreEventManager.emit(CORE_EVENTS.SYSTEM.ERROR, { errors: [serializedError] });\n } else {\n // Convert ErrorResponse (API error details array) to SerializedError[]\n const serializedErrors = errorDetails.map(\n (detail: Record<string, unknown>, index: number) => ({\n id: `${requestId}-${index}`,\n code: (detail.errorCode as string) ?? ERROR_CODES.CORE_API_CLIENT_REQUEST_FAILED,\n message: (detail.message as string) ?? error.message ?? 'API request failed',\n status: error.status,\n category: ERROR_CATEGORY.Network,\n timestamp: new Date().toISOString(),\n isRetryable: error.status\n ? error.status >= HTTP_STATUS.INTERNAL_SERVER_ERROR\n : false,\n source: 'api-client',\n dismissed: false,\n context: {\n method,\n url,\n requestId,\n field: detail.field as string | undefined,\n valueGiven: detail.valueGiven,\n allowedValues: detail.allowedValues,\n constraints: detail.constraints,\n },\n })\n );\n\n // Emit array of errors to Core\n CoreEventManager.emit(CORE_EVENTS.SYSTEM.ERROR, { errors: serializedErrors });\n }\n } catch (e) {\n // If event emission fails, log but don't break the error flow\n console.error('[ApiClientService] Failed to emit error event:', e);\n }\n\n // Also emit API-specific error event for logging, monitoring, etc.\n ApiClientService.emitApiError(error, {\n method,\n url,\n requestId,\n status: error.status,\n duration: 0,\n });\n };\n\n // Step 4: Merge with priority: envDefaults → envMetadata → apiConfig → coreErrorHandler\n const userOnError = apiConfig?.onError;\n const combinedOnError = userOnError\n ? Array.isArray(userOnError)\n ? [...userOnError, coreErrorHandler]\n : [userOnError, coreErrorHandler]\n : coreErrorHandler;\n\n const mergedOptions = mergeConfigs(\n envDefaults, // Environment defaults (lowest priority)\n envMetadataMapped, // Environment metadata (medium priority)\n { ...(apiConfig ?? {}), onError: combinedOnError } // API configuration + core error handler\n ) as ApiClientOptions;\n\n // Step 5: Validate the merged configuration\n validateEnvironmentConfig(envConfig, mergedOptions);\n\n // Step 6: Create the client instance with merged configuration\n this.instance = await createApiClient(mergedOptions);\n\n // Step 6: Set as default client for @plyaz/api services and hooks (if enabled)\n applyDefaultClientSetting(this.instance, envConfig);\n } catch (error) {\n throw new ApiPackageError(\n 'service.initialization.failed',\n PACKAGE_STATUS_CODES.INITIALIZATION_FAILED,\n API_ERROR_CODES.CLIENT_INITIALIZATION_FAILED,\n {\n cause: error instanceof Error ? error : undefined,\n context: {\n operation: OPERATIONS.INITIALIZATION,\n originalError: error instanceof Error ? error.message : String(error),\n i18n: {\n error: error instanceof Error ? error.message : String(error),\n },\n },\n }\n );\n }\n }\n\n /**\n * Get the initialized client instance\n *\n * @throws {ApiPackageError} If client not initialized\n */\n static getClient(): ApiClientWithEvents<ClientEventManager, EndpointsList> {\n if (!this.instance) {\n throw new ApiPackageError(\n 'service.not_initialized',\n PACKAGE_STATUS_CODES.INITIALIZATION_FAILED,\n API_ERROR_CODES.CLIENT_INITIALIZATION_FAILED,\n {\n context: {\n operation: OPERATIONS.INITIALIZATION,\n i18n: {\n hint: 'Call ApiClientService.init(envConfig, apiConfig) before accessing the client',\n },\n },\n }\n );\n }\n return this.instance;\n }\n\n /**\n * Check if client is initialized\n */\n static isInitialized(): boolean {\n return this.instance !== null;\n }\n\n /**\n * Reinitialize with new config and options\n */\n static async reinitialize(\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n ): Promise<ApiClientWithEvents<ClientEventManager, EndpointsList>> {\n this.dispose();\n return this.init(envConfig, apiConfig);\n }\n\n /**\n * Dispose of the client instance\n */\n static dispose(): void {\n if (this.instance && 'dispose' in this.instance) {\n this.instance.dispose?.();\n }\n this.instance = null;\n this.isInitializing = false;\n this.initPromise = null;\n }\n\n /**\n * Emits an API error event via CoreEventManager.\n * Called when API operations fail to integrate with global error handling.\n *\n * **CRITICAL**: This event emission triggers automatic error state updates.\n * The global error store MUST subscribe to CORE_EVENTS.API.REQUEST_ERROR to:\n * 1. Capture all API errors automatically\n * 2. Update global error state for UI display\n * 3. Ensure individual domain stores remain error-free (only domain data)\n *\n * This is the unified error hook that:\n * - On frontend: Emits event that global error store subscribes to\n * - On backend: Emits event for logging/monitoring (can be configured to rethrow)\n *\n * @param error - The error that occurred\n * @param options - Additional context for the error\n * @param options.method - HTTP method (GET, POST, etc.)\n * @param options.url - Request URL\n * @param options.requestId - Unique request identifier\n * @param options.status - HTTP status code (if available)\n * @param options.duration - Request duration in ms\n * @param options.rethrow - Whether to rethrow the error after emitting (default: false)\n *\n * @example\n * ```typescript\n * // Global error store setup (in @plyaz/store)\n * CoreEventManager.on(CORE_EVENTS.API.REQUEST_ERROR, (payload) => {\n * errorStore.setError({\n * message: payload.error.message,\n * status: payload.status,\n * url: payload.url,\n * requestId: payload.requestId,\n * });\n * });\n *\n * // Frontend usage - emit to store\n * ApiClientService.emitApiError(error, {\n * method: 'GET',\n * url: '/api/users',\n * requestId: '123',\n * duration: 500,\n * });\n *\n * // Backend usage - emit and rethrow\n * ApiClientService.emitApiError(error, {\n * method: 'POST',\n * url: '/api/orders',\n * requestId: '456',\n * duration: 1200,\n * rethrow: true,\n * });\n * ```\n */\n static emitApiError(\n error: unknown,\n options: {\n method: string;\n url: string;\n requestId: string;\n status?: number;\n duration: number;\n rethrow?: boolean;\n }\n ): void {\n const payload: CoreApiRequestErrorPayload = {\n method: options.method,\n url: options.url,\n requestId: options.requestId,\n status: options.status,\n error,\n duration: options.duration,\n };\n\n CoreEventManager.emit(CORE_EVENTS.API.REQUEST_ERROR, payload);\n\n // Optionally rethrow for backend error propagation\n if (options.rethrow && error instanceof Error) {\n throw error;\n }\n }\n\n /**\n * Create a dedicated API client instance (NOT the singleton)\n *\n * Use this when you need an isolated client with its own configuration\n * that doesn't affect or get affected by the shared singleton instance.\n *\n * @param envConfig - Environment metadata (env, apiKey)\n * @param apiConfig - API configuration (baseURL, encryption, timeout, etc.)\n * @returns Promise that resolves to a new dedicated client instance\n *\n * @example\n * ```typescript\n * // Create a dedicated client for feature flags service\n * const flagsClient = await ApiClientService.createInstance(\n * { env: 'production' },\n * {\n * baseURL: 'https://flags.example.com',\n * timeout: 5000,\n * }\n * );\n *\n * // This client is independent from ApiClientService.getClient()\n * flagsClient.updateConfig({ timeout: 3000 }); // Only affects this instance\n * ```\n */\n static async createInstance(\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n ): Promise<ApiClientWithEvents<ClientEventManager, EndpointsList>> {\n try {\n // Step 1: Get environment-specific defaults based on env\n const envDefaults = getConfigForEnvironment(envConfig.env);\n\n // Step 2: Build config from envConfig (environment metadata only)\n const envMetadataMapped = mapEnvironmentMetadata(envConfig, envDefaults);\n\n // Step 3: Merge with priority: envDefaults → envMetadata → apiConfig\n const mergedOptions = mergeConfigs(\n envDefaults,\n envMetadataMapped,\n apiConfig ?? {}\n ) as ApiClientOptions;\n\n // Step 4: Validate the merged configuration\n validateEnvironmentConfig(envConfig, mergedOptions);\n\n // Step 5: Create a NEW client instance (not stored as singleton)\n const dedicatedClient = await createApiClient(mergedOptions);\n\n // Note: Do NOT call applyDefaultClientSetting - this is a dedicated instance\n // that should not become the default client for @plyaz/api services\n\n return dedicatedClient;\n } catch (error) {\n throw new ApiPackageError(\n 'service.instance_creation.failed',\n PACKAGE_STATUS_CODES.INITIALIZATION_FAILED,\n API_ERROR_CODES.CLIENT_INITIALIZATION_FAILED,\n {\n cause: error instanceof Error ? error : undefined,\n context: {\n operation: OPERATIONS.INITIALIZATION,\n originalError: error instanceof Error ? error.message : String(error),\n i18n: {\n error: error instanceof Error ? error.message : String(error),\n },\n },\n }\n );\n }\n }\n}\n\n// Export convenience helpers\nexport const getApiClient = (): ApiClientWithEvents<ClientEventManager, EndpointsList> =>\n ApiClientService.getClient();\n\nexport const initApiClient = (\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n): Promise<ApiClientWithEvents<ClientEventManager, EndpointsList>> =>\n ApiClientService.init(envConfig, apiConfig);\n\nexport const createApiClientInstance = (\n envConfig: CoreApiEnvironmentConfig,\n apiConfig?: Partial<ApiClientOptions>\n): Promise<ApiClientWithEvents<ClientEventManager, EndpointsList>> =>\n ApiClientService.createInstance(envConfig, apiConfig);\n","/**\n * Base Observability Adapter\n *\n * Abstract base class for all observability adapters.\n * Provides common functionality and enforces the adapter interface.\n *\n * @module base/observability\n */\n\nimport { PackageLogger } from '@plyaz/logger';\nimport type {\n ObservabilityAdapter,\n ObservabilityAdapterConfig,\n ObservabilityProvider,\n Metric,\n SpanOptions,\n Span,\n LogEntry,\n ObservabilityEvent,\n SpanContext,\n} from '@plyaz/types/observability';\nimport { generateTraceId, generateSpanId } from '@/utils/common';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Abstract Base Adapter\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Abstract base class for observability adapters.\n *\n * Provides common functionality:\n * - Initialization lifecycle\n * - Default tag management\n * - Error handling\n * - Logging\n *\n * Subclasses must implement provider-specific methods.\n */\nexport abstract class BaseAdapter implements ObservabilityAdapter {\n abstract readonly provider: ObservabilityProvider;\n abstract readonly name: string;\n\n protected _isInitialized = false;\n protected _config: ObservabilityAdapterConfig | null = null;\n protected readonly logger: PackageLogger;\n\n constructor() {\n this.logger = new PackageLogger({\n packageName: 'core',\n service: 'ObservabilityAdapter',\n });\n }\n\n get isInitialized(): boolean {\n return this._isInitialized;\n }\n\n get config(): ObservabilityAdapterConfig | null {\n return this._config;\n }\n\n // ─── Lifecycle ─────────────────────────────────────────────────────────────\n\n async initialize(config: ObservabilityAdapterConfig): Promise<void> {\n if (this._isInitialized) {\n this.logger.warn(`${this.name} already initialized`);\n return;\n }\n\n this._config = config;\n\n if (config.enabled === false) {\n this.logger.info(`${this.name} disabled by configuration`);\n return;\n }\n\n await this.doInitialize(config);\n this._isInitialized = true;\n this.logger.info(`${this.name} initialized`, {\n provider: this.provider,\n serviceName: config.serviceName,\n environment: config.environment,\n });\n }\n\n async shutdown(): Promise<void> {\n if (!this._isInitialized) {\n return;\n }\n\n await this.flush();\n await this.doShutdown();\n this._isInitialized = false;\n this.logger.info(`${this.name} shut down`);\n }\n\n async isHealthy(): Promise<boolean> {\n if (!this._isInitialized) {\n return false;\n }\n return this.doHealthCheck();\n }\n\n // ─── Abstract Methods (Provider-specific) ──────────────────────────────────\n\n protected abstract doInitialize(config: ObservabilityAdapterConfig): Promise<void>;\n protected abstract doShutdown(): Promise<void>;\n protected abstract doHealthCheck(): Promise<boolean>;\n\n // ─── Metrics ───────────────────────────────────────────────────────────────\n\n async recordMetric(metric: Metric): Promise<void> {\n if (!this._isInitialized || this._config?.enabled === false) {\n return;\n }\n\n const metricWithDefaults = this.applyDefaultTags(metric);\n await this.doRecordMetric(metricWithDefaults);\n }\n\n async incrementCounter(\n name: string,\n value: number = 1,\n tags?: Record<string, string>\n ): Promise<void> {\n await this.recordMetric({\n type: 'counter',\n name,\n value,\n tags: { ...this._config?.defaultTags, ...tags },\n });\n }\n\n async setGauge(name: string, value: number, tags?: Record<string, string>): Promise<void> {\n await this.recordMetric({\n type: 'gauge',\n name,\n value,\n tags: { ...this._config?.defaultTags, ...tags },\n });\n }\n\n async recordHistogram(name: string, value: number, tags?: Record<string, string>): Promise<void> {\n await this.recordMetric({\n type: 'histogram',\n name,\n value,\n tags: { ...this._config?.defaultTags, ...tags },\n });\n }\n\n protected abstract doRecordMetric(metric: Metric): Promise<void>;\n\n // ─── Tracing ───────────────────────────────────────────────────────────────\n\n startSpan(options: SpanOptions): Span {\n if (!this._isInitialized || this._config?.enabled === false) {\n return this.createNoopSpan(options);\n }\n\n // Apply sampling\n if (this._config?.samplingRate !== undefined && this._config.samplingRate < 1) {\n if (Math.random() > this._config.samplingRate) {\n return this.createNoopSpan(options);\n }\n }\n\n return this.doStartSpan(options);\n }\n\n getActiveSpan(): Span | null {\n if (!this._isInitialized) {\n return null;\n }\n return this.doGetActiveSpan();\n }\n\n async withSpan<T>(options: SpanOptions, fn: (span: Span) => Promise<T>): Promise<T> {\n const span = this.startSpan(options);\n try {\n const result = await fn(span);\n span.setStatus('ok');\n return result;\n } catch (error) {\n span.setStatus('error', error instanceof Error ? error.message : String(error));\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n }\n\n protected abstract doStartSpan(options: SpanOptions): Span;\n protected abstract doGetActiveSpan(): Span | null;\n\n // ─── Logging ───────────────────────────────────────────────────────────────\n\n async log(entry: LogEntry): Promise<void> {\n if (!this._isInitialized || this._config?.enabled === false) {\n return;\n }\n\n const entryWithDefaults = {\n ...entry,\n timestamp: entry.timestamp ?? Date.now(),\n service: entry.service ?? this._config?.serviceName,\n };\n\n await this.doLog(entryWithDefaults);\n }\n\n protected abstract doLog(entry: LogEntry): Promise<void>;\n\n // ─── Events ────────────────────────────────────────────────────────────────\n\n async sendEvent(event: ObservabilityEvent): Promise<void> {\n if (!this._isInitialized || this._config?.enabled === false) {\n return;\n }\n\n const eventWithDefaults = {\n ...event,\n timestamp: event.timestamp ?? Date.now(),\n tags: { ...this._config?.defaultTags, ...event.tags },\n };\n\n await this.doSendEvent(eventWithDefaults);\n }\n\n protected abstract doSendEvent(event: ObservabilityEvent): Promise<void>;\n\n // ─── Flush ─────────────────────────────────────────────────────────────────\n\n async flush(): Promise<void> {\n if (!this._isInitialized) {\n return;\n }\n await this.doFlush();\n }\n\n protected abstract doFlush(): Promise<void>;\n\n // ─── Helpers ───────────────────────────────────────────────────────────────\n\n /**\n * Apply default tags to a metric\n */\n protected applyDefaultTags(metric: Metric): Metric {\n if (!this._config?.defaultTags) {\n return metric;\n }\n\n return {\n ...metric,\n tags: {\n ...this._config.defaultTags,\n ...metric.tags,\n },\n };\n }\n\n /**\n * Create a no-op span (for disabled/sampled-out traces)\n */\n // eslint-disable-next-line no-unused-vars\n protected createNoopSpan(_options: SpanOptions): Span {\n const context: SpanContext = {\n traceId: generateTraceId(),\n spanId: generateSpanId(),\n };\n\n return {\n context,\n setAttribute: () => {},\n setAttributes: () => {},\n addEvent: () => {},\n setStatus: () => {},\n end: () => {},\n recordException: () => {},\n };\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// No-Op Adapter\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * No-op adapter that does nothing.\n * Use when observability is disabled.\n */\nexport class NoopAdapter extends BaseAdapter {\n readonly provider = 'noop' as const;\n readonly name = 'NoopAdapter';\n\n protected async doInitialize(): Promise<void> {}\n protected async doShutdown(): Promise<void> {}\n protected async doHealthCheck(): Promise<boolean> {\n return true;\n }\n protected async doRecordMetric(): Promise<void> {}\n protected doStartSpan(options: SpanOptions): Span {\n return this.createNoopSpan(options);\n }\n protected doGetActiveSpan(): Span | null {\n return null;\n }\n protected async doLog(): Promise<void> {}\n protected async doSendEvent(): Promise<void> {}\n protected async doFlush(): Promise<void> {}\n}\n","/**\n * Logger Adapter\n *\n * Uses @plyaz/logger for observability output.\n * Can be used standalone OR alongside other adapters (Datadog, Grafana)\n * to always have console/file logging regardless of external providers.\n *\n * @example Standalone usage\n * ```typescript\n * const logger = new LoggerAdapter();\n * await logger.initialize({ serviceName: 'my-service' });\n * ```\n *\n * @example As console fallback with Datadog\n * ```typescript\n * const observability = new ObservabilityService({\n * mode: 'parallel',\n * adapters: [datadogAdapter, loggerAdapter], // Both receive all events\n * });\n * ```\n *\n * @module base/observability\n */\n\nimport { PackageLogger } from '@plyaz/logger';\nimport type {\n ObservabilityAdapterConfig,\n Metric,\n SpanOptions,\n Span,\n LogEntry,\n ObservabilityEvent,\n SpanContext,\n SpanAttributes,\n SpanEvent,\n SpanStatus,\n ConsoleAdapterConfig,\n} from '@plyaz/types/observability';\nimport { generateTraceId, generateSpanId } from '@/utils/common';\nimport { BaseAdapter } from './BaseAdapter';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Logger Adapter\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Logger adapter that uses @plyaz/logger for output.\n *\n * This adapter integrates observability with the existing logging infrastructure,\n * providing structured logging for metrics, spans, and events through PackageLogger.\n *\n * Use this adapter:\n * - As standalone for development/debugging\n * - Alongside Datadog/Grafana to always have local console output\n * - As a fallback in priority mode when external providers fail\n */\nexport class LoggerAdapter extends BaseAdapter {\n readonly provider = 'console' as const;\n readonly name = 'LoggerAdapter';\n\n private observabilityLogger!: PackageLogger;\n private logMetrics = true;\n private logSpans = true;\n private logEvents = true;\n\n protected async doInitialize(config: ObservabilityAdapterConfig): Promise<void> {\n const consoleConfig = config as ConsoleAdapterConfig;\n\n // Create dedicated logger for observability output\n this.observabilityLogger = new PackageLogger({\n packageName: 'observability',\n service: config.serviceName ?? 'LoggerAdapter',\n environment: config.environment as 'development' | 'staging' | 'production' | undefined,\n minLevel: consoleConfig.logLevel ?? 'debug',\n });\n\n // All logging enabled by default\n this.logMetrics = true;\n this.logSpans = true;\n this.logEvents = true;\n }\n\n protected async doShutdown(): Promise<void> {\n // Logger doesn't need explicit shutdown\n }\n\n protected async doHealthCheck(): Promise<boolean> {\n return true;\n }\n\n protected async doRecordMetric(metric: Metric): Promise<void> {\n if (!this.logMetrics) return;\n\n this.observabilityLogger.debug(`[METRIC] ${metric.type}:${metric.name}`, {\n metricType: metric.type,\n metricName: metric.name,\n value: 'value' in metric ? metric.value : undefined,\n unit: metric.unit,\n tags: metric.tags,\n });\n }\n\n protected doStartSpan(options: SpanOptions): Span {\n const context: SpanContext = {\n traceId: generateTraceId(),\n spanId: generateSpanId(),\n parentSpanId: options.parentContext?.spanId,\n };\n\n const startTime = options.startTime ?? Date.now();\n\n if (this.logSpans) {\n this.observabilityLogger.debug(`[SPAN START] ${options.name}`, {\n traceId: context.traceId,\n spanId: context.spanId,\n parentSpanId: context.parentSpanId,\n kind: options.kind,\n attributes: options.attributes,\n });\n }\n\n const events: SpanEvent[] = [];\n let attributes: SpanAttributes = { ...options.attributes };\n let status: SpanStatus = 'unset';\n let statusMessage: string | undefined;\n\n const logSpans = this.logSpans;\n const logger = this.observabilityLogger;\n\n return {\n context,\n setAttribute: (key, value) => {\n attributes[key] = value;\n },\n setAttributes: attrs => {\n attributes = { ...attributes, ...attrs };\n },\n addEvent: event => {\n events.push(event);\n if (logSpans) {\n logger.debug(`[SPAN EVENT] ${options.name}: ${event.name}`, {\n traceId: context.traceId,\n spanId: context.spanId,\n eventAttributes: event.attributes,\n });\n }\n },\n setStatus: (s, message) => {\n status = s;\n statusMessage = message;\n },\n end: endTime => {\n const duration = (endTime ?? Date.now()) - startTime;\n if (logSpans) {\n const logMethod = status === 'error' ? 'warn' : 'debug';\n logger[logMethod](`[SPAN END] ${options.name}`, {\n traceId: context.traceId,\n spanId: context.spanId,\n durationMs: duration,\n status,\n statusMessage,\n attributes,\n eventCount: events.length,\n });\n }\n },\n recordException: error => {\n if (logSpans) {\n logger.error(`[SPAN ERROR] ${options.name}`, {\n traceId: context.traceId,\n spanId: context.spanId,\n error: error.message,\n stack: error.stack,\n });\n }\n },\n };\n }\n\n protected doGetActiveSpan(): Span | null {\n return null; // Logger adapter doesn't track active spans\n }\n\n protected async doLog(entry: LogEntry): Promise<void> {\n const meta = {\n service: entry.service,\n traceId: entry.traceId,\n spanId: entry.spanId,\n ...entry.context,\n };\n\n // Map observability log levels to logger methods\n switch (entry.level) {\n case 'debug':\n this.observabilityLogger.debug(entry.message, meta);\n break;\n case 'info':\n this.observabilityLogger.info(entry.message, meta);\n break;\n case 'warn':\n this.observabilityLogger.warn(entry.message, meta);\n break;\n case 'error':\n this.observabilityLogger.error(entry.message, meta);\n break;\n case 'fatal':\n this.observabilityLogger.fatal(entry.message, meta);\n break;\n }\n }\n\n protected async doSendEvent(event: ObservabilityEvent): Promise<void> {\n if (!this.logEvents) return;\n\n this.observabilityLogger.info(`[EVENT] ${event.name}`, {\n eventName: event.name,\n properties: event.properties,\n tags: event.tags,\n });\n }\n\n protected async doFlush(): Promise<void> {\n // Logger handles its own buffering/flushing\n }\n}\n","/**\n * Observability Service\n *\n * Injectable service for observability (metrics, tracing, logging).\n * Works like CacheManager, DatabaseService, and ApiClient - can be injected into domain services.\n *\n * Adapters are initialized separately with their own configs.\n * This service only orchestrates - it doesn't know about adapter-specific configs.\n *\n * @module base/observability\n */\n\nimport { PackageLogger } from '@plyaz/logger';\nimport { CorePackageError } from '@plyaz/errors';\nimport { ERROR_CODES } from '@plyaz/types/errors';\nimport type {\n ObservabilityAdapter,\n ObservabilityAdapterConfig,\n Metric,\n SpanOptions,\n Span,\n LogEntry,\n ObservabilityEvent,\n OperationContext,\n MonitoringOperationResult,\n AdapterWithPriority,\n AdapterEntry,\n ObservabilityServiceConfig,\n ObservabilityServiceInterface,\n} from '@plyaz/types/observability';\nimport { OBSERVABILITY_METRICS } from '@plyaz/types/observability';\nimport { NoopAdapter } from './BaseAdapter';\nimport { LoggerAdapter } from './LoggerAdapter';\n\n// Default timeout for adapter operations (5 seconds)\nconst DEFAULT_ADAPTER_TIMEOUT_MS = 5000;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Observability Service Implementation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * ObservabilityService - Main observability service that implements ObservabilityAdapter.\n *\n * This service orchestrates multiple adapters and can be injected into domain services.\n * Logger adapter is always included by default for console output.\n *\n * ```typescript\n * // 1. Initialize adapters separately\n * const datadogAdapter = new DatadogAdapter();\n * await datadogAdapter.initialize({ apiKey: '...', serviceName: 'my-service' });\n *\n * // 2. Create service - logger is auto-added by default\n * const observability = new ObservabilityService();\n * await observability.initialize({\n * mode: 'parallel',\n * adapters: [datadogAdapter], // Logger added automatically\n * serviceName: 'my-service',\n * });\n *\n * // 3. Use in domain services (implements ObservabilityAdapter)\n * await observability.incrementCounter('api.requests', 1);\n * ```\n */\nexport class ObservabilityService implements ObservabilityAdapter, ObservabilityServiceInterface {\n readonly provider = 'custom' as const;\n readonly name = 'ObservabilityService';\n\n private _isInitialized = false;\n private _config: ObservabilityServiceConfig | null = null;\n private readonly logger: PackageLogger;\n private readonly adapterEntries: AdapterEntry[] = [];\n private mode: 'single' | 'parallel' | 'priority' = 'parallel';\n private readonly noopAdapter = new NoopAdapter();\n private loggerAdapter: LoggerAdapter | null = null;\n\n constructor() {\n this.logger = new PackageLogger({\n packageName: 'core',\n service: 'ObservabilityService',\n });\n }\n\n get isInitialized(): boolean {\n return this._isInitialized;\n }\n\n /**\n * Check if service has at least one working adapter\n */\n get isReady(): boolean {\n return this.adapterEntries.some(e => e.adapter.isInitialized);\n }\n\n /**\n * Get all adapters (for compatibility)\n */\n private get adapters(): ObservabilityAdapter[] {\n return this.adapterEntries.map(e => e.adapter);\n }\n\n /**\n * Get initialized adapter entries\n */\n private get initializedEntries(): AdapterEntry[] {\n return this.adapterEntries.filter(e => e.adapter.isInitialized);\n }\n\n /**\n * Get primary (non-failover) initialized adapters\n */\n private get primaryEntries(): AdapterEntry[] {\n return this.initializedEntries.filter(e => !e.failover);\n }\n\n /**\n * Get failover initialized adapters\n */\n private get failoverEntries(): AdapterEntry[] {\n return this.initializedEntries.filter(e => e.failover);\n }\n\n // ─── Lifecycle ─────────────────────────────────────────────────────────────\n\n /**\n * Check if input is an adapter with priority config\n */\n private isAdapterWithPriority(\n input: ObservabilityAdapter | AdapterWithPriority\n ): input is AdapterWithPriority {\n return (\n 'adapter' in input &&\n typeof (input as AdapterWithPriority).adapter?.isInitialized === 'boolean'\n );\n }\n\n /**\n * Normalize adapter input to adapter with priority and failover config\n */\n private normalizeAdapter(\n input: ObservabilityAdapter | AdapterWithPriority,\n defaultPriority: number\n ): { adapter: ObservabilityAdapter; priority: number; failover: boolean } {\n if (this.isAdapterWithPriority(input)) {\n return {\n adapter: input.adapter,\n priority: input.priority ?? defaultPriority,\n failover: input.failover ?? false,\n };\n }\n return { adapter: input, priority: defaultPriority, failover: false };\n }\n\n /**\n * Initialize the observability service.\n * Logger adapter is always added by default unless explicitly disabled.\n * Adapters are sorted by priority (higher = first), with failover adapters after primary.\n */\n async initialize(config: ObservabilityAdapterConfig & ObservabilityServiceConfig): Promise<void> {\n if (this._isInitialized) {\n this.logger.warn('ObservabilityService already initialized');\n return;\n }\n\n this._config = config;\n this.mode = config.mode ?? 'parallel';\n\n // Collect adapters with priorities\n const entries: AdapterEntry[] = [];\n\n // Add provided adapters\n if (config.adapter) {\n entries.push(this.normalizeAdapter(config.adapter, 0));\n }\n if (config.adapters) {\n config.adapters.forEach((a, index) => {\n // Default priority decreases with array position for stable sorting\n entries.push(this.normalizeAdapter(a, -index));\n });\n }\n\n // Always add logger adapter by default (for console output)\n // Unless there's already a console/logger adapter\n const hasLoggerAdapter = entries.some(\n e => e.adapter.provider === 'console' || e.adapter.name === 'LoggerAdapter'\n );\n if (!hasLoggerAdapter) {\n this.loggerAdapter = new LoggerAdapter();\n await this.loggerAdapter.initialize({\n enabled: config.enabled !== false,\n serviceName: config.serviceName,\n environment: config.environment,\n defaultTags: config.defaultTags,\n });\n // Logger is a failover by default with lowest priority\n entries.push({ adapter: this.loggerAdapter, priority: -1000, failover: true });\n }\n\n // Sort: primary adapters first (by priority desc), then failover adapters (by priority desc)\n entries.sort((a, b) => {\n // Primary adapters come before failover\n if (a.failover !== b.failover) {\n return a.failover ? 1 : -1;\n }\n // Within same category, sort by priority (higher first)\n return b.priority - a.priority;\n });\n\n // Store sorted entries\n this.adapterEntries.push(...entries);\n\n this._isInitialized = true;\n\n this.logger.debug('ObservabilityService initialized', {\n mode: this.mode,\n adapterCount: this.adapterEntries.length,\n primaryCount: this.primaryEntries.length,\n failoverCount: this.failoverEntries.length,\n adapters: this.adapterEntries.map(e => ({\n name: e.adapter.name,\n provider: e.adapter.provider,\n priority: e.priority,\n failover: e.failover,\n initialized: e.adapter.isInitialized,\n })),\n });\n }\n\n async shutdown(): Promise<void> {\n await Promise.all(this.adapters.map(adapter => adapter.shutdown()));\n this._isInitialized = false;\n this.logger.info('ObservabilityService shut down');\n }\n\n async isHealthy(): Promise<boolean> {\n if (this.adapters.length === 0) {\n return false;\n }\n\n const results = await Promise.all(\n this.adapters.map(adapter => adapter.isHealthy().catch(() => false))\n );\n\n // For parallel mode, all must be healthy; for priority/single, at least one\n return this.mode === 'parallel' ? results.every(Boolean) : results.some(Boolean);\n }\n\n async flush(): Promise<void> {\n await this.executeOnAdapters('flush', adapter => adapter.flush());\n }\n\n // ─── Execute on Adapters ───────────────────────────────────────────────────\n\n private get config(): ObservabilityServiceConfig {\n return this._config ?? {};\n }\n\n private async executeOnAdapters<T>(\n operation: string,\n fn: (adapter: ObservabilityAdapter) => Promise<T>\n ): Promise<void> {\n const entries = this.initializedEntries;\n if (entries.length === 0) {\n return;\n }\n\n const timeout = this.config.adapterTimeout ?? DEFAULT_ADAPTER_TIMEOUT_MS;\n\n switch (this.mode) {\n case 'parallel':\n await this.executeParallelWithFailover(operation, fn, timeout);\n break;\n case 'priority':\n await this.executePriorityWithFailover(operation, fn, timeout);\n break;\n case 'single':\n default:\n await this.executeSingle(operation, entries[0].adapter, fn, timeout);\n break;\n }\n }\n\n private async executeSingle<T>(\n operation: string,\n adapter: ObservabilityAdapter,\n fn: (adapter: ObservabilityAdapter) => Promise<T>,\n timeout: number\n ): Promise<void> {\n try {\n await this.withTimeout(fn(adapter), timeout);\n } catch (error) {\n this.logger.error(`${operation} failed on ${adapter.name}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n /**\n * Execute on primary adapters in parallel.\n * If all primary adapters fail, execute on failover adapters.\n */\n // eslint-disable-next-line complexity\n private async executeParallelWithFailover<T>(\n operation: string,\n fn: (adapter: ObservabilityAdapter) => Promise<T>,\n timeout: number\n ): Promise<void> {\n const primary = this.primaryEntries;\n const failover = this.failoverEntries;\n\n // Execute on primary adapters\n if (primary.length > 0) {\n const results = await Promise.allSettled(\n primary.map(e => this.withTimeout(fn(e.adapter), timeout))\n );\n\n const errors = results\n .map((r, i) =>\n r.status === 'rejected' ? { adapter: primary[i].adapter.name, error: r.reason } : null\n )\n .filter(Boolean);\n\n const allFailed = errors.length === primary.length;\n\n if (errors.length > 0 && !allFailed) {\n this.logger.warn(`${operation} failed on some primary adapters`, { errors });\n }\n\n // If all primary adapters failed, use failover\n if (allFailed && failover.length > 0) {\n this.logger.warn(`${operation} failed on all primary adapters, using failover`, { errors });\n await this.executeParallel(\n operation,\n failover.map(e => e.adapter),\n fn,\n timeout\n );\n return;\n }\n\n if (this.config.failOnAnyError && errors.length > 0) {\n throw new CorePackageError(\n `${operation} failed on adapters: ${errors.map(e => e?.adapter).join(', ')}`,\n ERROR_CODES.CORE_OPERATION_FAILED\n );\n }\n } else if (failover.length > 0) {\n // No primary adapters, use failover directly\n await this.executeParallel(\n operation,\n failover.map(e => e.adapter),\n fn,\n timeout\n );\n }\n }\n\n private async executeParallel<T>(\n operation: string,\n adapters: ObservabilityAdapter[],\n fn: (adapter: ObservabilityAdapter) => Promise<T>,\n timeout: number\n ): Promise<void> {\n const results = await Promise.allSettled(\n adapters.map(adapter => this.withTimeout(fn(adapter), timeout))\n );\n\n const errors = results\n .map((r, i) =>\n r.status === 'rejected' ? { adapter: adapters[i].name, error: r.reason } : null\n )\n .filter(Boolean);\n\n if (errors.length > 0) {\n this.logger.warn(`${operation} failed on some adapters`, { errors });\n }\n }\n\n /**\n * Execute on primary adapters in priority order.\n * If all primary adapters fail, try failover adapters.\n */\n // eslint-disable-next-line complexity\n private async executePriorityWithFailover<T>(\n operation: string,\n fn: (adapter: ObservabilityAdapter) => Promise<T>,\n timeout: number\n ): Promise<void> {\n const primary = this.primaryEntries;\n const failover = this.failoverEntries;\n\n // Try primary adapters first\n for (const entry of primary) {\n try {\n await this.withTimeout(fn(entry.adapter), timeout);\n return; // Success - stop trying\n } catch (error) {\n const errorName = error instanceof Error ? error.name : 'Error';\n const shouldFallback =\n !this.config.fallbackOnErrors || this.config.fallbackOnErrors.includes(errorName);\n\n if (shouldFallback) {\n this.logger.warn(`${operation} failed on ${entry.adapter.name}, trying next`, {\n error: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n throw error;\n }\n }\n\n // All primary failed, try failover adapters\n for (const entry of failover) {\n try {\n await this.withTimeout(fn(entry.adapter), timeout);\n return; // Success\n } catch (error) {\n this.logger.warn(`${operation} failed on failover ${entry.adapter.name}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n // Continue to next failover adapter\n }\n }\n\n this.logger.error(`${operation} failed on all adapters (primary and failover)`);\n }\n\n private async withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\n return Promise.race([\n promise,\n new Promise<T>((_, reject) =>\n setTimeout(() => reject(new Error(`Operation timed out after ${timeoutMs}ms`)), timeoutMs)\n ),\n ]);\n }\n\n // ─── Metrics ───────────────────────────────────────────────────────────────\n\n async recordMetric(metric: Metric): Promise<void> {\n await this.executeOnAdapters('recordMetric', adapter => adapter.recordMetric(metric));\n }\n\n async incrementCounter(\n name: string,\n value: number = 1,\n tags?: Record<string, string>\n ): Promise<void> {\n await this.executeOnAdapters('incrementCounter', adapter =>\n adapter.incrementCounter(name, value, tags)\n );\n }\n\n async setGauge(name: string, value: number, tags?: Record<string, string>): Promise<void> {\n await this.executeOnAdapters('setGauge', adapter => adapter.setGauge(name, value, tags));\n }\n\n async recordHistogram(name: string, value: number, tags?: Record<string, string>): Promise<void> {\n await this.executeOnAdapters('recordHistogram', adapter =>\n adapter.recordHistogram(name, value, tags)\n );\n }\n\n // ─── Tracing ───────────────────────────────────────────────────────────────\n\n startSpan(options: SpanOptions): Span {\n // For tracing, use first initialized adapter\n const entry = this.initializedEntries[0];\n return entry?.adapter.startSpan(options) ?? this.noopAdapter.startSpan(options);\n }\n\n async withSpan<T>(options: SpanOptions, fn: (span: Span) => Promise<T>): Promise<T> {\n const entry = this.initializedEntries[0];\n if (!entry) {\n return fn(this.noopAdapter.startSpan(options));\n }\n return entry.adapter.withSpan(options, fn);\n }\n\n getActiveSpan(): Span | null {\n const entry = this.initializedEntries[0];\n return entry?.adapter.getActiveSpan() ?? null;\n }\n\n // ─── Logging ───────────────────────────────────────────────────────────────\n\n async log(entry: LogEntry): Promise<void> {\n await this.executeOnAdapters('log', adapter => adapter.log(entry));\n }\n\n // ─── Events ────────────────────────────────────────────────────────────────\n\n async sendEvent(event: ObservabilityEvent): Promise<void> {\n await this.executeOnAdapters('sendEvent', adapter => adapter.sendEvent(event));\n }\n\n // ─── Service Operation Tracking ────────────────────────────────────────────\n\n /**\n * Track a service operation with automatic metrics and tracing.\n *\n * @example\n * ```typescript\n * const { result, metrics } = await observability.trackOperation(\n * {\n * serviceName: 'UserService',\n * operation: 'create',\n * entityType: 'user',\n * startTime: Date.now(),\n * },\n * async () => {\n * return await this.repository.create(userData);\n * }\n * );\n * ```\n */\n // eslint-disable-next-line complexity\n async trackOperation<T>(\n context: OperationContext,\n operation: () => Promise<T>\n ): Promise<{ result: T; metrics: MonitoringOperationResult }> {\n const startTime = context.startTime ?? Date.now();\n\n // Start span\n const span = this.startSpan({\n name: `${context.serviceName}.${context.operation}`,\n attributes: {\n 'service.name': context.serviceName,\n 'operation.name': context.operation,\n ...(context.entityType && { 'entity.type': context.entityType }),\n ...(context.entityId && { 'entity.id': context.entityId }),\n ...context.attributes,\n },\n parentContext: context.parentContext,\n });\n\n // Increment operation counter\n await this.incrementCounter(OBSERVABILITY_METRICS.SERVICE_OPERATION_COUNT, 1, {\n service: context.serviceName,\n operation: context.operation,\n ...(context.entityType && { entity_type: context.entityType }),\n });\n\n try {\n const result = await operation();\n const duration = Date.now() - startTime;\n\n span.setStatus('ok');\n\n await this.recordHistogram(OBSERVABILITY_METRICS.SERVICE_OPERATION_DURATION, duration, {\n service: context.serviceName,\n operation: context.operation,\n status: 'success',\n });\n\n return {\n result,\n metrics: { success: true, duration, data: result },\n };\n } catch (error) {\n const duration = Date.now() - startTime;\n\n span.setStatus('error', error instanceof Error ? error.message : String(error));\n if (error instanceof Error) {\n span.recordException(error);\n }\n\n await this.incrementCounter(OBSERVABILITY_METRICS.SERVICE_OPERATION_ERROR, 1, {\n service: context.serviceName,\n operation: context.operation,\n error_type: error instanceof Error ? error.name : 'UnknownError',\n });\n\n await this.recordHistogram(OBSERVABILITY_METRICS.SERVICE_OPERATION_DURATION, duration, {\n service: context.serviceName,\n operation: context.operation,\n status: 'error',\n });\n\n throw error;\n } finally {\n span.end();\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Factory Function\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Create an ObservabilityService with pre-initialized adapters.\n *\n * @example\n * ```typescript\n * // Initialize adapters first\n * const datadogAdapter = new DatadogAdapter();\n * await datadogAdapter.initialize({ apiKey: '...', serviceName: 'my-service' });\n *\n * // Create and initialize service (logger auto-added)\n * const observability = await createObservabilityService({\n * mode: 'parallel',\n * adapters: [datadogAdapter],\n * serviceName: 'my-service',\n * });\n *\n * // Priority mode (fallback chain)\n * const observability = await createObservabilityService({\n * mode: 'priority',\n * adapters: [datadogAdapter, grafanaAdapter],\n * serviceName: 'my-service',\n * });\n * ```\n */\nexport async function createObservabilityService(\n config: ObservabilityServiceConfig & { serviceName?: string; environment?: string } = {}\n): Promise<ObservabilityService> {\n const service = new ObservabilityService();\n await service.initialize(config);\n return service;\n}\n","/**\n * Core Dependencies Configuration\n *\n * Similar to @plyaz/api's setGlobalConfig pattern.\n * Backend services are registered here by entry points, not imported directly.\n *\n * IMPORTANT: This file must NOT import from backend service files (DbService, CacheService, etc.)\n * as that would cause the bundler to include backend dependencies in the frontend bundle.\n *\n * @example\n * ```typescript\n * // entry-backend.ts\n * import { setCoreDependencies } from './config/dependencies';\n * import { DbService } from './services/DbService';\n * import { CacheService } from './services/CacheService';\n *\n * setCoreDependencies({\n * DbService,\n * CacheService,\n * StorageService,\n * NotificationService,\n * });\n *\n * // entry-frontend.ts\n * // Don't call setCoreDependencies - no backend deps loaded\n * ```\n */\n\nimport type {\n CoreDbServiceStatic,\n CoreCacheServiceStatic,\n CoreStorageServiceStatic,\n CoreNotificationServiceStatic,\n CoreServerErrorMiddlewareStatic,\n} from '@plyaz/types/core';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Dependencies Container\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface CoreDependencies {\n DbService?: CoreDbServiceStatic;\n CacheService?: CoreCacheServiceStatic;\n StorageService?: CoreStorageServiceStatic;\n NotificationService?: CoreNotificationServiceStatic;\n ServerErrorMiddleware?: CoreServerErrorMiddlewareStatic;\n}\n\n// Global dependencies container\nlet _dependencies: CoreDependencies = {};\n\n/**\n * Set core dependencies (called by entry points)\n *\n * @example\n * ```typescript\n * // entry-backend.ts\n * import { DbService } from './services/DbService';\n * import { CacheService } from './services/CacheService';\n *\n * setCoreDependencies({\n * DbService,\n * CacheService,\n * });\n * ```\n */\nexport function setCoreDependencies(deps: CoreDependencies): void {\n _dependencies = { ..._dependencies, ...deps };\n}\n\n/**\n * Get core dependencies\n */\nexport function getCoreDependencies(): CoreDependencies {\n return _dependencies;\n}\n\n/**\n * Check if a dependency is available\n */\nexport function hasCoreDependency(key: keyof CoreDependencies): boolean {\n return _dependencies[key] !== undefined;\n}\n\n/**\n * Get a specific dependency\n */\nexport function getCoreDependency<K extends keyof CoreDependencies>(\n key: K\n): CoreDependencies[K] | undefined {\n return _dependencies[key];\n}\n\n/**\n * Clear all dependencies (useful for testing)\n */\nexport function clearCoreDependencies(): void {\n _dependencies = {};\n}\n","// This eslint disable is an edge-case as we need to ensure that we're able to load CoreInitializer regardless if FE, BE or specific frameworks\n/**\n * Service Registry - Frontend Service Auto-Initialization\n *\n * Provides a generic, scalable pattern for initializing domain services.\n * Services implement the InitializableDomainService interface and are\n * initialized automatically without hardcoded switch statements.\n *\n * @example\n * ```typescript\n * import { ServiceRegistry } from '@plyaz/core';\n * import { FeatureFlagDomainService } from '@plyaz/core/frontend';\n * import { ExampleDomainService } from '@plyaz/core/domain';\n *\n * // Initialize services\n * await ServiceRegistry.initialize({\n * apiClient: { baseURL: '/api' },\n * services: [\n * { service: FeatureFlagDomainService, config: { enabled: true } },\n * { service: ExampleDomainService, config: { enabled: true, useRealApi: false } },\n * ],\n * });\n *\n * // Access services by key\n * const flags = ServiceRegistry.get('featureFlags');\n * const isEnabled = await flags.isEnabled('my-flag');\n *\n * // Or get with type safety\n * const example = ServiceRegistry.get<ExampleDomainService>('example');\n * ```\n */\n\nimport { CorePackageError } from '@plyaz/errors';\nimport { ERROR_CODES, BACKEND_RUNTIMES, FRONTEND_RUNTIMES } from '@plyaz/types';\nimport { PackageLogger } from '@plyaz/logger';\nimport type { ApiClientOptions } from '@plyaz/types/api';\nimport type { RootStoreSlice } from '@plyaz/types/store';\nimport type {\n CoreDomainServiceInstance,\n CoreServiceCreateOptions,\n CoreServiceEntry,\n CoreServiceInitConfig,\n CoreServiceRegistryConfig,\n CoreCacheConfig,\n CoreObservabilityConfig,\n CoreRuntimeEnvironment,\n CoreDbServiceConfig,\n CoreStorageConfig,\n CoreNotificationConfig,\n // Service instance types (from @plyaz/types, not backend modules)\n CoreDbServiceInstance,\n CoreCacheManagerInstance,\n CoreStorageServiceInstance,\n CoreNotificationServiceInstance,\n} from '@plyaz/types/core';\nimport type { ObservabilityAdapter } from '@plyaz/types/observability';\nimport { createObservabilityService } from '../base/observability';\nimport { ApiClientService } from '../services/ApiClientService';\nimport { getCoreDependency } from '../config/dependencies';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal Types\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface PendingService {\n entry: CoreServiceEntry;\n initWhen: CoreServiceInitConfig['initWhen'];\n}\n\ninterface ServiceMetadata {\n entry: CoreServiceEntry;\n isSingleton: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Service Registry\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Service Registry\n *\n * Manages frontend domain service instances with auto-initialization.\n * Supports immediate, lazy, and conditional initialization.\n *\n * Key features:\n * - Generic: No switch statements, services implement common interface\n * - Scalable: Add new services without modifying registry code\n * - Flexible: Immediate, lazy, or conditional initialization\n * - Type-safe: Get services with proper typing\n */\nexport class ServiceRegistry {\n private static readonly logger = new PackageLogger({\n packageName: 'core',\n service: 'ServiceRegistry',\n });\n\n /** Initialized singleton service instances by key */\n private static _services = new Map<string, CoreDomainServiceInstance>();\n\n /** Pending services for lazy initialization */\n private static _pending = new Map<string, PendingService>();\n\n /** Service metadata (config, singleton flag) by key */\n private static _metadata = new Map<string, ServiceMetadata>();\n\n /** Global environment */\n private static _environment: 'production' | 'staging' | 'development' | 'test' = 'development';\n\n /** Runtime environment (node, browser, bun, etc.) */\n private static _runtime: CoreRuntimeEnvironment = 'node';\n\n /** Global API client options */\n private static _apiClientOptions: ApiClientOptions | null = null;\n\n /** Global database config */\n private static _dbConfig: Partial<CoreDbServiceConfig> | null = null;\n\n /** Global cache config */\n private static _cacheConfig: CoreCacheConfig | null = null;\n\n /** Global observability config */\n private static _observabilityConfig: CoreObservabilityConfig | null = null;\n\n /** Global observability adapter instance */\n private static _observabilityInstance: ObservabilityAdapter | null = null;\n\n /** Global storage config */\n private static _storageConfig: CoreStorageConfig | null = null;\n\n /** Global notifications config */\n private static _notificationsConfig: CoreNotificationConfig | null = null;\n\n /** Store registry interface from Core (type-safe) */\n private static _storeRegistry: {\n getStore<K extends keyof RootStoreSlice>(key: K): RootStoreSlice[K] | undefined;\n } | null = null;\n\n /** Initialization promises (for concurrent access during lazy init) */\n private static _initPromises = new Map<string, Promise<CoreDomainServiceInstance>>();\n\n // ─────────────────────────────────────────────────────────────────────────\n // Initialization\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Initialize the service registry with the provided configuration.\n *\n * @param config - Registry configuration with services to initialize\n *\n * @example\n * ```typescript\n * await ServiceRegistry.initialize({\n * apiClient: { baseURL: '/api' },\n * services: [\n * { service: FeatureFlagDomainService, config: { enabled: true } },\n * { service: ExampleDomainService, config: { enabled: true, initWhen: 'lazy' } },\n * ],\n * });\n * ```\n */\n // eslint-disable-next-line complexity\n static async initialize(config: CoreServiceRegistryConfig): Promise<void> {\n ServiceRegistry._environment = config.environment ?? 'development';\n ServiceRegistry._runtime = config.runtime ?? 'node';\n ServiceRegistry._apiClientOptions = config.apiClient ?? null;\n ServiceRegistry._dbConfig = config.db ?? null;\n ServiceRegistry._cacheConfig = config.cache ?? null;\n ServiceRegistry._observabilityConfig = config.observability ?? null;\n ServiceRegistry._storageConfig = config.storage ?? null;\n ServiceRegistry._notificationsConfig = config.notifications ?? null;\n ServiceRegistry._storeRegistry = config.stores ?? null;\n\n const immediatePromises: Promise<void>[] = [];\n\n for (const entry of config.services) {\n const serviceKey = entry.service.serviceKey;\n const initWhen = entry.config.initWhen ?? 'immediate';\n const enabled = entry.config.enabled !== false;\n const isSingleton = entry.config.singleton !== false; // Default: true\n\n // Store metadata for all services (even disabled)\n ServiceRegistry._metadata.set(serviceKey, { entry, isSingleton });\n\n // Skip disabled services\n if (!enabled) {\n ServiceRegistry.logger.debug(`Service ${serviceKey} is disabled, skipping`);\n continue;\n }\n\n // Handle initialization timing\n if (initWhen === 'immediate' && isSingleton) {\n // Only auto-initialize singletons\n immediatePromises.push(\n ServiceRegistry.initializeService(entry).then(() => {\n ServiceRegistry.logger.debug(`Service ${serviceKey} initialized (singleton)`);\n })\n );\n } else if (isSingleton) {\n // Store for lazy/conditional initialization\n ServiceRegistry._pending.set(serviceKey, { entry, initWhen });\n ServiceRegistry.logger.debug(\n `Service ${serviceKey} registered for ${initWhen} initialization`\n );\n } else {\n // Non-singleton: just store metadata, create on demand via create()\n ServiceRegistry.logger.debug(\n `Service ${serviceKey} registered (non-singleton, use create())`\n );\n }\n }\n\n // Wait for all immediate initializations\n await Promise.all(immediatePromises);\n\n const initializedKeys = [...ServiceRegistry._services.keys()];\n const pendingKeys = [...ServiceRegistry._pending.keys()];\n const nonSingletonKeys = [...ServiceRegistry._metadata.entries()]\n .filter(([, meta]) => !meta.isSingleton)\n .map(([key]) => key);\n\n ServiceRegistry.logger.info('Service registry initialized', {\n initialized: initializedKeys,\n pending: pendingKeys,\n nonSingleton: nonSingletonKeys,\n });\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Service Access\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Get a singleton service instance by key (synchronous).\n * Throws if the service is not initialized or is non-singleton.\n *\n * @param key - Service key (e.g., 'featureFlags', 'example')\n * @returns The service instance\n * @throws CorePackageError if service not found, not initialized, or non-singleton\n *\n * @example\n * ```typescript\n * const flags = ServiceRegistry.get<FeatureFlagDomainService>('featureFlags');\n * const isEnabled = await flags.isEnabled('my-flag');\n * ```\n */\n static get<T extends CoreDomainServiceInstance = CoreDomainServiceInstance>(key: string): T {\n const service = ServiceRegistry._services.get(key);\n if (service) {\n return service as T;\n }\n\n // Check if non-singleton (must use create())\n const metadata = ServiceRegistry._metadata.get(key);\n if (metadata && !metadata.isSingleton) {\n throw new CorePackageError(\n `Service '${key}' is configured as non-singleton. ` +\n `Use await ServiceRegistry.create('${key}') to create a new instance.`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n // Check if pending lazy initialization\n const pending = ServiceRegistry._pending.get(key);\n if (pending) {\n throw new CorePackageError(\n `Service '${key}' is configured for lazy initialization. ` +\n `Use await ServiceRegistry.getAsync('${key}') instead.`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n throw new CorePackageError(\n `Service '${key}' not found. Register it in ServiceRegistry.initialize()`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n /**\n * Create a new instance of a service.\n * Use this for non-singleton services or when you need a fresh instance.\n *\n * Note: The caller is responsible for disposing the returned instance.\n *\n * @param key - Service key\n * @param configOverrides - Optional config overrides for this instance\n * @returns Promise resolving to a new service instance\n *\n * @example\n * ```typescript\n * // Non-singleton service - always creates new instance\n * const instance1 = await ServiceRegistry.create<WorkerService>('worker');\n * const instance2 = await ServiceRegistry.create<WorkerService>('worker');\n * instance1 !== instance2; // true\n *\n * // With config overrides\n * const customWorker = await ServiceRegistry.create<WorkerService>('worker', {\n * apiClient: { baseURL: 'https://custom-api.com' },\n * });\n *\n * // Don't forget to dispose when done!\n * instance1.dispose();\n * instance2.dispose();\n * ```\n */\n static async create<T extends CoreDomainServiceInstance = CoreDomainServiceInstance>(\n key: string,\n configOverrides?: Partial<CoreServiceInitConfig>\n ): Promise<T> {\n const metadata = ServiceRegistry._metadata.get(key);\n if (!metadata) {\n throw new CorePackageError(\n `Service '${key}' not found. Register it in ServiceRegistry.initialize()`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n // Merge config with overrides\n const mergedEntry: CoreServiceEntry = {\n service: metadata.entry.service,\n config: { ...metadata.entry.config, ...configOverrides },\n };\n\n // Create new instance (don't store in registry)\n return ServiceRegistry.initializeService(mergedEntry, false) as Promise<T>;\n }\n\n /**\n * Get a service instance by key with async initialization if needed.\n * Use this for lazy-initialized services.\n *\n * @param key - Service key\n * @returns Promise resolving to the service instance\n *\n * @example\n * ```typescript\n * const example = await ServiceRegistry.getAsync<ExampleDomainService>('example');\n * const entities = await example.getAll();\n * ```\n */\n static async getAsync<T extends CoreDomainServiceInstance = CoreDomainServiceInstance>(\n key: string\n ): Promise<T> {\n // Return immediately if already initialized\n const existing = ServiceRegistry._services.get(key);\n if (existing) {\n return existing as T;\n }\n\n // Check for in-progress initialization\n const inProgress = ServiceRegistry._initPromises.get(key);\n if (inProgress) {\n return (await inProgress) as T;\n }\n\n // Check if pending lazy initialization\n const pending = ServiceRegistry._pending.get(key);\n if (pending) {\n // Handle conditional initialization\n if (typeof pending.initWhen === 'function') {\n const shouldInit = await pending.initWhen();\n if (!shouldInit) {\n throw new CorePackageError(\n `Service '${key}' initialization condition returned false`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n }\n\n // Initialize and return\n const service = await ServiceRegistry.initializeService(pending.entry);\n ServiceRegistry._pending.delete(key);\n return service as T;\n }\n\n throw new CorePackageError(\n `Service '${key}' not found. Register it in ServiceRegistry.initialize()`,\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n /**\n * Check if a service is registered (either initialized or pending).\n *\n * @param key - Service key\n */\n static has(key: string): boolean {\n return ServiceRegistry._services.has(key) || ServiceRegistry._pending.has(key);\n }\n\n /**\n * Check if a service is initialized and ready.\n *\n * @param key - Service key\n */\n static isInitialized(key: string): boolean {\n return ServiceRegistry._services.has(key);\n }\n\n /**\n * Get all initialized service keys.\n */\n static getInitializedKeys(): string[] {\n return [...ServiceRegistry._services.keys()];\n }\n\n /**\n * Get all pending (lazy) service keys.\n */\n static getPendingKeys(): string[] {\n return [...ServiceRegistry._pending.keys()];\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Internal: Service Initialization\n // ─────────────────────────────────────────────────────────────────────────\n\n /** Build API client options and instance for service */\n // eslint-disable-next-line complexity\n private static async buildApiClientOptions(\n config: CoreServiceInitConfig,\n entry: CoreServiceEntry\n ): Promise<{ dedicated: boolean; options?: ApiClientOptions; instance?: unknown } | undefined> {\n const dedicatedApiClient = config.dedicatedApiClient;\n const isDedicated = dedicatedApiClient === true || typeof dedicatedApiClient === 'object';\n const serviceKey = entry.service.serviceKey;\n\n const options: ApiClientOptions | undefined = isDedicated\n ? typeof dedicatedApiClient === 'object'\n ? { ...ServiceRegistry._apiClientOptions, ...dedicatedApiClient }\n : (ServiceRegistry._apiClientOptions ?? undefined)\n : (ServiceRegistry._apiClientOptions ?? undefined);\n\n if (!options) {\n return undefined;\n }\n\n // Get or create API client instance\n let apiInstance: unknown;\n if (isDedicated && options) {\n // Create dedicated API client instance for this service\n try {\n // Use the global environment from initialization\n const envConfig = {\n env: ServiceRegistry._environment,\n setAsDefault: false, // Dedicated instances should not become default\n };\n apiInstance = await ApiClientService.createInstance(envConfig, options);\n ServiceRegistry.logger.debug(\n `Created dedicated API client instance for service '${serviceKey}'`,\n {\n environment: ServiceRegistry._environment,\n }\n );\n } catch (error) {\n ServiceRegistry.logger.warn(\n `Failed to create dedicated API client for service '${serviceKey}'`,\n {\n error: error instanceof Error ? error.message : String(error),\n }\n );\n }\n } else {\n // Use global shared API client\n try {\n apiInstance = ApiClientService.getClient();\n } catch {\n ServiceRegistry.logger.debug(\n `Global API client not initialized, service '${serviceKey}' will not have API`\n );\n }\n }\n\n return {\n dedicated: isDedicated,\n options,\n instance: apiInstance,\n };\n }\n\n /** Build DB config and instance for service with runtime validation */\n // eslint-disable-next-line complexity\n private static async buildDbConfig(\n config: CoreServiceInitConfig,\n entry: CoreServiceEntry\n ): Promise<\n | {\n dedicated: boolean;\n config?: Partial<CoreDbServiceConfig>;\n instance?: CoreDbServiceInstance;\n }\n | undefined\n > {\n const dedicatedDb = config.dedicatedDb;\n const isDedicated = dedicatedDb === true || typeof dedicatedDb === 'object';\n const serviceKey = entry.service.serviceKey;\n\n // Runtime validation: DB should only be injected for backend services\n const isBackendRuntime = BACKEND_RUNTIMES.includes(ServiceRegistry._runtime);\n\n if ((isDedicated || ServiceRegistry._dbConfig) && !isBackendRuntime) {\n ServiceRegistry.logger.warn(\n `Service '${serviceKey}' is requesting database injection in '${ServiceRegistry._runtime}' runtime. ` +\n `Database is only available in backend runtimes (${BACKEND_RUNTIMES.join(', ')}). ` +\n `This service will not have database access.`\n );\n return undefined; // Skip DB injection for non-backend runtimes\n }\n\n const dbConfig: Partial<CoreDbServiceConfig> | undefined = isDedicated\n ? typeof dedicatedDb === 'object'\n ? { ...ServiceRegistry._dbConfig, ...dedicatedDb }\n : (ServiceRegistry._dbConfig ?? undefined)\n : (ServiceRegistry._dbConfig ?? undefined);\n\n if (!dbConfig) {\n return undefined;\n }\n\n const DbService = getCoreDependency('DbService');\n if (!DbService) {\n ServiceRegistry.logger.debug(\n `DbService not registered, service '${serviceKey}' will not have DB`\n );\n return undefined;\n }\n\n // Get or create DB instance\n let dbInstance: CoreDbServiceInstance | undefined;\n if (isDedicated && dbConfig) {\n // Create dedicated database instance for this service\n try {\n dbInstance = await DbService.createInstance?.(dbConfig as CoreDbServiceConfig);\n ServiceRegistry.logger.debug(\n `Created dedicated database instance for service '${serviceKey}'`\n );\n } catch (error) {\n ServiceRegistry.logger.warn(\n `Failed to create dedicated database instance for service '${serviceKey}'`,\n {\n error: error instanceof Error ? error.message : String(error),\n }\n );\n }\n } else {\n // Use global shared database\n try {\n dbInstance = DbService.getInstance();\n } catch {\n ServiceRegistry.logger.debug(\n `Global DB not initialized, service '${serviceKey}' will not have DB`\n );\n }\n }\n\n return {\n dedicated: isDedicated,\n config: dbConfig,\n instance: dbInstance,\n };\n }\n\n /** Build cache config and instance for service with runtime validation */\n // eslint-disable-next-line complexity\n private static async buildCacheConfig(\n config: CoreServiceInitConfig,\n entry: CoreServiceEntry\n ): Promise<\n | { dedicated: boolean; config?: CoreCacheConfig; instance?: CoreCacheManagerInstance }\n | undefined\n > {\n const dedicatedCache = config.dedicatedCache;\n const isDedicated = dedicatedCache === true || typeof dedicatedCache === 'object';\n const serviceKey = entry.service.serviceKey;\n\n const cacheConfig: CoreCacheConfig | undefined = isDedicated\n ? typeof dedicatedCache === 'object'\n ? ({ ...ServiceRegistry._cacheConfig, ...dedicatedCache } as CoreCacheConfig)\n : (ServiceRegistry._cacheConfig ?? undefined)\n : (ServiceRegistry._cacheConfig ?? undefined);\n\n if (!cacheConfig) {\n return undefined;\n }\n\n // Runtime validation: Cache on frontend is not supported (CacheManager uses ioredis which requires Node.js)\n const isFrontendRuntime = FRONTEND_RUNTIMES.includes(ServiceRegistry._runtime);\n\n if (isFrontendRuntime) {\n ServiceRegistry.logger.debug(\n `Service '${serviceKey}' skipping cache (frontend runtime - use Zustand store + react-query instead)`\n );\n return undefined;\n }\n\n const CacheService = getCoreDependency('CacheService');\n if (!CacheService) {\n ServiceRegistry.logger.debug(\n `CacheService not registered, service '${serviceKey}' will not have cache`\n );\n return undefined;\n }\n\n // Backend-only: Get cache manager instance from CacheService\n let cacheInstance: CoreCacheManagerInstance | undefined;\n try {\n cacheInstance = CacheService.getInstance().getCacheManager();\n if (isDedicated) {\n ServiceRegistry.logger.debug(\n `Using shared cache for service '${serviceKey}' (dedicated cache not implemented via DI)`,\n { strategy: cacheConfig.strategy }\n );\n }\n } catch {\n ServiceRegistry.logger.debug(\n `Global cache not initialized, service '${serviceKey}' will not have cache`\n );\n }\n\n return {\n dedicated: isDedicated,\n config: cacheConfig,\n instance: cacheInstance,\n };\n }\n\n /** Build observability config and instance for service */\n // eslint-disable-next-line complexity\n private static buildObservabilityConfig(\n config: CoreServiceInitConfig,\n // eslint-disable-next-line no-unused-vars\n _entry: CoreServiceEntry\n ):\n | { dedicated: boolean; config?: CoreObservabilityConfig; instance?: ObservabilityAdapter }\n | undefined {\n const dedicatedObservability = config.dedicatedObservability;\n const isDedicated =\n dedicatedObservability === true || typeof dedicatedObservability === 'object';\n\n const observabilityConfig: CoreObservabilityConfig | undefined = isDedicated\n ? typeof dedicatedObservability === 'object'\n ? ({\n ...ServiceRegistry._observabilityConfig,\n ...dedicatedObservability,\n } as CoreObservabilityConfig)\n : (ServiceRegistry._observabilityConfig ?? undefined)\n : (ServiceRegistry._observabilityConfig ?? undefined);\n\n if (!observabilityConfig) {\n return undefined;\n }\n\n // Instance will be set async if dedicated\n return {\n dedicated: isDedicated,\n config: observabilityConfig,\n instance: isDedicated ? undefined : (ServiceRegistry._observabilityInstance ?? undefined),\n };\n }\n\n /** Build storage config and instance for service with runtime validation (backend-only) */\n // eslint-disable-next-line complexity\n private static async buildStorageConfig(\n config: CoreServiceInitConfig,\n entry: CoreServiceEntry\n ): Promise<\n | { dedicated: boolean; config?: CoreStorageConfig; instance?: CoreStorageServiceInstance }\n | undefined\n > {\n const dedicatedStorage = config.dedicatedStorage;\n const isDedicated = dedicatedStorage === true || typeof dedicatedStorage === 'object';\n const serviceKey = entry.service.serviceKey;\n\n // Runtime validation: Storage is backend-only\n const isBackendRuntime = BACKEND_RUNTIMES.includes(ServiceRegistry._runtime);\n\n if ((isDedicated || ServiceRegistry._storageConfig) && !isBackendRuntime) {\n ServiceRegistry.logger.warn(\n `Service '${serviceKey}' is requesting storage injection in '${ServiceRegistry._runtime}' runtime. ` +\n `Storage is only available in backend runtimes (${BACKEND_RUNTIMES.join(', ')}). ` +\n `This service will not have storage access.`\n );\n return undefined;\n }\n\n const storageConfig: CoreStorageConfig | undefined = isDedicated\n ? typeof dedicatedStorage === 'object'\n ? { ...ServiceRegistry._storageConfig, ...dedicatedStorage }\n : (ServiceRegistry._storageConfig ?? undefined)\n : (ServiceRegistry._storageConfig ?? undefined);\n\n if (!storageConfig) {\n return undefined;\n }\n\n const StorageService = getCoreDependency('StorageService');\n if (!StorageService) {\n ServiceRegistry.logger.debug(\n `StorageService not registered, service '${serviceKey}' will not have storage`\n );\n return undefined;\n }\n\n // Get or create storage instance\n let storageInstance: CoreStorageServiceInstance | undefined;\n if (isDedicated && storageConfig) {\n try {\n storageInstance = await StorageService.createInstance?.(storageConfig);\n ServiceRegistry.logger.debug(\n `Created dedicated storage instance for service '${serviceKey}'`\n );\n } catch (error) {\n ServiceRegistry.logger.warn(\n `Failed to create dedicated storage instance for service '${serviceKey}'`,\n { error: error instanceof Error ? error.message : String(error) }\n );\n }\n } else {\n try {\n storageInstance = StorageService.getInstance();\n } catch {\n ServiceRegistry.logger.debug(\n `Global storage not initialized, service '${serviceKey}' will not have storage`\n );\n }\n }\n\n return {\n dedicated: isDedicated,\n config: storageConfig,\n instance: storageInstance,\n };\n }\n\n /** Build notifications config and instance for service with runtime validation (backend-only) */\n // eslint-disable-next-line complexity\n private static async buildNotificationsConfig(\n config: CoreServiceInitConfig,\n entry: CoreServiceEntry\n ): Promise<\n | {\n dedicated: boolean;\n config?: CoreNotificationConfig;\n instance?: CoreNotificationServiceInstance;\n }\n | undefined\n > {\n const dedicatedNotifications = config.dedicatedNotifications;\n const isDedicated =\n dedicatedNotifications === true || typeof dedicatedNotifications === 'object';\n const serviceKey = entry.service.serviceKey;\n\n // Runtime validation: Notifications is backend-only\n const isBackendRuntime = BACKEND_RUNTIMES.includes(ServiceRegistry._runtime);\n\n if ((isDedicated || ServiceRegistry._notificationsConfig) && !isBackendRuntime) {\n ServiceRegistry.logger.warn(\n `Service '${serviceKey}' is requesting notifications injection in '${ServiceRegistry._runtime}' runtime. ` +\n `Notifications is only available in backend runtimes (${BACKEND_RUNTIMES.join(', ')}). ` +\n `This service will not have notifications access.`\n );\n return undefined;\n }\n\n const notificationsConfig: CoreNotificationConfig | undefined = isDedicated\n ? typeof dedicatedNotifications === 'object'\n ? { ...ServiceRegistry._notificationsConfig, ...dedicatedNotifications }\n : (ServiceRegistry._notificationsConfig ?? undefined)\n : (ServiceRegistry._notificationsConfig ?? undefined);\n\n if (!notificationsConfig) {\n return undefined;\n }\n\n const NotificationService = getCoreDependency('NotificationService');\n if (!NotificationService) {\n ServiceRegistry.logger.debug(\n `NotificationService not registered, service '${serviceKey}' will not have notifications`\n );\n return undefined;\n }\n\n // Get or create notifications instance\n let notificationsInstance: CoreNotificationServiceInstance | undefined;\n if (isDedicated && notificationsConfig) {\n try {\n notificationsInstance = await NotificationService.createInstance?.(notificationsConfig);\n ServiceRegistry.logger.debug(\n `Created dedicated notifications instance for service '${serviceKey}'`\n );\n } catch (error) {\n ServiceRegistry.logger.warn(\n `Failed to create dedicated notifications instance for service '${serviceKey}'`,\n { error: error instanceof Error ? error.message : String(error) }\n );\n }\n } else {\n try {\n notificationsInstance = NotificationService.getInstance();\n } catch {\n ServiceRegistry.logger.debug(\n `Global notifications not initialized, service '${serviceKey}' will not have notifications`\n );\n }\n }\n\n return {\n dedicated: isDedicated,\n config: notificationsConfig,\n instance: notificationsInstance,\n };\n }\n\n /**\n * Create a dedicated ObservabilityService instance for a service.\n * Uses the same adapter pattern as global observability but with service-specific config.\n */\n private static async createDedicatedObservability(\n serviceKey: string,\n config: CoreObservabilityConfig\n ): Promise<ObservabilityAdapter | undefined> {\n // Skip if explicitly disabled\n if (config.enabled === false) {\n return undefined;\n }\n\n try {\n // createObservabilityService auto-adds LoggerAdapter as failover\n const dedicatedService = await createObservabilityService({\n mode: config.mode ?? 'parallel',\n serviceName: `${config.serviceName ?? 'service'}-${serviceKey}`,\n environment: config.environment,\n adapters: config.adapters,\n });\n\n ServiceRegistry.logger.debug(\n `Created dedicated ObservabilityService for service '${serviceKey}'`\n );\n\n return dedicatedService;\n } catch (err) {\n ServiceRegistry.logger.warn(\n `Failed to create dedicated observability for '${serviceKey}', falling back to global`,\n { error: err instanceof Error ? err.message : String(err) }\n );\n return ServiceRegistry._observabilityInstance ?? undefined;\n }\n }\n\n /**\n * Set the global observability adapter instance.\n * Called by Core.initialize() after creating the adapter.\n */\n static setObservabilityInstance(instance: ObservabilityAdapter): void {\n ServiceRegistry._observabilityInstance = instance;\n ServiceRegistry.logger.debug('Global observability instance set');\n }\n\n /**\n * Get the global observability adapter instance.\n */\n static getObservabilityInstance(): ObservabilityAdapter | null {\n return ServiceRegistry._observabilityInstance;\n }\n\n /**\n * Initialize a single service from an entry.\n * Uses the service class's static create() method.\n * Merges per-service config with global config.\n */\n private static async initializeService(\n entry: CoreServiceEntry,\n storeSingleton = true\n ): Promise<CoreDomainServiceInstance> {\n const { service: ServiceClass, config } = entry;\n const serviceKey = ServiceClass.serviceKey;\n const isSingleton = config.singleton !== false;\n\n // For singletons, check for concurrent initialization\n if (storeSingleton && isSingleton) {\n const existingPromise = ServiceRegistry._initPromises.get(serviceKey);\n if (existingPromise) return existingPromise;\n }\n\n const initPromise = ServiceRegistry.doInitializeService(entry, { isSingleton, storeSingleton });\n\n if (storeSingleton && isSingleton) {\n ServiceRegistry._initPromises.set(serviceKey, initPromise);\n }\n\n return initPromise;\n }\n\n /** Build stores for service injection */\n private static buildStoresForService(\n config: CoreServiceInitConfig\n ): Partial<RootStoreSlice> | undefined {\n const allKeys = new Set<keyof RootStoreSlice>();\n\n // Add primary store\n if (config.store) {\n allKeys.add(config.store);\n }\n\n // Add read stores\n if (config.readStores) {\n config.readStores.forEach(key => allKeys.add(key));\n }\n\n if (allKeys.size === 0) {\n return undefined;\n }\n\n if (!ServiceRegistry._storeRegistry) {\n ServiceRegistry.logger.warn('Store registry not initialized, cannot inject stores');\n return undefined;\n }\n\n const stores: Partial<RootStoreSlice> = {};\n for (const key of allKeys) {\n const store = ServiceRegistry._storeRegistry.getStore(key);\n if (store) {\n (stores as Record<keyof RootStoreSlice, unknown>)[key] = store;\n ServiceRegistry.logger.debug(`Injected store '${key}' into service`);\n } else {\n ServiceRegistry.logger.warn(`Store '${key}' requested but not found in registry`);\n }\n }\n\n return Object.keys(stores).length > 0 ? stores : undefined;\n }\n\n /** Perform the actual service initialization */\n // eslint-disable-next-line complexity\n private static async doInitializeService(\n entry: CoreServiceEntry,\n options: { isSingleton: boolean; storeSingleton: boolean }\n ): Promise<CoreDomainServiceInstance> {\n const { service: serviceClass, config } = entry;\n const serviceKey = serviceClass.serviceKey;\n const { isSingleton, storeSingleton } = options;\n\n try {\n ServiceRegistry.logger.debug(`Initializing service: ${serviceKey}`);\n\n // Build dependencies (async operations) with runtime validation\n const apiClient = await ServiceRegistry.buildApiClientOptions(config, entry);\n const db = await ServiceRegistry.buildDbConfig(config, entry);\n const cache = await ServiceRegistry.buildCacheConfig(config, entry);\n const observability = ServiceRegistry.buildObservabilityConfig(config, entry);\n const storage = await ServiceRegistry.buildStorageConfig(config, entry);\n const notifications = await ServiceRegistry.buildNotificationsConfig(config, entry);\n const stores = ServiceRegistry.buildStoresForService(config);\n\n // Create dedicated observability instance if requested\n let observabilityInstance = observability?.instance;\n if (observability?.dedicated && observability.config) {\n observabilityInstance = await ServiceRegistry.createDedicatedObservability(\n serviceKey,\n observability.config\n );\n }\n\n const createOptions: CoreServiceCreateOptions = {\n apiClient,\n db,\n cache,\n observability: observability\n ? { ...observability, instance: observabilityInstance }\n : undefined,\n storage,\n notifications,\n injected: {\n ...(stores ? { stores } : {}),\n cache: cache?.instance,\n db: db?.instance,\n api: apiClient?.instance,\n observability: observabilityInstance,\n storage: storage?.instance,\n notifications: notifications?.instance,\n },\n isSingleton,\n };\n\n ServiceRegistry.logger.debug(`Service ${serviceKey} config:`, {\n apiClientDedicated: createOptions.apiClient?.dedicated,\n dbDedicated: createOptions.db?.dedicated,\n observabilityDedicated: createOptions.observability?.dedicated,\n storageDedicated: createOptions.storage?.dedicated,\n notificationsDedicated: createOptions.notifications?.dedicated,\n injected: {\n hasCache: !!createOptions.injected?.cache,\n hasDb: !!createOptions.injected?.db,\n hasApi: !!createOptions.injected?.api,\n hasObservability: !!createOptions.injected?.observability,\n hasStorage: !!createOptions.injected?.storage,\n hasNotifications: !!createOptions.injected?.notifications,\n hasStores: !!createOptions.injected?.stores,\n },\n });\n\n const instance = await serviceClass.create(config, createOptions);\n\n if (storeSingleton && isSingleton) {\n ServiceRegistry._services.set(serviceKey, instance);\n ServiceRegistry.logger.info(`Service initialized: ${serviceKey} (singleton)`);\n } else {\n ServiceRegistry.logger.info(`Service created: ${serviceKey} (instance)`);\n }\n\n return instance;\n } catch (error) {\n ServiceRegistry.logger.error(`Failed to initialize service: ${serviceKey}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n if (storeSingleton && isSingleton) {\n ServiceRegistry._initPromises.delete(serviceKey);\n }\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Disposal\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Dispose a specific service by key.\n *\n * @param key - Service key to dispose\n */\n static dispose(key: string): void {\n const service = ServiceRegistry._services.get(key);\n if (service) {\n service.dispose();\n ServiceRegistry._services.delete(key);\n ServiceRegistry.logger.info(`Service disposed: ${key}`);\n }\n ServiceRegistry._pending.delete(key);\n }\n\n /**\n * Dispose all services and clear the registry.\n */\n static disposeAll(): void {\n // Dispose all initialized services\n for (const [key, service] of ServiceRegistry._services) {\n try {\n service.dispose();\n ServiceRegistry.logger.debug(`Disposed service: ${key}`);\n } catch (error) {\n ServiceRegistry.logger.error(`Error disposing service: ${key}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Clear all state\n ServiceRegistry._services.clear();\n ServiceRegistry._pending.clear();\n ServiceRegistry._metadata.clear();\n ServiceRegistry._initPromises.clear();\n ServiceRegistry._apiClientOptions = null;\n ServiceRegistry._dbConfig = null;\n ServiceRegistry._cacheConfig = null;\n ServiceRegistry._observabilityConfig = null;\n ServiceRegistry._observabilityInstance = null;\n ServiceRegistry._storageConfig = null;\n ServiceRegistry._notificationsConfig = null;\n\n ServiceRegistry.logger.info('Service registry disposed');\n }\n\n /**\n * Check if a service is configured as singleton.\n *\n * @param key - Service key\n * @returns true if singleton (default), false if non-singleton\n */\n static isSingleton(key: string): boolean {\n const metadata = ServiceRegistry._metadata.get(key);\n return metadata?.isSingleton ?? true;\n }\n\n /**\n * Get all non-singleton service keys.\n * These services must be created via `create()` method.\n */\n static getNonSingletonKeys(): string[] {\n return [...ServiceRegistry._metadata.entries()]\n .filter(([, meta]) => !meta.isSingleton)\n .map(([key]) => key);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Dynamic Registration\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Register a new service dynamically after initialization.\n *\n * @param entry - Service entry to register\n * @param initNow - Whether to initialize immediately (default: true)\n *\n * @example\n * ```typescript\n * // Register and initialize immediately\n * await ServiceRegistry.register({\n * service: NewDomainService,\n * config: { enabled: true },\n * });\n *\n * // Register for lazy initialization\n * ServiceRegistry.register({\n * service: LazyService,\n * config: { enabled: true, initWhen: 'lazy' },\n * }, false);\n * ```\n */\n static async register(entry: CoreServiceEntry, initNow = true): Promise<void> {\n const serviceKey = entry.service.serviceKey;\n\n // Check if already registered\n if (ServiceRegistry._services.has(serviceKey) || ServiceRegistry._pending.has(serviceKey)) {\n ServiceRegistry.logger.warn(`Service '${serviceKey}' is already registered`);\n return;\n }\n\n const initWhen = entry.config.initWhen ?? 'immediate';\n\n if (initNow && initWhen === 'immediate') {\n await ServiceRegistry.initializeService(entry);\n } else {\n ServiceRegistry._pending.set(serviceKey, { entry, initWhen });\n ServiceRegistry.logger.debug(\n `Service ${serviceKey} registered for ${initWhen} initialization`\n );\n }\n }\n\n /**\n * Unregister a service (dispose if initialized).\n *\n * @param key - Service key to unregister\n */\n static unregister(key: string): void {\n ServiceRegistry.dispose(key);\n }\n}\n","/**\n * Runtime Detection Utilities\n *\n * Utilities for detecting the current JavaScript runtime environment.\n */\n\nimport type { CoreRuntimeEnvironment } from '@plyaz/types/core';\nimport { PackageLogger } from '@plyaz/logger';\n\nconst logger = new PackageLogger({ packageName: 'core', service: 'Runtime' });\n\n/**\n * Check if a module is available via require.resolve\n */\nfunction isModuleAvailable(moduleName: string): boolean {\n const nodeRequire = globalThis.require;\n if (!nodeRequire) return false;\n\n const resolveModule = nodeRequire.resolve;\n if (!resolveModule) return false;\n\n try {\n resolveModule(moduleName);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Check for alternative runtimes (Deno, Bun) */\nfunction detectAltRuntime(): CoreRuntimeEnvironment | null {\n if (typeof globalThis.Deno !== 'undefined') return 'deno';\n if (typeof globalThis.Bun !== 'undefined') return 'bun';\n return null;\n}\n\n/** Check for edge runtime */\nfunction detectEdgeRuntime(): CoreRuntimeEnvironment | null {\n if (typeof globalThis.EdgeRuntime !== 'undefined') return 'edge';\n const isEdgeLike =\n typeof globalThis.caches !== 'undefined' &&\n typeof globalThis.Request !== 'undefined' &&\n typeof process === 'undefined';\n return isEdgeLike ? 'edge' : null;\n}\n\n/** Check for browser environment */\nfunction detectBrowser(): CoreRuntimeEnvironment | null {\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n return 'browser';\n }\n return null;\n}\n\n/** Check for Node.js framework */\nfunction detectNodeFramework(): CoreRuntimeEnvironment {\n // Check for Nuxt (SSR)\n if (process.env.__NUXT__ || process.env.NUXT_APP) return 'nuxt';\n // Check for Next.js (SSR)\n if (process.env.__NEXT_PRIVATE_ORIGIN || process.env.NEXT_RUNTIME) return 'nextjs';\n // Check for NestJS via module detection\n if (isModuleAvailable('@nestjs/core')) return 'nestjs';\n // Check for Express via module detection\n if (isModuleAvailable('express')) return 'express';\n return 'node';\n}\n\n/**\n * Detect the current runtime environment\n */\nexport function detectRuntime(): CoreRuntimeEnvironment {\n // Check alternative runtimes first\n const altRuntime = detectAltRuntime();\n if (altRuntime) return altRuntime;\n\n // Check for edge runtime\n const edgeRuntime = detectEdgeRuntime();\n if (edgeRuntime) return edgeRuntime;\n\n // Check for browser\n const browser = detectBrowser();\n if (browser) return browser;\n\n // Server-side detection (Node.js based)\n if (typeof process !== 'undefined' && process.versions?.node) {\n return detectNodeFramework();\n }\n\n return 'unknown';\n}\n\n/**\n * Load environment variables from a .env file\n */\nexport async function loadEnvFile(envPath: string, verbose?: boolean): Promise<void> {\n try {\n const dotenv = await import('dotenv');\n const result = dotenv.config({ path: envPath });\n\n if (result.error) {\n logger.warn(`Failed to load env file: ${result.error.message}`);\n } else if (verbose) {\n logger.info(`Loaded env from: ${envPath}`);\n }\n } catch {\n logger.warn('dotenv not available, skipping .env file loading');\n }\n}\n","// This eslint disable is an edge-case as we need to ensure that we're able to load CoreInitializer regardless if FE, BE or specific frameworks\n/**\n * CoreInitializer - Unified initialization for @plyaz/core\n *\n * Provides a single entry point to initialize all core services with\n * environment-aware configuration. Works across all JavaScript runtimes.\n *\n * @example Backend with full config\n * ```typescript\n * import { Core } from '@plyaz/core';\n *\n * await Core.initialize({\n * envPath: '.env',\n * db: { adapter: 'drizzle' },\n * api: {\n * env: 'production',\n * baseURL: 'https://api.example.com',\n * },\n * });\n *\n * // Access services\n * const db = Core.db;\n * const api = Core.api;\n * ```\n *\n * @example Frontend (Nuxt/Next.js)\n * ```typescript\n * import { Core } from '@plyaz/core';\n *\n * await Core.initialize({\n * skipDb: true,\n * api: { baseURL: 'https://api.example.com' },\n * });\n *\n * const api = Core.api;\n * ```\n *\n * @example NestJS with DI\n * ```typescript\n * // app.module.ts\n * import { CoreModule } from '@plyaz/core/adapters';\n * import { FeatureFlagModule } from '@plyaz/core/backend/featureFlags';\n *\n * @Module({\n * imports: [\n * CoreModule.forRoot({ envPath: '.env', db: { adapter: 'drizzle' } }),\n * FeatureFlagModule.forRoot({ provider: 'database' }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n\nimport { PackageLogger } from '@plyaz/logger';\nimport { ApiClientService } from '../services/ApiClientService';\nimport { CoreEventManager } from '../events/CoreEventManager';\nimport { ServiceRegistry } from './ServiceRegistry';\nimport type {\n CoreRuntimeEnvironment,\n CoreRuntimeContext,\n CoreEnvVars,\n CoreAppEnvironment,\n CoreAppContext,\n CoreApiInitOptions,\n CoreServiceRuntime,\n CoreInitOptions as BaseCoreInitOptions,\n CoreServicesResultBase,\n CoreServiceEntry,\n CoreDomainServiceInstance,\n CoreSystemErrorPayload,\n CoreFeatureFlagInitConfig,\n CoreErrorHandlerInitConfig,\n CoreCacheConfig,\n CoreObservabilityConfig,\n CoreDbServiceConfig,\n CoreStorageConfig,\n CoreNotificationConfig,\n // Service instance types (from @plyaz/types, not backend modules)\n CoreDbServiceInstance,\n CoreCacheServiceInstance,\n CoreStorageServiceInstance,\n CoreNotificationServiceInstance,\n} from '@plyaz/types/core';\nimport type { ObservabilityAdapter } from '@plyaz/types/observability';\nimport { ObservabilityService } from '../base/observability/ObservabilityService';\nimport { LoggerAdapter } from '../base/observability/LoggerAdapter';\nimport type { FeatureFlagValue, FeatureFlagStoreSlice } from '@plyaz/types/features';\nimport { ERROR_CODES, BACKEND_RUNTIMES, FRONTEND_RUNTIMES } from '@plyaz/types';\nimport { BaseError, CorePackageError, initializeErrorSystem } from '@plyaz/errors';\n// Core error handling (frontend-safe)\nimport {\n initializeGlobalErrorHandler,\n setEventEmitter,\n clearEventEmitter,\n} from '@plyaz/errors/middleware';\n// ServerErrorMiddleware is backend-only, import dynamically where needed\nimport type { ErrorStoreActions, GlobalErrorHandler } from '@plyaz/types/errors';\nimport { detectRuntime, loadEnvFile } from '../utils/runtime';\nimport {\n createStandaloneFeatureFlagStore,\n useRootStore,\n STORE_KEYS,\n type StoreKey,\n} from '@plyaz/store';\nimport { CORE_EVENTS, type CoreEvent } from '@plyaz/types/core';\nimport type { RootStoreSlice } from '@plyaz/types/store';\nimport type { StoreApi } from 'zustand/vanilla';\nimport { getCoreDependency } from '../config/dependencies';\n\n// Constants\nconst DEFAULT_MAX_ERRORS = 100;\n\n/**\n * Core initialization options with specific types for this package\n */\nexport interface CoreInitOptions\n extends Omit<\n BaseCoreInitOptions<\n Partial<CoreDbServiceConfig>,\n CoreApiInitOptions,\n CoreCacheConfig,\n CoreStorageConfig,\n CoreNotificationConfig\n >,\n 'observability' | 'skipObservability'\n > {\n /** Observability configuration */\n observability?: CoreObservabilityConfig;\n /** Skip observability initialization */\n skipObservability?: boolean;\n /**\n * Global error handler configuration.\n * Auto-initializes by default to catch all uncaught errors.\n * Set `enabled: false` to disable if you want to use your own error handling.\n *\n * @example\n * ```typescript\n * await Core.initialize({\n * errorHandler: {\n * enabled: true,\n * logToConsole: true,\n * maxErrors: 200,\n * filter: (error) => error instanceof MyError,\n * },\n * });\n * ```\n */\n errorHandler?: CoreErrorHandlerInitConfig;\n\n /** Feature flags configuration */\n featureFlags?: CoreFeatureFlagInitConfig;\n\n /**\n * Domain services to auto-initialize (frontend pattern).\n * Uses ServiceRegistry for automatic initialization.\n *\n * @example\n * ```typescript\n * await Core.initialize({\n * services: [\n * { service: FeatureFlagDomainService, config: { enabled: true } },\n * { service: ExampleDomainService, config: { enabled: true, useRealApi: true } },\n * ],\n * });\n *\n * // Access via ServiceRegistry\n * const flags = ServiceRegistry.get<FeatureFlagDomainService>('featureFlags');\n * ```\n */\n services?: CoreServiceEntry[];\n}\n\n/**\n * Core initialization result with specific types for this package\n */\nexport type CoreServicesResult = CoreServicesResultBase<\n CoreDbServiceInstance,\n typeof ApiClientService,\n CoreCacheServiceInstance,\n ObservabilityAdapter,\n CoreStorageServiceInstance,\n CoreNotificationServiceInstance\n>;\n\n// Domain store keys are automatically derived from STORE_KEYS\n// Excluding global stores (error, featureFlags) which are read-only by default\n\n/**\n * Function type for getting core domain services.\n * Used by entry points to inject runtime-appropriate services.\n *\n * @internal This is injected by entry points, not used directly.\n */\nexport type GetCoreDomainServicesFn = (isFrontend: boolean) => Promise<CoreServiceEntry[]>;\n\n/**\n * Injected function to get core domain services.\n * Set by entry points (entry-backend.ts) before Core.initialize().\n * Frontend entries don't set this - they just don't load default services.\n */\nlet _getCoreDomainServices: GetCoreDomainServicesFn | null = null;\n\n/**\n * Set the function to get core domain services.\n * Called by entry-backend.ts to inject the backend-aware service loader.\n *\n * @internal Used by entry points only.\n */\nexport function setGetCoreDomainServices(fn: GetCoreDomainServicesFn): void {\n _getCoreDomainServices = fn;\n}\n\nexport class Core {\n private static initialized = false;\n private static _coreServices: CoreServicesResult = {\n db: null,\n api: null,\n cache: null,\n observability: null,\n storage: null,\n notifications: null,\n env: {},\n runtime: 'unknown',\n appContext: 'webapp',\n };\n\n /**\n * Logger for Core initialization (created lazily)\n */\n private static _logger: PackageLogger | null = null;\n\n /**\n * Logger transport config (set during initialize)\n */\n private static _loggerTransport: 'pino' | 'console' = 'pino';\n\n /**\n * Get or create the Core logger\n */\n private static get logger(): PackageLogger {\n Core._logger ??= new PackageLogger({\n packageName: 'core',\n service: 'Core',\n transport: Core._loggerTransport,\n });\n return Core._logger;\n }\n\n /**\n * Configure logger transport (call before first log)\n */\n private static configureLogger(transport?: 'pino' | 'console'): void {\n if (transport && transport !== Core._loggerTransport) {\n Core._loggerTransport = transport;\n // Reset logger so it gets recreated with new transport\n Core._logger = null;\n }\n }\n\n /**\n * Log a message during initialization.\n * Uses PackageLogger, respects verbose flag.\n */\n private static log(message: string, verbose?: boolean, data?: Record<string, unknown>): void {\n if (!verbose) return;\n if (data) {\n Core.logger.info(message, data);\n } else {\n Core.logger.info(message);\n }\n }\n\n /**\n * Log a debug message during initialization.\n */\n private static logDebug(\n message: string,\n verbose?: boolean,\n data?: Record<string, unknown>\n ): void {\n if (!verbose) return;\n if (data) {\n Core.logger.debug(message, data);\n } else {\n Core.logger.debug(message);\n }\n }\n\n /**\n * Observability configuration\n */\n private static _observabilityConfig: CoreObservabilityConfig = {};\n\n /**\n * Global error handler instance\n */\n private static _errorHandler: GlobalErrorHandler | null = null;\n\n /**\n * Error handler configuration\n */\n private static _errorConfig: CoreErrorHandlerInitConfig = {};\n\n /**\n * HTTP error handler/middleware based on runtime.\n * Auto-created during initialization.\n */\n private static _httpErrorHandler: unknown = null;\n\n /**\n * Event listener cleanup functions\n */\n private static _eventCleanupFns: (() => void)[] = [];\n\n /**\n * Feature flag configuration\n */\n private static _flagConfig: CoreFeatureFlagInitConfig = {};\n\n /**\n * Root store instance (contains errors, feature flags, and all other slices)\n * Initialized during Core.initialize() - frontend uses React hook store, backend uses vanilla store\n * All store access should go through Core.rootStore - no separate stores needed\n */\n private static _rootStore: StoreApi<RootStoreSlice> | null = null;\n\n /**\n * Setup environment and context\n */\n private static async setupEnvironment(options: CoreInitOptions): Promise<CoreAppEnvironment> {\n const { envPath, environment, appContext, env, verbose } = options;\n\n Core._coreServices.appContext = appContext ?? 'webapp';\n Core.log(`App context: ${Core._coreServices.appContext}`, verbose);\n\n const globalEnvironment: CoreAppEnvironment =\n environment ?? (process.env.NODE_ENV as CoreAppEnvironment) ?? 'development';\n Core.log(`Global environment: ${globalEnvironment}`, verbose);\n\n Core._coreServices.runtime = detectRuntime();\n Core.log(`Detected runtime: ${Core._coreServices.runtime}`, verbose);\n\n if (envPath) await loadEnvFile(envPath, verbose);\n Core._coreServices.env = { ...process.env, ...env };\n\n return globalEnvironment;\n }\n\n /**\n * Initialize a service with error handling\n */\n private static async initService<T>(\n name: string,\n init: () => Promise<T>,\n verbose?: boolean\n ): Promise<T | undefined> {\n try {\n return await init();\n } catch (error) {\n Core.logger.error(`Failed to initialize ${name}`, { error: (error as Error).message });\n if (verbose) Core.logger.error('Full error', { error });\n return undefined;\n }\n }\n\n /** Initialize error handler if enabled */\n private static async initErrorHandlerIfEnabled(options: CoreInitOptions): Promise<void> {\n const { errorHandler: config, verbose } = options;\n if (config?.enabled === false) {\n Core.log('Global error handler disabled by configuration', verbose);\n return;\n }\n await Core.initService(\n 'error handler',\n async () => {\n await Core.initializeErrorHandler(config, verbose);\n Core.subscribeToErrorEvents(verbose);\n },\n verbose\n );\n }\n\n /** Initialize API client if not skipped */\n private static async initApiIfEnabled(\n options: CoreInitOptions,\n env: CoreAppEnvironment\n ): Promise<void> {\n const { api: apiConfig, skipApi, verbose } = options;\n if (skipApi) return;\n\n await Core.initService(\n 'API client',\n async () => {\n await Core.initializeApi(apiConfig, env, verbose);\n Core._coreServices.api = ApiClientService;\n Core.log('API client service initialized', verbose);\n },\n verbose\n );\n Core._coreServices.api = ApiClientService;\n }\n\n /** Initialize cache service if not skipped (backend-only due to ioredis dependency) */\n private static async initCacheIfEnabled(options: CoreInitOptions): Promise<void> {\n const { cache: cacheConfig, skipCache, verbose } = options;\n if (skipCache) {\n Core.log('Cache service skipped (skipCache: true)', verbose);\n return;\n }\n\n // Skip cache initialization if no config provided\n if (!cacheConfig) {\n Core.log('Cache service skipped (no config provided)', verbose);\n return;\n }\n\n // Skip on frontend runtimes (CacheService pulls in ioredis which requires Node.js)\n if (Core.isFrontend) {\n Core.log('Cache service skipped (frontend runtime detected)', verbose);\n return;\n }\n\n await Core.initService(\n 'cache',\n async () => {\n await Core.initializeCache(cacheConfig as CoreCacheConfig, verbose);\n const CacheService = getCoreDependency('CacheService');\n if (CacheService) {\n Core._coreServices.cache = CacheService.getInstance();\n Core.log('Cache service initialized', verbose);\n }\n },\n verbose\n );\n }\n\n /** Initialize observability if not skipped */\n private static async initObservabilityIfEnabled(\n options: CoreInitOptions,\n globalEnvironment: CoreAppEnvironment\n ): Promise<void> {\n const { observability: observabilityConfig, skipObservability, verbose } = options;\n if (skipObservability) {\n Core.log('Observability service skipped (skipObservability: true)', verbose);\n return;\n }\n\n // Always use ObservabilityService - it adds LoggerAdapter by default\n const config = observabilityConfig ?? { enabled: true };\n\n await Core.initService(\n 'observability',\n async () => {\n await Core.initializeObservability(config, verbose, globalEnvironment);\n Core.log('Observability service initialized', verbose);\n },\n verbose\n );\n }\n\n /** Initialize storage service if not skipped (backend-only) */\n private static async initStorageIfEnabled(options: CoreInitOptions): Promise<void> {\n const { storage: storageConfig, skipStorage, verbose } = options;\n\n // Skip if explicitly disabled\n if (skipStorage) {\n Core.log('Storage service skipped (skipStorage: true)', verbose);\n return;\n }\n\n // Skip if no config provided\n if (!storageConfig) {\n Core.log('Storage service skipped (no config provided)', verbose);\n return;\n }\n\n // Skip on frontend runtimes (storage is backend-only)\n if (Core.isFrontend) {\n Core.log('Storage service skipped (frontend runtime detected)', verbose);\n return;\n }\n\n await Core.initService(\n 'storage',\n async () => {\n const StorageService = getCoreDependency('StorageService');\n if (!StorageService) {\n Core.log('Storage service skipped (dependency not registered)', verbose);\n return;\n }\n await StorageService.initialize(storageConfig);\n Core._coreServices.storage = StorageService.getInstance();\n Core.log('Storage service initialized', verbose);\n },\n verbose\n );\n }\n\n /** Initialize notifications service if not skipped (backend-only) */\n private static async initNotificationsIfEnabled(options: CoreInitOptions): Promise<void> {\n const { notifications: notificationsConfig, skipNotifications, verbose } = options;\n\n // Skip if explicitly disabled\n if (skipNotifications) {\n Core.log('Notifications service skipped (skipNotifications: true)', verbose);\n return;\n }\n\n // Skip if no config provided\n if (!notificationsConfig) {\n Core.log('Notifications service skipped (no config provided)', verbose);\n return;\n }\n\n // Skip on frontend runtimes (notifications is backend-only)\n if (Core.isFrontend) {\n Core.log('Notifications service skipped (frontend runtime detected)', verbose);\n return;\n }\n\n await Core.initService(\n 'notifications',\n async () => {\n const NotificationService = getCoreDependency('NotificationService');\n if (!NotificationService) {\n Core.log('Notifications service skipped (dependency not registered)', verbose);\n return;\n }\n await NotificationService.initialize(notificationsConfig);\n Core._coreServices.notifications = NotificationService.getInstance();\n Core.log('Notifications service initialized', verbose);\n },\n verbose\n );\n }\n\n /**\n * Initialize domain services\n *\n * Loads core domain services using the injected loader (if available),\n * then merges with any user-provided services.\n * User-provided service configs override core defaults.\n *\n * Note: Frontend entries don't inject a loader, so they only use user-provided services.\n */\n private static async initDomainServicesIfConfigured(\n options: CoreInitOptions,\n globalEnvironment: CoreAppEnvironment\n ): Promise<void> {\n const { api: apiConfig, services: userServices, verbose } = options;\n const runtime = Core._coreServices.runtime;\n\n // Load core services using injected loader (backend sets this, frontend doesn't)\n const coreDomainServices = _getCoreDomainServices\n ? await _getCoreDomainServices(Core.isFrontend)\n : [];\n\n // Merge core services with user-provided services\n // User services can override core service configs by using the same service class\n const coreServiceKeys = new Set(coreDomainServices.map(s => s.service.serviceKey));\n const userOverrides = (userServices ?? []).filter(s =>\n coreServiceKeys.has(s.service.serviceKey)\n );\n const additionalUserServices = (userServices ?? []).filter(\n s => !coreServiceKeys.has(s.service.serviceKey)\n );\n\n // Build merged services: core (with overrides applied) + additional user services\n const mergedServices: CoreServiceEntry[] = coreDomainServices\n .map(coreService => {\n const override = userOverrides.find(\n u => u.service.serviceKey === coreService.service.serviceKey\n );\n return override\n ? { ...coreService, config: { ...coreService.config, ...override.config } }\n : coreService;\n })\n .concat(additionalUserServices);\n\n // Skip if somehow no services\n if (mergedServices.length === 0) return;\n\n await Core.initService(\n 'domain services',\n async () => {\n Core.log('Initializing domain services via ServiceRegistry...', verbose);\n Core.logDebug('Core services', verbose, {\n services: coreDomainServices.map(s => s.service.serviceKey),\n });\n if (userServices?.length) {\n Core.logDebug('User services', verbose, {\n services: userServices.map(s => s.service.serviceKey),\n });\n }\n await ServiceRegistry.initialize({\n environment: globalEnvironment,\n runtime,\n apiClient: apiConfig ? { baseURL: apiConfig.baseURL, ...apiConfig } : undefined,\n services: mergedServices,\n stores: {\n // Returns specific slice from namespaced root store (type-safe)\n getStore: <K extends keyof RootStoreSlice>(key: K): RootStoreSlice[K] | undefined =>\n Core.getDomainStore(key),\n },\n });\n Core.log('Domain services initialized', verbose, {\n keys: ServiceRegistry.getInitializedKeys(),\n });\n },\n verbose\n );\n }\n\n /**\n * Initialize all core services\n */\n\n static async initialize(options: CoreInitOptions = {}): Promise<CoreServicesResult> {\n // Configure logger transport first (before any logs)\n Core.configureLogger(options.logger?.transport);\n\n if (Core.initialized) {\n Core.log('Already initialized, returning existing services', options.verbose);\n return Core._coreServices;\n }\n\n const { db: dbConfig, featureFlags: featureFlagsConfig, skipDb, verbose } = options;\n const globalEnvironment = await Core.setupEnvironment(options);\n\n await Core.initErrorHandlerIfEnabled(options);\n\n if (!Core.shouldSkipDbService(skipDb, verbose)) {\n const db = await Core.initService(\n 'database',\n () => Core.initializeDb(dbConfig, verbose),\n verbose\n );\n Core._coreServices.db = db ?? null;\n }\n\n await Core.initApiIfEnabled(options, globalEnvironment);\n\n await Core.initCacheIfEnabled(options);\n\n await Core.initObservabilityIfEnabled(options, globalEnvironment);\n\n await Core.initStorageIfEnabled(options);\n\n await Core.initNotificationsIfEnabled(options);\n\n if (featureFlagsConfig?.enabled !== false) {\n await Core.initService(\n 'feature flags',\n () => Core.initializeFeatureFlags(featureFlagsConfig, verbose),\n verbose\n );\n }\n\n await Core.initDomainServicesIfConfigured(options, globalEnvironment);\n\n Core.initialized = true;\n Core.log('Initialization complete', verbose);\n return Core._coreServices;\n }\n\n /**\n * Get initialized domain service keys\n * Use Core.getService(key) or ServiceRegistry.get(key) to access individual services.\n *\n * @example\n * ```typescript\n * const keys = Core.serviceKeys;\n * const exampleService = Core.getService('example');\n * ```\n */\n static get serviceKeys(): string[] {\n return ServiceRegistry.getInitializedKeys();\n }\n\n /**\n * All stores - unified access to ALL slices from single root store\n * All stores (global + domain) are slices of ONE Zustand store instance.\n *\n * **Auto-generated from STORE_KEYS** - No manual registration needed!\n *\n * **Benefits:**\n * - ✅ Access without hooks (store.getState())\n * - ✅ Cross-slice subscriptions work automatically\n * - ✅ Single source of truth\n * - ✅ Automatically scales with new stores\n *\n * @example\n * const errorStore = Core.stores.error; // Global slice\n * const flagsStore = Core.stores.featureFlags; // Global slice\n * const exampleStore = Core.stores.example; // Domain slice\n */\n static get stores(): Record<StoreKey, RootStoreSlice | undefined> {\n const rootState = Core._rootStore?.getState();\n\n // Dynamically generate store accessors from STORE_KEYS\n return Object.values(STORE_KEYS).reduce(\n (acc, key) => {\n Object.defineProperty(acc, key, {\n get: () => rootState,\n enumerable: true,\n });\n return acc;\n },\n {} as Record<StoreKey, RootStoreSlice | undefined>\n );\n }\n\n /**\n * Get a specific store slice by key (for ServiceRegistry injection).\n * Returns the actual slice from the namespaced root store.\n *\n * @param key - Store key (type-safe: 'example' | 'errors' | 'featureFlags')\n * @returns Specific store slice or undefined\n *\n * @example\n * ```typescript\n * const exampleSlice = Core.getDomainStore('example'); // ✅ Returns ExampleFrontendStoreSlice\n * const errorSlice = Core.getDomainStore('errors'); // ✅ Returns ErrorStoreSlice\n * const invalid = Core.getDomainStore('invalid'); // ❌ TypeScript error!\n * ```\n */\n static getDomainStore<K extends keyof RootStoreSlice>(key: K): RootStoreSlice[K] | undefined;\n static getDomainStore<T = RootStoreSlice>(): T | undefined;\n static getDomainStore<K extends keyof RootStoreSlice>(\n key?: K\n ): RootStoreSlice[K] | RootStoreSlice | undefined {\n const rootState = Core._rootStore?.getState();\n if (!rootState) return undefined;\n\n // If no key provided, return entire root store\n if (!key) return rootState;\n\n // Return specific slice from namespaced store (type-safe)\n return rootState[key];\n }\n\n /**\n * Event manager for subscribing to domain events\n * @example Core.events.on('example:created', handler)\n */\n static get events(): typeof CoreEventManager {\n return CoreEventManager;\n }\n\n /**\n * Get database service instance\n * @throws Error if not initialized\n */\n static get db(): CoreDbServiceInstance {\n if (!Core._coreServices.db) {\n throw new CorePackageError(\n 'Database service not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.db;\n }\n\n /**\n * Get API client service\n */\n static get api(): typeof ApiClientService {\n if (!Core._coreServices.api) {\n throw new CorePackageError(\n 'API client service not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.api;\n }\n\n /**\n * Get cache service instance (backend-only)\n * @throws Error if not initialized\n */\n static get cache(): CoreCacheServiceInstance {\n if (!Core._coreServices.cache) {\n throw new CorePackageError(\n 'Cache service not initialized. Call Core.initialize() with cache config first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.cache;\n }\n\n /**\n * Get observability adapter instance\n * @throws Error if not initialized\n *\n * @example\n * ```typescript\n * // Record a metric\n * await Core.observability.recordMetric({\n * type: 'counter',\n * name: 'api.requests',\n * value: 1,\n * tags: { endpoint: '/users' },\n * });\n *\n * // Start a span\n * const span = Core.observability.startSpan({ name: 'processOrder' });\n * try {\n * // ... do work\n * span.setStatus('ok');\n * } catch (e) {\n * span.recordException(e);\n * span.setStatus('error');\n * } finally {\n * span.end();\n * }\n * ```\n */\n static get observability(): ObservabilityAdapter {\n if (!Core._coreServices.observability) {\n throw new CorePackageError(\n 'Observability service not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.observability;\n }\n\n /**\n * Check if observability is initialized\n */\n static get isObservabilityInitialized(): boolean {\n return Core._coreServices.observability !== null;\n }\n\n /**\n * Get observability configuration\n */\n static get observabilityConfig(): CoreObservabilityConfig {\n return Core._observabilityConfig;\n }\n\n /**\n * Get storage service instance (backend-only)\n * @throws Error if not initialized\n *\n * @example\n * ```typescript\n * const storage = Core.storage.getStorage();\n * await storage.uploadFile({ file, filename: 'doc.pdf' });\n * ```\n */\n static get storage(): CoreStorageServiceInstance {\n if (!Core._coreServices.storage) {\n throw new CorePackageError(\n 'Storage service not initialized. Call Core.initialize() with storage config first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.storage;\n }\n\n /**\n * Check if storage is initialized\n */\n static get isStorageInitialized(): boolean {\n return Core._coreServices.storage !== null;\n }\n\n /**\n * Get notifications service instance (backend-only)\n * @throws Error if not initialized\n *\n * @example\n * ```typescript\n * const notifications = Core.notifications.getNotifications();\n * await notifications.sendEmail({ to: 'user@example.com', templateId: 'welcome' });\n * ```\n */\n static get notifications(): CoreNotificationServiceInstance {\n if (!Core._coreServices.notifications) {\n throw new CorePackageError(\n 'Notifications service not initialized. Call Core.initialize() with notifications config first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._coreServices.notifications;\n }\n\n /**\n * Check if notifications is initialized\n */\n static get isNotificationsInitialized(): boolean {\n return Core._coreServices.notifications !== null;\n }\n\n /**\n * Get root store (contains all slices: errors, feature flags, etc.)\n * Use this to access the full store state and all slice actions globally.\n *\n * @example\n * ```typescript\n * // Access error actions\n * const state = Core.rootStore.getState();\n * state.addError({ ... });\n *\n * // Access flags\n * console.log(state.flags);\n *\n * // Subscribe to store changes\n * Core.rootStore.subscribe((state) => {\n * console.log('Errors:', state.errors);\n * console.log('Flags:', state.flags);\n * });\n * ```\n */\n static get rootStore(): StoreApi<RootStoreSlice> {\n if (!Core._rootStore) {\n throw new CorePackageError(\n 'Root store not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._rootStore;\n }\n\n /**\n * Get global error store actions.\n * Provides access to the error store for querying and managing errors.\n *\n * @example\n * ```typescript\n * // Get all errors\n * const allErrors = useErrorStore.getState().errors;\n *\n * // Clear all errors\n * Core.errors.clearErrors();\n *\n * // Dismiss an error\n * Core.errors.dismissError(errorId);\n * ```\n */\n static get errors(): ErrorStoreActions {\n if (!Core._errorHandler) {\n throw new CorePackageError(\n 'Error handler not initialized. Call Core.initialize() first or set errorHandler.enabled: true.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._errorHandler.getStore();\n }\n\n /**\n * Get feature flags store\n * Provides synchronous access to feature flag values from the store.\n *\n * @example\n * ```typescript\n * // Check if a flag is enabled\n * const isEnabled = Core.flags.isEnabled('NEW_FEATURE');\n *\n * // Get a flag value\n * const provider = Core.flags.getValue<string>('PAYMENT_PROVIDER');\n *\n * // Refresh flags from source\n * await Core.flags.refresh();\n * ```\n */\n static get flags(): FeatureFlagStoreSlice {\n if (!Core._rootStore) {\n throw new CorePackageError(\n 'Root store not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n // Return the feature flag slice from root store\n // Root store state includes all flag methods (isEnabled, getValue, refresh, etc.)\n return Core._rootStore.getState() as unknown as FeatureFlagStoreSlice;\n }\n\n /**\n * Check if error handler is initialized\n */\n static get isErrorHandlerInitialized(): boolean {\n return Core._errorHandler !== null;\n }\n\n /**\n * Get the HTTP error handler/middleware based on runtime.\n * Returns different types based on detected runtime:\n *\n * - **Express**: Error handler middleware function\n * ```typescript\n * app.use(Core.httpErrorHandler);\n * ```\n *\n * - **NestJS**: Exception filter class\n * ```typescript\n * app.useGlobalFilters(new (Core.httpErrorHandler)());\n * ```\n *\n * - **Next.js**: Object with App Router and Pages Router handlers\n * ```typescript\n * // App Router\n * export const GET = Core.httpErrorHandler.withErrorHandler(handler);\n * // Pages Router\n * export default Core.httpErrorHandler.createNextApiErrorHandler()(handler);\n * ```\n *\n * - **Node.js/Bun/Deno**: Object with handleError and createMiddleware\n * ```typescript\n * Core.httpErrorHandler.handleError(error, req, res);\n * ```\n *\n * - **Browser**: null (no HTTP handler needed)\n *\n * @returns The HTTP error handler for the current runtime\n */\n static get httpErrorHandler(): unknown {\n return Core._httpErrorHandler;\n }\n\n /**\n * Check if feature flags are initialized\n */\n static get isFlagsInitialized(): boolean {\n return Core._rootStore?.getState()?.featureFlags?.isInitialized ?? false;\n }\n\n /**\n * Get error handler configuration\n */\n static get errorConfig(): CoreErrorHandlerInitConfig {\n return Core._errorConfig;\n }\n\n /**\n * Get feature flag configuration\n */\n static get flagConfig(): CoreFeatureFlagInitConfig {\n return Core._flagConfig;\n }\n\n /**\n * Get loaded environment variables\n */\n static get env(): CoreEnvVars {\n return Core._coreServices.env;\n }\n\n /**\n * Get detected runtime environment\n */\n static get runtime(): CoreRuntimeEnvironment {\n return Core._coreServices.runtime;\n }\n\n /**\n * Get current app context\n */\n static get appContext(): CoreAppContext {\n return Core._coreServices.appContext;\n }\n\n /**\n * Check if Core is initialized\n */\n static get isInitialized(): boolean {\n return Core.initialized;\n }\n\n /**\n * Check if running on a backend runtime\n */\n static get isBackend(): boolean {\n return BACKEND_RUNTIMES.includes(Core._coreServices.runtime);\n }\n\n /**\n * Check if running on a frontend runtime\n */\n static get isFrontend(): boolean {\n return FRONTEND_RUNTIMES.includes(Core._coreServices.runtime);\n }\n\n /**\n * Get runtime context (backend, frontend, or universal)\n * Universal means the runtime can be either (SSR frameworks like Next.js, Nuxt, Edge)\n */\n static getRuntimeContext(): CoreRuntimeContext {\n if (BACKEND_RUNTIMES.includes(Core._coreServices.runtime)) {\n return 'backend';\n }\n if (FRONTEND_RUNTIMES.includes(Core._coreServices.runtime)) {\n return 'frontend';\n }\n return 'universal';\n }\n\n /**\n * Assert that the current runtime matches the expected runtime(s)\n * Throws an error if the runtime doesn't match\n *\n * @param expected - Expected runtime(s) to check against\n * @param serviceName - Name of the service for error message\n * @throws CorePackageError if runtime doesn't match\n *\n * @example\n * ```typescript\n * // Assert backend-only\n * Core.assertRuntime('backend', 'DatabaseService');\n *\n * // Assert multiple runtimes\n * Core.assertRuntime(['backend', 'universal'], 'CacheService');\n * ```\n */\n static assertRuntime(\n expected: CoreServiceRuntime | readonly CoreServiceRuntime[],\n serviceName: string\n ): void {\n const runtimes = Array.isArray(expected) ? expected : [expected];\n const currentContext = Core.getRuntimeContext();\n\n // Check if current context matches any of the expected runtimes\n const isAllowed = runtimes.some(runtime => {\n if (runtime === 'universal') return true;\n if (runtime === currentContext) return true;\n // Universal context (SSR) can run both frontend and backend code\n if (currentContext === 'universal') return true;\n return false;\n });\n\n if (!isAllowed) {\n throw new CorePackageError(\n `${serviceName} cannot run in ${currentContext} runtime. ` +\n `Allowed runtimes: ${runtimes.join(', ')}. ` +\n `Current runtime: ${Core._coreServices.runtime}`,\n ERROR_CODES.FEATURE_NOT_SUPPORTED\n );\n }\n }\n\n /**\n * Check if a service runtime is compatible with current runtime\n * Returns true/false instead of throwing\n *\n * @param expected - Expected runtime(s) to check against\n */\n static isRuntimeCompatible(\n expected: CoreServiceRuntime | readonly CoreServiceRuntime[]\n ): boolean {\n const runtimes = Array.isArray(expected) ? expected : [expected];\n const currentContext = Core.getRuntimeContext();\n\n return runtimes.some(runtime => {\n if (runtime === 'universal') return true;\n if (runtime === currentContext) return true;\n if (currentContext === 'universal') return true;\n return false;\n });\n }\n\n /**\n * Get a registered domain service by key.\n * Convenience method that wraps ServiceRegistry.get().\n *\n * @param key - Service key (e.g., 'featureFlags', 'example')\n * @returns The service instance\n *\n * @example\n * ```typescript\n * const flags = Core.getService<FeatureFlagDomainService>('featureFlags');\n * const isEnabled = await flags.isEnabled('my-flag');\n * ```\n */\n static getService<T extends CoreDomainServiceInstance = CoreDomainServiceInstance>(\n key: string\n ): T {\n return ServiceRegistry.get<T>(key);\n }\n\n /**\n * Get a registered domain service by key with async initialization if needed.\n * Convenience method that wraps ServiceRegistry.getAsync().\n *\n * @param key - Service key\n * @returns Promise resolving to the service instance\n */\n static async getServiceAsync<T extends CoreDomainServiceInstance = CoreDomainServiceInstance>(\n key: string\n ): Promise<T> {\n return ServiceRegistry.getAsync<T>(key);\n }\n\n /**\n * Check if a domain service is registered.\n */\n static hasService(key: string): boolean {\n return ServiceRegistry.has(key);\n }\n\n /**\n * Reset Core (useful for testing)\n */\n // eslint-disable-next-line complexity\n static async reset(): Promise<void> {\n // Close database\n if (Core._coreServices.db) {\n await Core._coreServices.db.getDatabase()?.close?.();\n }\n\n // Dispose cache\n if (Core._coreServices.cache) {\n const CacheService = getCoreDependency('CacheService');\n CacheService?.reset?.();\n }\n\n // Dispose observability\n if (Core._coreServices.observability) {\n await Core._coreServices.observability.shutdown();\n }\n Core._observabilityConfig = {};\n\n // Dispose storage\n if (Core._coreServices.storage) {\n await Core._coreServices.storage.close();\n const StorageService = getCoreDependency('StorageService');\n await StorageService?.reset?.();\n }\n\n // Dispose notifications\n if (Core._coreServices.notifications) {\n await Core._coreServices.notifications.close();\n const NotificationService = getCoreDependency('NotificationService');\n await NotificationService?.reset?.();\n }\n\n // Dispose error handler\n if (Core._errorHandler) {\n Core._errorHandler.destroy();\n Core._errorHandler = null;\n clearEventEmitter(); // Clean up CoreEventManager integration\n }\n Core._errorConfig = {};\n Core._httpErrorHandler = null;\n\n // Cleanup event listeners\n for (const cleanup of Core._eventCleanupFns) {\n cleanup();\n }\n Core._eventCleanupFns = [];\n\n // Dispose feature flags slice from root store\n if (Core._rootStore) {\n const state = Core._rootStore.getState();\n if (state.featureFlags?.dispose) {\n state.featureFlags.dispose();\n }\n Core._rootStore = null;\n }\n Core._flagConfig = {};\n\n // Dispose all registered services via ServiceRegistry\n ServiceRegistry.disposeAll();\n\n // Dispose event manager\n CoreEventManager.dispose();\n\n Core._coreServices = {\n db: null,\n api: null,\n cache: null,\n observability: null,\n storage: null,\n notifications: null,\n env: {},\n runtime: 'unknown',\n appContext: 'webapp',\n };\n Core.initialized = false;\n }\n\n /**\n * Determines whether to skip DbService initialization.\n *\n * DbService is backend-only and should never be initialized on frontend runtimes.\n * This method:\n * - Returns true (skip) if skipDb was explicitly set to true\n * - Returns true (skip) if running on frontend, with a warning\n * - Warns if someone explicitly tried to init DbService on frontend (skipDb: false)\n *\n * @param skipDb - User-provided skipDb option\n * @param verbose - Enable verbose logging\n * @returns true if DbService should be skipped\n */\n private static shouldSkipDbService(skipDb: boolean | undefined, verbose?: boolean): boolean {\n // User explicitly requested to skip\n if (skipDb === true) {\n Core.log('Database service skipped (skipDb: true)', verbose);\n return true;\n }\n\n // Check if running on frontend\n const isFrontend = Core.isFrontend;\n\n if (isFrontend) {\n // User explicitly tried to init DbService on frontend (skipDb: false)\n if (skipDb === false) {\n Core.logger.warn(\n 'DbService cannot be initialized on frontend runtime. ' +\n 'DbService is backend-only and requires Node.js. ' +\n 'Use API calls from frontend instead. Skipping database initialization.'\n );\n } else if (verbose) {\n // skipDb was undefined (default) - just log that we're skipping\n Core.log(\n 'Database service skipped (frontend runtime detected). ' +\n 'DbService is only available on backend.',\n verbose\n );\n }\n return true;\n }\n\n // Backend or universal runtime - don't skip\n return false;\n }\n\n /**\n * Initialize database service\n * Config validation is handled by DbService\n */\n private static async initializeDb(\n config?: Partial<CoreDbServiceConfig>,\n verbose?: boolean\n ): Promise<CoreDbServiceInstance> {\n Core.log(`Initializing database with adapter: ${config?.adapter ?? 'drizzle'}`, verbose);\n\n const DbService = getCoreDependency('DbService');\n if (!DbService) {\n throw new CorePackageError(\n 'DbService not available. Ensure setCoreDependencies() was called in entry-backend.ts',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return DbService.initialize({\n adapter: 'drizzle',\n ...config,\n } as CoreDbServiceConfig);\n }\n\n /**\n * Initialize API client service\n * Config validation is handled by ApiClientService\n */\n private static async initializeApi(\n config?: CoreApiInitOptions,\n globalEnvironment?: CoreAppEnvironment,\n verbose?: boolean\n ): Promise<void> {\n const { env: apiEnv, setAsDefault, ...apiClientOptions } = config ?? {};\n const resolvedEnv = apiEnv ?? globalEnvironment ?? 'development';\n\n Core.log(`Initializing API client for environment: ${resolvedEnv}`, verbose);\n\n await ApiClientService.init(\n {\n env: resolvedEnv,\n setAsDefault: setAsDefault ?? true,\n },\n apiClientOptions\n );\n }\n\n /**\n * Initialize cache service (backend-only)\n * Config validation is handled by CacheService\n */\n private static async initializeCache(config: CoreCacheConfig, verbose?: boolean): Promise<void> {\n Core.log(`Initializing cache with strategy: ${config.strategy}`, verbose);\n\n const CacheService = getCoreDependency('CacheService');\n if (!CacheService) {\n throw new CorePackageError(\n 'CacheService not available. Ensure setCoreDependencies() was called in entry-backend.ts',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n await CacheService.initialize(config);\n }\n\n /**\n * Initialize observability service based on config.\n * Always includes LoggerAdapter as failover for console output.\n */\n private static async initializeObservability(\n config: CoreObservabilityConfig,\n verbose?: boolean,\n environment?: CoreAppEnvironment\n ): Promise<void> {\n Core.log(`Initializing observability with provider: ${config.provider ?? 'auto'}`, verbose);\n\n // Use environment from config or passed parameter\n const env = config.environment ?? environment ?? 'development';\n Core._observabilityConfig = { ...config, environment: env };\n\n // Collect adapters with priorities\n const adapters: { adapter: ObservabilityAdapter; priority: number; failover?: boolean }[] = [];\n\n // Always add LoggerAdapter as failover for console output\n const loggerAdapter = new LoggerAdapter();\n await loggerAdapter.initialize({\n enabled: config.enabled !== false,\n serviceName: config.serviceName,\n environment: env,\n defaultTags: config.defaultTags,\n });\n adapters.push({ adapter: loggerAdapter, priority: -100, failover: true });\n\n // TODO: Add DatadogAdapter when configured (high priority, primary)\n // if (config.provider === 'datadog' || config.datadog) {\n // const datadogAdapter = new DatadogAdapter();\n // await datadogAdapter.initialize({\n // ...config,\n // ...config.datadog,\n // environment: env,\n // });\n // adapters.push({ adapter: datadogAdapter, priority: 100, failover: false });\n // }\n\n // Create ObservabilityService with all adapters\n const observability = new ObservabilityService();\n await observability.initialize({\n mode: config.mode ?? 'parallel',\n adapters,\n enabled: config.enabled,\n serviceName: config.serviceName,\n environment: env,\n defaultTags: config.defaultTags,\n samplingRate: config.samplingRate,\n flushInterval: config.flushInterval,\n adapterTimeout: config.flushInterval,\n });\n\n Core.log(\n `ObservabilityService initialized with ${adapters.length} adapters (env: ${env})`,\n verbose\n );\n\n Core._coreServices.observability = observability;\n // Set on ServiceRegistry for injection\n ServiceRegistry.setObservabilityInstance(observability);\n }\n\n /**\n * Initialize global error handler\n */\n /** Create and initialize root store (includes error store + all other slices) */\n private static async initializeRootStore(\n config?: CoreErrorHandlerInitConfig,\n verbose?: boolean\n ): Promise<void> {\n const isFrontend = typeof window !== 'undefined';\n\n if (isFrontend) {\n Core.log('Using frontend root store (Zustand)', verbose);\n // Frontend: use the React hook store's vanilla store API\n Core._rootStore = useRootStore as unknown as StoreApi<RootStoreSlice>;\n } else {\n Core.log('Creating backend composite store (in-memory)', verbose);\n const ServerErrorMiddleware = getCoreDependency('ServerErrorMiddleware');\n if (!ServerErrorMiddleware) {\n throw new CorePackageError(\n 'ServerErrorMiddleware not available. Ensure setCoreDependencies() was called in entry-backend.ts',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n // Backend: create in-memory error store + feature flag store (NOT Zustand)\n const backendErrorStore = ServerErrorMiddleware.createErrorStore({\n maxErrors: config?.maxErrors ?? DEFAULT_MAX_ERRORS,\n onErrorAdded: config?.onError as ((error: unknown) => void) | undefined,\n });\n\n // Create standalone feature flag store for backend\n const backendFlagStore = createStandaloneFeatureFlagStore();\n\n // Combine error + feature flag stores to match RootStoreSlice interface\n const compositeStore = {\n // Error store methods\n ...backendErrorStore,\n // Feature flag store methods\n ...backendFlagStore,\n };\n\n // Wrap backend composite store to match root store interface (getState() pattern)\n Core._rootStore = {\n getState: () => compositeStore,\n subscribe: () => () => {}, // No-op for backend\n destroy: () => {\n backendErrorStore.reset();\n backendFlagStore.dispose?.();\n },\n } as unknown as StoreApi<RootStoreSlice>;\n }\n }\n\n /** Get error store actions from root store */\n private static getErrorStoreActions(): ErrorStoreActions {\n if (!Core._rootStore) {\n throw new CorePackageError(\n 'Root store not initialized. Call Core.initialize() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n return Core._rootStore.getState().errors;\n }\n\n /** Build global error handler config */\n // eslint-disable-next-line complexity\n private static buildErrorHandlerConfig(\n config?: CoreErrorHandlerInitConfig\n ): Parameters<typeof initializeGlobalErrorHandler>[1] {\n return {\n source: config?.source ?? 'global',\n maxErrors: config?.maxErrors ?? DEFAULT_MAX_ERRORS,\n filter: config?.filter,\n onError: config?.onError,\n logToConsole: config?.logToConsole ?? false,\n };\n }\n\n // eslint-disable-next-line complexity\n private static async initializeErrorHandler(\n config?: CoreErrorHandlerInitConfig,\n verbose?: boolean\n ): Promise<void> {\n if (config?.enabled === false) {\n Core.log('Error handler disabled by configuration', verbose);\n return;\n }\n\n Core._errorConfig = config ?? {};\n Core.log('Initializing global error handler...', verbose);\n\n // Initialize error system (translations, catalogs)\n // This is safe to call multiple times - it checks if already initialized\n initializeErrorSystem({\n defaultLocale: Core._errorConfig.localization?.defaultLocale,\n fallbackLocale: Core._errorConfig.localization?.fallbackLocale,\n additionalCatalogs: Core._errorConfig.localization?.additionalCatalogs,\n replaceBuiltIn: Core._errorConfig.localization?.replaceBuiltIn,\n });\n\n // Initialize root store (contains error store + all slices)\n await Core.initializeRootStore(Core._errorConfig, verbose);\n\n // Wire up CoreEventManager for automatic error event emission\n // This allows errors captured by the global handler to emit events\n setEventEmitter(CoreEventManager.emit.bind(CoreEventManager));\n\n const errorStore = Core.getErrorStoreActions();\n Core._errorHandler = initializeGlobalErrorHandler(\n errorStore,\n Core.buildErrorHandlerConfig(Core._errorConfig)\n );\n\n // Subscribe to SYSTEM.ERROR events from ApiClientService and other sources\n // Core handles updating the appropriate store based on runtime context\n const errorEventCleanup = CoreEventManager.on(\n CORE_EVENTS.SYSTEM.ERROR,\n (event: CoreEvent<CoreSystemErrorPayload>) => {\n if (!Core._rootStore) return;\n\n try {\n const { errors } = event.data;\n if (errors && errors.length > 0) {\n // Update the appropriate store based on runtime\n // Frontend: Zustand store, Backend: In-memory store (both via root store)\n Core._rootStore.getState().errors.addErrors(errors);\n Core.log(`Added ${errors.length} error(s) to store`, verbose);\n }\n } catch (e) {\n Core.logger.error('Failed to handle error event', { error: e });\n }\n }\n );\n\n // Store cleanup function\n Core._eventCleanupFns.push(errorEventCleanup);\n\n Core.log('Global error handler initialized with CoreEventManager integration', verbose);\n\n // Auto-create HTTP error handler based on runtime (unless disabled)\n if (Core._errorConfig.httpHandler !== false) {\n await Core.createHttpErrorHandler(Core._errorConfig, verbose);\n }\n }\n\n /**\n * Create HTTP error handler based on detected runtime.\n * Stores the handler in Core._httpErrorHandler for access via Core.httpErrorHandler\n */\n // eslint-disable-next-line complexity\n private static async createHttpErrorHandler(\n config?: CoreErrorHandlerInitConfig,\n verbose?: boolean\n ): Promise<void> {\n const runtime = Core._coreServices.runtime;\n const isProduction = Core._coreServices.env.NODE_ENV === 'production';\n\n // Skip for browser runtime (no HTTP error handler needed)\n if (runtime === 'browser') {\n Core._httpErrorHandler = null;\n Core.log('Skipping HTTP handler for browser runtime', verbose);\n return;\n }\n\n const ServerErrorMiddleware = getCoreDependency('ServerErrorMiddleware');\n if (!ServerErrorMiddleware) {\n Core.log('Skipping HTTP handler (ServerErrorMiddleware not registered)', verbose);\n return;\n }\n\n // Build common config for all HTTP handlers\n const httpConfig = {\n source: runtime,\n includeStack: config?.includeStack ?? !isProduction,\n logErrors: config?.logger ?? config?.logToConsole ?? true,\n errorHandler: Core._errorHandler ?? undefined,\n };\n\n switch (runtime) {\n case 'express':\n Core._httpErrorHandler = ServerErrorMiddleware.createHttpErrorHandler(httpConfig);\n Core.log('Created Express error handler middleware', verbose);\n break;\n\n case 'nestjs':\n Core._httpErrorHandler = ServerErrorMiddleware.createNestJsExceptionFilter(httpConfig);\n Core.log('Created NestJS exception filter', verbose);\n break;\n\n case 'nextjs':\n // For Next.js, provide both App Router and Pages Router handlers\n Core._httpErrorHandler = {\n /** For App Router: export const GET = withErrorHandler(handler) */\n withErrorHandler: <T>(handler: T, overrideConfig = {}) =>\n ServerErrorMiddleware.withErrorHandler(\n handler as Parameters<typeof ServerErrorMiddleware.withErrorHandler>[0],\n { ...httpConfig, ...overrideConfig }\n ),\n /** For Pages Router: export default createNextApiErrorHandler()(handler) */\n createNextApiErrorHandler: (overrideConfig = {}) =>\n ServerErrorMiddleware.createNextApiErrorHandler({ ...httpConfig, ...overrideConfig }),\n };\n Core.log('Created Next.js error handlers', verbose);\n break;\n\n case 'node':\n case 'bun':\n case 'deno':\n // Generic Node.js handler\n Core._httpErrorHandler = {\n /** Handle error: handleNodeError(error, req, res) */\n handleError: (error: unknown, req: unknown, res: unknown) =>\n ServerErrorMiddleware.handleNodeError(\n error,\n req as Parameters<typeof ServerErrorMiddleware.handleNodeError>[1],\n // eslint-disable-next-line no-magic-numbers -- Type parameter index for handleNodeError\n res as Parameters<typeof ServerErrorMiddleware.handleNodeError>[2],\n httpConfig\n ),\n /** Create middleware for use with native http */\n createMiddleware: () => ServerErrorMiddleware.createHttpErrorHandler(httpConfig),\n };\n Core.log(`Created ${runtime} error handler`, verbose);\n break;\n\n default:\n // For unknown runtimes, provide generic handler\n Core._httpErrorHandler = ServerErrorMiddleware.createHttpErrorHandler(httpConfig);\n Core.log(`Created generic HTTP error handler for ${runtime}`, verbose);\n }\n }\n\n /**\n * Subscribe to CoreEventManager error events\n * Forwards system, entity, API, validation, database, and auth errors to the global error handler.\n *\n * Note: Database errors (DATABASE.ERROR) are only subscribed on backend runtimes since\n * DbService is backend-only (skipDb: true on frontend).\n */\n private static subscribeToErrorEvents(verbose?: boolean): void {\n if (!Core._errorHandler) {\n return;\n }\n\n Core.log('Subscribing to error events...', verbose);\n\n // Subscribe to system errors (universal)\n const cleanupSystemError = CoreEventManager.on(CORE_EVENTS.SYSTEM.ERROR, event => {\n if (Core._errorHandler && event.data?.errors?.length) {\n // Capture each error in the array\n for (const err of event.data.errors) {\n Core._errorHandler.captureError(err, 'system');\n }\n }\n });\n\n // Subscribe to entity errors (universal)\n const cleanupEntityError = CoreEventManager.on(CORE_EVENTS.ENTITY.ERROR, event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'entity');\n }\n });\n\n // Subscribe to API errors (universal)\n const cleanupApiError = CoreEventManager.on(CORE_EVENTS.API.REQUEST_ERROR, event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'api');\n }\n });\n\n // Subscribe to validation errors (universal)\n const cleanupValidationError = CoreEventManager.on(CORE_EVENTS.VALIDATION.FAILED, event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'validation');\n }\n });\n\n // Subscribe to auth errors (universal - can happen on both frontend and backend)\n const cleanupAuthUnauthorized = CoreEventManager.on(CORE_EVENTS.AUTH.UNAUTHORIZED, event => {\n if (Core._errorHandler && event.data?.error) {\n Core._errorHandler.captureError(event.data.error, 'auth');\n }\n });\n\n const cleanupAuthSessionExpired = CoreEventManager.on(\n CORE_EVENTS.AUTH.SESSION_EXPIRED,\n event => {\n if (Core._errorHandler && event.data?.error) {\n Core._errorHandler.captureError(event.data.error, 'auth');\n }\n }\n );\n\n // Store universal cleanup functions\n Core._eventCleanupFns.push(\n cleanupSystemError,\n cleanupEntityError,\n cleanupApiError,\n cleanupValidationError,\n cleanupAuthUnauthorized,\n cleanupAuthSessionExpired\n );\n\n // Subscribe to database errors (backend-only)\n // Database events only fire when DbService is initialized (skipDb: false)\n if (Core.isRuntimeCompatible('backend')) {\n const cleanupDatabaseError = CoreEventManager.on(CORE_EVENTS.DATABASE.ERROR, event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'database');\n }\n });\n Core._eventCleanupFns.push(cleanupDatabaseError);\n\n // Subscribe to storage errors (backend-only)\n const cleanupStorageError = CoreEventManager.on(CORE_EVENTS.STORAGE.ERROR, event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'storage');\n }\n });\n Core._eventCleanupFns.push(cleanupStorageError);\n\n // Subscribe to notification errors (backend-only)\n const cleanupNotificationError = CoreEventManager.on(\n CORE_EVENTS.NOTIFICATION.ERROR,\n event => {\n if (Core._errorHandler && event.data) {\n Core._errorHandler.captureError(event.data.error, 'notification');\n }\n }\n );\n Core._eventCleanupFns.push(cleanupNotificationError);\n\n Core.log('Subscribed to backend error events (database, storage, notification)', verbose);\n }\n\n const eventTypes = ['system', 'entity', 'api', 'validation', 'auth'];\n if (Core.isRuntimeCompatible('backend')) {\n eventTypes.push('database', 'storage', 'notification');\n }\n Core.log(`Subscribed to error events: ${eventTypes.join(', ')}`, verbose);\n }\n\n /** Handle fetch flags error and return empty flags */\n private static handleFetchFlagsError(\n error: unknown,\n config?: CoreFeatureFlagInitConfig,\n verbose?: boolean\n ): Record<string, FeatureFlagValue> {\n if (verbose) Core.logger.error('Failed to fetch feature flags', { error });\n\n // If already a package error, use as-is; otherwise wrap it\n const packageError =\n error instanceof BaseError\n ? (error as CorePackageError)\n : new CorePackageError(\n error instanceof Error ? error.message : String(error),\n ERROR_CODES.CORE_FEATURE_FLAG_PROVIDER_ERROR,\n { cause: error instanceof Error ? error : undefined }\n );\n config?.onError?.(packageError);\n return {};\n }\n\n /** Create fetch flags function */\n private static createFetchFlagsFn(\n config?: CoreFeatureFlagInitConfig,\n verbose?: boolean\n ): () => Promise<Record<string, FeatureFlagValue>> {\n // eslint-disable-next-line complexity\n return async () => {\n try {\n const client = ApiClientService.getClient();\n const endpoint = config?.apiEndpoint ?? '/feature-flags';\n const response = await client.get<{ flags: Record<string, FeatureFlagValue> }>(endpoint);\n\n if (!response.isSuccess) {\n throw new CorePackageError(\n response.error?.message ?? 'Failed to fetch feature flags',\n ERROR_CODES.CORE_FEATURE_FLAG_PROVIDER_ERROR\n );\n }\n\n return response.data?.flags ?? {};\n } catch (error) {\n return Core.handleFetchFlagsError(error, config, verbose);\n }\n };\n }\n\n /**\n * Initialize feature flags slice within root store\n */\n\n private static async initializeFeatureFlags(\n config?: CoreFeatureFlagInitConfig,\n verbose?: boolean\n ): Promise<void> {\n if (config?.enabled === false) {\n Core.log('Feature flags disabled by configuration', verbose);\n return;\n }\n\n if (!Core._rootStore) {\n throw new CorePackageError(\n 'Root store not initialized. Call Core.initializeErrorHandler() first.',\n ERROR_CODES.CLIENT_INITIALIZATION_FAILED\n );\n }\n\n Core._flagConfig = config ?? {};\n Core.log('Initializing feature flags from root store...', verbose);\n\n // Initialize the feature flag slice within the root store\n const state = Core._rootStore.getState();\n await state.featureFlags.initialize({\n defaults: Core._flagConfig.defaults,\n polling: Core._flagConfig.polling,\n fetchFn: Core.createFetchFlagsFn(Core._flagConfig, verbose),\n onFlagChange: Core._flagConfig.onFlagChange,\n onError: Core._flagConfig.onError,\n });\n\n Core.log('Feature flags initialized', verbose);\n }\n}\n\n// Export for convenience (excluding server-only services - use backend entry for those)\n// Note: CacheService and DEFAULT_ENCRYPTION_FIELDS are only exported from entry-backend.ts\nexport { ApiClientService };\n","/**\n * DbService - Singleton Database Connection Manager\n *\n * @description Manages database connections for the entire application using a singleton pattern.\n * This service wraps @plyaz/db and provides a centralized way to initialize and access\n * the database across all domains (feature flags, users, campaigns, backoffice, etc.).\n *\n * **Architecture:**\n * - Uses `createDatabaseService()` from @plyaz/db which builds an adapter chain\n * - Supports Drizzle (direct PostgreSQL), Supabase (REST API), or raw SQL adapters\n * - Extension layers: Encryption → SoftDelete → Caching → Audit → ReadReplica\n *\n * **Adapter Configuration:**\n * - **Drizzle**: Requires `connectionString` (PostgreSQL URL)\n * - **Supabase**: Requires `supabaseUrl`, `supabaseServiceKey`, `supabaseAnonKey`\n * - **SQL**: Requires `connectionString`\n *\n * **Required Environment Variables (Drizzle with Supabase):**\n * - DATABASE_URL: PostgreSQL connection string (from Supabase Dashboard > Database > URI)\n *\n * **Required Environment Variables (Supabase REST API):**\n * - SUPABASE_URL: Your Supabase project URL\n * - SUPABASE_SERVICE_ROLE_KEY: Service role key for admin operations\n * - SUPABASE_ANON_PUBLIC_KEY: Anonymous key for public operations\n *\n * @example Using with Core.initialize() (Recommended)\n * ```typescript\n * import { Core } from '@plyaz/core';\n *\n * // Core.initialize() handles loading env and passing to DbService\n * await Core.initialize({\n * envPath: '.env',\n * db: {\n * adapter: 'sql',\n * cache: { enabled: true, ttl: 60 },\n * },\n * });\n *\n * // Access via Core.db\n * const db = Core.db.getDatabase();\n * const result = await db.list('users', { pagination: { limit: 10, offset: 0 } });\n * ```\n *\n * @example Direct Usage (requires explicit config)\n * ```typescript\n * // Direct usage requires explicit connectionString\n * await DbService.initialize({\n * adapter: 'drizzle',\n * drizzle: {\n * connectionString: 'postgresql://user:pass@localhost:5432/db',\n * poolSize: 20,\n * },\n * });\n * ```\n *\n * @example With Extensions\n * ```typescript\n * await Core.initialize({\n * envPath: '.env',\n * db: {\n * adapter: 'drizzle',\n * softDelete: {\n * enabled: true,\n * field: 'deleted_at',\n * excludeTables: ['audit_logs', 'feature_flag_evaluations'],\n * },\n * cache: {\n * enabled: true,\n * provider: 'memory',\n * ttl: 300,\n * },\n * audit: {\n * enabled: true,\n * retentionDays: 90,\n * },\n * },\n * });\n * ```\n *\n * @example Using with BaseRepository\n * ```typescript\n * import { BaseRepository } from '@plyaz/db';\n * import { DbService } from '@plyaz/core';\n *\n * class UserRepository extends BaseRepository<User> {\n * constructor() {\n * super(DbService.getInstance().getDatabase(), 'users');\n * }\n * }\n * ```\n *\n * @module services\n */\n\nimport { createDatabaseService } from '@plyaz/db';\nimport { DatabasePackageError } from '@plyaz/errors';\nimport {\n type DatabaseServiceInterface,\n type DatabaseServiceConfig,\n type DrizzleConfig,\n type SupabaseConfig,\n type SqlConfig,\n type Transaction,\n} from '@plyaz/types/db';\nimport { DATABASE_ERROR_CODES } from '@plyaz/types/errors';\nimport { CORE_EVENTS, type CoreDatabaseErrorPayload } from '@plyaz/types/core';\nimport { CoreEventManager } from '../events/CoreEventManager';\n\n/**\n * Default fields to encrypt per table\n * Contains sensitive PII and financial data that should be encrypted at rest\n *\n * @see docs/db-schemas/dbdiagram_schema.dbml for field definitions\n */\nexport const DEFAULT_ENCRYPTION_FIELDS: Record<string, string[]> = {\n // User PII\n users: ['password_hash', 'phone_number', 'date_of_birth'],\n\n // KYC sensitive data\n 'backoffice.kyc_submissions': ['tax_id', 'address_line1', 'address_line2'],\n\n // Connected accounts OAuth tokens\n connected_accounts: ['access_token_encrypted', 'refresh_token_encrypted', 'wallet_address'],\n\n // Payment payout accounts\n user_payout_accounts: ['provider_account_id', 'account_holder_name'],\n\n // Sessions\n sessions: ['token'],\n};\n\n// Re-export DbServiceConfig from @plyaz/types/core\nexport type { CoreDbServiceConfig } from '@plyaz/types/core';\n\n// Local alias for internal use\nimport type {\n CoreDbServiceConfig as DbServiceConfig,\n CoreDbServiceInstance,\n} from '@plyaz/types/core';\n\n/**\n * Default configuration for DbService\n *\n * **Adapter Selection Guide:**\n *\n * | Adapter | Connection | Auto-Register | RLS | Use Case |\n * |-------------|------------------|---------------|----------|-----------------------------------|\n * | `'sql'` | PostgreSQL URL | ✓ Yes | Bypassed | **Recommended** for backend |\n * | `'supabase'`| Supabase API | ✓ Yes | Enforced | Frontend / RLS-required scenarios |\n * | `'drizzle'` | PostgreSQL URL | ✓ Yes* | Bypassed | Type-safe ORM (with PgTable schemas) |\n *\n * *Drizzle supports dual-mode: uses PgTable schemas if registered, falls back to raw SQL otherwise.\n *\n * **Recommended:** Use `'sql'` adapter for backend services with Supabase PostgreSQL.\n * Direct PostgreSQL connection = best performance, bypasses RLS for full backend access.\n */\n// Database configuration constants\nconst DEFAULT_CACHE_TTL_SECONDS = 300; // 5 minutes\nconst DEFAULT_AUDIT_RETENTION_DAYS = 180; // GDPR/SOX compliance (6 months minimum)\nconst DEFAULT_POOL_SIZE = 10;\n\nconst DEFAULT_CONFIG: Partial<DbServiceConfig> = {\n adapter: 'sql',\n cache: {\n enabled: true,\n provider: 'memory',\n ttl: DEFAULT_CACHE_TTL_SECONDS,\n },\n softDelete: {\n enabled: true,\n field: 'deleted_at',\n excludeTables: [\n 'audit_logs',\n 'audit.audit_logs',\n 'audit.feature_flag_evaluations',\n 'feature_flag_evaluations',\n 'notification_events',\n 'payments_activity',\n 'campaign_analytics',\n 'admin_actions',\n 'backoffice.admin_actions',\n ],\n },\n audit: {\n enabled: true, // Enabled by default for compliance\n retentionDays: DEFAULT_AUDIT_RETENTION_DAYS,\n excludeFields: ['password_hash', 'api_key_hash', 'token_hash'],\n excludeTables: ['audit_logs', 'audit.audit_logs'], // Don't audit the audit table itself\n schema: 'audit', // Use dedicated audit schema\n usePartitionedTables: true, // Use daily partitioned tables (audit_log_yyyy_mm_dd)\n },\n // NOTE: Encryption requires key from environment or DbService.initialize()\n // Enable via: DbService.initialize({ encryption: { enabled: true, key: process.env.ENCRYPTION_KEY!, fields: DEFAULT_ENCRYPTION_FIELDS } })\n};\n\n/**\n * Complete table registry from database migrations\n * Maps logical table names to their ID columns\n *\n * @see docs/db-schemas/migrations/ for schema definitions\n * @see docs/db-schemas/dbdiagram_schema.dbml for full schema\n */\n/**\n * TABLE_REGISTRY - Custom ID Column and Schema Registry\n *\n * ONLY register tables with:\n * 1. Custom ID columns (anything other than 'id')\n * 2. Custom database schemas (anything other than 'public')\n *\n * Tables with standard 'id' column in 'public' schema do NOT need registration.\n * You can also override ID column and schema per-query using OperationConfig.\n *\n * Schema can be defined in the table key or in the config object (or both):\n * - 'schema.table': { idColumn: 'key' } ← Schema in key only\n * - 'schema.table': { idColumn: 'key', schema: 'schema' } ← Redundant but allowed\n * - 'schema.table': {} ← Empty config, schema in key\n * - 'table': { idColumn: 'key', schema: 'schema' } ← Schema in config only\n *\n * @example\n * ```typescript\n * // Using registry\n * await db.get('feature_flags', 'my-flag-key'); // Uses 'key' column from registry\n *\n * // Per-query override\n * await db.get('custom_table', 'some-key', { idColumn: 'custom_id' });\n *\n * // Schema override\n * await db.get('logs', '123', { schema: 'logging' });\n * ```\n */\nexport const TABLE_REGISTRY: Record<string, { idColumn?: string; schema?: string }> = {\n // Migration 008: Feature Flags (custom ID column 'key')\n feature_flags: { idColumn: 'key' },\n\n // Test Feature Flags (custom ID column 'key')\n test_feature_flags: { idColumn: 'key' },\n\n // Migration 010: Universal Analytics (custom ID column 'user_id')\n user_analytics_summary: { idColumn: 'user_id' },\n};\n\n/**\n * DbService - Singleton Database Connection Manager\n *\n * Provides centralized database connection management for all domains.\n * Uses @plyaz/db under the hood with configurable adapters and extensions.\n */\nexport class DbService implements CoreDbServiceInstance {\n private static instance: DbService | null = null;\n private databaseService: DatabaseServiceInterface | null = null;\n private namedAdapters: Map<string, DatabaseServiceInterface> = new Map();\n private config: DbServiceConfig | null = null;\n private initialized = false;\n\n private constructor() {}\n\n /**\n * Emits a database error event via CoreEventManager.\n * Called when database operations fail to integrate with global error handling.\n *\n * @param error - The error that occurred\n * @param operation - The operation that failed (e.g., 'transaction', 'query', 'healthCheck')\n * @param table - Optional table name involved in the operation\n * @param query - Optional query string that failed\n * @param recoverable - Whether the error is recoverable (default: false)\n */\n private emitDatabaseError(\n error: unknown,\n operation: string,\n options?: {\n table?: string;\n query?: string;\n recoverable?: boolean;\n }\n ): void {\n const payload: CoreDatabaseErrorPayload = {\n error,\n operation,\n table: options?.table,\n query: options?.query,\n recoverable: options?.recoverable ?? false,\n };\n CoreEventManager.emit(CORE_EVENTS.DATABASE.ERROR, payload);\n }\n\n /**\n * Gets the singleton instance of DbService\n *\n * @returns {DbService} The singleton instance\n */\n static getInstance(): DbService {\n DbService.instance ??= new DbService();\n return DbService.instance;\n }\n\n /**\n * Checks if the database service has been initialized\n *\n * @returns {boolean} True if initialized\n */\n static isInitialized(): boolean {\n return DbService.instance?.initialized ?? false;\n }\n\n /**\n * Resets the database service by closing connections and clearing the singleton instance\n *\n * @description Properly closes the database connection and clears the singleton.\n * Useful for testing or when you need to reinitialize with different configuration.\n *\n * @example\n * ```typescript\n * await DbService.reset();\n * await DbService.initialize({ adapter: 'sql', ... });\n * ```\n */\n static async reset(): Promise<void> {\n if (DbService.instance) {\n try {\n await DbService.instance.databaseService?.close?.();\n } catch {\n // Ignore close errors (pool might already be closed)\n }\n DbService.instance = null;\n }\n }\n\n /**\n * Initializes the database connection\n *\n * @description Sets up the database connection using the provided configuration\n * or environment variables. This method is idempotent - calling it multiple\n * times won't create additional connections.\n *\n * **Environment Variables:**\n * - `DATABASE_URL` - PostgreSQL connection string (for sql/drizzle adapters)\n * - `ENCRYPTION_KEY` - 32-byte encryption key for field encryption (optional)\n * - `SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY`, `SUPABASE_ANON_PUBLIC_KEY` - For supabase adapter\n *\n * **Encryption:** If `ENCRYPTION_KEY` env is set, encryption is auto-enabled\n * using `DEFAULT_ENCRYPTION_FIELDS`. Override via config.encryption.\n *\n * @param {DbServiceConfig} [config] - Optional configuration\n * @returns {Promise<DbService>} The initialized DbService instance\n * @throws {DatabasePackageError} When configuration is invalid or connection fails\n *\n * @example\n * ```typescript\n * // Minimal - uses DATABASE_URL env, auto-enables encryption if ENCRYPTION_KEY set\n * await DbService.initialize();\n *\n * // With explicit encryption\n * await DbService.initialize({\n * adapter: 'sql',\n * encryption: {\n * enabled: true,\n * key: 'your-32-byte-encryption-key-here!!',\n * fields: DEFAULT_ENCRYPTION_FIELDS,\n * },\n * });\n *\n * // Or via Core.initialize() with env:\n * await Core.initialize({\n * env: { ENCRYPTION_KEY: '...' },\n * db: { adapter: 'sql' },\n * });\n * ```\n */\n /** Build encryption config from user config */\n private static buildEncryptionConfig(config?: DbServiceConfig): DbServiceConfig['encryption'] {\n const encryption = config?.encryption;\n if (!encryption?.key) return undefined;\n\n return {\n enabled: encryption.enabled ?? true,\n key: encryption.key,\n fields: encryption.fields ?? DEFAULT_ENCRYPTION_FIELDS,\n algorithm: encryption.algorithm ?? 'aes-256-gcm',\n };\n }\n\n /** Merge user config with defaults */\n private static mergeConfig(config?: DbServiceConfig): DbServiceConfig {\n return {\n ...DEFAULT_CONFIG,\n ...config,\n softDelete: { ...DEFAULT_CONFIG.softDelete, ...config?.softDelete },\n cache: { ...DEFAULT_CONFIG.cache, ...config?.cache },\n audit: { ...DEFAULT_CONFIG.audit, ...config?.audit },\n encryption: DbService.buildEncryptionConfig(config),\n } as DbServiceConfig;\n }\n\n /** Initialize named adapters */\n private async initializeNamedAdapters(mergedConfig: DbServiceConfig): Promise<void> {\n if (!mergedConfig.adapters) return;\n\n for (const [name, adapterConfig] of Object.entries(mergedConfig.adapters)) {\n const namedDbConfig = this.buildDatabaseConfig({\n ...mergedConfig,\n adapter: adapterConfig.adapter,\n drizzle: adapterConfig.drizzle,\n supabase: adapterConfig.supabase,\n sql: adapterConfig.sql,\n });\n\n const namedService = await createDatabaseService(namedDbConfig);\n this.namedAdapters.set(name, namedService);\n }\n }\n\n static async initialize(config?: DbServiceConfig): Promise<DbService> {\n const instance = DbService.getInstance();\n\n if (instance.initialized) {\n return instance;\n }\n\n const mergedConfig = DbService.mergeConfig(config);\n instance.config = mergedConfig;\n\n const dbConfig = instance.buildDatabaseConfig(mergedConfig);\n instance.databaseService = await createDatabaseService(dbConfig);\n\n await instance.initializeNamedAdapters(mergedConfig);\n\n instance.initialized = true;\n return instance;\n }\n\n /**\n * Builds the DatabaseServiceConfig based on the adapter type\n * @private\n */\n\n /** Builds adapter-specific config based on adapter type */\n private buildAdapterConfig(\n adapter: string,\n config: DbServiceConfig\n ): DrizzleConfig | SupabaseConfig | SqlConfig {\n const builders: Record<string, () => DrizzleConfig | SupabaseConfig | SqlConfig> = {\n drizzle: () => this.buildDrizzleConfig(config),\n supabase: () => this.buildSupabaseConfig(config),\n sql: () => this.buildSqlConfig(config),\n };\n\n const builder = builders[adapter];\n if (!builder) {\n throw new DatabasePackageError(\n `Unsupported adapter type: ${adapter}`,\n DATABASE_ERROR_CODES.CONFIG_REQUIRED\n );\n }\n return builder();\n }\n\n /** Builds soft delete extension config */\n private buildSoftDeleteExtension(\n config: DbServiceConfig\n ): DatabaseServiceConfig['softDelete'] | undefined {\n if (!config.softDelete?.enabled) return undefined;\n return {\n enabled: true,\n field: config.softDelete.field ?? 'deleted_at',\n excludeTables: config.softDelete.excludeTables,\n };\n }\n\n /** Builds cache extension config */\n private buildCacheExtension(config: DbServiceConfig): DatabaseServiceConfig['cache'] | undefined {\n if (!config.cache?.enabled) return undefined;\n return {\n enabled: true,\n ttl: config.cache.ttl ?? DEFAULT_CACHE_TTL_SECONDS,\n provider: config.cache.provider ?? 'memory',\n invalidation: config.cache.invalidation ?? 'write',\n };\n }\n\n /** Builds audit extension config */\n private buildAuditExtension(config: DbServiceConfig): DatabaseServiceConfig['audit'] | undefined {\n if (!config.audit?.enabled) return undefined;\n return {\n enabled: true,\n retentionDays: config.audit.retentionDays ?? DEFAULT_AUDIT_RETENTION_DAYS,\n excludeFields: config.audit.excludeFields,\n excludeTables: config.audit.excludeTables,\n schema: config.audit.schema ?? 'audit',\n usePartitionedTables: config.audit.usePartitionedTables ?? true,\n };\n }\n\n /** Builds encryption extension config */\n private buildEncryptionExtension(\n config: DbServiceConfig\n ): DatabaseServiceConfig['encryption'] | undefined {\n if (!config.encryption?.enabled || !config.encryption.key) return undefined;\n return {\n enabled: true,\n key: config.encryption.key,\n fields: config.encryption.fields ?? {},\n algorithm: config.encryption.algorithm,\n };\n }\n\n private buildDatabaseConfig(config: DbServiceConfig): DatabaseServiceConfig {\n const adapter = config.adapter ?? 'drizzle';\n\n const dbConfig: DatabaseServiceConfig = {\n adapter: adapter as DatabaseServiceConfig['adapter'],\n config: this.buildAdapterConfig(adapter, config),\n };\n\n // Apply extensions\n const softDelete = this.buildSoftDeleteExtension(config);\n const cache = this.buildCacheExtension(config);\n const audit = this.buildAuditExtension(config);\n const encryption = this.buildEncryptionExtension(config);\n\n if (softDelete) dbConfig.softDelete = softDelete;\n if (cache) dbConfig.cache = cache;\n if (audit) dbConfig.audit = audit;\n if (encryption) dbConfig.encryption = encryption;\n\n return dbConfig;\n }\n\n /**\n * Builds Drizzle adapter configuration\n * @private\n */\n private buildDrizzleConfig(config: DbServiceConfig): DrizzleConfig {\n // Get connection string from config (Core.initialize() passes env values)\n const connectionString = config.drizzle?.connectionString;\n\n if (!connectionString) {\n throw new DatabasePackageError(\n 'Drizzle adapter requires a PostgreSQL connection string. ' +\n 'Provide `drizzle.connectionString` in config or use Core.initialize() with DATABASE_URL in env. ' +\n 'For Supabase, find this in Dashboard > Database > Connection string (URI).',\n DATABASE_ERROR_CODES.CONFIG_REQUIRED\n );\n }\n\n // Build table ID column mappings from TABLE_REGISTRY\n const tableIdColumns = this.buildTableIdColumns();\n\n return {\n connectionString,\n poolSize: config.drizzle?.poolSize ?? DEFAULT_POOL_SIZE,\n ssl: config.drizzle?.ssl,\n schema: config.drizzle?.schema, // Pass through schema configuration\n tableIdColumns,\n };\n }\n\n /**\n * Builds Supabase adapter configuration\n * @private\n */\n // eslint-disable-next-line complexity\n private buildSupabaseConfig(config: DbServiceConfig): SupabaseConfig {\n // Get Supabase config (Core.initialize() passes env values)\n const supabaseUrl = config.supabase?.supabaseUrl;\n const supabaseServiceKey = config.supabase?.supabaseServiceKey;\n const supabaseAnonKey = config.supabase?.supabaseAnonKey;\n\n if (!supabaseUrl || !supabaseServiceKey) {\n throw new DatabasePackageError(\n 'Supabase adapter requires supabaseUrl and supabaseServiceKey. ' +\n 'Provide in config or use Core.initialize() with SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY in env.',\n DATABASE_ERROR_CODES.CONFIG_REQUIRED\n );\n }\n\n if (!supabaseAnonKey) {\n throw new DatabasePackageError(\n 'Supabase adapter requires supabaseAnonKey. ' +\n 'Provide in config or use Core.initialize() with SUPABASE_ANON_PUBLIC_KEY in env.',\n DATABASE_ERROR_CODES.CONFIG_REQUIRED\n );\n }\n\n // Build table ID column mappings from TABLE_REGISTRY\n const tableIdColumns = this.buildTableIdColumns();\n\n return {\n supabaseUrl,\n supabaseServiceKey,\n supabaseAnonKey,\n schema: config.supabase?.schema ?? 'public',\n tableIdColumns,\n };\n }\n\n /**\n * Builds SQL adapter configuration\n * @private\n */\n private buildSqlConfig(config: DbServiceConfig): SqlConfig {\n // Get connection string from config (Core.initialize() passes env values)\n const connectionString = config.sql?.connectionString;\n\n if (!connectionString) {\n throw new DatabasePackageError(\n 'SQL adapter requires a connection string. ' +\n 'Provide `sql.connectionString` in config or use Core.initialize() with DATABASE_URL in env.',\n DATABASE_ERROR_CODES.CONFIG_REQUIRED\n );\n }\n\n // Build table ID column mappings from TABLE_REGISTRY\n const tableIdColumns = this.buildTableIdColumns();\n\n return {\n connectionString,\n dialect: config.sql?.dialect ?? 'postgresql',\n schema: config.sql?.schema, // Pass through schema configuration\n tableIdColumns,\n };\n }\n\n /**\n * Builds table ID column mappings from TABLE_REGISTRY\n * @private\n * @returns Record of table names to ID column names\n */\n // eslint-disable-next-line complexity\n private buildTableIdColumns(): Record<string, string> {\n const tableIdColumns: Record<string, string> = {};\n const baseNameConflicts = new Set<string>();\n const baseNameMappings = new Map<string, string>();\n\n // First pass: identify base name conflicts\n // e.g., if we have both 'public.users' and 'backoffice.users',\n // we can't map 'users' → one ID column\n for (const tableName of Object.keys(TABLE_REGISTRY)) {\n if (tableName.includes('.')) {\n const baseName = tableName.split('.').pop()!;\n if (baseNameMappings.has(baseName) || TABLE_REGISTRY[baseName]) {\n baseNameConflicts.add(baseName);\n } else {\n baseNameMappings.set(baseName, tableName);\n }\n }\n }\n\n // Second pass: build ID column mappings\n for (const [tableName, config] of Object.entries(TABLE_REGISTRY)) {\n const idColumn = config.idColumn ?? 'id';\n\n // Only include non-standard ID columns (not 'id')\n if (idColumn === 'id') continue;\n\n // Always map the full table name (with or without schema)\n tableIdColumns[tableName] = idColumn;\n\n // If the table name includes a schema (e.g., 'backoffice.flagged_content'),\n // also map the base name (e.g., 'flagged_content') for convenience\n // unless there's a conflict with another schema's table\n if (!tableName.includes('.')) continue;\n\n const baseName = tableName.split('.').pop()!;\n if (!baseNameConflicts.has(baseName)) {\n tableIdColumns[baseName] = idColumn;\n }\n }\n\n return tableIdColumns;\n }\n\n /**\n * Gets the initialized database service instance\n *\n * @param {string} [adapterName] - Optional named adapter to use instead of default\n * @returns {DatabaseServiceInterface} The database service instance\n * @throws {DatabasePackageError} When database is not initialized or named adapter not found\n */\n getDatabase(adapterName?: string): DatabaseServiceInterface {\n if (adapterName) {\n const namedAdapter = this.namedAdapters.get(adapterName);\n if (!namedAdapter) {\n throw new DatabasePackageError(\n `Named adapter '${adapterName}' not found. Available adapters: ${Array.from(this.namedAdapters.keys()).join(', ')}`,\n DATABASE_ERROR_CODES.INIT_FAILED\n );\n }\n return namedAdapter;\n }\n\n if (!this.databaseService) {\n throw new DatabasePackageError(\n 'Database not initialized. Call DbService.initialize() first.',\n DATABASE_ERROR_CODES.INIT_FAILED\n );\n }\n return this.databaseService;\n }\n\n /**\n * Gets a named adapter by name\n *\n * @param {string} name - The name of the adapter\n * @returns {DatabaseServiceInterface} The named adapter instance\n * @throws {DatabasePackageError} When adapter not found\n */\n getAdapter(name: string): DatabaseServiceInterface {\n return this.getDatabase(name);\n }\n\n /**\n * Lists all available named adapters\n *\n * @returns {string[]} Array of adapter names\n */\n getAvailableAdapters(): string[] {\n return ['default', ...Array.from(this.namedAdapters.keys())];\n }\n\n /**\n * Executes a database transaction with automatic rollback on failure\n *\n * @template T The return type of the transaction callback\n * @param {Function} callback - Function that receives transaction object\n * @returns {Promise<T>} The result of the transaction callback\n * @throws {DatabasePackageError} When transaction fails\n */\n async transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T> {\n const db = this.getDatabase();\n const result = await db.transaction(callback);\n\n if (!result.success) {\n const errorMessage = result.error?.message ?? 'Transaction failed';\n const error = new DatabasePackageError(errorMessage, DATABASE_ERROR_CODES.TRANSACTION_FAILED);\n // Emit database error event for global error handling\n this.emitDatabaseError(error, 'transaction', { recoverable: true });\n throw error;\n }\n\n if (result.value === undefined || result.value === null) {\n const error = new DatabasePackageError(\n 'Transaction returned no value',\n DATABASE_ERROR_CODES.INVALID_RESULT\n );\n this.emitDatabaseError(error, 'transaction', { recoverable: false });\n throw error;\n }\n\n return result.value;\n }\n\n /**\n * Sets audit context for subsequent operations\n *\n * @param context - Audit context (userId, requestId, etc.)\n */\n async setAuditContext(context: {\n userId?: string;\n requestId?: string;\n ipAddress?: string;\n userAgent?: string;\n }): Promise<void> {\n const db = this.getDatabase();\n await db.setAuditContext(context);\n }\n\n /**\n * Performs a health check on the database connection\n *\n * @returns Health check result\n */\n async healthCheck(): Promise<{ isHealthy: boolean; responseTime?: number; error?: string }> {\n try {\n const db = this.getDatabase();\n const result = await db.healthCheck();\n\n if (result.success && result.value) {\n return {\n isHealthy: result.value.isHealthy,\n responseTime: result.value.responseTime,\n };\n }\n\n // Health check failed - emit error event\n const errorMessage = result.error?.message ?? 'Health check failed';\n this.emitDatabaseError(\n new DatabasePackageError(errorMessage, DATABASE_ERROR_CODES.CONNECTION_ERROR),\n 'healthCheck',\n { recoverable: true }\n );\n\n return {\n isHealthy: false,\n error: errorMessage,\n };\n } catch (error) {\n // Exception during health check - emit error event\n this.emitDatabaseError(error, 'healthCheck', { recoverable: true });\n\n return {\n isHealthy: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n }\n\n /**\n * Gets the table registry with all known tables and their ID columns\n *\n * @returns The complete table registry\n */\n static getTableRegistry(): typeof TABLE_REGISTRY {\n return TABLE_REGISTRY;\n }\n\n /**\n * Gets ID column for a specific table\n *\n * @param tableName - Name of the table\n * @returns ID column name or 'id' as default\n */\n static getTableIdColumn(tableName: string): string {\n return TABLE_REGISTRY[tableName]?.idColumn ?? 'id';\n }\n\n /**\n * Reinitializes the database connection with new config\n *\n * @param {DbServiceConfig} [config] - New configuration\n * @returns {Promise<DbService>} The reinitialized DbService instance\n */\n static async reinitialize(config?: DbServiceConfig): Promise<DbService> {\n const instance = DbService.getInstance();\n await instance.close();\n instance.initialized = false;\n return DbService.initialize(config);\n }\n\n /**\n * Closes the database connection and cleans up resources\n */\n async close(): Promise<void> {\n this.databaseService = null;\n this.initialized = false;\n this.config = null;\n }\n\n /**\n * Gets the current configuration\n *\n * @returns {DbServiceConfig | null} Current config or null if not initialized\n */\n getConfig(): DbServiceConfig | null {\n return this.config;\n }\n\n /**\n * Gets the current adapter type\n *\n * @returns The adapter type or null if not initialized\n */\n getAdapterType(): 'drizzle' | 'supabase' | 'sql' | null {\n return this.config?.adapter ?? null;\n }\n\n /**\n * Creates a dedicated database service instance (NOT the singleton)\n *\n * Use this when you need an isolated database connection with its own configuration\n * that doesn't affect or get affected by the shared singleton instance.\n *\n * @param config - Database service configuration\n * @returns Promise that resolves to a new dedicated DbService instance\n *\n * @example\n * ```typescript\n * // Create a dedicated instance for analytics database\n * const analyticsDb = await DbService.createInstance({\n * adapter: 'sql',\n * sql: { connectionString: process.env.ANALYTICS_DB_URL },\n * cache: { enabled: false }, // No caching for analytics\n * });\n *\n * // This instance is independent from DbService.getInstance()\n * const data = await analyticsDb.getDatabase().list('events');\n *\n * // Clean up when done\n * await analyticsDb.close();\n * ```\n */\n // eslint-disable-next-line complexity\n static async createInstance(config: DbServiceConfig): Promise<DbService> {\n // Create a new instance (not the singleton)\n const dedicatedInstance = new DbService();\n\n // Build encryption config if key provided\n const encryptionKey = config.encryption?.key;\n const encryptionConfig = encryptionKey\n ? {\n enabled: config.encryption?.enabled ?? true,\n key: encryptionKey,\n fields: config.encryption?.fields ?? DEFAULT_ENCRYPTION_FIELDS,\n algorithm: config.encryption?.algorithm ?? ('aes-256-gcm' as const),\n }\n : undefined;\n\n const mergedConfig = {\n ...DEFAULT_CONFIG,\n ...config,\n // Deep merge extensions\n softDelete: { ...DEFAULT_CONFIG.softDelete, ...config.softDelete },\n cache: { ...DEFAULT_CONFIG.cache, ...config.cache },\n audit: { ...DEFAULT_CONFIG.audit, ...config.audit },\n // Encryption only if key is available\n encryption: encryptionConfig,\n } as DbServiceConfig;\n\n dedicatedInstance.config = mergedConfig;\n\n // Build adapter configuration based on adapter type\n const dbConfig = dedicatedInstance.buildDatabaseConfig(mergedConfig);\n\n dedicatedInstance.databaseService = await createDatabaseService(dbConfig);\n\n // Initialize named adapters if configured\n if (mergedConfig.adapters) {\n for (const [name, adapterConfig] of Object.entries(mergedConfig.adapters)) {\n const namedDbConfig = dedicatedInstance.buildDatabaseConfig({\n ...mergedConfig,\n adapter: adapterConfig.adapter,\n drizzle: adapterConfig.drizzle,\n supabase: adapterConfig.supabase,\n sql: adapterConfig.sql,\n });\n\n const namedService = await createDatabaseService(namedDbConfig);\n dedicatedInstance.namedAdapters.set(name, namedService);\n }\n }\n\n dedicatedInstance.initialized = true;\n\n return dedicatedInstance;\n }\n}\n\n/** Type alias for DbService instance (use for type-only imports to avoid bundling) */\nexport type DbServiceInstance = DbService;\n","/**\n * NestJS Module for @plyaz/core\n *\n * Provides dependency injection integration for NestJS applications.\n *\n * @example\n * ```typescript\n * // app.module.ts\n * import { CoreModule } from '@plyaz/core/nestjs';\n *\n * @Module({\n * imports: [\n * CoreModule.forRoot({\n * envPath: '.env',\n * db: { adapter: 'sql' },\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example Async configuration\n * ```typescript\n * CoreModule.forRootAsync({\n * imports: [ConfigModule],\n * useFactory: (config: ConfigService) => ({\n * db: {\n * adapter: 'sql',\n * sql: { connectionString: config.get('DATABASE_URL') },\n * },\n * }),\n * inject: [ConfigService],\n * })\n * ```\n */\n\nimport type { DynamicModule, Provider } from '@nestjs/common';\nimport { Core, type CoreInitOptions } from '../CoreInitializer';\nimport { DbService } from '../../services/DbService';\nimport type { CoreNestJsCoreModuleAsyncOptions } from '@plyaz/types/core';\n\n/**\n * Injection tokens for Core services\n */\nexport const CORE_OPTIONS = Symbol('CORE_OPTIONS');\nexport const DB_SERVICE = Symbol('DB_SERVICE');\n\n/**\n * Async configuration options for CoreModule\n * Uses CoreInitOptions for type safety with Core.initialize()\n */\ntype CoreModuleAsyncOptions = CoreNestJsCoreModuleAsyncOptions;\n\n/**\n * CoreModule - NestJS DI module for @plyaz/core\n */\nexport class CoreModule {\n /**\n * Register CoreModule with static configuration\n */\n static forRoot(options: CoreInitOptions = {}): DynamicModule {\n const providers: Provider[] = [\n {\n provide: CORE_OPTIONS,\n useValue: options,\n },\n {\n provide: DbService,\n useFactory: async () => {\n await Core.initialize(options);\n return Core.db;\n },\n },\n {\n provide: DB_SERVICE,\n useFactory: async () => {\n await Core.initialize(options);\n return Core.db;\n },\n },\n ];\n\n return {\n module: CoreModule,\n global: true,\n providers,\n exports: [DbService, DB_SERVICE, CORE_OPTIONS],\n };\n }\n\n /**\n * Register CoreModule with async configuration\n */\n static forRootAsync(options: CoreModuleAsyncOptions): DynamicModule {\n const providers: Provider[] = [\n {\n provide: CORE_OPTIONS,\n useFactory: options.useFactory,\n inject: options.inject ?? [],\n },\n {\n provide: DbService,\n useFactory: async (coreOptions: CoreInitOptions) => {\n await Core.initialize(coreOptions);\n return Core.db;\n },\n inject: [CORE_OPTIONS],\n },\n {\n provide: DB_SERVICE,\n useFactory: async (coreOptions: CoreInitOptions) => {\n await Core.initialize(coreOptions);\n return Core.db;\n },\n inject: [CORE_OPTIONS],\n },\n ];\n\n return {\n module: CoreModule,\n global: true,\n imports: options.imports ?? [],\n providers,\n exports: [DbService, DB_SERVICE, CORE_OPTIONS],\n };\n }\n}\n"]}
|