@burdenoff/be-sdk 2026.1121.1 → 2026.1123.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/index.d.ts +1 -1
- package/dist/dsar-orchestrator-BlOSa9A_.js +126 -0
- package/dist/dsar-orchestrator-BlOSa9A_.js.map +1 -0
- package/dist/feature-flags/index.d.ts +1 -1
- package/dist/{index-CG6wj66Y.d.ts → index-CzMD97-N.d.ts} +40 -2
- package/dist/{index-BcqQs-Uq.d.ts → index-DSA8h4W3.d.ts} +2 -2
- package/dist/{index-YMGOJins.d.ts → index-nP7g1FZm.d.ts} +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +6 -1
- package/dist/server/index.js.map +1 -1
- package/dist/{types-CWybW61E.d.ts → types-De_pO1Wz.d.ts} +2 -0
- package/package.json +1 -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// 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;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jB,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;;;;AAkpBA,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 { 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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,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"}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { C as VerifiedDelegationContext, D as WorkspaceGuardConfig, E as YogaPlugin, O as WorkspaceMembershipValidation, S as ServerInstance, T as WspaceGraphQLContext, _ as RESTEndpoint, a as IActor, b as ServerI18nConfig, c as IOrganization, d as ITenant, f as ITracking, g as PrismaClientConstructor, h as ModuleGraphConfig, i as GraphQLContext, k as createWorkspaceGuardPlugin, l as IProduct, m as JWTPayload, n as ConsentContext, o as IContextFilterInput, p as IWorkspace, r as ElysiaApp, s as IOperationContext, t as ActorProvenance, u as IProject, v as ServerConfig, w as WorkspaceSecret, x as ServerInfo, y as ServerDefinition } from "../types-
|
|
1
|
+
import { C as VerifiedDelegationContext, D as WorkspaceGuardConfig, E as YogaPlugin, O as WorkspaceMembershipValidation, S as ServerInstance, T as WspaceGraphQLContext, _ as RESTEndpoint, a as IActor, b as ServerI18nConfig, c as IOrganization, d as ITenant, f as ITracking, g as PrismaClientConstructor, h as ModuleGraphConfig, i as GraphQLContext, k as createWorkspaceGuardPlugin, l as IProduct, m as JWTPayload, n as ConsentContext, o as IContextFilterInput, p as IWorkspace, r as ElysiaApp, s as IOperationContext, t as ActorProvenance, u as IProject, v as ServerConfig, w as WorkspaceSecret, x as ServerInfo, y as ServerDefinition } from "../types-De_pO1Wz.js";
|
|
2
2
|
import { n as PrismaClientBase } from "../client-BgAEvDC2.js";
|
|
3
3
|
import { a as ActorOrigin, c as readAssistantSessionAttribution, i as ASSISTANT_SESSION_ID_HEADER, l as toAssistantSessionAttribution, n as AI_ASSISTANT_ACTOR_ORIGIN, o as AssistantSessionAttribution, r as ASSISTANT_CORRELATION_ID_HEADER, s as parseAssistantSessionHeaders, t as ACTOR_ORIGIN_HEADER } from "../assistant-session-DA5ZKJOr.js";
|
|
4
4
|
import { r as I18nContext, s as LocaleCode } from "../types-DgaQqvxo.js";
|
|
5
|
-
import { A as
|
|
5
|
+
import { $ as configureDefaultAuth, A as assertDsarOrchestrator, B as getContextOptions, C as DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, D as DsarOrchestratorRejectionReason, E as DsarOrchestratorOptions, F as getDelegatedPrincipal, G as createRawBodyRouter, H as OrdinaryRoute, I as resolveOnBehalfOf, J as createServer, K as extendRequestIdleTimeout, L as ContextBuilderOptions, M as isDsarOrchestratorActor, N as resolveDsarCallerIdentity, O as ResolvedDsarCaller, P as DelegatedPrincipal, Q as configureAuth, R as buildContext, S as DSAR_ALLOWED_ORCHESTRATORS_ENV, T as DsarOrchestratorForbiddenError, U as RawBodyResolution, V as MAX_IDLE_TIMEOUT_SECONDS, W as RawBodyRouter, X as FetchWorkspaceSecretFn, Y as AuthConfig, Z as authCheck, _ as MutationAuditPluginOptions, a as UserFacingErrorOptions, at as tenantCheck, b as sanitizeAuditValue, c as createHumanReadableErrorPlugin, d as normalizeExecutionResultErrors, et as decodeJWT, f as normalizeGraphQLResponse, g as MUTATION_AUDIT_RESOURCE_TYPE, h as MUTATION_AUDIT_ACTIVITY_TYPE, i as NormalizedErrorState, it as requireWorkspace, j as getAllowedDsarOrchestrators, k as VERIFIED_SERVICE_IDENTITY_HEADER, l as formatHttpError, m as toUserFacingGraphQLError, n as HttpErrorPayload, nt as generateSymmetricSecret, o as UserFacingGraphQLError, ot as verifyJWT, p as normalizeGraphQLResponsePayload, q as configureServerAuth, r as HttpErrorResult, rt as orgCheck, s as createHttpErrorResponse, st as workspaceCheck, t as ErrorNormalizationOptions, tt as fetchWorkspaceSecret, u as normalizeError, v as createMutationAuditPlugin, w as DsarOrchestratorContext, x as DEFAULT_DSAR_ORCHESTRATOR_ID, y as getMutationFieldNames, z as configureContext } from "../index-CzMD97-N.js";
|
|
6
6
|
import { t as suppressMutationAudit } from "../explicit-activity-scope-D8VeGGpt.js";
|
|
7
|
-
export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, type ActorOrigin, type ActorProvenance, type AssistantSessionAttribution, type AuthConfig, type ConsentContext, type ContextBuilderOptions, type DelegatedPrincipal, type ElysiaApp, type ErrorNormalizationOptions, type FetchWorkspaceSecretFn, type GraphQLContext, type HttpErrorPayload, type HttpErrorResult, type I18nContext, type IActor, type IContextFilterInput, type IOperationContext, type IOrganization, type IProduct, type IProject, type ITenant, type ITracking, type IWorkspace, type JWTPayload, type LocaleCode, MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, type ModuleGraphConfig, type MutationAuditPluginOptions, type NormalizedErrorState, type OrdinaryRoute, type PrismaClientBase, type PrismaClientConstructor, type RESTEndpoint, type RawBodyResolution, type RawBodyRouter, type ServerConfig, type ServerDefinition, type ServerI18nConfig, type ServerInfo, type ServerInstance, type UserFacingErrorOptions, UserFacingGraphQLError, type VerifiedDelegationContext, type WorkspaceGuardConfig, type WorkspaceMembershipValidation, type WorkspaceSecret, type WspaceGraphQLContext, type YogaPlugin, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, requireWorkspace, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, workspaceCheck };
|
|
7
|
+
export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, type ActorOrigin, type ActorProvenance, type AssistantSessionAttribution, type AuthConfig, type ConsentContext, type ContextBuilderOptions, DEFAULT_DSAR_ORCHESTRATOR_ID, DSAR_ALLOWED_ORCHESTRATORS_ENV, DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, type DelegatedPrincipal, type DsarOrchestratorContext, DsarOrchestratorForbiddenError, type DsarOrchestratorOptions, type DsarOrchestratorRejectionReason, type ElysiaApp, type ErrorNormalizationOptions, type FetchWorkspaceSecretFn, type GraphQLContext, type HttpErrorPayload, type HttpErrorResult, type I18nContext, type IActor, type IContextFilterInput, type IOperationContext, type IOrganization, type IProduct, type IProject, type ITenant, type ITracking, type IWorkspace, type JWTPayload, type LocaleCode, MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, type ModuleGraphConfig, type MutationAuditPluginOptions, type NormalizedErrorState, type OrdinaryRoute, type PrismaClientBase, type PrismaClientConstructor, type RESTEndpoint, type RawBodyResolution, type RawBodyRouter, type ResolvedDsarCaller, type ServerConfig, type ServerDefinition, type ServerI18nConfig, type ServerInfo, type ServerInstance, type UserFacingErrorOptions, UserFacingGraphQLError, VERIFIED_SERVICE_IDENTITY_HEADER, type VerifiedDelegationContext, type WorkspaceGuardConfig, type WorkspaceMembershipValidation, type WorkspaceSecret, type WspaceGraphQLContext, type YogaPlugin, assertDsarOrchestrator, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getAllowedDsarOrchestrators, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, isDsarOrchestratorActor, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, requireWorkspace, resolveDsarCallerIdentity, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, workspaceCheck };
|
package/dist/server/index.js
CHANGED
|
@@ -7,6 +7,7 @@ import { l as I18n } from "../i18n-BBMYFd0P.js";
|
|
|
7
7
|
import { o as getMetricsRegistry } from "../metrics-collector-C2eShrlW.js";
|
|
8
8
|
import { t as getWorkspaceQuotaRegistry } from "../metrics-BrLwNUrb.js";
|
|
9
9
|
import { t as collectPromDefaultMetrics } from "../bun-runtime-metrics-CPy5D6NT.js";
|
|
10
|
+
import { a as VERIFIED_SERVICE_IDENTITY_HEADER, c as isDsarOrchestratorActor, i as DsarOrchestratorForbiddenError, l as resolveDsarCallerIdentity, n as DSAR_ALLOWED_ORCHESTRATORS_ENV, o as assertDsarOrchestrator, r as DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, s as getAllowedDsarOrchestrators, t as DEFAULT_DSAR_ORCHESTRATOR_ID } from "../dsar-orchestrator-BlOSa9A_.js";
|
|
10
11
|
import { i as suppressMutationAudit, r as runInExplicitActivityScope, t as createExplicitActivityScope } from "../explicit-activity-scope-DikJ7NAE.js";
|
|
11
12
|
import { GraphQLError, Kind, OperationTypeNode } from "graphql";
|
|
12
13
|
import crypto from "node:crypto";
|
|
@@ -368,10 +369,12 @@ async function extractActor(request) {
|
|
|
368
369
|
logger.debug("[ServerContext] Using gateway-authenticated actor from headers");
|
|
369
370
|
const actorType = getHeader(request, "x-actor-type") || "user";
|
|
370
371
|
const userRole = getHeader(request, "x-user-role");
|
|
372
|
+
const verifiedServiceIdentity = getHeader(request, "x-verified-service-identity")?.trim() || void 0;
|
|
371
373
|
return {
|
|
372
374
|
id: actorId,
|
|
373
375
|
type: actorType,
|
|
374
376
|
provenance: actorProvenance(request),
|
|
377
|
+
...verifiedServiceIdentity ? { verifiedServiceIdentity } : {},
|
|
375
378
|
workspace_id: getHeader(request, "x-workspace-id"),
|
|
376
379
|
tenant_id: getHeader(request, "x-tenant-id"),
|
|
377
380
|
org_id: getHeader(request, "x-org-id") || getHeader(request, "x-organization-id"),
|
|
@@ -482,6 +485,7 @@ async function buildContext(request) {
|
|
|
482
485
|
const trustedGatewayHeaders = shouldTrustActorHeaders(request);
|
|
483
486
|
const verifiedDelegation = decodeVerifiedDelegation(getHeader(request, "x-verified-delegation"), actor, workspace?.id, trustedGatewayHeaders);
|
|
484
487
|
const assistantSession = actor && trustedGatewayHeaders ? parseAssistantSessionHeaders((name) => getHeader(request, name)) : void 0;
|
|
488
|
+
const verifiedServiceIdentity = actor && trustedGatewayHeaders ? getHeader(request, "x-verified-service-identity")?.trim() || void 0 : void 0;
|
|
485
489
|
let i18n;
|
|
486
490
|
if (contextOptions.i18n) i18n = contextOptions.i18n.createContextFromRequest(request);
|
|
487
491
|
const geo = extractGeography(request);
|
|
@@ -532,6 +536,7 @@ async function buildContext(request) {
|
|
|
532
536
|
product,
|
|
533
537
|
tracking,
|
|
534
538
|
verifiedDelegation,
|
|
539
|
+
...verifiedServiceIdentity ? { verifiedServiceIdentity } : {},
|
|
535
540
|
...assistantSession ? { assistantSession } : {},
|
|
536
541
|
onBehalfOf: onBehalfOf || actor?.id || "",
|
|
537
542
|
db: contextOptions.getDb(),
|
|
@@ -2124,5 +2129,5 @@ function createMutationAuditPlugin(options) {
|
|
|
2124
2129
|
} };
|
|
2125
2130
|
}
|
|
2126
2131
|
|
|
2127
|
-
export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, UserFacingGraphQLError, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, requireWorkspace, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, workspaceCheck };
|
|
2132
|
+
export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, DEFAULT_DSAR_ORCHESTRATOR_ID, DSAR_ALLOWED_ORCHESTRATORS_ENV, DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, DsarOrchestratorForbiddenError, MAX_IDLE_TIMEOUT_SECONDS, MUTATION_AUDIT_ACTIVITY_TYPE, MUTATION_AUDIT_RESOURCE_TYPE, UserFacingGraphQLError, VERIFIED_SERVICE_IDENTITY_HEADER, assertDsarOrchestrator, authCheck, buildContext, configureAuth, configureContext, configureDefaultAuth, configureServerAuth, createHttpErrorResponse, createHumanReadableErrorPlugin, createMutationAuditPlugin, createRawBodyRouter, createServer, createWorkspaceGuardPlugin, decodeJWT, extendRequestIdleTimeout, fetchWorkspaceSecret, formatHttpError, generateSymmetricSecret, getAllowedDsarOrchestrators, getContextOptions, getDelegatedPrincipal, getMutationFieldNames, isDsarOrchestratorActor, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, orgCheck, parseAssistantSessionHeaders, readAssistantSessionAttribution, requireWorkspace, resolveDsarCallerIdentity, resolveOnBehalfOf, sanitizeAuditValue, suppressMutationAudit, tenantCheck, toAssistantSessionAttribution, toUserFacingGraphQLError, verifyJWT, workspaceCheck };
|
|
2128
2133
|
//# sourceMappingURL=index.js.map
|