@burdenoff/be-sdk 2026.1202.5 → 2026.1202.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/{EventQueueFactory-DbLEV5h_.js → EventQueueFactory-0XHOTKEv.js} +19 -13
  2. package/dist/{EventQueueFactory-DbLEV5h_.js.map → EventQueueFactory-0XHOTKEv.js.map} +1 -1
  3. package/dist/activity/index.d.ts +2 -2
  4. package/dist/auth/index.d.ts +1 -1
  5. package/dist/{backoff-Di7sEjSw.js → backoff-Ck5QMdig.js} +2 -2
  6. package/dist/{backoff-Di7sEjSw.js.map → backoff-Ck5QMdig.js.map} +1 -1
  7. package/dist/bootstrap/index.d.ts +1 -1
  8. package/dist/context/index.d.ts +1 -1
  9. package/dist/env-cCfoPZ7m.js +122 -0
  10. package/dist/env-cCfoPZ7m.js.map +1 -0
  11. package/dist/event-queue/index.d.ts +2 -2
  12. package/dist/event-queue/index.js +6 -6
  13. package/dist/{event-queue-ANzylLK1.js → event-queue-CpVi7BET.js} +11 -8
  14. package/dist/event-queue-CpVi7BET.js.map +1 -0
  15. package/dist/feature-flags/index.d.ts +1 -1
  16. package/dist/graph/index.d.ts +1 -1
  17. package/dist/graph/index.js +2 -2
  18. package/dist/{graph-emitter-CwSyGt3g.js → graph-emitter-CtfPpHxL.js} +8 -4
  19. package/dist/{graph-emitter-CwSyGt3g.js.map → graph-emitter-CtfPpHxL.js.map} +1 -1
  20. package/dist/{graph-BTaqvVYQ.js → graph-hPqNRoKC.js} +4 -4
  21. package/dist/{graph-BTaqvVYQ.js.map → graph-hPqNRoKC.js.map} +1 -1
  22. package/dist/graphql/index.js +1 -1
  23. package/dist/{graphql-D_DkedFZ.js → graphql-Cn-OBnyu.js} +2 -2
  24. package/dist/{graphql-D_DkedFZ.js.map → graphql-Cn-OBnyu.js.map} +1 -1
  25. package/dist/{graphql-DcZAKC6p.d.ts → graphql-DPkc5IMZ.d.ts} +1 -1
  26. package/dist/{index-UQSbAERe.d.ts → index--w3AsbqC.d.ts} +2 -2
  27. package/dist/{index-BMy-d2_f.d.ts → index-12QwfPvR.d.ts} +3 -3
  28. package/dist/{index-GzZunmGS.d.ts → index-B30y7Yry.d.ts} +3 -3
  29. package/dist/{index-C96mNrLW.d.ts → index-C4MFjzOT.d.ts} +2 -2
  30. package/dist/{index-CQ3vxT5P.d.ts → index-CDdrBQom.d.ts} +1 -0
  31. package/dist/{index-CeaJcbar.d.ts → index-ChJqXbVL.d.ts} +8 -4
  32. package/dist/{index-B4ckqUZX.d.ts → index-Cx77z1cc.d.ts} +1 -1
  33. package/dist/{index-Cl3Xiw1O.d.ts → index-DM5zS9TT.d.ts} +2 -2
  34. package/dist/{index-Cs426iRP.d.ts → index-DMKCyeBm.d.ts} +4 -4
  35. package/dist/{index-BmL-JjQK.d.ts → index-DMq2xPV7.d.ts} +1 -1
  36. package/dist/{index-C4hRRihw.d.ts → index-Dl32yXnZ.d.ts} +1 -1
  37. package/dist/{index-j1B6eYHc.d.ts → index-Ds_V1Crj.d.ts} +2 -2
  38. package/dist/{index-CZWopQsh.d.ts → index-PvHsCusi.d.ts} +1 -1
  39. package/dist/index.d.ts +14 -14
  40. package/dist/index.js +12 -8
  41. package/dist/index.js.map +1 -1
  42. package/dist/init/index.js +1 -1
  43. package/dist/{init-knkrqVvJ.js → init-CsfDrW9M.js} +3 -3
  44. package/dist/{init-knkrqVvJ.js.map → init-CsfDrW9M.js.map} +1 -1
  45. package/dist/instrumentation/index.d.ts +2 -2
  46. package/dist/logger/index.d.ts +1 -1
  47. package/dist/{middleware-InVCyjUX.js → middleware-aO50bLUO.js} +2 -2
  48. package/dist/{middleware-InVCyjUX.js.map → middleware-aO50bLUO.js.map} +1 -1
  49. package/dist/notifications/index.d.ts +1 -1
  50. package/dist/payments/index.d.ts +2 -2
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +2 -2
  53. package/dist/{prisma-DcMrbj7W.js → prisma-BlB0aalN.js} +3 -3
  54. package/dist/{prisma-DcMrbj7W.js.map → prisma-BlB0aalN.js.map} +1 -1
  55. package/dist/rbac/index.d.ts +1 -1
  56. package/dist/resource-caps/index.d.ts +1 -1
  57. package/dist/search/index.d.ts +2 -2
  58. package/dist/server/index.d.ts +2 -2
  59. package/dist/telemetry/index.d.ts +2 -2
  60. package/dist/tracker/index.d.ts +2 -2
  61. package/dist/translation/index.d.ts +2 -2
  62. package/dist/types/index.d.ts +1 -1
  63. package/dist/types/index.js.map +1 -1
  64. package/dist/{types-C36JkwDg.d.ts → types-BxZmaW3v.d.ts} +1 -1
  65. package/dist/usage/index.d.ts +1 -1
  66. package/dist/{workspace-extension-C0qib11C.d.ts → workspace-extension-DAs06Hv_.d.ts} +1 -1
  67. package/package.json +1 -1
  68. package/dist/env-DdaoGjIt.js +0 -74
  69. package/dist/env-DdaoGjIt.js.map +0 -1
  70. package/dist/event-queue-ANzylLK1.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/client/graphql.ts","../src/client/tenant-backend.ts","../src/index.ts"],"sourcesContent":["/**\n * GraphQL Client for Burdenoff Backend SDK\n * Handles communication with workspaces-backend and tenant-backend\n */\n\nimport type { Variables } from 'graphql-request';\nimport { GraphQLClient } from 'graphql-request';\nimport { GatewayClient } from '../gateway/client.js';\nimport { GatewayError, GatewayErrorType } from '../gateway/types.js';\nimport type { ServiceLayer } from '../types/layer.js';\nimport type { SDKConfig, SDKContext } from '../types/index.js';\nimport { APIError, NetworkError, TimeoutError } from '../types/index.js';\n\nfunction isServiceLayer(value: string | undefined): value is ServiceLayer {\n return value === 'wspace' || value === 'global';\n}\n\n/**\n * GraphQL client wrapper with retry logic and error handling\n */\nexport class BurdenoffGraphQLClient {\n private workspacesClient: GraphQLClient;\n /**\n * Cross-layer (tenant) calls go through the unified GatewayClient, which\n * targets the peer layer's PUBLIC gateway and mints a short-lived `service`\n * actor JWT (via signServiceJwt) so the gateway admits the M2M call and the\n * subgraph sees a trusted service context. This is the same mechanism used by\n * `GatewayClient.crossLayerQuery` everywhere else — kept consistent here so\n * tenant SDK calls (notifications, tenant lookups) authenticate identically.\n */\n private tenantGateway?: GatewayClient;\n private config: SDKConfig;\n private defaultContext: SDKContext;\n\n constructor(config: SDKConfig, defaultContext: SDKContext = {}) {\n this.config = config;\n this.defaultContext = defaultContext;\n\n // Initialize workspaces API client (should point to wspace-int-gateway for M2M calls)\n this.workspacesClient = new GraphQLClient(config.workspacesApiUrl, {\n headers: this.getHeaders(defaultContext),\n });\n\n // Cross-layer (tenant) calls go through the unified GatewayClient. The\n // configured tenantApiUrl is the peer layer's PUBLIC gateway; GatewayClient\n // mints the service JWT for it. `layer`/`serviceName` fall back to the\n // standard SERVICE_LAYER/SERVICE_NAME env vars.\n if (config.tenantApiUrl) {\n this.tenantGateway = new GatewayClient({\n layer:\n config.serviceLayer ??\n (isServiceLayer(process.env['SERVICE_LAYER']) ? process.env['SERVICE_LAYER'] : 'wspace'),\n serviceName: config.serviceName ?? process.env['SERVICE_NAME'] ?? 'burdenoff-be-sdk',\n crossLayerGatewayUrl: config.tenantApiUrl,\n timeout: config.timeout,\n // Honor the SDK's retry config (same field shape) so callers that lower\n // maxAttempts for non-idempotent tenant mutations (e.g. notification\n // sends) are respected instead of falling back to the gateway default.\n retry: config.retry,\n });\n }\n }\n\n /**\n * Get headers for GraphQL request\n * Includes actor context headers for RBAC authorization\n */\n private getHeaders(context: SDKContext): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (context.token) {\n headers['Authorization'] = `Bearer ${context.token}`;\n }\n\n // Actor context headers for RBAC\n if (context.actorId) {\n headers['x-actor-id'] = context.actorId;\n }\n\n if (context.actorType) {\n headers['x-actor-type'] = context.actorType;\n }\n\n if (context.workspaceId) {\n headers['x-workspace-id'] = context.workspaceId;\n }\n\n if (context.productId) {\n headers['x-product-id'] = context.productId;\n }\n\n return headers;\n }\n\n /**\n * Update context for future requests\n */\n public updateContext(context: Partial<SDKContext>): void {\n this.defaultContext = { ...this.defaultContext, ...context };\n this.workspacesClient.setHeaders(this.getHeaders(this.defaultContext));\n // The tenant GatewayClient derives per-request headers (and mints its own\n // service JWT) at call time, so there is no persistent header state to update.\n }\n\n /**\n * Execute GraphQL query/mutation against workspaces API\n */\n public async query<T>(query: string, variables?: Variables, context?: SDKContext): Promise<T> {\n return this.executeWithRetry(\n () => this.executeQuery(this.workspacesClient, query, variables, context),\n 'workspaces'\n );\n }\n\n /**\n * Execute GraphQL query/mutation against the tenant (cross-layer) API.\n *\n * Routed through GatewayClient.crossLayerQuery: targets the peer layer's\n * PUBLIC gateway and mints a short-lived `service` actor JWT. Only routing\n * context (workspace / product) is forwarded — the end-user identity is not,\n * because cross-layer tenant operations are service-to-service M2M. Retry and\n * circuit-breaking are handled inside GatewayClient.\n */\n public async tenantQuery<T>(query: string, variables?: Variables, context?: SDKContext): Promise<T> {\n if (!this.tenantGateway) {\n throw new APIError('Tenant API URL not configured', {\n operation: 'tenantQuery',\n });\n }\n\n const mergedContext = { ...this.defaultContext, ...context };\n const headers: Record<string, string> = {};\n if (mergedContext.workspaceId) {\n headers['x-workspace-id'] = mergedContext.workspaceId;\n }\n if (mergedContext.productId) {\n headers['x-product-id'] = mergedContext.productId;\n }\n if (mergedContext.organizationId) {\n headers['x-org-id'] = mergedContext.organizationId;\n }\n\n try {\n const response = await this.tenantGateway.crossLayerQuery<T>({\n query,\n variables: variables as Record<string, unknown> | undefined,\n headers,\n });\n\n if (response.data == null) {\n throw new APIError('Tenant query returned no data', { api: 'tenant' });\n }\n return response.data;\n } catch (error) {\n throw this.mapTenantError(error);\n }\n }\n\n /**\n * Map a GatewayClient failure back to the SDK's APIError contract so existing\n * tenant callers (which inspect `error.message` / extensions, e.g. \"Forbidden\")\n * keep working unchanged.\n */\n private mapTenantError(error: unknown): Error {\n if (error instanceof APIError) {\n return error;\n }\n if (error instanceof GatewayError) {\n const first = error.graphqlErrors?.[0];\n if (first) {\n return new APIError(first.message, {\n graphqlErrors: error.graphqlErrors,\n extensions: first.extensions,\n });\n }\n // Preserve the SDK's error-subtype contract: callers may branch on\n // `instanceof NetworkError` / `TimeoutError`, which the legacy tenant path\n // (executeQuery → handleError) used to throw.\n if (error.type === GatewayErrorType.NETWORK_ERROR) {\n return new NetworkError(error.message, { gatewayErrorType: error.type });\n }\n if (error.type === GatewayErrorType.TIMEOUT_ERROR) {\n return new TimeoutError(error.message, { gatewayErrorType: error.type });\n }\n return new APIError(error.message, { gatewayErrorType: error.type });\n }\n return this.handleError(error);\n }\n\n /**\n * Execute GraphQL request\n */\n private async executeQuery<T>(\n client: GraphQLClient,\n query: string,\n variables?: Variables,\n context?: SDKContext\n ): Promise<T> {\n try {\n // A per-call context applies to this request only. It used to be written onto the\n // shared client with setHeaders(), which leaked one call's actor and workspace headers\n // into every later call (and into concurrent calls) made without a context.\n if (!context) {\n return await client.request<T>(query, variables);\n }\n const mergedContext = { ...this.defaultContext, ...context };\n return await client.request<T>({\n document: query,\n variables,\n requestHeaders: this.getHeaders(mergedContext),\n });\n } catch (error) {\n throw this.handleError(error);\n }\n }\n\n /**\n * Execute with retry logic\n */\n private async executeWithRetry<T>(operation: () => Promise<T>, api: 'workspaces' | 'tenant'): Promise<T> {\n const maxAttempts = this.config.retry?.maxAttempts || 3;\n const initialDelay = this.config.retry?.initialDelay || 1000;\n const maxDelay = this.config.retry?.maxDelay || 10000;\n const backoffMultiplier = this.config.retry?.backoffMultiplier || 2;\n\n let lastError: Error | undefined;\n let delay = initialDelay;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error as Error;\n\n // Don't retry on certain errors\n if (error instanceof APIError && !this.shouldRetry(error)) {\n throw error;\n }\n\n // Don't retry on last attempt\n if (attempt === maxAttempts) {\n break;\n }\n\n // Wait before retrying\n await this.sleep(Math.min(delay, maxDelay));\n delay *= backoffMultiplier;\n }\n }\n\n throw new APIError(`GraphQL request failed after ${maxAttempts} attempts`, {\n api,\n lastError: lastError?.message,\n });\n }\n\n /**\n * Determine if error should be retried\n */\n private shouldRetry(error: APIError): boolean {\n // Retry on network errors and timeouts\n if (error instanceof NetworkError || error instanceof TimeoutError) {\n return true;\n }\n\n // Retry on 5xx server errors\n if (error.code === 'SERVER_ERROR') {\n return true;\n }\n\n // Don't retry on client errors (4xx)\n return false;\n }\n\n /**\n * Handle GraphQL errors\n */\n private handleError(error: unknown): Error {\n if (error instanceof Error) {\n // Check for network errors\n if (error.message.includes('fetch failed') || error.message.includes('ECONNREFUSED')) {\n return new NetworkError('Network error while connecting to API', {\n originalError: error.message,\n });\n }\n\n // Check for timeout errors\n if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {\n return new TimeoutError('Request timed out', {\n originalError: error.message,\n });\n }\n\n // GraphQL errors\n if ('response' in error && error.response) {\n const response = error.response as {\n errors?: Array<{ message: string; extensions?: Record<string, unknown> }>;\n };\n if (response.errors && response.errors.length > 0) {\n const firstError = response.errors[0];\n if (firstError) {\n return new APIError(firstError.message, {\n graphqlErrors: response.errors,\n extensions: firstError.extensions,\n });\n }\n }\n }\n\n return new APIError(error.message, {\n originalError: error.message,\n });\n }\n\n return new APIError('Unknown error occurred', {\n error: String(error),\n });\n }\n\n /**\n * Sleep utility for retry delays\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n /**\n * Get current context\n */\n public getContext(): SDKContext {\n return { ...this.defaultContext };\n }\n}\n","/**\n * Tenant Backend Client\n * Centralized client for accessing tenant-backend services (notifications, auth, etc.)\n *\n * This is a reusable utility that can be used by any backend to communicate with tenant-backend.\n */\n\nimport { BurdenoffGraphQLClient } from './graphql.js';\nimport { TenantNotificationsModule } from '../notifications/tenant-notifications.js';\nimport { logger } from '../logger/index.js';\nimport type { SDKConfig } from '../types/index.js';\n\nexport interface TenantBackendClientConfig {\n /** Tenant backend GraphQL URL */\n tenantBackendUrl: string;\n /** Workspaces backend GraphQL URL (for SDK initialization) */\n workspacesBackendUrl?: string;\n /** Optional API key for tenant backend authentication */\n apiKey?: string;\n}\n\n/**\n * Tenant Backend Client\n * Provides access to centralized tenant-backend services using be-sdk\n *\n * @example\n * ```typescript\n * import { TenantBackendClient } from '@burdenoff/be-sdk';\n *\n * const client = new TenantBackendClient({\n * tenantBackendUrl: process.env.GLOBAL_INT_GATEWAY_URL!,\n * workspacesBackendUrl: process.env.WORKSPACES_BACKEND_URL,\n * apiKey: process.env.TENANT_BACKEND_API_KEY,\n * });\n *\n * // Send notification\n * await client.notifications.sendWithTemplate({\n * templateSlug: 'user-welcome',\n * recipients: ['user@example.com'],\n * variables: { userName: 'John' },\n * });\n *\n * // Execute raw query\n * const result = await client.query(`\n * query GetUser($id: ID!) {\n * user(id: $id) { id name email }\n * }\n * `, { id: 'user-123' });\n * ```\n */\nexport class TenantBackendClient {\n private graphqlClient: BurdenoffGraphQLClient;\n private config: TenantBackendClientConfig;\n\n /** Notifications module for sending notifications via tenant backend */\n public readonly notifications: TenantNotificationsModule;\n\n constructor(config: TenantBackendClientConfig) {\n this.config = config;\n\n // Build SDK config\n const sdkConfig: SDKConfig = {\n workspacesApiUrl: config.workspacesBackendUrl || 'http://localhost:4000/graphql',\n tenantApiUrl: config.tenantBackendUrl,\n };\n\n // Initialize GraphQL client\n this.graphqlClient = new BurdenoffGraphQLClient(sdkConfig, {});\n\n // Initialize notifications module with empty context (context will be set per request)\n this.notifications = new TenantNotificationsModule(this.graphqlClient, {});\n\n logger.info('[TenantBackend] Client initialized using be-sdk', {\n tenantUrl: config.tenantBackendUrl,\n workspacesUrl: config.workspacesBackendUrl,\n hasApiKey: !!config.apiKey,\n });\n }\n\n /**\n * Update authentication token\n *\n * @param token - JWT token for authentication\n */\n public setAuthToken(token: string): void {\n this.graphqlClient.updateContext({ token });\n logger.debug('[TenantBackend] Authentication token updated');\n }\n\n /**\n * Execute raw GraphQL query against tenant backend\n *\n * @param query - GraphQL query string\n * @param variables - Query variables\n * @returns Query result\n *\n * @example\n * ```typescript\n * const result = await client.query(`\n * query GetTemplate($slug: String!) {\n * notificationTemplate(slug: $slug) {\n * id\n * slug\n * subject\n * }\n * }\n * `, { slug: 'user-welcome' });\n * ```\n */\n public async query<T>(query: string, variables?: Record<string, unknown>): Promise<T> {\n return this.graphqlClient.tenantQuery<T>(query, variables);\n }\n\n /**\n * Health check\n *\n * @returns True if tenant backend is reachable, false otherwise\n */\n public async healthCheck(): Promise<boolean> {\n try {\n const query = `\n query HealthCheck {\n __typename\n }\n `;\n await this.graphqlClient.tenantQuery(query);\n return true;\n } catch (error) {\n logger.error('[TenantBackend] Health check failed', {\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n return false;\n }\n }\n\n /**\n * Get GraphQL client for advanced usage\n *\n * @returns Underlying BurdenoffGraphQLClient\n */\n public getClient(): BurdenoffGraphQLClient {\n return this.graphqlClient;\n }\n\n /**\n * Get client configuration\n *\n * @returns Client configuration\n */\n public getConfig(): TenantBackendClientConfig {\n return { ...this.config };\n }\n}\n\n/**\n * Create a TenantBackendClient instance\n *\n * @param config - Client configuration\n * @returns TenantBackendClient instance\n *\n * @example\n * ```typescript\n * import { createTenantBackendClient } from '@burdenoff/be-sdk';\n *\n * const client = createTenantBackendClient({\n * tenantBackendUrl: process.env.GLOBAL_INT_GATEWAY_URL!,\n * });\n * ```\n */\nexport function createTenantBackendClient(config: TenantBackendClientConfig): TenantBackendClient {\n return new TenantBackendClient(config);\n}\n","/**\n * Burdenoff Backend SDK\n * Comprehensive SDK for all Burdenoff products\n *\n * @packageDocumentation\n */\n\nimport { BurdenoffGraphQLClient } from './client/graphql.js';\nimport type { SDKConfig, SDKContext } from './types/index.js';\nimport type { Logger } from './logger/index.js';\nimport { logger } from './logger/index.js';\nimport { ContextManager } from './context/index.js';\nimport { AuthModule } from './auth/index.js';\nimport { NotificationsModule } from './notifications/index.js';\nimport { TenantNotificationsModule } from './notifications/tenant-notifications.js';\nimport { RBACModule } from './rbac/index.js';\nimport { ActivityModule } from './activity/index.js';\nimport { UsageModule } from './usage/index.js';\nimport { TrackerModule } from './tracker/index.js';\nimport { DatabaseModule } from './database/index.js';\nimport { EventsModule, EventQueueFactory, QueueType, resolveEventStreamsUrl } from './event-queue/index.js';\nimport type { IEventPublisher, PublisherConfig } from './event-queue/index.js';\nimport { disposeAll } from './lifecycle/index.js';\nimport { GraphModule } from './graph/index.js';\nimport { SearchModule } from './search/index.js';\nimport { TranslationModule } from './translation/index.js';\nimport { PaymentsModule } from './payments/index.js';\nimport type { BootstrapModule } from './bootstrap/index.js';\nimport { createBootstrap } from './bootstrap/index.js';\n// Temporal is lazy-loaded to avoid requiring @temporalio/client when not used\nimport type { TemporalModule } from './temporal/index.js';\n\n/**\n * Main Burdenoff SDK class\n *\n * @example\n * ```typescript\n * import { BurdenoffSDK } from '@burdenoff/be-sdk';\n *\n * const sdk = new BurdenoffSDK({\n * workspacesApiUrl: 'https://api.burdenoff.com/graphql',\n * timeout: 30000,\n * });\n *\n * // Use the unified tracker (most common use case)\n * const result = await sdk.tracker.track({\n * userId: 'user123',\n * action: 'create_project',\n * resourceType: 'project',\n * workspaceId: 'ws123',\n * usage: {\n * quotaName: 'myproduct.projects.count',\n * productId: 'myproduct',\n * amount: 1,\n * },\n * });\n * ```\n */\nexport class BurdenoffSDK {\n private client: BurdenoffGraphQLClient;\n private defaultContext: SDKContext;\n\n // Event queue publisher state (Redis Streams)\n private eventPublisher: IEventPublisher | null = null;\n private eventPublisherInitPromise: Promise<void> | null = null;\n private eventQueueConfig: import('./types/index.js').EventQueueSDKConfig | null = null;\n\n // Initialization state\n private initializationPromise: Promise<void> | null = null;\n private isShuttingDown = false;\n\n /** Authentication module */\n public readonly auth: AuthModule;\n\n /** Notifications module (workspaces-backend) */\n public readonly notifications: NotificationsModule;\n\n /** Tenant Notifications module (tenant-backend - RECOMMENDED) */\n public readonly tenantNotifications: TenantNotificationsModule;\n\n /** RBAC module */\n public readonly rbac: RBACModule;\n\n /** Activity tracking module */\n public readonly activity: ActivityModule;\n\n /** Usage & Quota module */\n public readonly usage: UsageModule;\n\n /** Unified Tracker module (MOST IMPORTANT - use this for most operations) */\n public readonly tracker: TrackerModule;\n\n /** Database helpers module */\n public readonly database: typeof DatabaseModule;\n\n /** Events/Queue module */\n public readonly events: EventsModule;\n\n /** Graph integration module */\n public readonly graph: GraphModule;\n\n /** Search module */\n public readonly search: SearchModule;\n\n /** Translation module */\n public readonly translation: TranslationModule;\n\n /** Payments module */\n public readonly payments: PaymentsModule;\n\n /** Temporal workflow orchestration module (lazy-loaded) */\n private _temporal: TemporalModule | null = null;\n private _temporalPromise: Promise<TemporalModule> | null = null;\n private _temporalConfig: { moduleType?: string; address?: string; namespace?: string; taskQueue?: string } | null =\n null;\n\n /**\n * Get Temporal workflow orchestration module (lazy-loaded)\n * Only loads @temporalio/client when this method is called\n *\n * @returns Promise resolving to TemporalModule\n * @example\n * ```typescript\n * const temporal = await sdk.getTemporalModule();\n * await temporal.startWorkflow('myWorkflow', { ... });\n * ```\n */\n public async getTemporalModule(): Promise<TemporalModule> {\n if (this._temporal) {\n return this._temporal;\n }\n\n if (!this._temporalPromise) {\n this._temporalPromise = this.loadTemporalModule();\n }\n\n return this._temporalPromise;\n }\n\n /**\n * Load temporal module dynamically\n * @private\n */\n private async loadTemporalModule(): Promise<TemporalModule> {\n const { TemporalModule: TM } = (await import('./temporal/index.js')) as { TemporalModule: typeof TemporalModule };\n this._temporal = this._temporalConfig?.moduleType\n ? new TM({\n moduleType: this._temporalConfig.moduleType as 'workspace' | 'tenant',\n address: this._temporalConfig.address,\n namespace: this._temporalConfig.namespace,\n taskQueue: this._temporalConfig.taskQueue,\n })\n : TM.fromEnv();\n return this._temporal;\n }\n\n /** Logger instance */\n public readonly logger: Logger;\n\n /** Context manager */\n public readonly context: typeof ContextManager;\n\n /**\n * Create SDK instance\n */\n constructor(config: SDKConfig, defaultContext: SDKContext = {}) {\n // Initialize client\n this.client = new BurdenoffGraphQLClient(config, defaultContext);\n this.defaultContext = defaultContext;\n\n // Initialize logger\n this.logger = logger;\n if (config.logger) {\n this.logger.setLevel(config.logger.level);\n this.logger.setConsoleEnabled(config.logger.console);\n if (config.logger.transport) {\n this.logger.addTransport(config.logger.transport);\n }\n }\n\n // Initialize context manager\n this.context = ContextManager;\n if (Object.keys(defaultContext).length > 0) {\n ContextManager.setContext(defaultContext);\n }\n\n // Initialize all modules\n this.auth = new AuthModule(this.client, defaultContext);\n this.notifications = new NotificationsModule(this.client, defaultContext);\n this.tenantNotifications = new TenantNotificationsModule(this.client, defaultContext);\n this.rbac = new RBACModule(this.client, defaultContext);\n this.activity = new ActivityModule(this.client, defaultContext);\n this.usage = new UsageModule(this.client, defaultContext);\n this.tracker = new TrackerModule(this.client, defaultContext);\n this.database = DatabaseModule;\n this.events = new EventsModule(this.client, defaultContext);\n this.graph = new GraphModule(this.client, defaultContext);\n this.search = new SearchModule(this.client, defaultContext);\n this.translation = new TranslationModule(this.client, defaultContext);\n this.payments = new PaymentsModule(this.client, defaultContext);\n\n // Store Temporal configuration for lazy loading (avoids requiring @temporalio/client when not used)\n if (config.temporalModuleType) {\n this._temporalConfig = {\n moduleType: config.temporalModuleType,\n address: config.temporalAddress,\n namespace: config.temporalNamespace,\n taskQueue: config.temporalTaskQueue,\n };\n }\n\n // Store event queue configuration. Auto-enabled when REDIS_STREAMS_URL or\n // REDIS_URL is set even if no explicit config block is provided.\n if (config.eventQueue || resolveEventStreamsUrl()) {\n this.eventQueueConfig = {\n autoConnect: true,\n maxReconnectAttempts: -1,\n reconnectTimeWait: 2000,\n ...config.eventQueue,\n };\n }\n\n logger.info('[SDK] Burdenoff SDK initialized', {\n workspacesApiUrl: config.workspacesApiUrl,\n tenantApiUrl: config.tenantApiUrl,\n hasDefaultContext: Object.keys(defaultContext).length > 0,\n hasEventQueueConfig: !!this.eventQueueConfig,\n hasTemporalConfig: !!config.temporalModuleType,\n });\n\n // Schedule background initialization outside the constructor\n // This defers async work to after constructor completes (satisfies no-async-constructor)\n this.scheduleBackgroundInit();\n }\n\n /**\n * Schedule background initialization outside constructor\n * Uses queueMicrotask to defer async work while maintaining initialization order\n * @private\n */\n private scheduleBackgroundInit(): void {\n queueMicrotask(() => {\n this.initializationPromise = this.initializeAsync();\n });\n }\n\n /**\n * Update SDK context\n */\n public setContext(context: SDKContext): void {\n this.defaultContext = { ...this.defaultContext, ...context };\n this.client.updateContext(context);\n ContextManager.setContext(this.defaultContext);\n }\n\n /**\n * Get current context\n */\n public getContext(): SDKContext | undefined {\n return ContextManager.getContext();\n }\n\n /**\n * Run function with specific context\n */\n public async withContext<T>(context: SDKContext, fn: () => Promise<T>): Promise<T> {\n return ContextManager.withContext(context, fn);\n }\n\n /**\n * Background initialization for event queue and other async resources\n * @private\n */\n private async initializeAsync(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n if (this.eventQueueConfig?.autoConnect) {\n promises.push(\n this.initializeEventQueue().catch((error) => {\n logger.warn('[SDK] Failed to auto-connect to Redis Streams', { error });\n })\n );\n }\n\n await Promise.allSettled(promises);\n }\n\n /**\n * Initialize the Redis Streams event publisher\n * @private\n */\n private async initializeEventQueue(): Promise<void> {\n if (!this.eventQueueConfig || this.eventPublisher) return;\n\n const url = this.eventQueueConfig.url || resolveEventStreamsUrl();\n if (!url) {\n logger.warn('[SDK] No REDIS_STREAMS_URL / REDIS_URL available — event publisher disabled');\n return;\n }\n\n const publisherConfig: PublisherConfig = {\n type: QueueType.REDIS_STREAMS,\n url,\n password: this.eventQueueConfig.password,\n name: this.eventQueueConfig.name || 'burdenoff-sdk-publisher',\n maxReconnectAttempts: this.eventQueueConfig.maxReconnectAttempts ?? -1,\n reconnectTimeWait: this.eventQueueConfig.reconnectTimeWait ?? 2000,\n };\n\n this.eventPublisher = EventQueueFactory.createPublisher(publisherConfig);\n await this.eventPublisher.connect();\n\n logger.info('[SDK] Redis Streams event publisher initialized', {\n url,\n name: this.eventQueueConfig.name,\n });\n }\n\n /**\n * Get the event publisher instance (lazy initialization).\n *\n * @example\n * ```typescript\n * const publisher = await sdk.getEventPublisher();\n * await publisher.publish({\n * subject: 'events.user.created',\n * data: { userId: 'user-123' }\n * });\n * ```\n */\n public async getEventPublisher(): Promise<IEventPublisher> {\n if (this.eventPublisher) return this.eventPublisher;\n if (!this.eventQueueConfig) {\n throw new Error(\n '[SDK] Event queue not configured - set REDIS_STREAMS_URL / REDIS_URL or provide config.eventQueue'\n );\n }\n\n if (!this.eventPublisherInitPromise) {\n this.eventPublisherInitPromise = this.initializeEventQueue();\n }\n await this.eventPublisherInitPromise;\n\n if (!this.eventPublisher) {\n throw new Error('[SDK] Event publisher initialization failed');\n }\n return this.eventPublisher;\n }\n\n /**\n * Wait for SDK initialization to complete\n *\n * @example\n * ```typescript\n * await sdk.waitForReady();\n * ```\n */\n public async waitForReady(): Promise<void> {\n if (this.initializationPromise) {\n await this.initializationPromise;\n }\n }\n\n /**\n * Check event queue (Redis Streams) health status\n *\n * @example\n * ```typescript\n * const health = await sdk.isEventQueueHealthy();\n * if (health.status === 'healthy') {\n * console.log('Event queue is connected');\n * }\n * ```\n */\n public async isEventQueueHealthy(): Promise<import('./types/index.js').EventQueueHealthStatus> {\n if (!this.eventQueueConfig) {\n return { status: 'not_configured', connected: false };\n }\n\n if (!this.eventPublisher) {\n return {\n status: 'unhealthy',\n connected: false,\n url: this.eventQueueConfig.url,\n details: { reason: 'Not initialized' },\n };\n }\n\n try {\n const healthCheck = await this.eventPublisher.healthCheck();\n return {\n status: healthCheck.status as 'healthy' | 'unhealthy',\n connected: this.eventPublisher.isConnected(),\n url: this.eventQueueConfig.url,\n details: healthCheck.details,\n };\n } catch (error) {\n return {\n status: 'unhealthy',\n connected: false,\n url: this.eventQueueConfig.url,\n details: { error: error instanceof Error ? error.message : String(error) },\n };\n }\n }\n\n /**\n * Check Temporal health status\n *\n * @example\n * ```typescript\n * const health = await sdk.isTemporalHealthy();\n * if (health.status === 'healthy') {\n * console.log('Temporal is connected');\n * }\n * ```\n */\n public async isTemporalHealthy(): Promise<import('./types/index.js').TemporalHealthStatus> {\n // If temporal hasn't been loaded yet, it's not configured\n if (!this._temporal) {\n return { status: 'not_configured', connected: false };\n }\n\n const config = this._temporal.getConfig();\n\n if (!config.address) {\n return { status: 'not_configured', connected: false };\n }\n\n try {\n const client = this._temporal.getClient();\n // Use the public isClientConnected method\n const connected = client.isClientConnected();\n\n return {\n status: connected ? 'healthy' : 'unhealthy',\n connected: connected,\n address: config.address,\n namespace: config.namespace,\n details: { taskQueue: config.taskQueue },\n };\n } catch (error: unknown) {\n return {\n status: 'unhealthy',\n connected: false,\n address: config.address,\n namespace: config.namespace,\n details: { error: error instanceof Error ? error.message : String(error) },\n };\n }\n }\n\n /**\n * Get overall SDK health status\n *\n * @example\n * ```typescript\n * const health = await sdk.getHealthStatus();\n * console.log('Event Queue:', health.eventQueue.status);\n * console.log('Temporal:', health.temporal.status);\n * ```\n */\n public async getHealthStatus(): Promise<import('./types/index.js').SDKHealthStatus> {\n const [eventQueue, temporal] = await Promise.all([this.isEventQueueHealthy(), this.isTemporalHealthy()]);\n return { eventQueue, temporal };\n }\n\n /**\n * Graceful shutdown - disconnect all resources\n *\n * @example\n * ```typescript\n * // On application shutdown\n * await sdk.shutdown({ timeout: 5000, force: true });\n * ```\n */\n public async shutdown(options: import('./types/index.js').SDKShutdownOptions = {}): Promise<void> {\n if (this.isShuttingDown) {\n logger.warn('[SDK] Shutdown already in progress');\n return;\n }\n this.isShuttingDown = true;\n\n const timeout = options.timeout ?? 5000;\n const force = options.force ?? true;\n\n logger.info('[SDK] Starting graceful shutdown', { timeout, force });\n\n const shutdownPromises: Promise<void>[] = [];\n\n if (this.eventPublisher) {\n shutdownPromises.push(\n this.eventPublisher.disconnect().catch((error) => {\n logger.error('[SDK] Error disconnecting event publisher', { error });\n })\n );\n }\n\n if (this._temporal) {\n shutdownPromises.push(\n this._temporal.disconnect().catch((error: unknown) => {\n logger.error('[SDK] Error disconnecting Temporal', { error });\n })\n );\n }\n\n // Close every other long-lived connection registered process-wide — the\n // Redis Streams event consumer(s) (whose blocking clients nothing else\n // closes) and cache clients — so shutdown is complete regardless of how\n // those resources were constructed. disposeAll is bounded + never throws.\n shutdownPromises.push(disposeAll(timeout));\n\n try {\n await Promise.race([\n Promise.allSettled(shutdownPromises),\n new Promise((_, reject) => setTimeout(() => reject(new Error('[SDK] Shutdown timeout exceeded')), timeout)),\n ]);\n\n logger.info('[SDK] Shutdown completed successfully');\n } catch (error) {\n if (!force) {\n throw error;\n }\n logger.warn('[SDK] Shutdown timeout exceeded, forcing shutdown', { error });\n }\n }\n\n /**\n * Create bootstrap instance\n */\n public static createBootstrap(config: Parameters<typeof createBootstrap>[0]): BootstrapModule {\n return createBootstrap(config);\n }\n}\n\n// ============================================================================\n// Core SDK Exports (Top-level)\n// ============================================================================\n\nexport { BurdenoffGraphQLClient } from './client/graphql.js';\nexport { TenantBackendClient, createTenantBackendClient } from './client/tenant-backend.js';\nexport type { TenantBackendClientConfig } from './client/tenant-backend.js';\nexport {\n createInternalClient,\n createInternalClientForWorkspaces,\n createInternalClientForTenant,\n} from './client/internal-client.js';\nexport { ContextManager } from './context/index.js';\nexport { AuthModule } from './auth/index.js';\nexport { NotificationsModule } from './notifications/index.js';\nexport {\n RBACModule,\n createRBACDirective,\n createRBACDirectiveForLayer,\n createRBACDirectiveFromEnv,\n type RBACDirectiveConfig,\n type LayerAwareRBACConfig,\n} from './rbac/index.js';\nexport {\n ActivityModule,\n ActivityOperationUnsupportedError,\n type Activity,\n type ActivityActorType,\n type GetActivitiesOptions,\n type LogActivityOptions,\n} from './activity/index.js';\nexport { UsageModule } from './usage/index.js';\nexport {\n BillingUsageClient,\n type BillingUsageClientConfig,\n type BillingUsageOperationInput,\n type OrgBillingUsageOperationInput,\n type WorkspaceBillingUsageOperationInput,\n type QuotaLimit,\n} from './usage/billing.js';\nexport { TrackerModule } from './tracker/index.js';\nexport { DatabaseModule } from './database/index.js';\nexport { EventsModule } from './event-queue/index.js';\nexport {\n registerDisposable,\n unregisterDisposable,\n getRegisteredDisposableCount,\n disposeAll,\n type ShutdownDisposable,\n} from './lifecycle/index.js';\nexport { GraphModule } from './graph/index.js';\nexport { SearchModule } from './search/index.js';\nexport { TranslationModule } from './translation/index.js';\nexport type {\n TranslationExportFormat,\n ProductTranslationTree,\n ExportProductTranslationsOptions,\n ProductTranslationsExportResult,\n UpsertProductTranslationsOptions,\n UpsertProductTranslationsResult,\n} from './translation/index.js';\nexport { PaymentsModule } from './payments/index.js';\nexport {\n ResourceCapsModule,\n ResourceCapExceededError,\n RESOURCE_CAP_DEFAULTS,\n getResourceCaps,\n configureResourceCaps,\n type ResourceName,\n type ResourceCap,\n type ResourceCapsConfig,\n type BillingPlanTransport,\n type PlanTier,\n type ResourceCapDefaults,\n type WorkspaceResourceCapScope,\n} from './resource-caps/index.js';\n// Generic sharing (invite/accept/permission). Primary entrypoint is the\n// '@burdenoff/be-sdk/sharing' subpath; namespace-exported here to avoid symbol\n// collisions at the package root.\nexport * as Sharing from './sharing/index.js';\n// Shared entity tags (TagsGatewayAdapter + prefixed SDL + resolver factory over\n// wspace-tags-svc). Primary entrypoint is the '@burdenoff/be-sdk/tags' subpath;\n// namespace-exported here to avoid symbol collisions at the package root.\nexport * as Tags from './tags/index.js';\n// Shared files client (upload / metadata / download URL / bytes / delete over\n// wspace-files-svc, plus the FileReference binary-data pointer). Primary\n// entrypoint is the '@burdenoff/be-sdk/files' subpath; namespace-exported here\n// to avoid symbol collisions at the package root.\nexport * as Files from './files/index.js';\n// Shared AI-credit meter (quote on global-billing + idempotent trackUsage on\n// wspace-activity). Primary entrypoint is the '@burdenoff/be-sdk/ai-credits'\n// subpath; namespace-exported here for discoverability.\nexport * as AiCredits from './ai-credits/index.js';\nexport { BootstrapModule, createBootstrap } from './bootstrap/index.js';\nexport {\n TemporalModule,\n TemporalClient,\n TemporalClientFactory,\n TemporalWorker,\n TemporalWorkerFactory,\n TemporalWorkerManager,\n type TemporalClientConfig,\n type TemporalWorkerConfig,\n type WorkflowStartOptions,\n} from './temporal/index.js';\n\n// Export core SDK types (only SDK-specific types, not module types)\nexport type {\n SDKConfig,\n SDKContext,\n LoggerConfig,\n LoggerTransport,\n EventQueueSDKConfig,\n EventQueueHealthStatus,\n TemporalHealthStatus,\n SDKHealthStatus,\n SDKShutdownOptions,\n // Layer types\n ServiceLayer,\n LayerConfig,\n LayerGatewayConfig,\n LayerResourceUrls,\n LayerFullConfig,\n GatewayRoutingConfig,\n CircuitBreakerConfig,\n GatewayRetryConfig,\n GatewayRequestHeaders,\n} from './types/index.js';\n\n// Export layer defaults\nexport {\n DEFAULT_GATEWAY_ROUTING,\n DEFAULT_LAYER_RESOURCES,\n DEFAULT_LAYER_STREAMS,\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n} from './types/index.js';\n\n// ============================================================================\n// Namespaced Exports (Recommended - Avoids Collisions)\n// ============================================================================\n\n/**\n * Logger namespace - Logging functionality\n *\n * @example\n * ```typescript\n * import { Logger } from '@burdenoff/be-sdk';\n *\n * Logger.logger.info('Message');\n * Logger.log('Message');\n * Logger.error('Error message');\n * ```\n */\nexport * as Logger from './logger/index.js';\n\n/**\n * Cache namespace - Caching functionality\n *\n * @example\n * ```typescript\n * import { Cache } from '@burdenoff/be-sdk';\n *\n * const cache = Cache.createCache('my-namespace');\n * await cache.connect();\n * await cache.set('key', 'value', { ttl: 60 });\n * ```\n */\nexport * as Cache from './cache/index.js';\n\n/**\n * EventQueue namespace - Event queue/messaging functionality\n *\n * @example\n * ```typescript\n * import { EventQueue } from '@burdenoff/be-sdk';\n *\n * const publisher = EventQueue.createPublisher();\n * await publisher.connect();\n * await publisher.publish({ subject: 'events.test', data: { foo: 'bar' } });\n * ```\n */\nexport * as EventQueue from './event-queue/index.js';\n\n/**\n * Lifecycle namespace - graceful-shutdown registry for long-lived connections\n *\n * @example\n * ```typescript\n * import { Lifecycle } from '@burdenoff/be-sdk';\n *\n * // Close every registered connection (event bus, cache) on shutdown.\n * await Lifecycle.disposeAll();\n * ```\n */\nexport * as Lifecycle from './lifecycle/index.js';\n\n/**\n * Graph namespace - Graph database operations\n *\n * @example\n * ```typescript\n * import { Graph } from '@burdenoff/be-sdk';\n *\n * const syncService = new Graph.GraphSyncService();\n * await syncService.processEvent(event);\n * ```\n */\nexport * as Graph from './graph/index.js';\n\n/**\n * Middleware namespace - HTTP/GraphQL middleware\n *\n * @example\n * ```typescript\n * import { Middleware } from '@burdenoff/be-sdk';\n *\n * app.use(Middleware.SecurityMiddleware);\n * app.use(Middleware.setupMetricsMiddleware());\n * ```\n */\nexport * as Middleware from './middleware/index.js';\n\n/**\n * Observability namespace - Monitoring, tracing, metrics\n *\n * @example\n * ```typescript\n * import { Observability } from '@burdenoff/be-sdk';\n *\n * const tracer = Observability.createTracer('my-service');\n * ```\n */\nexport * as Observability from './observability/index.js';\n\n/**\n * GraphQL namespace - GraphQL utilities\n *\n * @example\n * ```typescript\n * import { GraphQL } from '@burdenoff/be-sdk';\n *\n * const schema = GraphQL.buildSchema(typeDefs);\n * ```\n */\nexport * as GraphQL from './graphql/index.js';\n\n/**\n * Prisma namespace - Prisma utilities and helpers\n *\n * @example\n * ```typescript\n * import { Prisma } from '@burdenoff/be-sdk';\n *\n * const client = Prisma.createPrismaClient();\n * ```\n */\nexport * as Prisma from './prisma/index.js';\n\n/**\n * Utils namespace - General utilities\n *\n * @example\n * ```typescript\n * import { Utils } from '@burdenoff/be-sdk';\n *\n * const id = Utils.generateId();\n * ```\n */\nexport * as Utils from './utils/index.js';\n\n/**\n * I18n namespace - Internationalization utilities\n *\n * @example\n * ```typescript\n * import { I18n } from '@burdenoff/be-sdk';\n *\n * const i18n = new I18n.I18n({\n * defaultLocale: 'en-US',\n * localesPath: './locales',\n * });\n * await i18n.initialize();\n *\n * const ctx = i18n.createContextFromRequest(request);\n * const message = ctx.t('errors.notFound', { resource: 'Tag' });\n * ```\n */\nexport * as I18n from './i18n/index.js';\n\n/**\n * Translation helper functions - Direct exports for convenience\n *\n * Use `t()` in GraphQL resolvers and providers to get translated messages:\n *\n * @example\n * ```typescript\n * import { t, createTranslator } from '@burdenoff/be-sdk';\n *\n * // Direct usage with context\n * const message = t(ctx, 'tags.errors.notFound', 'Tag not found');\n * const message = t(ctx, 'tags.errors.keyExists', 'Tag {{key}} already exists', { key: 'my-tag' });\n *\n * // Create bound translator\n * const translate = createTranslator(ctx);\n * const msg = translate('tags.errors.notFound', 'Tag not found');\n * ```\n */\nexport { t, createTranslator, hasI18n, getLocale, getLanguage } from './i18n/helpers.js';\nexport type { I18nCapableContext, Translator } from './i18n/helpers.js';\n\n/**\n * Export namespace - Data export utilities\n *\n * @example\n * ```typescript\n * import { Export } from '@burdenoff/be-sdk';\n *\n * class UserExporter extends Export.BaseModuleExporter<User> {\n * moduleKey = 'users';\n * // ...\n * }\n *\n * const csv = Export.convertToCSV(data);\n * const paginated = Export.PaginationService.paginate(items, { page: 1 });\n * ```\n */\nexport * as Export from './export/index.js';\n\n/**\n * Init namespace - Initialization utilities\n *\n * @example\n * ```typescript\n * import { Init } from '@burdenoff/be-sdk';\n *\n * await Init.initializeArangoSchema();\n * ```\n */\nexport * as Init from './init/index.js';\n\n/**\n * DataLoader namespace - DataLoader utilities for batching and caching\n *\n * @example\n * ```typescript\n * import { DataLoader } from '@burdenoff/be-sdk';\n *\n * const tagLoader = DataLoader.createEntityLoader<Tag, string>({\n * batchFn: async (ids) => db.tag.findMany({ where: { id: { in: [...ids] } } }),\n * getKey: (tag) => tag.id,\n * });\n *\n * const tag = await tagLoader.load('tag-123');\n * ```\n */\nexport * as DataLoader from './dataloader/index.js';\n\n/**\n * Notifications namespace - Notification functionality\n *\n * @example\n * ```typescript\n * import { Notifications } from '@burdenoff/be-sdk';\n *\n * await notifications.sendWithTemplate({\n * templateSlug: 'welcome-email',\n * recipients: ['user@example.com'],\n * variables: { name: 'John' }\n * });\n * ```\n */\nexport * as Notifications from './notifications/tenant-notifications.js';\n\n/**\n * Instrumentation namespace - OpenTelemetry instrumentation utilities\n *\n * Provides comprehensive tracing, metrics, and logging instrumentation\n * for microservices with conditional enable/disable support.\n *\n * @example\n * ```typescript\n * import { Instrumentation } from '@burdenoff/be-sdk';\n *\n * // Initialize instrumentation\n * const { tracer, metrics } = Instrumentation.initializeInstrumentation('my-service', {\n * features: { tracing: true, metrics: true, logging: true }\n * });\n *\n * // Create spans\n * await tracer.withSpan('operation', async (span) => {\n * span.setAttribute('key', 'value');\n * });\n *\n * // Create metrics\n * const counter = Instrumentation.createCounter('requests_total', 'Total requests');\n * counter.inc({ endpoint: '/api/users' });\n *\n * // Use decorators\n * class MyService {\n * @Instrumentation.Trace()\n * async myMethod() { ... }\n *\n * @Instrumentation.Instrument({ tracing: true, metrics: true, logging: true })\n * async trackedMethod() { ... }\n * }\n *\n * // GraphQL instrumentation plugin\n * const yoga = createYoga({\n * plugins: [Instrumentation.createGraphQLInstrumentationPlugin()],\n * });\n * ```\n */\nexport * as Instrumentation from './instrumentation/index.js';\n\n/**\n * Layer namespace - Service layer detection and configuration\n *\n * Provides automatic detection of service layer (wspace vs global) and\n * configuration of layer-specific resource URLs.\n *\n * @example\n * ```typescript\n * import { Layer } from '@burdenoff/be-sdk';\n *\n * // Create layer manager\n * const layerManager = new Layer.LayerManager({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Get layer-specific URLs\n * const internalGatewayUrl = layerManager.getInternalGatewayUrl();\n * const crossLayerGatewayUrl = layerManager.getCrossLayerGatewayUrl();\n * const eventQueueUrl = layerManager.getEventQueueUrl();\n * const valkeyUrl = layerManager.getValkeyUrl();\n *\n * // Create from environment\n * const manager = Layer.createLayerManagerFromEnv('wspace-tags-svc');\n *\n * // Detect layer from service name\n * const layer = Layer.detectLayerFromServiceName('global-auth-svc'); // 'global'\n * ```\n */\nexport * as Layer from './layer/index.js';\n\n/**\n * Crypto namespace - Encryption utilities for sensitive data\n *\n * Provides AES-256-GCM encryption/decryption for storing sensitive\n * data like credentials, API keys, and secrets.\n *\n * @example\n * ```typescript\n * import { Crypto } from '@burdenoff/be-sdk';\n *\n * // Generate a key (store this securely, e.g., in env vars)\n * const key = Crypto.generateEncryptionKey();\n *\n * // Encrypt sensitive data\n * const encrypted = Crypto.encrypt('my-api-key', key);\n *\n * // Decrypt when needed\n * const decrypted = Crypto.decrypt(encrypted, key);\n *\n * // Check if value is already encrypted\n * if (!Crypto.isEncrypted(value)) {\n * value = Crypto.encrypt(value, key);\n * }\n * ```\n */\nexport * as Crypto from './crypto/index.js';\n\n/**\n * Gateway namespace - Unified gateway client with circuit breaker\n *\n * Provides GraphQL client with automatic circuit breaker, retry logic,\n * and layer-aware routing for internal and cross-layer communication.\n *\n * @example\n * ```typescript\n * import { Gateway } from '@burdenoff/be-sdk';\n *\n * // Create gateway client\n * const client = new Gateway.GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * serviceIdentity: 'wspace-tags-svc',\n * internalGatewayUrl: 'http://wspace-int-gateway:4000/graphql',\n * crossLayerGatewayUrl: 'http://global-public-gateway:4000/graphql',\n * });\n *\n * // Make internal (same-layer) query\n * const result = await client.internalQuery({\n * query: 'query GetTags { tags { id name } }',\n * });\n *\n * // Make cross-layer query (e.g., wspace -> global)\n * const tenant = await client.crossLayerQuery({\n * query: 'query GetTenant($id: ID!) { tenant(id: $id) { name } }',\n * variables: { id: 'tenant-123' },\n * });\n *\n * // Create from environment\n * const gatewayClient = Gateway.createGatewayClientFromEnv('wspace-tags-svc');\n * ```\n */\nexport * as Gateway from './gateway/index.js';\n\n/**\n * FeatureFlags namespace - In-house feature flag evaluation\n *\n * @example\n * ```typescript\n * import { FeatureFlags } from '@burdenoff/be-sdk';\n *\n * const provider = new FeatureFlags.FeatureFlagProvider({\n * gatewayUrl: 'http://global-int-gateway:4000/global/graphql',\n * });\n *\n * const isEnabled = await provider.isEnabled('calendar.recurring-events', {\n * actorId: 'user-123',\n * actorType: 'user',\n * workspaceId: 'ws-456',\n * });\n * ```\n */\nexport * as FeatureFlags from './feature-flags/index.js';\n\n/**\n * Captcha namespace - reCAPTCHA v2/v3 token verification\n *\n * Provides environment-toggleable reCAPTCHA verification using Google's\n * siteverify API. Supports both v2 (checkbox) and v3 (invisible/score-based).\n *\n * @example\n * ```typescript\n * import { Captcha } from '@burdenoff/be-sdk';\n *\n * // Auto-bypass when CAPTCHA_ENABLED !== \"true\"\n * const result = await Captcha.verifyCaptchaIfEnabled({\n * token: input.recaptchaToken,\n * expectedAction: 'login',\n * minScore: 0.5,\n * });\n *\n * if (!result.success) {\n * throw new Error('Captcha verification failed');\n * }\n * ```\n */\nexport * as Captcha from './captcha/index.js';\nexport { verifyCaptcha, verifyCaptchaIfEnabled, isCaptchaEnabled } from './captcha/index.js';\nexport type { RecaptchaVerifyOptions, RecaptchaVerifyResult } from './captcha/index.js';\n\n/**\n * Platform Primitives\n *\n * Reusable building blocks consumed by every svc as part of the\n * scale-refactor: hardened HTTP client, leader lock, rate limiter,\n * paginator, dataloader factory, cache-invalidation, monthly PG\n * partition helpers, multi-provider LLM router.\n */\nexport * as Platform from './platform/index.js';\n\n/**\n * User-identity validators (BOFF-7261).\n *\n * Server-side mirror of `microfe-auth/src/auth/utils/validation.ts` so\n * `signUp`, `updateCurrentUserProfile`, and `updateUser` enforce the\n * same name/username invariants whether the call arrives via the UI form,\n * the GraphQL API directly, or a programmatic client. See BOFF-7261.\n */\nexport * as Validation from './validation/index.js';\nexport {\n validateName,\n validateUsername,\n validateUserFields,\n lengthInCodePoints,\n NAME_MIN_LENGTH,\n NAME_MAX_LENGTH,\n USERNAME_MIN_LENGTH,\n USERNAME_MAX_LENGTH,\n} from './validation/index.js';\nexport type {\n NameErrorCode,\n NameValidationResult,\n UsernameErrorCode,\n UsernameValidationResult,\n UserFieldKey,\n UserFieldError,\n ValidatedUserFields,\n UserFieldsValidationResult,\n} from './validation/index.js';\n\n/**\n * Whole-schema `@rbac` coverage guard for svc unit tests (VC/FG parity G03).\n * Lifted from wspace-healthybowl-svc's rbac-coverage test.\n */\nexport { assertRbacCoverage, analyzeRbacCoverage, RbacCoverageError } from './validation/index.js';\nexport type { RbacCoverageOptions, RbacCoverageReport, RbacCoverageSource } from './validation/index.js';\n\n/**\n * Product rename aliases (Botlit → BotManor, botmanor-migration WP-E).\n *\n * Readers accept both names (`normalizeProductSlug`, `quotaKeyVariants`,\n * `isSameRbacResource`, …); writers emit via `emitName` / `emit*`, driven by\n * `PRODUCT_RENAME_EMIT`. Also available as `@burdenoff/be-sdk/product-alias`.\n */\nexport * as ProductAlias from './product-alias/index.js';\nexport {\n PRODUCT_RENAMES,\n PRODUCT_SLUG_ALIASES,\n PRODUCT_RENAME_EMIT,\n RENAME_CONCERNS,\n toCurrentName,\n toLegacyName,\n nameVariants,\n isSameName,\n isLegacyName,\n emitName,\n normalizeProductSlug,\n productSlugVariants,\n isSameProductSlug,\n emitProductSlug,\n normalizeQuotaKey,\n quotaKeyVariants,\n isSameQuotaKey,\n emitQuotaKey,\n normalizeBillingId,\n billingIdVariants,\n isSameBillingId,\n emitBillingId,\n normalizeRbacResource,\n rbacResourceVariants,\n isSameRbacResource,\n emitRbacResource,\n normalizeTemplateKey,\n templateKeyVariants,\n isSameTemplateKey,\n emitTemplateKey,\n normalizeGraphQLName,\n isSameGraphQLName,\n readRenamedEnv,\n} from './product-alias/index.js';\nexport type { ProductRename, RenameConcern, EmitGeneration } from './product-alias/index.js';\n\n// ============================================================================\n// DSAR Orchestrator Identity Guard (BOFF-9550)\n// ============================================================================\nexport {\n DEFAULT_DSAR_ORCHESTRATOR_ID,\n VERIFIED_SERVICE_IDENTITY_HEADER,\n DSAR_ALLOWED_ORCHESTRATORS_ENV,\n DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV,\n DsarOrchestratorForbiddenError,\n getAllowedDsarOrchestrators,\n resolveDsarCallerIdentity,\n isDsarOrchestratorActor,\n assertDsarOrchestrator,\n type DsarOrchestratorContext,\n type DsarOrchestratorOptions,\n type ResolvedDsarCaller,\n type DsarOrchestratorRejectionReason,\n} from './server/dsar-orchestrator.js';\n\n// ============================================================================\n// Default Export\n// ============================================================================\n\nexport default BurdenoffSDK;\n\n/**\n * Create SDK instance (convenience function)\n */\nexport function createSDK(config: SDKConfig, context?: SDKContext): BurdenoffSDK {\n return new BurdenoffSDK(config, context);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,eAAe,OAAkD;CACxE,OAAO,UAAU,YAAY,UAAU;AACzC;;;;AAKA,IAAa,yBAAb,MAAoC;CAClC,AAAQ;;;;;;;;;CASR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,QAAmB,iBAA6B,CAAC,GAAG;EAC9D,KAAK,SAAS;EACd,KAAK,iBAAiB;EAGtB,KAAK,mBAAmB,IAAI,cAAc,OAAO,kBAAkB,EACjE,SAAS,KAAK,WAAW,cAAc,EACzC,CAAC;EAMD,IAAI,OAAO,cACT,KAAK,gBAAgB,IAAI,cAAc;GACrC,OACE,OAAO,iBACN,eAAe,QAAQ,IAAI,gBAAgB,IAAI,QAAQ,IAAI,mBAAmB;GACjF,aAAa,OAAO,eAAe,QAAQ,IAAI,mBAAmB;GAClE,sBAAsB,OAAO;GAC7B,SAAS,OAAO;GAIhB,OAAO,OAAO;EAChB,CAAC;CAEL;;;;;CAMA,AAAQ,WAAW,SAA6C;EAC9D,MAAM,UAAkC,EACtC,gBAAgB,mBAClB;EAEA,IAAI,QAAQ,OACV,QAAQ,mBAAmB,UAAU,QAAQ;EAI/C,IAAI,QAAQ,SACV,QAAQ,gBAAgB,QAAQ;EAGlC,IAAI,QAAQ,WACV,QAAQ,kBAAkB,QAAQ;EAGpC,IAAI,QAAQ,aACV,QAAQ,oBAAoB,QAAQ;EAGtC,IAAI,QAAQ,WACV,QAAQ,kBAAkB,QAAQ;EAGpC,OAAO;CACT;;;;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E,MAAM,mBAAoC,CAAC;EAE3C,IAAI,KAAK,gBACP,iBAAiB,KACf,KAAK,eAAe,WAAW,CAAC,CAAC,OAAO,UAAU;GAChD,OAAO,MAAM,6CAA6C,EAAE,MAAM,CAAC;EACrE,CAAC,CACH;EAGF,IAAI,KAAK,WACP,iBAAiB,KACf,KAAK,UAAU,WAAW,CAAC,CAAC,OAAO,UAAmB;GACpD,OAAO,MAAM,sCAAsC,EAAE,MAAM,CAAC;EAC9D,CAAC,CACH;EAOF,iBAAiB,KAAK,WAAW,OAAO,CAAC;EAEzC,IAAI;GACF,MAAM,QAAQ,KAAK,CACjB,QAAQ,WAAW,gBAAgB,GACnC,IAAI,SAAS,GAAG,WAAW,iBAAiB,uBAAO,IAAI,MAAM,iCAAiC,CAAC,GAAG,OAAO,CAAC,CAC5G,CAAC;GAED,OAAO,KAAK,uCAAuC;EACrD,SAAS,OAAO;GACd,IAAI,CAAC,OACH,MAAM;GAER,OAAO,KAAK,qDAAqD,EAAE,MAAM,CAAC;EAC5E;CACF;;;;CAKA,OAAc,gBAAgB,QAAgE;EAC5F,OAAO,gBAAgB,MAAM;CAC/B;AACF;;;;AAqqBA,SAAgB,UAAU,QAAmB,SAAoC;CAC/E,OAAO,IAAI,aAAa,QAAQ,OAAO;AACzC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/client/graphql.ts","../src/client/tenant-backend.ts","../src/index.ts"],"sourcesContent":["/**\n * GraphQL Client for Burdenoff Backend SDK\n * Handles communication with workspaces-backend and tenant-backend\n */\n\nimport type { Variables } from 'graphql-request';\nimport { GraphQLClient } from 'graphql-request';\nimport { GatewayClient } from '../gateway/client.js';\nimport { GatewayError, GatewayErrorType } from '../gateway/types.js';\nimport type { ServiceLayer } from '../types/layer.js';\nimport type { SDKConfig, SDKContext } from '../types/index.js';\nimport { APIError, NetworkError, TimeoutError } from '../types/index.js';\n\nfunction isServiceLayer(value: string | undefined): value is ServiceLayer {\n return value === 'wspace' || value === 'global';\n}\n\n/**\n * GraphQL client wrapper with retry logic and error handling\n */\nexport class BurdenoffGraphQLClient {\n private workspacesClient: GraphQLClient;\n /**\n * Cross-layer (tenant) calls go through the unified GatewayClient, which\n * targets the peer layer's PUBLIC gateway and mints a short-lived `service`\n * actor JWT (via signServiceJwt) so the gateway admits the M2M call and the\n * subgraph sees a trusted service context. This is the same mechanism used by\n * `GatewayClient.crossLayerQuery` everywhere else — kept consistent here so\n * tenant SDK calls (notifications, tenant lookups) authenticate identically.\n */\n private tenantGateway?: GatewayClient;\n private config: SDKConfig;\n private defaultContext: SDKContext;\n\n constructor(config: SDKConfig, defaultContext: SDKContext = {}) {\n this.config = config;\n this.defaultContext = defaultContext;\n\n // Initialize workspaces API client (should point to wspace-int-gateway for M2M calls)\n this.workspacesClient = new GraphQLClient(config.workspacesApiUrl, {\n headers: this.getHeaders(defaultContext),\n });\n\n // Cross-layer (tenant) calls go through the unified GatewayClient. The\n // configured tenantApiUrl is the peer layer's PUBLIC gateway; GatewayClient\n // mints the service JWT for it. `layer`/`serviceName` fall back to the\n // standard SERVICE_LAYER/SERVICE_NAME env vars.\n if (config.tenantApiUrl) {\n this.tenantGateway = new GatewayClient({\n layer:\n config.serviceLayer ??\n (isServiceLayer(process.env['SERVICE_LAYER']) ? process.env['SERVICE_LAYER'] : 'wspace'),\n serviceName: config.serviceName ?? process.env['SERVICE_NAME'] ?? 'burdenoff-be-sdk',\n crossLayerGatewayUrl: config.tenantApiUrl,\n timeout: config.timeout,\n // Honor the SDK's retry config (same field shape) so callers that lower\n // maxAttempts for non-idempotent tenant mutations (e.g. notification\n // sends) are respected instead of falling back to the gateway default.\n retry: config.retry,\n });\n }\n }\n\n /**\n * Get headers for GraphQL request\n * Includes actor context headers for RBAC authorization\n */\n private getHeaders(context: SDKContext): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (context.token) {\n headers['Authorization'] = `Bearer ${context.token}`;\n }\n\n // Actor context headers for RBAC\n if (context.actorId) {\n headers['x-actor-id'] = context.actorId;\n }\n\n if (context.actorType) {\n headers['x-actor-type'] = context.actorType;\n }\n\n if (context.workspaceId) {\n headers['x-workspace-id'] = context.workspaceId;\n }\n\n if (context.productId) {\n headers['x-product-id'] = context.productId;\n }\n\n return headers;\n }\n\n /**\n * Update context for future requests\n */\n public updateContext(context: Partial<SDKContext>): void {\n this.defaultContext = { ...this.defaultContext, ...context };\n this.workspacesClient.setHeaders(this.getHeaders(this.defaultContext));\n // The tenant GatewayClient derives per-request headers (and mints its own\n // service JWT) at call time, so there is no persistent header state to update.\n }\n\n /**\n * Execute GraphQL query/mutation against workspaces API\n */\n public async query<T>(query: string, variables?: Variables, context?: SDKContext): Promise<T> {\n return this.executeWithRetry(\n () => this.executeQuery(this.workspacesClient, query, variables, context),\n 'workspaces'\n );\n }\n\n /**\n * Execute GraphQL query/mutation against the tenant (cross-layer) API.\n *\n * Routed through GatewayClient.crossLayerQuery: targets the peer layer's\n * PUBLIC gateway and mints a short-lived `service` actor JWT. Only routing\n * context (workspace / product) is forwarded — the end-user identity is not,\n * because cross-layer tenant operations are service-to-service M2M. Retry and\n * circuit-breaking are handled inside GatewayClient.\n */\n public async tenantQuery<T>(query: string, variables?: Variables, context?: SDKContext): Promise<T> {\n if (!this.tenantGateway) {\n throw new APIError('Tenant API URL not configured', {\n operation: 'tenantQuery',\n });\n }\n\n const mergedContext = { ...this.defaultContext, ...context };\n const headers: Record<string, string> = {};\n if (mergedContext.workspaceId) {\n headers['x-workspace-id'] = mergedContext.workspaceId;\n }\n if (mergedContext.productId) {\n headers['x-product-id'] = mergedContext.productId;\n }\n if (mergedContext.organizationId) {\n headers['x-org-id'] = mergedContext.organizationId;\n }\n\n try {\n const response = await this.tenantGateway.crossLayerQuery<T>({\n query,\n variables: variables as Record<string, unknown> | undefined,\n headers,\n });\n\n if (response.data == null) {\n throw new APIError('Tenant query returned no data', { api: 'tenant' });\n }\n return response.data;\n } catch (error) {\n throw this.mapTenantError(error);\n }\n }\n\n /**\n * Map a GatewayClient failure back to the SDK's APIError contract so existing\n * tenant callers (which inspect `error.message` / extensions, e.g. \"Forbidden\")\n * keep working unchanged.\n */\n private mapTenantError(error: unknown): Error {\n if (error instanceof APIError) {\n return error;\n }\n if (error instanceof GatewayError) {\n const first = error.graphqlErrors?.[0];\n if (first) {\n return new APIError(first.message, {\n graphqlErrors: error.graphqlErrors,\n extensions: first.extensions,\n });\n }\n // Preserve the SDK's error-subtype contract: callers may branch on\n // `instanceof NetworkError` / `TimeoutError`, which the legacy tenant path\n // (executeQuery → handleError) used to throw.\n if (error.type === GatewayErrorType.NETWORK_ERROR) {\n return new NetworkError(error.message, { gatewayErrorType: error.type });\n }\n if (error.type === GatewayErrorType.TIMEOUT_ERROR) {\n return new TimeoutError(error.message, { gatewayErrorType: error.type });\n }\n return new APIError(error.message, { gatewayErrorType: error.type });\n }\n return this.handleError(error);\n }\n\n /**\n * Execute GraphQL request\n */\n private async executeQuery<T>(\n client: GraphQLClient,\n query: string,\n variables?: Variables,\n context?: SDKContext\n ): Promise<T> {\n try {\n // A per-call context applies to this request only. It used to be written onto the\n // shared client with setHeaders(), which leaked one call's actor and workspace headers\n // into every later call (and into concurrent calls) made without a context.\n if (!context) {\n return await client.request<T>(query, variables);\n }\n const mergedContext = { ...this.defaultContext, ...context };\n return await client.request<T>({\n document: query,\n variables,\n requestHeaders: this.getHeaders(mergedContext),\n });\n } catch (error) {\n throw this.handleError(error);\n }\n }\n\n /**\n * Execute with retry logic\n */\n private async executeWithRetry<T>(operation: () => Promise<T>, api: 'workspaces' | 'tenant'): Promise<T> {\n const maxAttempts = this.config.retry?.maxAttempts || 3;\n const initialDelay = this.config.retry?.initialDelay || 1000;\n const maxDelay = this.config.retry?.maxDelay || 10000;\n const backoffMultiplier = this.config.retry?.backoffMultiplier || 2;\n\n let lastError: Error | undefined;\n let delay = initialDelay;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error as Error;\n\n // Don't retry on certain errors\n if (error instanceof APIError && !this.shouldRetry(error)) {\n throw error;\n }\n\n // Don't retry on last attempt\n if (attempt === maxAttempts) {\n break;\n }\n\n // Wait before retrying\n await this.sleep(Math.min(delay, maxDelay));\n delay *= backoffMultiplier;\n }\n }\n\n throw new APIError(`GraphQL request failed after ${maxAttempts} attempts`, {\n api,\n lastError: lastError?.message,\n });\n }\n\n /**\n * Determine if error should be retried\n */\n private shouldRetry(error: APIError): boolean {\n // Retry on network errors and timeouts\n if (error instanceof NetworkError || error instanceof TimeoutError) {\n return true;\n }\n\n // Retry on 5xx server errors\n if (error.code === 'SERVER_ERROR') {\n return true;\n }\n\n // Don't retry on client errors (4xx)\n return false;\n }\n\n /**\n * Handle GraphQL errors\n */\n private handleError(error: unknown): Error {\n if (error instanceof Error) {\n // Check for network errors\n if (error.message.includes('fetch failed') || error.message.includes('ECONNREFUSED')) {\n return new NetworkError('Network error while connecting to API', {\n originalError: error.message,\n });\n }\n\n // Check for timeout errors\n if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {\n return new TimeoutError('Request timed out', {\n originalError: error.message,\n });\n }\n\n // GraphQL errors\n if ('response' in error && error.response) {\n const response = error.response as {\n errors?: Array<{ message: string; extensions?: Record<string, unknown> }>;\n };\n if (response.errors && response.errors.length > 0) {\n const firstError = response.errors[0];\n if (firstError) {\n return new APIError(firstError.message, {\n graphqlErrors: response.errors,\n extensions: firstError.extensions,\n });\n }\n }\n }\n\n return new APIError(error.message, {\n originalError: error.message,\n });\n }\n\n return new APIError('Unknown error occurred', {\n error: String(error),\n });\n }\n\n /**\n * Sleep utility for retry delays\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n /**\n * Get current context\n */\n public getContext(): SDKContext {\n return { ...this.defaultContext };\n }\n}\n","/**\n * Tenant Backend Client\n * Centralized client for accessing tenant-backend services (notifications, auth, etc.)\n *\n * This is a reusable utility that can be used by any backend to communicate with tenant-backend.\n */\n\nimport { BurdenoffGraphQLClient } from './graphql.js';\nimport { TenantNotificationsModule } from '../notifications/tenant-notifications.js';\nimport { logger } from '../logger/index.js';\nimport type { SDKConfig } from '../types/index.js';\n\nexport interface TenantBackendClientConfig {\n /** Tenant backend GraphQL URL */\n tenantBackendUrl: string;\n /** Workspaces backend GraphQL URL (for SDK initialization) */\n workspacesBackendUrl?: string;\n /** Optional API key for tenant backend authentication */\n apiKey?: string;\n}\n\n/**\n * Tenant Backend Client\n * Provides access to centralized tenant-backend services using be-sdk\n *\n * @example\n * ```typescript\n * import { TenantBackendClient } from '@burdenoff/be-sdk';\n *\n * const client = new TenantBackendClient({\n * tenantBackendUrl: process.env.GLOBAL_INT_GATEWAY_URL!,\n * workspacesBackendUrl: process.env.WORKSPACES_BACKEND_URL,\n * apiKey: process.env.TENANT_BACKEND_API_KEY,\n * });\n *\n * // Send notification\n * await client.notifications.sendWithTemplate({\n * templateSlug: 'user-welcome',\n * recipients: ['user@example.com'],\n * variables: { userName: 'John' },\n * });\n *\n * // Execute raw query\n * const result = await client.query(`\n * query GetUser($id: ID!) {\n * user(id: $id) { id name email }\n * }\n * `, { id: 'user-123' });\n * ```\n */\nexport class TenantBackendClient {\n private graphqlClient: BurdenoffGraphQLClient;\n private config: TenantBackendClientConfig;\n\n /** Notifications module for sending notifications via tenant backend */\n public readonly notifications: TenantNotificationsModule;\n\n constructor(config: TenantBackendClientConfig) {\n this.config = config;\n\n // Build SDK config\n const sdkConfig: SDKConfig = {\n workspacesApiUrl: config.workspacesBackendUrl || 'http://localhost:4000/graphql',\n tenantApiUrl: config.tenantBackendUrl,\n };\n\n // Initialize GraphQL client\n this.graphqlClient = new BurdenoffGraphQLClient(sdkConfig, {});\n\n // Initialize notifications module with empty context (context will be set per request)\n this.notifications = new TenantNotificationsModule(this.graphqlClient, {});\n\n logger.info('[TenantBackend] Client initialized using be-sdk', {\n tenantUrl: config.tenantBackendUrl,\n workspacesUrl: config.workspacesBackendUrl,\n hasApiKey: !!config.apiKey,\n });\n }\n\n /**\n * Update authentication token\n *\n * @param token - JWT token for authentication\n */\n public setAuthToken(token: string): void {\n this.graphqlClient.updateContext({ token });\n logger.debug('[TenantBackend] Authentication token updated');\n }\n\n /**\n * Execute raw GraphQL query against tenant backend\n *\n * @param query - GraphQL query string\n * @param variables - Query variables\n * @returns Query result\n *\n * @example\n * ```typescript\n * const result = await client.query(`\n * query GetTemplate($slug: String!) {\n * notificationTemplate(slug: $slug) {\n * id\n * slug\n * subject\n * }\n * }\n * `, { slug: 'user-welcome' });\n * ```\n */\n public async query<T>(query: string, variables?: Record<string, unknown>): Promise<T> {\n return this.graphqlClient.tenantQuery<T>(query, variables);\n }\n\n /**\n * Health check\n *\n * @returns True if tenant backend is reachable, false otherwise\n */\n public async healthCheck(): Promise<boolean> {\n try {\n const query = `\n query HealthCheck {\n __typename\n }\n `;\n await this.graphqlClient.tenantQuery(query);\n return true;\n } catch (error) {\n logger.error('[TenantBackend] Health check failed', {\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n return false;\n }\n }\n\n /**\n * Get GraphQL client for advanced usage\n *\n * @returns Underlying BurdenoffGraphQLClient\n */\n public getClient(): BurdenoffGraphQLClient {\n return this.graphqlClient;\n }\n\n /**\n * Get client configuration\n *\n * @returns Client configuration\n */\n public getConfig(): TenantBackendClientConfig {\n return { ...this.config };\n }\n}\n\n/**\n * Create a TenantBackendClient instance\n *\n * @param config - Client configuration\n * @returns TenantBackendClient instance\n *\n * @example\n * ```typescript\n * import { createTenantBackendClient } from '@burdenoff/be-sdk';\n *\n * const client = createTenantBackendClient({\n * tenantBackendUrl: process.env.GLOBAL_INT_GATEWAY_URL!,\n * });\n * ```\n */\nexport function createTenantBackendClient(config: TenantBackendClientConfig): TenantBackendClient {\n return new TenantBackendClient(config);\n}\n","/**\n * Burdenoff Backend SDK\n * Comprehensive SDK for all Burdenoff products\n *\n * @packageDocumentation\n */\n\nimport { BurdenoffGraphQLClient } from './client/graphql.js';\nimport type { SDKConfig, SDKContext } from './types/index.js';\nimport type { Logger } from './logger/index.js';\nimport { logger } from './logger/index.js';\nimport { ContextManager } from './context/index.js';\nimport { AuthModule } from './auth/index.js';\nimport { NotificationsModule } from './notifications/index.js';\nimport { TenantNotificationsModule } from './notifications/tenant-notifications.js';\nimport { RBACModule } from './rbac/index.js';\nimport { ActivityModule } from './activity/index.js';\nimport { UsageModule } from './usage/index.js';\nimport { TrackerModule } from './tracker/index.js';\nimport { DatabaseModule } from './database/index.js';\nimport {\n EventsModule,\n EventQueueFactory,\n QueueType,\n resolveEventStreamsKeyScope,\n resolveEventStreamsPassword,\n resolveEventStreamsUrl,\n} from './event-queue/index.js';\nimport type { IEventPublisher, PublisherConfig } from './event-queue/index.js';\nimport { disposeAll } from './lifecycle/index.js';\nimport { GraphModule } from './graph/index.js';\nimport { SearchModule } from './search/index.js';\nimport { TranslationModule } from './translation/index.js';\nimport { PaymentsModule } from './payments/index.js';\nimport type { BootstrapModule } from './bootstrap/index.js';\nimport { createBootstrap } from './bootstrap/index.js';\n// Temporal is lazy-loaded to avoid requiring @temporalio/client when not used\nimport type { TemporalModule } from './temporal/index.js';\n\n/**\n * Main Burdenoff SDK class\n *\n * @example\n * ```typescript\n * import { BurdenoffSDK } from '@burdenoff/be-sdk';\n *\n * const sdk = new BurdenoffSDK({\n * workspacesApiUrl: 'https://api.burdenoff.com/graphql',\n * timeout: 30000,\n * });\n *\n * // Use the unified tracker (most common use case)\n * const result = await sdk.tracker.track({\n * userId: 'user123',\n * action: 'create_project',\n * resourceType: 'project',\n * workspaceId: 'ws123',\n * usage: {\n * quotaName: 'myproduct.projects.count',\n * productId: 'myproduct',\n * amount: 1,\n * },\n * });\n * ```\n */\nexport class BurdenoffSDK {\n private client: BurdenoffGraphQLClient;\n private defaultContext: SDKContext;\n\n // Event queue publisher state (Redis Streams)\n private eventPublisher: IEventPublisher | null = null;\n private eventPublisherInitPromise: Promise<void> | null = null;\n private eventQueueConfig: import('./types/index.js').EventQueueSDKConfig | null = null;\n\n // Initialization state\n private initializationPromise: Promise<void> | null = null;\n private isShuttingDown = false;\n\n /** Authentication module */\n public readonly auth: AuthModule;\n\n /** Notifications module (workspaces-backend) */\n public readonly notifications: NotificationsModule;\n\n /** Tenant Notifications module (tenant-backend - RECOMMENDED) */\n public readonly tenantNotifications: TenantNotificationsModule;\n\n /** RBAC module */\n public readonly rbac: RBACModule;\n\n /** Activity tracking module */\n public readonly activity: ActivityModule;\n\n /** Usage & Quota module */\n public readonly usage: UsageModule;\n\n /** Unified Tracker module (MOST IMPORTANT - use this for most operations) */\n public readonly tracker: TrackerModule;\n\n /** Database helpers module */\n public readonly database: typeof DatabaseModule;\n\n /** Events/Queue module */\n public readonly events: EventsModule;\n\n /** Graph integration module */\n public readonly graph: GraphModule;\n\n /** Search module */\n public readonly search: SearchModule;\n\n /** Translation module */\n public readonly translation: TranslationModule;\n\n /** Payments module */\n public readonly payments: PaymentsModule;\n\n /** Temporal workflow orchestration module (lazy-loaded) */\n private _temporal: TemporalModule | null = null;\n private _temporalPromise: Promise<TemporalModule> | null = null;\n private _temporalConfig: { moduleType?: string; address?: string; namespace?: string; taskQueue?: string } | null =\n null;\n\n /**\n * Get Temporal workflow orchestration module (lazy-loaded)\n * Only loads @temporalio/client when this method is called\n *\n * @returns Promise resolving to TemporalModule\n * @example\n * ```typescript\n * const temporal = await sdk.getTemporalModule();\n * await temporal.startWorkflow('myWorkflow', { ... });\n * ```\n */\n public async getTemporalModule(): Promise<TemporalModule> {\n if (this._temporal) {\n return this._temporal;\n }\n\n if (!this._temporalPromise) {\n this._temporalPromise = this.loadTemporalModule();\n }\n\n return this._temporalPromise;\n }\n\n /**\n * Load temporal module dynamically\n * @private\n */\n private async loadTemporalModule(): Promise<TemporalModule> {\n const { TemporalModule: TM } = (await import('./temporal/index.js')) as { TemporalModule: typeof TemporalModule };\n this._temporal = this._temporalConfig?.moduleType\n ? new TM({\n moduleType: this._temporalConfig.moduleType as 'workspace' | 'tenant',\n address: this._temporalConfig.address,\n namespace: this._temporalConfig.namespace,\n taskQueue: this._temporalConfig.taskQueue,\n })\n : TM.fromEnv();\n return this._temporal;\n }\n\n /** Logger instance */\n public readonly logger: Logger;\n\n /** Context manager */\n public readonly context: typeof ContextManager;\n\n /**\n * Create SDK instance\n */\n constructor(config: SDKConfig, defaultContext: SDKContext = {}) {\n // Initialize client\n this.client = new BurdenoffGraphQLClient(config, defaultContext);\n this.defaultContext = defaultContext;\n\n // Initialize logger\n this.logger = logger;\n if (config.logger) {\n this.logger.setLevel(config.logger.level);\n this.logger.setConsoleEnabled(config.logger.console);\n if (config.logger.transport) {\n this.logger.addTransport(config.logger.transport);\n }\n }\n\n // Initialize context manager\n this.context = ContextManager;\n if (Object.keys(defaultContext).length > 0) {\n ContextManager.setContext(defaultContext);\n }\n\n // Initialize all modules\n this.auth = new AuthModule(this.client, defaultContext);\n this.notifications = new NotificationsModule(this.client, defaultContext);\n this.tenantNotifications = new TenantNotificationsModule(this.client, defaultContext);\n this.rbac = new RBACModule(this.client, defaultContext);\n this.activity = new ActivityModule(this.client, defaultContext);\n this.usage = new UsageModule(this.client, defaultContext);\n this.tracker = new TrackerModule(this.client, defaultContext);\n this.database = DatabaseModule;\n this.events = new EventsModule(this.client, defaultContext);\n this.graph = new GraphModule(this.client, defaultContext);\n this.search = new SearchModule(this.client, defaultContext);\n this.translation = new TranslationModule(this.client, defaultContext);\n this.payments = new PaymentsModule(this.client, defaultContext);\n\n // Store Temporal configuration for lazy loading (avoids requiring @temporalio/client when not used)\n if (config.temporalModuleType) {\n this._temporalConfig = {\n moduleType: config.temporalModuleType,\n address: config.temporalAddress,\n namespace: config.temporalNamespace,\n taskQueue: config.temporalTaskQueue,\n };\n }\n\n // Store event queue configuration. Auto-enabled when REDIS_STREAMS_URL or\n // REDIS_URL is set even if no explicit config block is provided.\n if (config.eventQueue || resolveEventStreamsUrl()) {\n this.eventQueueConfig = {\n autoConnect: true,\n maxReconnectAttempts: -1,\n reconnectTimeWait: 2000,\n ...config.eventQueue,\n };\n }\n\n logger.info('[SDK] Burdenoff SDK initialized', {\n workspacesApiUrl: config.workspacesApiUrl,\n tenantApiUrl: config.tenantApiUrl,\n hasDefaultContext: Object.keys(defaultContext).length > 0,\n hasEventQueueConfig: !!this.eventQueueConfig,\n hasTemporalConfig: !!config.temporalModuleType,\n });\n\n // Schedule background initialization outside the constructor\n // This defers async work to after constructor completes (satisfies no-async-constructor)\n this.scheduleBackgroundInit();\n }\n\n /**\n * Schedule background initialization outside constructor\n * Uses queueMicrotask to defer async work while maintaining initialization order\n * @private\n */\n private scheduleBackgroundInit(): void {\n queueMicrotask(() => {\n this.initializationPromise = this.initializeAsync();\n });\n }\n\n /**\n * Update SDK context\n */\n public setContext(context: SDKContext): void {\n this.defaultContext = { ...this.defaultContext, ...context };\n this.client.updateContext(context);\n ContextManager.setContext(this.defaultContext);\n }\n\n /**\n * Get current context\n */\n public getContext(): SDKContext | undefined {\n return ContextManager.getContext();\n }\n\n /**\n * Run function with specific context\n */\n public async withContext<T>(context: SDKContext, fn: () => Promise<T>): Promise<T> {\n return ContextManager.withContext(context, fn);\n }\n\n /**\n * Background initialization for event queue and other async resources\n * @private\n */\n private async initializeAsync(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n if (this.eventQueueConfig?.autoConnect) {\n promises.push(\n this.initializeEventQueue().catch((error) => {\n logger.warn('[SDK] Failed to auto-connect to Redis Streams', { error });\n })\n );\n }\n\n await Promise.allSettled(promises);\n }\n\n /**\n * Initialize the Redis Streams event publisher\n * @private\n */\n private async initializeEventQueue(): Promise<void> {\n if (!this.eventQueueConfig || this.eventPublisher) return;\n\n const usesEnvUrl = !this.eventQueueConfig.url;\n const url = this.eventQueueConfig.url || resolveEventStreamsUrl();\n if (!url) {\n logger.warn('[SDK] No REDIS_STREAMS_URL / REDIS_URL available — event publisher disabled');\n return;\n }\n\n const password = this.eventQueueConfig.password ?? (usesEnvUrl ? resolveEventStreamsPassword() : undefined);\n const keyScope = this.eventQueueConfig.keyScope ?? (usesEnvUrl ? resolveEventStreamsKeyScope() : undefined);\n const publisherConfig: PublisherConfig = {\n type: QueueType.REDIS_STREAMS,\n url,\n ...(password !== undefined ? { password } : {}),\n ...(keyScope !== undefined ? { keyScope } : {}),\n name: this.eventQueueConfig.name || 'burdenoff-sdk-publisher',\n maxReconnectAttempts: this.eventQueueConfig.maxReconnectAttempts ?? -1,\n reconnectTimeWait: this.eventQueueConfig.reconnectTimeWait ?? 2000,\n };\n\n this.eventPublisher = EventQueueFactory.createPublisher(publisherConfig);\n await this.eventPublisher.connect();\n\n logger.info('[SDK] Redis Streams event publisher initialized', {\n url,\n name: this.eventQueueConfig.name,\n });\n }\n\n /**\n * Get the event publisher instance (lazy initialization).\n *\n * @example\n * ```typescript\n * const publisher = await sdk.getEventPublisher();\n * await publisher.publish({\n * subject: 'events.user.created',\n * data: { userId: 'user-123' }\n * });\n * ```\n */\n public async getEventPublisher(): Promise<IEventPublisher> {\n if (this.eventPublisher) return this.eventPublisher;\n if (!this.eventQueueConfig) {\n throw new Error(\n '[SDK] Event queue not configured - set REDIS_STREAMS_URL / REDIS_URL or provide config.eventQueue'\n );\n }\n\n if (!this.eventPublisherInitPromise) {\n this.eventPublisherInitPromise = this.initializeEventQueue();\n }\n await this.eventPublisherInitPromise;\n\n if (!this.eventPublisher) {\n throw new Error('[SDK] Event publisher initialization failed');\n }\n return this.eventPublisher;\n }\n\n /**\n * Wait for SDK initialization to complete\n *\n * @example\n * ```typescript\n * await sdk.waitForReady();\n * ```\n */\n public async waitForReady(): Promise<void> {\n if (this.initializationPromise) {\n await this.initializationPromise;\n }\n }\n\n /**\n * Check event queue (Redis Streams) health status\n *\n * @example\n * ```typescript\n * const health = await sdk.isEventQueueHealthy();\n * if (health.status === 'healthy') {\n * console.log('Event queue is connected');\n * }\n * ```\n */\n public async isEventQueueHealthy(): Promise<import('./types/index.js').EventQueueHealthStatus> {\n if (!this.eventQueueConfig) {\n return { status: 'not_configured', connected: false };\n }\n\n if (!this.eventPublisher) {\n return {\n status: 'unhealthy',\n connected: false,\n url: this.eventQueueConfig.url,\n details: { reason: 'Not initialized' },\n };\n }\n\n try {\n const healthCheck = await this.eventPublisher.healthCheck();\n return {\n status: healthCheck.status as 'healthy' | 'unhealthy',\n connected: this.eventPublisher.isConnected(),\n url: this.eventQueueConfig.url,\n details: healthCheck.details,\n };\n } catch (error) {\n return {\n status: 'unhealthy',\n connected: false,\n url: this.eventQueueConfig.url,\n details: { error: error instanceof Error ? error.message : String(error) },\n };\n }\n }\n\n /**\n * Check Temporal health status\n *\n * @example\n * ```typescript\n * const health = await sdk.isTemporalHealthy();\n * if (health.status === 'healthy') {\n * console.log('Temporal is connected');\n * }\n * ```\n */\n public async isTemporalHealthy(): Promise<import('./types/index.js').TemporalHealthStatus> {\n // If temporal hasn't been loaded yet, it's not configured\n if (!this._temporal) {\n return { status: 'not_configured', connected: false };\n }\n\n const config = this._temporal.getConfig();\n\n if (!config.address) {\n return { status: 'not_configured', connected: false };\n }\n\n try {\n const client = this._temporal.getClient();\n // Use the public isClientConnected method\n const connected = client.isClientConnected();\n\n return {\n status: connected ? 'healthy' : 'unhealthy',\n connected: connected,\n address: config.address,\n namespace: config.namespace,\n details: { taskQueue: config.taskQueue },\n };\n } catch (error: unknown) {\n return {\n status: 'unhealthy',\n connected: false,\n address: config.address,\n namespace: config.namespace,\n details: { error: error instanceof Error ? error.message : String(error) },\n };\n }\n }\n\n /**\n * Get overall SDK health status\n *\n * @example\n * ```typescript\n * const health = await sdk.getHealthStatus();\n * console.log('Event Queue:', health.eventQueue.status);\n * console.log('Temporal:', health.temporal.status);\n * ```\n */\n public async getHealthStatus(): Promise<import('./types/index.js').SDKHealthStatus> {\n const [eventQueue, temporal] = await Promise.all([this.isEventQueueHealthy(), this.isTemporalHealthy()]);\n return { eventQueue, temporal };\n }\n\n /**\n * Graceful shutdown - disconnect all resources\n *\n * @example\n * ```typescript\n * // On application shutdown\n * await sdk.shutdown({ timeout: 5000, force: true });\n * ```\n */\n public async shutdown(options: import('./types/index.js').SDKShutdownOptions = {}): Promise<void> {\n if (this.isShuttingDown) {\n logger.warn('[SDK] Shutdown already in progress');\n return;\n }\n this.isShuttingDown = true;\n\n const timeout = options.timeout ?? 5000;\n const force = options.force ?? true;\n\n logger.info('[SDK] Starting graceful shutdown', { timeout, force });\n\n const shutdownPromises: Promise<void>[] = [];\n\n if (this.eventPublisher) {\n shutdownPromises.push(\n this.eventPublisher.disconnect().catch((error) => {\n logger.error('[SDK] Error disconnecting event publisher', { error });\n })\n );\n }\n\n if (this._temporal) {\n shutdownPromises.push(\n this._temporal.disconnect().catch((error: unknown) => {\n logger.error('[SDK] Error disconnecting Temporal', { error });\n })\n );\n }\n\n // Close every other long-lived connection registered process-wide — the\n // Redis Streams event consumer(s) (whose blocking clients nothing else\n // closes) and cache clients — so shutdown is complete regardless of how\n // those resources were constructed. disposeAll is bounded + never throws.\n shutdownPromises.push(disposeAll(timeout));\n\n try {\n await Promise.race([\n Promise.allSettled(shutdownPromises),\n new Promise((_, reject) => setTimeout(() => reject(new Error('[SDK] Shutdown timeout exceeded')), timeout)),\n ]);\n\n logger.info('[SDK] Shutdown completed successfully');\n } catch (error) {\n if (!force) {\n throw error;\n }\n logger.warn('[SDK] Shutdown timeout exceeded, forcing shutdown', { error });\n }\n }\n\n /**\n * Create bootstrap instance\n */\n public static createBootstrap(config: Parameters<typeof createBootstrap>[0]): BootstrapModule {\n return createBootstrap(config);\n }\n}\n\n// ============================================================================\n// Core SDK Exports (Top-level)\n// ============================================================================\n\nexport { BurdenoffGraphQLClient } from './client/graphql.js';\nexport { TenantBackendClient, createTenantBackendClient } from './client/tenant-backend.js';\nexport type { TenantBackendClientConfig } from './client/tenant-backend.js';\nexport {\n createInternalClient,\n createInternalClientForWorkspaces,\n createInternalClientForTenant,\n} from './client/internal-client.js';\nexport { ContextManager } from './context/index.js';\nexport { AuthModule } from './auth/index.js';\nexport { NotificationsModule } from './notifications/index.js';\nexport {\n RBACModule,\n createRBACDirective,\n createRBACDirectiveForLayer,\n createRBACDirectiveFromEnv,\n type RBACDirectiveConfig,\n type LayerAwareRBACConfig,\n} from './rbac/index.js';\nexport {\n ActivityModule,\n ActivityOperationUnsupportedError,\n type Activity,\n type ActivityActorType,\n type GetActivitiesOptions,\n type LogActivityOptions,\n} from './activity/index.js';\nexport { UsageModule } from './usage/index.js';\nexport {\n BillingUsageClient,\n type BillingUsageClientConfig,\n type BillingUsageOperationInput,\n type OrgBillingUsageOperationInput,\n type WorkspaceBillingUsageOperationInput,\n type QuotaLimit,\n} from './usage/billing.js';\nexport { TrackerModule } from './tracker/index.js';\nexport { DatabaseModule } from './database/index.js';\nexport { EventsModule } from './event-queue/index.js';\nexport {\n registerDisposable,\n unregisterDisposable,\n getRegisteredDisposableCount,\n disposeAll,\n type ShutdownDisposable,\n} from './lifecycle/index.js';\nexport { GraphModule } from './graph/index.js';\nexport { SearchModule } from './search/index.js';\nexport { TranslationModule } from './translation/index.js';\nexport type {\n TranslationExportFormat,\n ProductTranslationTree,\n ExportProductTranslationsOptions,\n ProductTranslationsExportResult,\n UpsertProductTranslationsOptions,\n UpsertProductTranslationsResult,\n} from './translation/index.js';\nexport { PaymentsModule } from './payments/index.js';\nexport {\n ResourceCapsModule,\n ResourceCapExceededError,\n RESOURCE_CAP_DEFAULTS,\n getResourceCaps,\n configureResourceCaps,\n type ResourceName,\n type ResourceCap,\n type ResourceCapsConfig,\n type BillingPlanTransport,\n type PlanTier,\n type ResourceCapDefaults,\n type WorkspaceResourceCapScope,\n} from './resource-caps/index.js';\n// Generic sharing (invite/accept/permission). Primary entrypoint is the\n// '@burdenoff/be-sdk/sharing' subpath; namespace-exported here to avoid symbol\n// collisions at the package root.\nexport * as Sharing from './sharing/index.js';\n// Shared entity tags (TagsGatewayAdapter + prefixed SDL + resolver factory over\n// wspace-tags-svc). Primary entrypoint is the '@burdenoff/be-sdk/tags' subpath;\n// namespace-exported here to avoid symbol collisions at the package root.\nexport * as Tags from './tags/index.js';\n// Shared files client (upload / metadata / download URL / bytes / delete over\n// wspace-files-svc, plus the FileReference binary-data pointer). Primary\n// entrypoint is the '@burdenoff/be-sdk/files' subpath; namespace-exported here\n// to avoid symbol collisions at the package root.\nexport * as Files from './files/index.js';\n// Shared AI-credit meter (quote on global-billing + idempotent trackUsage on\n// wspace-activity). Primary entrypoint is the '@burdenoff/be-sdk/ai-credits'\n// subpath; namespace-exported here for discoverability.\nexport * as AiCredits from './ai-credits/index.js';\nexport { BootstrapModule, createBootstrap } from './bootstrap/index.js';\nexport {\n TemporalModule,\n TemporalClient,\n TemporalClientFactory,\n TemporalWorker,\n TemporalWorkerFactory,\n TemporalWorkerManager,\n type TemporalClientConfig,\n type TemporalWorkerConfig,\n type WorkflowStartOptions,\n} from './temporal/index.js';\n\n// Export core SDK types (only SDK-specific types, not module types)\nexport type {\n SDKConfig,\n SDKContext,\n LoggerConfig,\n LoggerTransport,\n EventQueueSDKConfig,\n EventQueueHealthStatus,\n TemporalHealthStatus,\n SDKHealthStatus,\n SDKShutdownOptions,\n // Layer types\n ServiceLayer,\n LayerConfig,\n LayerGatewayConfig,\n LayerResourceUrls,\n LayerFullConfig,\n GatewayRoutingConfig,\n CircuitBreakerConfig,\n GatewayRetryConfig,\n GatewayRequestHeaders,\n} from './types/index.js';\n\n// Export layer defaults\nexport {\n DEFAULT_GATEWAY_ROUTING,\n DEFAULT_LAYER_RESOURCES,\n DEFAULT_LAYER_STREAMS,\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n} from './types/index.js';\n\n// ============================================================================\n// Namespaced Exports (Recommended - Avoids Collisions)\n// ============================================================================\n\n/**\n * Logger namespace - Logging functionality\n *\n * @example\n * ```typescript\n * import { Logger } from '@burdenoff/be-sdk';\n *\n * Logger.logger.info('Message');\n * Logger.log('Message');\n * Logger.error('Error message');\n * ```\n */\nexport * as Logger from './logger/index.js';\n\n/**\n * Cache namespace - Caching functionality\n *\n * @example\n * ```typescript\n * import { Cache } from '@burdenoff/be-sdk';\n *\n * const cache = Cache.createCache('my-namespace');\n * await cache.connect();\n * await cache.set('key', 'value', { ttl: 60 });\n * ```\n */\nexport * as Cache from './cache/index.js';\n\n/**\n * EventQueue namespace - Event queue/messaging functionality\n *\n * @example\n * ```typescript\n * import { EventQueue } from '@burdenoff/be-sdk';\n *\n * const publisher = EventQueue.createPublisher();\n * await publisher.connect();\n * await publisher.publish({ subject: 'events.test', data: { foo: 'bar' } });\n * ```\n */\nexport * as EventQueue from './event-queue/index.js';\n\n/**\n * Lifecycle namespace - graceful-shutdown registry for long-lived connections\n *\n * @example\n * ```typescript\n * import { Lifecycle } from '@burdenoff/be-sdk';\n *\n * // Close every registered connection (event bus, cache) on shutdown.\n * await Lifecycle.disposeAll();\n * ```\n */\nexport * as Lifecycle from './lifecycle/index.js';\n\n/**\n * Graph namespace - Graph database operations\n *\n * @example\n * ```typescript\n * import { Graph } from '@burdenoff/be-sdk';\n *\n * const syncService = new Graph.GraphSyncService();\n * await syncService.processEvent(event);\n * ```\n */\nexport * as Graph from './graph/index.js';\n\n/**\n * Middleware namespace - HTTP/GraphQL middleware\n *\n * @example\n * ```typescript\n * import { Middleware } from '@burdenoff/be-sdk';\n *\n * app.use(Middleware.SecurityMiddleware);\n * app.use(Middleware.setupMetricsMiddleware());\n * ```\n */\nexport * as Middleware from './middleware/index.js';\n\n/**\n * Observability namespace - Monitoring, tracing, metrics\n *\n * @example\n * ```typescript\n * import { Observability } from '@burdenoff/be-sdk';\n *\n * const tracer = Observability.createTracer('my-service');\n * ```\n */\nexport * as Observability from './observability/index.js';\n\n/**\n * GraphQL namespace - GraphQL utilities\n *\n * @example\n * ```typescript\n * import { GraphQL } from '@burdenoff/be-sdk';\n *\n * const schema = GraphQL.buildSchema(typeDefs);\n * ```\n */\nexport * as GraphQL from './graphql/index.js';\n\n/**\n * Prisma namespace - Prisma utilities and helpers\n *\n * @example\n * ```typescript\n * import { Prisma } from '@burdenoff/be-sdk';\n *\n * const client = Prisma.createPrismaClient();\n * ```\n */\nexport * as Prisma from './prisma/index.js';\n\n/**\n * Utils namespace - General utilities\n *\n * @example\n * ```typescript\n * import { Utils } from '@burdenoff/be-sdk';\n *\n * const id = Utils.generateId();\n * ```\n */\nexport * as Utils from './utils/index.js';\n\n/**\n * I18n namespace - Internationalization utilities\n *\n * @example\n * ```typescript\n * import { I18n } from '@burdenoff/be-sdk';\n *\n * const i18n = new I18n.I18n({\n * defaultLocale: 'en-US',\n * localesPath: './locales',\n * });\n * await i18n.initialize();\n *\n * const ctx = i18n.createContextFromRequest(request);\n * const message = ctx.t('errors.notFound', { resource: 'Tag' });\n * ```\n */\nexport * as I18n from './i18n/index.js';\n\n/**\n * Translation helper functions - Direct exports for convenience\n *\n * Use `t()` in GraphQL resolvers and providers to get translated messages:\n *\n * @example\n * ```typescript\n * import { t, createTranslator } from '@burdenoff/be-sdk';\n *\n * // Direct usage with context\n * const message = t(ctx, 'tags.errors.notFound', 'Tag not found');\n * const message = t(ctx, 'tags.errors.keyExists', 'Tag {{key}} already exists', { key: 'my-tag' });\n *\n * // Create bound translator\n * const translate = createTranslator(ctx);\n * const msg = translate('tags.errors.notFound', 'Tag not found');\n * ```\n */\nexport { t, createTranslator, hasI18n, getLocale, getLanguage } from './i18n/helpers.js';\nexport type { I18nCapableContext, Translator } from './i18n/helpers.js';\n\n/**\n * Export namespace - Data export utilities\n *\n * @example\n * ```typescript\n * import { Export } from '@burdenoff/be-sdk';\n *\n * class UserExporter extends Export.BaseModuleExporter<User> {\n * moduleKey = 'users';\n * // ...\n * }\n *\n * const csv = Export.convertToCSV(data);\n * const paginated = Export.PaginationService.paginate(items, { page: 1 });\n * ```\n */\nexport * as Export from './export/index.js';\n\n/**\n * Init namespace - Initialization utilities\n *\n * @example\n * ```typescript\n * import { Init } from '@burdenoff/be-sdk';\n *\n * await Init.initializeArangoSchema();\n * ```\n */\nexport * as Init from './init/index.js';\n\n/**\n * DataLoader namespace - DataLoader utilities for batching and caching\n *\n * @example\n * ```typescript\n * import { DataLoader } from '@burdenoff/be-sdk';\n *\n * const tagLoader = DataLoader.createEntityLoader<Tag, string>({\n * batchFn: async (ids) => db.tag.findMany({ where: { id: { in: [...ids] } } }),\n * getKey: (tag) => tag.id,\n * });\n *\n * const tag = await tagLoader.load('tag-123');\n * ```\n */\nexport * as DataLoader from './dataloader/index.js';\n\n/**\n * Notifications namespace - Notification functionality\n *\n * @example\n * ```typescript\n * import { Notifications } from '@burdenoff/be-sdk';\n *\n * await notifications.sendWithTemplate({\n * templateSlug: 'welcome-email',\n * recipients: ['user@example.com'],\n * variables: { name: 'John' }\n * });\n * ```\n */\nexport * as Notifications from './notifications/tenant-notifications.js';\n\n/**\n * Instrumentation namespace - OpenTelemetry instrumentation utilities\n *\n * Provides comprehensive tracing, metrics, and logging instrumentation\n * for microservices with conditional enable/disable support.\n *\n * @example\n * ```typescript\n * import { Instrumentation } from '@burdenoff/be-sdk';\n *\n * // Initialize instrumentation\n * const { tracer, metrics } = Instrumentation.initializeInstrumentation('my-service', {\n * features: { tracing: true, metrics: true, logging: true }\n * });\n *\n * // Create spans\n * await tracer.withSpan('operation', async (span) => {\n * span.setAttribute('key', 'value');\n * });\n *\n * // Create metrics\n * const counter = Instrumentation.createCounter('requests_total', 'Total requests');\n * counter.inc({ endpoint: '/api/users' });\n *\n * // Use decorators\n * class MyService {\n * @Instrumentation.Trace()\n * async myMethod() { ... }\n *\n * @Instrumentation.Instrument({ tracing: true, metrics: true, logging: true })\n * async trackedMethod() { ... }\n * }\n *\n * // GraphQL instrumentation plugin\n * const yoga = createYoga({\n * plugins: [Instrumentation.createGraphQLInstrumentationPlugin()],\n * });\n * ```\n */\nexport * as Instrumentation from './instrumentation/index.js';\n\n/**\n * Layer namespace - Service layer detection and configuration\n *\n * Provides automatic detection of service layer (wspace vs global) and\n * configuration of layer-specific resource URLs.\n *\n * @example\n * ```typescript\n * import { Layer } from '@burdenoff/be-sdk';\n *\n * // Create layer manager\n * const layerManager = new Layer.LayerManager({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Get layer-specific URLs\n * const internalGatewayUrl = layerManager.getInternalGatewayUrl();\n * const crossLayerGatewayUrl = layerManager.getCrossLayerGatewayUrl();\n * const eventQueueUrl = layerManager.getEventQueueUrl();\n * const valkeyUrl = layerManager.getValkeyUrl();\n *\n * // Create from environment\n * const manager = Layer.createLayerManagerFromEnv('wspace-tags-svc');\n *\n * // Detect layer from service name\n * const layer = Layer.detectLayerFromServiceName('global-auth-svc'); // 'global'\n * ```\n */\nexport * as Layer from './layer/index.js';\n\n/**\n * Crypto namespace - Encryption utilities for sensitive data\n *\n * Provides AES-256-GCM encryption/decryption for storing sensitive\n * data like credentials, API keys, and secrets.\n *\n * @example\n * ```typescript\n * import { Crypto } from '@burdenoff/be-sdk';\n *\n * // Generate a key (store this securely, e.g., in env vars)\n * const key = Crypto.generateEncryptionKey();\n *\n * // Encrypt sensitive data\n * const encrypted = Crypto.encrypt('my-api-key', key);\n *\n * // Decrypt when needed\n * const decrypted = Crypto.decrypt(encrypted, key);\n *\n * // Check if value is already encrypted\n * if (!Crypto.isEncrypted(value)) {\n * value = Crypto.encrypt(value, key);\n * }\n * ```\n */\nexport * as Crypto from './crypto/index.js';\n\n/**\n * Gateway namespace - Unified gateway client with circuit breaker\n *\n * Provides GraphQL client with automatic circuit breaker, retry logic,\n * and layer-aware routing for internal and cross-layer communication.\n *\n * @example\n * ```typescript\n * import { Gateway } from '@burdenoff/be-sdk';\n *\n * // Create gateway client\n * const client = new Gateway.GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * serviceIdentity: 'wspace-tags-svc',\n * internalGatewayUrl: 'http://wspace-int-gateway:4000/graphql',\n * crossLayerGatewayUrl: 'http://global-public-gateway:4000/graphql',\n * });\n *\n * // Make internal (same-layer) query\n * const result = await client.internalQuery({\n * query: 'query GetTags { tags { id name } }',\n * });\n *\n * // Make cross-layer query (e.g., wspace -> global)\n * const tenant = await client.crossLayerQuery({\n * query: 'query GetTenant($id: ID!) { tenant(id: $id) { name } }',\n * variables: { id: 'tenant-123' },\n * });\n *\n * // Create from environment\n * const gatewayClient = Gateway.createGatewayClientFromEnv('wspace-tags-svc');\n * ```\n */\nexport * as Gateway from './gateway/index.js';\n\n/**\n * FeatureFlags namespace - In-house feature flag evaluation\n *\n * @example\n * ```typescript\n * import { FeatureFlags } from '@burdenoff/be-sdk';\n *\n * const provider = new FeatureFlags.FeatureFlagProvider({\n * gatewayUrl: 'http://global-int-gateway:4000/global/graphql',\n * });\n *\n * const isEnabled = await provider.isEnabled('calendar.recurring-events', {\n * actorId: 'user-123',\n * actorType: 'user',\n * workspaceId: 'ws-456',\n * });\n * ```\n */\nexport * as FeatureFlags from './feature-flags/index.js';\n\n/**\n * Captcha namespace - reCAPTCHA v2/v3 token verification\n *\n * Provides environment-toggleable reCAPTCHA verification using Google's\n * siteverify API. Supports both v2 (checkbox) and v3 (invisible/score-based).\n *\n * @example\n * ```typescript\n * import { Captcha } from '@burdenoff/be-sdk';\n *\n * // Auto-bypass when CAPTCHA_ENABLED !== \"true\"\n * const result = await Captcha.verifyCaptchaIfEnabled({\n * token: input.recaptchaToken,\n * expectedAction: 'login',\n * minScore: 0.5,\n * });\n *\n * if (!result.success) {\n * throw new Error('Captcha verification failed');\n * }\n * ```\n */\nexport * as Captcha from './captcha/index.js';\nexport { verifyCaptcha, verifyCaptchaIfEnabled, isCaptchaEnabled } from './captcha/index.js';\nexport type { RecaptchaVerifyOptions, RecaptchaVerifyResult } from './captcha/index.js';\n\n/**\n * Platform Primitives\n *\n * Reusable building blocks consumed by every svc as part of the\n * scale-refactor: hardened HTTP client, leader lock, rate limiter,\n * paginator, dataloader factory, cache-invalidation, monthly PG\n * partition helpers, multi-provider LLM router.\n */\nexport * as Platform from './platform/index.js';\n\n/**\n * User-identity validators (BOFF-7261).\n *\n * Server-side mirror of `microfe-auth/src/auth/utils/validation.ts` so\n * `signUp`, `updateCurrentUserProfile`, and `updateUser` enforce the\n * same name/username invariants whether the call arrives via the UI form,\n * the GraphQL API directly, or a programmatic client. See BOFF-7261.\n */\nexport * as Validation from './validation/index.js';\nexport {\n validateName,\n validateUsername,\n validateUserFields,\n lengthInCodePoints,\n NAME_MIN_LENGTH,\n NAME_MAX_LENGTH,\n USERNAME_MIN_LENGTH,\n USERNAME_MAX_LENGTH,\n} from './validation/index.js';\nexport type {\n NameErrorCode,\n NameValidationResult,\n UsernameErrorCode,\n UsernameValidationResult,\n UserFieldKey,\n UserFieldError,\n ValidatedUserFields,\n UserFieldsValidationResult,\n} from './validation/index.js';\n\n/**\n * Whole-schema `@rbac` coverage guard for svc unit tests (VC/FG parity G03).\n * Lifted from wspace-healthybowl-svc's rbac-coverage test.\n */\nexport { assertRbacCoverage, analyzeRbacCoverage, RbacCoverageError } from './validation/index.js';\nexport type { RbacCoverageOptions, RbacCoverageReport, RbacCoverageSource } from './validation/index.js';\n\n/**\n * Product rename aliases (Botlit → BotManor, botmanor-migration WP-E).\n *\n * Readers accept both names (`normalizeProductSlug`, `quotaKeyVariants`,\n * `isSameRbacResource`, …); writers emit via `emitName` / `emit*`, driven by\n * `PRODUCT_RENAME_EMIT`. Also available as `@burdenoff/be-sdk/product-alias`.\n */\nexport * as ProductAlias from './product-alias/index.js';\nexport {\n PRODUCT_RENAMES,\n PRODUCT_SLUG_ALIASES,\n PRODUCT_RENAME_EMIT,\n RENAME_CONCERNS,\n toCurrentName,\n toLegacyName,\n nameVariants,\n isSameName,\n isLegacyName,\n emitName,\n normalizeProductSlug,\n productSlugVariants,\n isSameProductSlug,\n emitProductSlug,\n normalizeQuotaKey,\n quotaKeyVariants,\n isSameQuotaKey,\n emitQuotaKey,\n normalizeBillingId,\n billingIdVariants,\n isSameBillingId,\n emitBillingId,\n normalizeRbacResource,\n rbacResourceVariants,\n isSameRbacResource,\n emitRbacResource,\n normalizeTemplateKey,\n templateKeyVariants,\n isSameTemplateKey,\n emitTemplateKey,\n normalizeGraphQLName,\n isSameGraphQLName,\n readRenamedEnv,\n} from './product-alias/index.js';\nexport type { ProductRename, RenameConcern, EmitGeneration } from './product-alias/index.js';\n\n// ============================================================================\n// DSAR Orchestrator Identity Guard (BOFF-9550)\n// ============================================================================\nexport {\n DEFAULT_DSAR_ORCHESTRATOR_ID,\n VERIFIED_SERVICE_IDENTITY_HEADER,\n DSAR_ALLOWED_ORCHESTRATORS_ENV,\n DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV,\n DsarOrchestratorForbiddenError,\n getAllowedDsarOrchestrators,\n resolveDsarCallerIdentity,\n isDsarOrchestratorActor,\n assertDsarOrchestrator,\n type DsarOrchestratorContext,\n type DsarOrchestratorOptions,\n type ResolvedDsarCaller,\n type DsarOrchestratorRejectionReason,\n} from './server/dsar-orchestrator.js';\n\n// ============================================================================\n// Default Export\n// ============================================================================\n\nexport default BurdenoffSDK;\n\n/**\n * Create SDK instance (convenience function)\n */\nexport function createSDK(config: SDKConfig, context?: SDKContext): BurdenoffSDK {\n return new BurdenoffSDK(config, context);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,eAAe,OAAkD;CACxE,OAAO,UAAU,YAAY,UAAU;AACzC;;;;AAKA,IAAa,yBAAb,MAAoC;CAClC,AAAQ;;;;;;;;;CASR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,QAAmB,iBAA6B,CAAC,GAAG;EAC9D,KAAK,SAAS;EACd,KAAK,iBAAiB;EAGtB,KAAK,mBAAmB,IAAI,cAAc,OAAO,kBAAkB,EACjE,SAAS,KAAK,WAAW,cAAc,EACzC,CAAC;EAMD,IAAI,OAAO,cACT,KAAK,gBAAgB,IAAI,cAAc;GACrC,OACE,OAAO,iBACN,eAAe,QAAQ,IAAI,gBAAgB,IAAI,QAAQ,IAAI,mBAAmB;GACjF,aAAa,OAAO,eAAe,QAAQ,IAAI,mBAAmB;GAClE,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AAO,KAAK,qDAAqD,EAAE,MAAM,CAAC;EAC5E;CACF;;;;CAKA,OAAc,gBAAgB,QAAgE;EAC5F,OAAO,gBAAgB,MAAM;CAC/B;AACF;;;;AAqqBA,SAAgB,UAAU,QAAmB,SAAoC;CAC/E,OAAO,IAAI,aAAa,QAAQ,OAAO;AACzC"}
@@ -1,4 +1,4 @@
1
- import { a as resetSDK, i as isSDKInitialized, r as initializeBurdenoffSDK, t as getSDKState } from "../init-knkrqVvJ.js";
1
+ import { a as resetSDK, i as isSDKInitialized, r as initializeBurdenoffSDK, t as getSDKState } from "../init-CsfDrW9M.js";
2
2
 
3
3
  export { getSDKState, initializeBurdenoffSDK, isSDKInitialized, resetSDK };
4
4
  //# sourceMappingURL=index.js.map
@@ -201,13 +201,13 @@ async function initializeCache(config) {
201
201
  * values are ignored — kept on the type only as a back-compat shim.
202
202
  */
203
203
  async function initializeEventQueue(_config) {
204
- const { resolveEventStreamsUrl } = await import("./env-DdaoGjIt.js").then((n) => n.r);
204
+ const { resolveEventStreamsUrl } = await import("./env-cCfoPZ7m.js").then((n) => n.r);
205
205
  if (!resolveEventStreamsUrl()) {
206
206
  logger.info("[SDK Init] REDIS_STREAMS_URL / REDIS_URL not set, skipping event queue init");
207
207
  return;
208
208
  }
209
209
  try {
210
- const { EventQueueFactory } = await import("./EventQueueFactory-DbLEV5h_.js").then((n) => n.n);
210
+ const { EventQueueFactory } = await import("./EventQueueFactory-0XHOTKEv.js").then((n) => n.n);
211
211
  const publisher = EventQueueFactory.createPublisherFromEnv();
212
212
  await publisher.connect();
213
213
  logger.info("[SDK Init] Redis Streams event publisher connected");
@@ -322,4 +322,4 @@ async function initializeLayerStreams(config) {
322
322
  }
323
323
 
324
324
  export { resetSDK as a, isSDKInitialized as i, init_exports as n, initializeBurdenoffSDK as r, getSDKState as t };
325
- //# sourceMappingURL=init-knkrqVvJ.js.map
325
+ //# sourceMappingURL=init-CsfDrW9M.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"init-knkrqVvJ.js","names":[],"sources":["../src/init/index.ts"],"sourcesContent":["/**\n * Burdenoff SDK Initialization Module\n *\n * Provides a unified initialization function for all state services\n * including database, cache, analytics, event queue, and graph sync.\n *\n * @module init\n * @category Initialization\n */\n\nimport { logger } from '../logger/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { GatewayClient } from '../gateway/index.js';\nimport { configureResourceCaps } from '../resource-caps/index.js';\nimport { createCounter } from '../instrumentation/metrics-collector.js';\nimport type { BurdenoffSDKInitConfig, InitializedSDKState } from './types.js';\n\n/**\n * Global SDK state\n */\nlet sdkState: InitializedSDKState | null = null;\nlet isInitialized = false;\n\n/**\n * Initialize Burdenoff SDK with unified configuration\n *\n * This function initializes all configured state services in the correct order:\n * 1. Logging configuration\n * 2. Database (Prisma with PostgreSQL)\n * 3. Cache (Valkey)\n * 4. Event Queue (Redis Streams)\n * 5. Graph Sync (Redis Streams-based — Apache AGE writes happen inside wspace-graph-svc)\n * 6. Analytics (ClickHouse)\n * 7. Observability (Metrics, OpenTelemetry)\n *\n * @param config - SDK initialization configuration\n * @returns Initialized SDK state\n *\n * @example\n * ```typescript\n * import { initializeBurdenoffSDK } from '@burdenoff/be-sdk/init';\n *\n * const state = await initializeBurdenoffSDK({\n * database: {\n * url: process.env.DATABASE_URL!,\n * maxConnections: 20,\n * },\n * graph: {\n * enabled: true,\n * eventsEnabled: true,\n * },\n * cache: {\n * valkey: {\n * url: process.env.VALKEY_URL!,\n * },\n * },\n * });\n * ```\n */\nexport async function initializeBurdenoffSDK(config: BurdenoffSDKInitConfig): Promise<InitializedSDKState> {\n if (isInitialized && sdkState) {\n logger.warn('[SDK Init] SDK already initialized, returning existing state');\n return sdkState;\n }\n\n logger.info('[SDK Init] Starting SDK initialization...');\n const startTime = Date.now();\n\n try {\n // 1. Configure logging\n await initializeLogging(config);\n\n // 2. Initialize layer manager (if configured)\n const { layerManager, gatewayClient } = await initializeLayer(config);\n\n // 2b. Wire resource caps to billing so plan-based limits actually apply.\n // `userBillingPlan` lives in the GLOBAL layer: global services reach it\n // on their own internal gateway; wspace services go cross-layer via the\n // public global gateway (service JWT). Without this, every resource cap\n // silently collapses to the free-tier fallback regardless of the\n // customer's plan (BOFF-4805). Primes the process-wide singleton so all\n // existing `getResourceCaps()` call sites resolve real plans unchanged.\n if (gatewayClient && config.layer) {\n const layerType = config.layer.type;\n const fallbackCounter = createCounter(\n 'resource_caps.clientless_fallback_total',\n 'Total number of times resource caps fell back because no billing source was configured at bootstrap'\n );\n configureResourceCaps({\n transport: async (query, variables) => {\n // Cap checks run on entity-create paths and ALWAYS fall back to the\n // configured billing-failure tier on failure, so a billing outage\n // must degrade fast rather than stall writes. Bound the lookup with a\n // short timeout and no retries instead of the gateway defaults\n // (~30s × 3 ≈ 90s). Results are cached 60s, so healthy lookups rarely\n // hit the gateway anyway. `skipCircuitBreaker` keeps this best-effort\n // probe OUT of the shared gateway circuit: its failures already\n // degrade to the fallback here, so they must not count toward opening\n // the internal/cross-layer circuit and fail-fast unrelated M2M calls\n // during a billing outage.\n const options = { query, variables, timeout: 8000, skipRetry: true, skipCircuitBreaker: true };\n const response =\n layerType === 'global'\n ? await gatewayClient.internalQuery(options)\n : await gatewayClient.crossLayerQuery(options);\n return response?.data ?? null;\n },\n // Emitting a dedicated clientless-fallback counter at bootstrap means\n // a service that somehow starts without a billing transport is\n // immediately visible in metrics (BOFF-4809). The resource-caps module\n // itself also emits `resource_caps.plan_resolution_total`, but that\n // only fires on the first cap check; this counter fires at bootstrap.\n onFallback: () => fallbackCounter.inc(),\n });\n logger.info('[SDK Init] Resource caps wired to billing', { layer: layerType });\n } else {\n logger.warn('[SDK Init] No layer/gateway configured — resource caps will use free-tier fallbacks (BOFF-4805)');\n }\n\n // 3. Initialize database (required)\n const prisma = await initializeDatabase(config);\n\n // 4. Initialize cache (optional)\n const valkey = await initializeCache(config);\n\n // 5. Initialize event queue (optional) — Redis Streams via REDIS_URL\n const eventPublisher = await initializeEventQueue(config);\n\n // 6. Initialize layer streams (if layer configured)\n if (config.layer?.autoCreateStreams !== false && config.layer) {\n await initializeLayerStreams(config);\n }\n\n // 7. Initialize graph sync (optional) — publisher emits to Redis Streams,\n // never opens a graph-DB connection\n const graphSync = await initializeGraphSync(config);\n\n // 8. Initialize analytics (optional)\n const clickhouse = await initializeAnalytics(config);\n\n // 9. Initialize observability (optional)\n await initializeObservability(config);\n\n // Create SDK state\n // graphSync is a publisher-side placeholder; services emit Redis Streams\n // events and wspace-graph-svc owns the sole Apache AGE connection.\n void graphSync;\n sdkState = {\n prisma,\n valkey,\n clickhouse,\n eventPublisher,\n layerManager,\n gatewayClient,\n graphSyncEnabled: config.graph?.enabled ?? false,\n analyticsEnabled: !!config.analytics?.clickhouse,\n observabilityEnabled: config.observability?.metrics?.enabled ?? false,\n layerAwareEnabled: !!config.layer,\n };\n\n isInitialized = true;\n\n const duration = Date.now() - startTime;\n // sdkState is guaranteed non-null here since we just assigned it above\n const initializedState = sdkState;\n logger.info(`[SDK Init] SDK initialized successfully in ${duration}ms`, {\n graphSyncEnabled: initializedState.graphSyncEnabled,\n analyticsEnabled: initializedState.analyticsEnabled,\n observabilityEnabled: initializedState.observabilityEnabled,\n layerAwareEnabled: initializedState.layerAwareEnabled,\n layer: config.layer?.type,\n serviceName: config.layer?.serviceName,\n });\n\n return initializedState;\n } catch (error) {\n logger.error('[SDK Init] Failed to initialize SDK:', error);\n throw error;\n }\n}\n\n/**\n * Get current SDK state\n * @throws Error if SDK is not initialized\n */\nexport function getSDKState(): InitializedSDKState {\n if (!isInitialized || !sdkState) {\n throw new Error('SDK not initialized. Call initializeBurdenoffSDK() first.');\n }\n return sdkState;\n}\n\n/**\n * Check if SDK is initialized\n */\nexport function isSDKInitialized(): boolean {\n return isInitialized;\n}\n\n/**\n * Reset SDK state (useful for testing)\n */\nexport async function resetSDK(): Promise<void> {\n logger.info('[SDK Init] Resetting SDK state...');\n\n if (sdkState) {\n // Cleanup resources\n // Note: Individual cleanup will be handled by service-specific shutdown handlers\n sdkState = null;\n }\n\n isInitialized = false;\n logger.info('[SDK Init] SDK state reset');\n}\n\n/**\n * Initialize logging configuration\n */\nasync function initializeLogging(config: BurdenoffSDKInitConfig): Promise<void> {\n logger.info('[SDK Init] Configuring logging...');\n\n const loggingConfig = config.logging ?? {};\n const isDevelopment = config.app?.nodeEnv === 'development';\n\n // Set log level\n const level = loggingConfig.level ?? 'info';\n logger.setLevel(level);\n\n // Set console logging\n const console = loggingConfig.console ?? true;\n logger.setConsoleEnabled(console);\n\n logger.info('[SDK Init] Logging configured', {\n level,\n console,\n format: loggingConfig.format ?? (isDevelopment ? 'pretty' : 'json'),\n });\n}\n\n/**\n * Initialize database (Prisma with PostgreSQL)\n */\nasync function initializeDatabase(config: BurdenoffSDKInitConfig): Promise<unknown> {\n logger.info('[SDK Init] Initializing database...');\n\n // Note: Database initialization is handled by createPrismaClient in prisma/client.ts\n // This is called by the application (e.g., workspaces-backend)\n // We just validate the config here\n if (!config.database?.url) {\n throw new Error('Database URL is required');\n }\n\n logger.info('[SDK Init] Database configuration validated', {\n maxConnections: config.database.maxConnections ?? 20,\n enableQueryLogging: config.database.enableQueryLogging ?? false,\n });\n\n // Return undefined as database client is created separately\n return undefined;\n}\n\n/**\n * Initialize cache (Valkey)\n */\nasync function initializeCache(config: BurdenoffSDKInitConfig): Promise<unknown> {\n const cacheConfig = config.cache?.valkey;\n\n if (!cacheConfig) {\n logger.info('[SDK Init] Cache not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing Valkey cache...');\n\n // Note: Valkey initialization is handled by cache module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] Valkey cache configuration validated', {\n url: cacheConfig.url ? '***' : undefined,\n defaultTTL: cacheConfig.defaultTTL ?? 3600,\n });\n\n return undefined;\n}\n\n/**\n * Initialize event queue (Redis Streams).\n *\n * NATS was retired on 2026-05-16. The publisher is created from\n * `REDIS_STREAMS_URL` when set, else `REDIS_URL` (set in every SM bundle). Legacy `config.eventQueue.nats`\n * values are ignored — kept on the type only as a back-compat shim.\n */\nasync function initializeEventQueue(_config: BurdenoffSDKInitConfig): Promise<unknown> {\n const { resolveEventStreamsUrl } = await import('../event-queue/env.js');\n if (!resolveEventStreamsUrl()) {\n logger.info('[SDK Init] REDIS_STREAMS_URL / REDIS_URL not set, skipping event queue init');\n return undefined;\n }\n\n try {\n const { EventQueueFactory } = await import('../event-queue/factory/EventQueueFactory.js');\n const publisher = EventQueueFactory.createPublisherFromEnv();\n await publisher.connect();\n\n logger.info('[SDK Init] Redis Streams event publisher connected');\n\n return publisher;\n } catch (error) {\n logger.warn('[SDK Init] Failed to connect Redis Streams event publisher (non-fatal)', {\n error: error instanceof Error ? error.message : String(error),\n note: 'Service will continue without event publishing. Use direct API calls as fallback.',\n });\n return undefined;\n }\n}\n\n/**\n * Initialize graph sync (Redis Streams publisher side).\n *\n * Services publish entity events to Redis Streams; the `wspace-graph-svc`\n * consumer (and only it) persists them into Apache AGE via Azure PG\n * sidecar. This SDK function does no DB work — it just validates that the\n * publisher-side config is sensible and logs it.\n */\nasync function initializeGraphSync(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.graph?.enabled) {\n logger.info('[SDK Init] Graph sync not enabled, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Graph sync enabled (publisher-only mode)', {\n eventsEnabled: config.graph.eventsEnabled ?? true,\n productSource: config.graph.productSource,\n streamName: config.graph.streamName ?? 'graph_events',\n syncInterval: config.graph.syncInterval ?? 1000,\n batchSize: config.graph.batchSize ?? 10,\n });\n\n return undefined;\n}\n\n/**\n * Initialize analytics (ClickHouse)\n */\nasync function initializeAnalytics(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.analytics?.clickhouse) {\n logger.info('[SDK Init] Analytics not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing ClickHouse for analytics...');\n\n // Note: ClickHouse initialization is handled by analytics module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] ClickHouse configuration validated', {\n url: config.analytics.clickhouse.url,\n database: config.analytics.clickhouse.database,\n requestTimeout: config.analytics.clickhouse.requestTimeout ?? 60000,\n });\n\n return undefined;\n}\n\n/**\n * Initialize observability (metrics, tracing)\n */\nasync function initializeObservability(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.observability?.metrics?.enabled && !config.observability?.openTelemetry?.enabled) {\n logger.info('[SDK Init] Observability not configured, skipping');\n return;\n }\n\n logger.info('[SDK Init] Initializing observability...');\n\n // Note: Observability initialization is handled by observability module\n // This is a placeholder for future implementation\n if (config.observability.metrics?.enabled) {\n logger.info('[SDK Init] Metrics configuration validated', {\n port: config.observability.metrics.port ?? 9090,\n endpoint: config.observability.metrics.endpoint ?? '/metrics',\n });\n }\n\n if (config.observability.openTelemetry?.enabled) {\n logger.info('[SDK Init] OpenTelemetry configuration validated', {\n serviceName: config.observability.openTelemetry.serviceName,\n samplingRate: config.observability.openTelemetry.samplingRate ?? 1.0,\n });\n }\n}\n\n/**\n * Initialize layer manager and gateway client\n */\nasync function initializeLayer(\n config: BurdenoffSDKInitConfig\n): Promise<{ layerManager?: LayerManager; gatewayClient?: GatewayClient }> {\n if (!config.layer) {\n logger.info('[SDK Init] Layer configuration not provided, skipping layer initialization');\n return {};\n }\n\n logger.info('[SDK Init] Initializing layer manager...', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n });\n\n // Create layer manager\n const layerManager = new LayerManager({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n });\n\n // Create gateway client\n const gatewayClient = new GatewayClient({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n logger.info('[SDK Init] Layer manager initialized', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n return { layerManager, gatewayClient };\n}\n\n/**\n * Initialize layer-specific Redis streams.\n *\n * No-op since the 2026-05-16 NATS retirement: Redis Streams are created\n * on demand by `XGROUP CREATE ... MKSTREAM` inside the consumer, so no\n * upfront connect-and-provision step is needed.\n */\nasync function initializeLayerStreams(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.layer) {\n return;\n }\n logger.debug('[SDK Init] Layer streams init is a no-op for Redis Streams (auto-created on first XADD/XGROUP)', {\n layer: config.layer.type,\n });\n}\n\n// Export types\nexport type * from './types.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAI,WAAuC;AAC3C,IAAI,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCpB,eAAsB,uBAAuB,QAA8D;CACzG,IAAI,iBAAiB,UAAU;EAC7B,OAAO,KAAK,8DAA8D;EAC1E,OAAO;CACT;CAEA,OAAO,KAAK,2CAA2C;CACvD,MAAM,YAAY,KAAK,IAAI;CAE3B,IAAI;EAEF,MAAM,kBAAkB,MAAM;EAG9B,MAAM,EAAE,cAAc,kBAAkB,MAAM,gBAAgB,MAAM;EASpE,IAAI,iBAAiB,OAAO,OAAO;GACjC,MAAM,YAAY,OAAO,MAAM;GAC/B,MAAM,kBAAkB,cACtB,2CACA,qGACF;GACA,sBAAsB;IACpB,WAAW,OAAO,OAAO,cAAc;KAWrC,MAAM,UAAU;MAAE;MAAO;MAAW,SAAS;MAAM,WAAW;MAAM,oBAAoB;KAAK;KAK7F,QAHE,cAAc,WACV,MAAM,cAAc,cAAc,OAAO,IACzC,MAAM,cAAc,gBAAgB,OAAO,EAClC,EAAE,QAAQ;IAC3B;IAMA,kBAAkB,gBAAgB,IAAI;GACxC,CAAC;GACD,OAAO,KAAK,6CAA6C,EAAE,OAAO,UAAU,CAAC;EAC/E,OACE,OAAO,KAAK,iGAAiG;EAI/G,MAAM,SAA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1B,iBAAiB,OAAO,MAAM;CAChC,CAAC;CAGD,MAAM,gBAAgB,IAAI,cAAc;EACtC,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,iBAAiB,OAAO,MAAM;EAC9B,oBAAoB,aAAa,sBAAsB;EACvD,sBAAsB,aAAa,wBAAwB;CAC7D,CAAC;CAED,OAAO,KAAK,wCAAwC;EAClD,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,oBAAoB,aAAa,sBAAsB;EACvD,sBAAsB,aAAa,wBAAwB;CAC7D,CAAC;CAED,OAAO;EAAE;EAAc;CAAc;AACvC;;;;;;;;AASA,eAAe,uBAAuB,QAA+C;CACnF,IAAI,CAAC,OAAO,OACV;CAEF,OAAO,MAAM,kGAAkG,EAC7G,OAAO,OAAO,MAAM,KACtB,CAAC;AACH"}
1
+ {"version":3,"file":"init-CsfDrW9M.js","names":[],"sources":["../src/init/index.ts"],"sourcesContent":["/**\n * Burdenoff SDK Initialization Module\n *\n * Provides a unified initialization function for all state services\n * including database, cache, analytics, event queue, and graph sync.\n *\n * @module init\n * @category Initialization\n */\n\nimport { logger } from '../logger/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { GatewayClient } from '../gateway/index.js';\nimport { configureResourceCaps } from '../resource-caps/index.js';\nimport { createCounter } from '../instrumentation/metrics-collector.js';\nimport type { BurdenoffSDKInitConfig, InitializedSDKState } from './types.js';\n\n/**\n * Global SDK state\n */\nlet sdkState: InitializedSDKState | null = null;\nlet isInitialized = false;\n\n/**\n * Initialize Burdenoff SDK with unified configuration\n *\n * This function initializes all configured state services in the correct order:\n * 1. Logging configuration\n * 2. Database (Prisma with PostgreSQL)\n * 3. Cache (Valkey)\n * 4. Event Queue (Redis Streams)\n * 5. Graph Sync (Redis Streams-based — Apache AGE writes happen inside wspace-graph-svc)\n * 6. Analytics (ClickHouse)\n * 7. Observability (Metrics, OpenTelemetry)\n *\n * @param config - SDK initialization configuration\n * @returns Initialized SDK state\n *\n * @example\n * ```typescript\n * import { initializeBurdenoffSDK } from '@burdenoff/be-sdk/init';\n *\n * const state = await initializeBurdenoffSDK({\n * database: {\n * url: process.env.DATABASE_URL!,\n * maxConnections: 20,\n * },\n * graph: {\n * enabled: true,\n * eventsEnabled: true,\n * },\n * cache: {\n * valkey: {\n * url: process.env.VALKEY_URL!,\n * },\n * },\n * });\n * ```\n */\nexport async function initializeBurdenoffSDK(config: BurdenoffSDKInitConfig): Promise<InitializedSDKState> {\n if (isInitialized && sdkState) {\n logger.warn('[SDK Init] SDK already initialized, returning existing state');\n return sdkState;\n }\n\n logger.info('[SDK Init] Starting SDK initialization...');\n const startTime = Date.now();\n\n try {\n // 1. Configure logging\n await initializeLogging(config);\n\n // 2. Initialize layer manager (if configured)\n const { layerManager, gatewayClient } = await initializeLayer(config);\n\n // 2b. Wire resource caps to billing so plan-based limits actually apply.\n // `userBillingPlan` lives in the GLOBAL layer: global services reach it\n // on their own internal gateway; wspace services go cross-layer via the\n // public global gateway (service JWT). Without this, every resource cap\n // silently collapses to the free-tier fallback regardless of the\n // customer's plan (BOFF-4805). Primes the process-wide singleton so all\n // existing `getResourceCaps()` call sites resolve real plans unchanged.\n if (gatewayClient && config.layer) {\n const layerType = config.layer.type;\n const fallbackCounter = createCounter(\n 'resource_caps.clientless_fallback_total',\n 'Total number of times resource caps fell back because no billing source was configured at bootstrap'\n );\n configureResourceCaps({\n transport: async (query, variables) => {\n // Cap checks run on entity-create paths and ALWAYS fall back to the\n // configured billing-failure tier on failure, so a billing outage\n // must degrade fast rather than stall writes. Bound the lookup with a\n // short timeout and no retries instead of the gateway defaults\n // (~30s × 3 ≈ 90s). Results are cached 60s, so healthy lookups rarely\n // hit the gateway anyway. `skipCircuitBreaker` keeps this best-effort\n // probe OUT of the shared gateway circuit: its failures already\n // degrade to the fallback here, so they must not count toward opening\n // the internal/cross-layer circuit and fail-fast unrelated M2M calls\n // during a billing outage.\n const options = { query, variables, timeout: 8000, skipRetry: true, skipCircuitBreaker: true };\n const response =\n layerType === 'global'\n ? await gatewayClient.internalQuery(options)\n : await gatewayClient.crossLayerQuery(options);\n return response?.data ?? null;\n },\n // Emitting a dedicated clientless-fallback counter at bootstrap means\n // a service that somehow starts without a billing transport is\n // immediately visible in metrics (BOFF-4809). The resource-caps module\n // itself also emits `resource_caps.plan_resolution_total`, but that\n // only fires on the first cap check; this counter fires at bootstrap.\n onFallback: () => fallbackCounter.inc(),\n });\n logger.info('[SDK Init] Resource caps wired to billing', { layer: layerType });\n } else {\n logger.warn('[SDK Init] No layer/gateway configured — resource caps will use free-tier fallbacks (BOFF-4805)');\n }\n\n // 3. Initialize database (required)\n const prisma = await initializeDatabase(config);\n\n // 4. Initialize cache (optional)\n const valkey = await initializeCache(config);\n\n // 5. Initialize event queue (optional) — Redis Streams via REDIS_URL\n const eventPublisher = await initializeEventQueue(config);\n\n // 6. Initialize layer streams (if layer configured)\n if (config.layer?.autoCreateStreams !== false && config.layer) {\n await initializeLayerStreams(config);\n }\n\n // 7. Initialize graph sync (optional) — publisher emits to Redis Streams,\n // never opens a graph-DB connection\n const graphSync = await initializeGraphSync(config);\n\n // 8. Initialize analytics (optional)\n const clickhouse = await initializeAnalytics(config);\n\n // 9. Initialize observability (optional)\n await initializeObservability(config);\n\n // Create SDK state\n // graphSync is a publisher-side placeholder; services emit Redis Streams\n // events and wspace-graph-svc owns the sole Apache AGE connection.\n void graphSync;\n sdkState = {\n prisma,\n valkey,\n clickhouse,\n eventPublisher,\n layerManager,\n gatewayClient,\n graphSyncEnabled: config.graph?.enabled ?? false,\n analyticsEnabled: !!config.analytics?.clickhouse,\n observabilityEnabled: config.observability?.metrics?.enabled ?? false,\n layerAwareEnabled: !!config.layer,\n };\n\n isInitialized = true;\n\n const duration = Date.now() - startTime;\n // sdkState is guaranteed non-null here since we just assigned it above\n const initializedState = sdkState;\n logger.info(`[SDK Init] SDK initialized successfully in ${duration}ms`, {\n graphSyncEnabled: initializedState.graphSyncEnabled,\n analyticsEnabled: initializedState.analyticsEnabled,\n observabilityEnabled: initializedState.observabilityEnabled,\n layerAwareEnabled: initializedState.layerAwareEnabled,\n layer: config.layer?.type,\n serviceName: config.layer?.serviceName,\n });\n\n return initializedState;\n } catch (error) {\n logger.error('[SDK Init] Failed to initialize SDK:', error);\n throw error;\n }\n}\n\n/**\n * Get current SDK state\n * @throws Error if SDK is not initialized\n */\nexport function getSDKState(): InitializedSDKState {\n if (!isInitialized || !sdkState) {\n throw new Error('SDK not initialized. Call initializeBurdenoffSDK() first.');\n }\n return sdkState;\n}\n\n/**\n * Check if SDK is initialized\n */\nexport function isSDKInitialized(): boolean {\n return isInitialized;\n}\n\n/**\n * Reset SDK state (useful for testing)\n */\nexport async function resetSDK(): Promise<void> {\n logger.info('[SDK Init] Resetting SDK state...');\n\n if (sdkState) {\n // Cleanup resources\n // Note: Individual cleanup will be handled by service-specific shutdown handlers\n sdkState = null;\n }\n\n isInitialized = false;\n logger.info('[SDK Init] SDK state reset');\n}\n\n/**\n * Initialize logging configuration\n */\nasync function initializeLogging(config: BurdenoffSDKInitConfig): Promise<void> {\n logger.info('[SDK Init] Configuring logging...');\n\n const loggingConfig = config.logging ?? {};\n const isDevelopment = config.app?.nodeEnv === 'development';\n\n // Set log level\n const level = loggingConfig.level ?? 'info';\n logger.setLevel(level);\n\n // Set console logging\n const console = loggingConfig.console ?? true;\n logger.setConsoleEnabled(console);\n\n logger.info('[SDK Init] Logging configured', {\n level,\n console,\n format: loggingConfig.format ?? (isDevelopment ? 'pretty' : 'json'),\n });\n}\n\n/**\n * Initialize database (Prisma with PostgreSQL)\n */\nasync function initializeDatabase(config: BurdenoffSDKInitConfig): Promise<unknown> {\n logger.info('[SDK Init] Initializing database...');\n\n // Note: Database initialization is handled by createPrismaClient in prisma/client.ts\n // This is called by the application (e.g., workspaces-backend)\n // We just validate the config here\n if (!config.database?.url) {\n throw new Error('Database URL is required');\n }\n\n logger.info('[SDK Init] Database configuration validated', {\n maxConnections: config.database.maxConnections ?? 20,\n enableQueryLogging: config.database.enableQueryLogging ?? false,\n });\n\n // Return undefined as database client is created separately\n return undefined;\n}\n\n/**\n * Initialize cache (Valkey)\n */\nasync function initializeCache(config: BurdenoffSDKInitConfig): Promise<unknown> {\n const cacheConfig = config.cache?.valkey;\n\n if (!cacheConfig) {\n logger.info('[SDK Init] Cache not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing Valkey cache...');\n\n // Note: Valkey initialization is handled by cache module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] Valkey cache configuration validated', {\n url: cacheConfig.url ? '***' : undefined,\n defaultTTL: cacheConfig.defaultTTL ?? 3600,\n });\n\n return undefined;\n}\n\n/**\n * Initialize event queue (Redis Streams).\n *\n * NATS was retired on 2026-05-16. The publisher is created from\n * `REDIS_STREAMS_URL` when set, else `REDIS_URL` (set in every SM bundle). Legacy `config.eventQueue.nats`\n * values are ignored — kept on the type only as a back-compat shim.\n */\nasync function initializeEventQueue(_config: BurdenoffSDKInitConfig): Promise<unknown> {\n const { resolveEventStreamsUrl } = await import('../event-queue/env.js');\n if (!resolveEventStreamsUrl()) {\n logger.info('[SDK Init] REDIS_STREAMS_URL / REDIS_URL not set, skipping event queue init');\n return undefined;\n }\n\n try {\n const { EventQueueFactory } = await import('../event-queue/factory/EventQueueFactory.js');\n const publisher = EventQueueFactory.createPublisherFromEnv();\n await publisher.connect();\n\n logger.info('[SDK Init] Redis Streams event publisher connected');\n\n return publisher;\n } catch (error) {\n logger.warn('[SDK Init] Failed to connect Redis Streams event publisher (non-fatal)', {\n error: error instanceof Error ? error.message : String(error),\n note: 'Service will continue without event publishing. Use direct API calls as fallback.',\n });\n return undefined;\n }\n}\n\n/**\n * Initialize graph sync (Redis Streams publisher side).\n *\n * Services publish entity events to Redis Streams; the `wspace-graph-svc`\n * consumer (and only it) persists them into Apache AGE via Azure PG\n * sidecar. This SDK function does no DB work — it just validates that the\n * publisher-side config is sensible and logs it.\n */\nasync function initializeGraphSync(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.graph?.enabled) {\n logger.info('[SDK Init] Graph sync not enabled, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Graph sync enabled (publisher-only mode)', {\n eventsEnabled: config.graph.eventsEnabled ?? true,\n productSource: config.graph.productSource,\n streamName: config.graph.streamName ?? 'graph_events',\n syncInterval: config.graph.syncInterval ?? 1000,\n batchSize: config.graph.batchSize ?? 10,\n });\n\n return undefined;\n}\n\n/**\n * Initialize analytics (ClickHouse)\n */\nasync function initializeAnalytics(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.analytics?.clickhouse) {\n logger.info('[SDK Init] Analytics not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing ClickHouse for analytics...');\n\n // Note: ClickHouse initialization is handled by analytics module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] ClickHouse configuration validated', {\n url: config.analytics.clickhouse.url,\n database: config.analytics.clickhouse.database,\n requestTimeout: config.analytics.clickhouse.requestTimeout ?? 60000,\n });\n\n return undefined;\n}\n\n/**\n * Initialize observability (metrics, tracing)\n */\nasync function initializeObservability(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.observability?.metrics?.enabled && !config.observability?.openTelemetry?.enabled) {\n logger.info('[SDK Init] Observability not configured, skipping');\n return;\n }\n\n logger.info('[SDK Init] Initializing observability...');\n\n // Note: Observability initialization is handled by observability module\n // This is a placeholder for future implementation\n if (config.observability.metrics?.enabled) {\n logger.info('[SDK Init] Metrics configuration validated', {\n port: config.observability.metrics.port ?? 9090,\n endpoint: config.observability.metrics.endpoint ?? '/metrics',\n });\n }\n\n if (config.observability.openTelemetry?.enabled) {\n logger.info('[SDK Init] OpenTelemetry configuration validated', {\n serviceName: config.observability.openTelemetry.serviceName,\n samplingRate: config.observability.openTelemetry.samplingRate ?? 1.0,\n });\n }\n}\n\n/**\n * Initialize layer manager and gateway client\n */\nasync function initializeLayer(\n config: BurdenoffSDKInitConfig\n): Promise<{ layerManager?: LayerManager; gatewayClient?: GatewayClient }> {\n if (!config.layer) {\n logger.info('[SDK Init] Layer configuration not provided, skipping layer initialization');\n return {};\n }\n\n logger.info('[SDK Init] Initializing layer manager...', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n });\n\n // Create layer manager\n const layerManager = new LayerManager({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n });\n\n // Create gateway client\n const gatewayClient = new GatewayClient({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n logger.info('[SDK Init] Layer manager initialized', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n return { layerManager, gatewayClient };\n}\n\n/**\n * Initialize layer-specific Redis streams.\n *\n * No-op since the 2026-05-16 NATS retirement: Redis Streams are created\n * on demand by `XGROUP CREATE ... MKSTREAM` inside the consumer, so no\n * upfront connect-and-provision step is needed.\n */\nasync function initializeLayerStreams(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.layer) {\n return;\n }\n logger.debug('[SDK Init] Layer streams init is a no-op for Redis Streams (auto-created on first XADD/XGROUP)', {\n layer: config.layer.type,\n });\n}\n\n// Export types\nexport type * from './types.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAI,WAAuC;AAC3C,IAAI,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCpB,eAAsB,uBAAuB,QAA8D;CACzG,IAAI,iBAAiB,UAAU;EAC7B,OAAO,KAAK,8DAA8D;EAC1E,OAAO;CACT;CAEA,OAAO,KAAK,2CAA2C;CACvD,MAAM,YAAY,KAAK,IAAI;CAE3B,IAAI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,cAAc,SAAS,SAChC,OAAO,KAAK,8CAA8C;EACxD,MAAM,OAAO,cAAc,QAAQ,QAAQ;EAC3C,UAAU,OAAO,cAAc,QAAQ,YAAY;CACrD,CAAC;CAGH,IAAI,OAAO,cAAc,eAAe,SACtC,OAAO,KAAK,oDAAoD;EAC9D,aAAa,OAAO,cAAc,cAAc;EAChD,cAAc,OAAO,cAAc,cAAc,gBAAgB;CACnE,CAAC;AAEL;;;;AAKA,eAAe,gBACb,QACyE;CACzE,IAAI,CAAC,OAAO,OAAO;EACjB,OAAO,KAAK,4EAA4E;EACxF,OAAO,CAAC;CACV;CAEA,OAAO,KAAK,4CAA4C;EACtD,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;CAC5B,CAAC;CAGD,MAAM,eAAe,IAAI,aAAa;EACpC,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,iBAAiB,OAAO,MAAM;CAChC,CAAC;CAGD,MAAM,gBAAgB,IAAI,cAAc;EACtC,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,iBAAiB,OAAO,MAAM;EAC9B,oBAAoB,aAAa,sBAAsB;EACvD,sBAAsB,aAAa,wBAAwB;CAC7D,CAAC;CAED,OAAO,KAAK,wCAAwC;EAClD,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,oBAAoB,aAAa,sBAAsB;EACvD,sBAAsB,aAAa,wBAAwB;CAC7D,CAAC;CAED,OAAO;EAAE;EAAc;CAAc;AACvC;;;;;;;;AASA,eAAe,uBAAuB,QAA+C;CACnF,IAAI,CAAC,OAAO,OACV;CAEF,OAAO,MAAM,kGAAkG,EAC7G,OAAO,OAAO,MAAM,KACtB,CAAC;AACH"}
@@ -1,3 +1,3 @@
1
- import { u as logger } from "../index-CZWopQsh.js";
2
- import { $ as isApolloInlineTraceAvailable, A as buildMetricsConfig, At as injectTraceContext, B as GraphQLOperationType, Bt as InstrumentationFeatureFlags, C as DEFAULT_METRICS_CONFIG, Ct as SpanKind, D as buildFeatureFlags, Dt as getTraceContext, E as buildDatabaseConfig, Et as extractTraceContext, F as isInstrumentationConfigInitialized, Ft as DatabaseInstrumentationConfig, G as createApolloInlineTracePlugin, Gt as STANDARD_METRICS, H as InstrumentationContextExtension, Ht as MetricDefinition, I as resetInstrumentationConfig, It as EventQueueInstrumentationConfig, J as extractOperationInfo, Jt as TraceContext, K as createGraphQLInstrumentationPlugin, Kt as SpanAttributes, L as updateInstrumentationConfig, Lt as GraphQLInstrumentationConfig, M as getInstrumentationConfig, Mt as startSpan, N as initializeInstrumentationConfig, Nt as withSpan, O as buildGraphQLConfig, Ot as getTracer, P as isFeatureEnabled, Pt as CacheInstrumentationConfig, Q as instrumentResolverMap, R as ApolloInlineTraceOptions, Rt as HTTPInstrumentationConfig, S as DEFAULT_LOGGING_CONFIG, St as SpanEvent, T as ENV_VARS, Tt as Tracer, U as OperationNameLabelOptions, Ut as MetricsConfig, V as HTTP_DURATION_OPERATION_NAME_ENV, Vt as LoggingConfig, W as PrometheusPluginOptions, Wt as OperationContext, X as getGraphQLSpanFromContext, Y as getGraphQLOperationFromContext, Yt as TracingConfig, Z as instrumentResolver, _ as DEFAULT_DATABASE_CONFIG, _t as getMetricsRegistry, at as DEFAULT_MAX_TOTAL_SERIES, b as DEFAULT_GRAPHQL_CONFIG, bt as resetMetricsRegistry, c as resetInstrumentation, ct as MetricLabels, d as Log, dt as OVERFLOW_LABEL_KEY, et as isPrometheusAvailable, f as Metric, ft as UpDownCounter, g as DEFAULT_CACHE_CONFIG, gt as createUpDownCounter, h as traced, ht as createHistogram, i as getLogger, it as DEFAULT_MAX_SERIES_PER_METRIC, j as buildTracingConfig, jt as isTracerInitialized, k as buildInstrumentationConfig, kt as initializeTracer, l as setupInstrumentation, lt as MetricsRegistry, m as instrumented, mt as createGauge, n as InstrumentationSetupResult, nt as resolveHttpDurationOperationName, o as initializeInstrumentation, ot as Gauge, p as Trace, pt as createCounter, q as createPrometheusPlugin, qt as SpanContext, r as SetupInstrumentationOptions, rt as Counter, s as isInstrumentationInitialized, st as Histogram, t as InitializeInstrumentationOptions, tt as normalizeOperationNameForMetric, u as Instrument, ut as MetricsRegistryOptions, v as DEFAULT_EVENT_QUEUE_CONFIG, vt as initializeMetricsRegistry, w as DEFAULT_TRACING_CONFIG, wt as SpanStatus, x as DEFAULT_HTTP_CONFIG, xt as Span, y as DEFAULT_FEATURE_FLAGS, yt as isMetricsRegistryInitialized, z as GraphQLOperationInfo, zt as InstrumentationConfig } from "../index-BmL-JjQK.js";
1
+ import { u as logger } from "../index-PvHsCusi.js";
2
+ import { $ as isApolloInlineTraceAvailable, A as buildMetricsConfig, At as injectTraceContext, B as GraphQLOperationType, Bt as InstrumentationFeatureFlags, C as DEFAULT_METRICS_CONFIG, Ct as SpanKind, D as buildFeatureFlags, Dt as getTraceContext, E as buildDatabaseConfig, Et as extractTraceContext, F as isInstrumentationConfigInitialized, Ft as DatabaseInstrumentationConfig, G as createApolloInlineTracePlugin, Gt as STANDARD_METRICS, H as InstrumentationContextExtension, Ht as MetricDefinition, I as resetInstrumentationConfig, It as EventQueueInstrumentationConfig, J as extractOperationInfo, Jt as TraceContext, K as createGraphQLInstrumentationPlugin, Kt as SpanAttributes, L as updateInstrumentationConfig, Lt as GraphQLInstrumentationConfig, M as getInstrumentationConfig, Mt as startSpan, N as initializeInstrumentationConfig, Nt as withSpan, O as buildGraphQLConfig, Ot as getTracer, P as isFeatureEnabled, Pt as CacheInstrumentationConfig, Q as instrumentResolverMap, R as ApolloInlineTraceOptions, Rt as HTTPInstrumentationConfig, S as DEFAULT_LOGGING_CONFIG, St as SpanEvent, T as ENV_VARS, Tt as Tracer, U as OperationNameLabelOptions, Ut as MetricsConfig, V as HTTP_DURATION_OPERATION_NAME_ENV, Vt as LoggingConfig, W as PrometheusPluginOptions, Wt as OperationContext, X as getGraphQLSpanFromContext, Y as getGraphQLOperationFromContext, Yt as TracingConfig, Z as instrumentResolver, _ as DEFAULT_DATABASE_CONFIG, _t as getMetricsRegistry, at as DEFAULT_MAX_TOTAL_SERIES, b as DEFAULT_GRAPHQL_CONFIG, bt as resetMetricsRegistry, c as resetInstrumentation, ct as MetricLabels, d as Log, dt as OVERFLOW_LABEL_KEY, et as isPrometheusAvailable, f as Metric, ft as UpDownCounter, g as DEFAULT_CACHE_CONFIG, gt as createUpDownCounter, h as traced, ht as createHistogram, i as getLogger, it as DEFAULT_MAX_SERIES_PER_METRIC, j as buildTracingConfig, jt as isTracerInitialized, k as buildInstrumentationConfig, kt as initializeTracer, l as setupInstrumentation, lt as MetricsRegistry, m as instrumented, mt as createGauge, n as InstrumentationSetupResult, nt as resolveHttpDurationOperationName, o as initializeInstrumentation, ot as Gauge, p as Trace, pt as createCounter, q as createPrometheusPlugin, qt as SpanContext, r as SetupInstrumentationOptions, rt as Counter, s as isInstrumentationInitialized, st as Histogram, t as InitializeInstrumentationOptions, tt as normalizeOperationNameForMetric, u as Instrument, ut as MetricsRegistryOptions, v as DEFAULT_EVENT_QUEUE_CONFIG, vt as initializeMetricsRegistry, w as DEFAULT_TRACING_CONFIG, wt as SpanStatus, x as DEFAULT_HTTP_CONFIG, xt as Span, y as DEFAULT_FEATURE_FLAGS, yt as isMetricsRegistryInitialized, z as GraphQLOperationInfo, zt as InstrumentationConfig } from "../index-DMq2xPV7.js";
3
3
  export { type ApolloInlineTraceOptions, type CacheInstrumentationConfig, type Counter, DEFAULT_CACHE_CONFIG, DEFAULT_DATABASE_CONFIG, DEFAULT_EVENT_QUEUE_CONFIG, DEFAULT_FEATURE_FLAGS, DEFAULT_GRAPHQL_CONFIG, DEFAULT_HTTP_CONFIG, DEFAULT_LOGGING_CONFIG, DEFAULT_MAX_SERIES_PER_METRIC, DEFAULT_MAX_TOTAL_SERIES, DEFAULT_METRICS_CONFIG, DEFAULT_TRACING_CONFIG, type DatabaseInstrumentationConfig, ENV_VARS, type EventQueueInstrumentationConfig, type Gauge, type GraphQLInstrumentationConfig, type GraphQLOperationInfo, type GraphQLOperationType, type HTTPInstrumentationConfig, HTTP_DURATION_OPERATION_NAME_ENV, type Histogram, InitializeInstrumentationOptions, Instrument, type InstrumentationConfig, type InstrumentationContextExtension, type InstrumentationFeatureFlags, InstrumentationSetupResult, Log, type LoggingConfig, Metric, type MetricDefinition, type MetricLabels, type MetricsConfig, MetricsRegistry, type MetricsRegistryOptions, OVERFLOW_LABEL_KEY, type OperationContext, type OperationNameLabelOptions, type PrometheusPluginOptions, STANDARD_METRICS, SetupInstrumentationOptions, type Span, type SpanAttributes, type SpanContext, type SpanEvent, SpanKind, SpanStatus, Trace, type TraceContext, Tracer, type TracingConfig, type UpDownCounter, buildDatabaseConfig, buildFeatureFlags, buildGraphQLConfig, buildInstrumentationConfig, buildMetricsConfig, buildTracingConfig, createApolloInlineTracePlugin, createCounter, createGauge, createGraphQLInstrumentationPlugin, createHistogram, createPrometheusPlugin, createUpDownCounter, extractOperationInfo, extractTraceContext, getGraphQLOperationFromContext, getGraphQLSpanFromContext, getInstrumentationConfig, getLogger, getMetricsRegistry, getTraceContext, getTracer, initializeInstrumentation, initializeInstrumentationConfig, initializeMetricsRegistry, initializeTracer, injectTraceContext, instrumentResolver, instrumentResolverMap, instrumented, isApolloInlineTraceAvailable, isFeatureEnabled, isInstrumentationConfigInitialized, isInstrumentationInitialized, isMetricsRegistryInitialized, isPrometheusAvailable, isTracerInitialized, logger, normalizeOperationNameForMetric, resetInstrumentation, resetInstrumentationConfig, resetMetricsRegistry, resolveHttpDurationOperationName, setupInstrumentation, startSpan, traced, updateInstrumentationConfig, withSpan };
@@ -1,2 +1,2 @@
1
- import { a as LoggerTransport, d as redactSensitiveFields, f as redactSensitiveString, i as LoggerConfig, l as log, n as LogMeta, o as debug, p as warn, r as Logger, s as error, t as LogLevel, u as logger } from "../index-CZWopQsh.js";
1
+ import { a as LoggerTransport, d as redactSensitiveFields, f as redactSensitiveString, i as LoggerConfig, l as log, n as LogMeta, o as debug, p as warn, r as Logger, s as error, t as LogLevel, u as logger } from "../index-PvHsCusi.js";
2
2
  export { LogLevel, LogMeta, Logger, LoggerConfig, LoggerTransport, debug, error, log, logger, redactSensitiveFields, redactSensitiveString, warn };
@@ -1,5 +1,5 @@
1
1
  import { a as logger } from "./logger-B6rCpb7D.js";
2
- import { i as safeStringify } from "./EventQueueFactory-DbLEV5h_.js";
2
+ import { i as safeStringify } from "./EventQueueFactory-0XHOTKEv.js";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import { createHash } from "node:crypto";
5
5
  import { PrismaPg } from "@prisma/adapter-pg";
@@ -1330,4 +1330,4 @@ function addGraphExtension(baseClient, config) {
1330
1330
  }
1331
1331
 
1332
1332
  export { getCollectionForEntity as _, createConnectionPool as a, shouldSyncRelationship as b, ensureServiceApplicationName as c, isTransientAcquireError as d, normalizeSqlTemplate as f, extractMinimalFields as g, extractEntityTitle as h, configurePrismaLogging as i, fingerprintSqlQuery as l, createRelationshipEvent as m, withDeferredGraphEvents as n, createPrismaAdapter as o, createEntityEvent as p, PrismaClientWrapper as r, createPrismaClient as s, addGraphExtension as t, installAcquireRetry as u, parseRelationship as v, GraphRegistry as x, shouldSyncEntity as y };
1333
- //# sourceMappingURL=middleware-InVCyjUX.js.map
1333
+ //# sourceMappingURL=middleware-aO50bLUO.js.map