@burdenoff/be-sdk 2026.516.3 → 2026.516.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/auth/index.js +1 -1
  2. package/dist/cache/index.js +2 -2
  3. package/dist/{chunk-TXW7ZKA2.js → chunk-3F4SLVRL.js} +5 -5
  4. package/dist/{chunk-TXW7ZKA2.js.map → chunk-3F4SLVRL.js.map} +1 -1
  5. package/dist/{chunk-R3XPCYHM.js → chunk-5SD7DU3L.js} +3 -3
  6. package/dist/{chunk-R3XPCYHM.js.map → chunk-5SD7DU3L.js.map} +1 -1
  7. package/dist/{chunk-5M3YVBTH.js → chunk-CFUKZDDU.js} +3 -3
  8. package/dist/{chunk-5M3YVBTH.js.map → chunk-CFUKZDDU.js.map} +1 -1
  9. package/dist/{chunk-UIJWXPOQ.js → chunk-GSEPF2B6.js} +7 -4
  10. package/dist/chunk-GSEPF2B6.js.map +1 -0
  11. package/dist/{chunk-ZA3IGCDJ.js → chunk-HP6JTFNR.js} +6 -2
  12. package/dist/chunk-HP6JTFNR.js.map +1 -0
  13. package/dist/{chunk-U2GLUZAO.js → chunk-MM3BD756.js} +4 -4
  14. package/dist/{chunk-U2GLUZAO.js.map → chunk-MM3BD756.js.map} +1 -1
  15. package/dist/{chunk-6WYNQ26B.js → chunk-O2MEBPDT.js} +3 -3
  16. package/dist/{chunk-6WYNQ26B.js.map → chunk-O2MEBPDT.js.map} +1 -1
  17. package/dist/{chunk-HF3EFD7G.js → chunk-OJDXWHRJ.js} +2 -2
  18. package/dist/{chunk-HF3EFD7G.js.map → chunk-OJDXWHRJ.js.map} +1 -1
  19. package/dist/{chunk-JO6XUKZ5.js → chunk-V2VEENJ2.js} +3 -3
  20. package/dist/{chunk-JO6XUKZ5.js.map → chunk-V2VEENJ2.js.map} +1 -1
  21. package/dist/{chunk-IPKUQS7K.js → chunk-VLEOOG2L.js} +3 -3
  22. package/dist/{chunk-IPKUQS7K.js.map → chunk-VLEOOG2L.js.map} +1 -1
  23. package/dist/{chunk-NGA6NTFG.js → chunk-ZPJ6VYE4.js} +3 -3
  24. package/dist/{chunk-NGA6NTFG.js.map → chunk-ZPJ6VYE4.js.map} +1 -1
  25. package/dist/database/index.js +1 -1
  26. package/dist/export/index.js +5 -5
  27. package/dist/gateway/index.js +4 -4
  28. package/dist/gateway/security/index.js +1 -1
  29. package/dist/graph/index.js +3 -3
  30. package/dist/index.js +20 -20
  31. package/dist/init/index.js +5 -5
  32. package/dist/layer/index.js +2 -2
  33. package/dist/notifications/index.js +1 -1
  34. package/dist/rbac/index.js +2 -2
  35. package/dist/temporal/index.js +2 -2
  36. package/dist/tracker/index.js +3 -3
  37. package/package.json +1 -1
  38. package/dist/chunk-UIJWXPOQ.js.map +0 -1
  39. package/dist/chunk-ZA3IGCDJ.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  export { AuthCookieHelper, AuthModule } from '../chunk-UNPJMENC.js';
2
2
  import '../chunk-MOCUBSTW.js';
3
3
  import '../chunk-O6RHB2YP.js';
4
- import '../chunk-ZA3IGCDJ.js';
4
+ import '../chunk-HP6JTFNR.js';
5
5
  import '../chunk-CBZNP6RF.js';
6
6
  import '../chunk-XE4OXN2W.js';
7
7
  //# sourceMappingURL=index.js.map
@@ -1,5 +1,5 @@
1
- export { CacheFactory, CacheProviderType, MemoryCacheProvider, ValkeyGlideProvider, closeAllCaches, createCache, getCache, getValkeyClient } from '../chunk-JO6XUKZ5.js';
2
- import '../chunk-ZA3IGCDJ.js';
1
+ export { CacheFactory, CacheProviderType, MemoryCacheProvider, ValkeyGlideProvider, closeAllCaches, createCache, getCache, getValkeyClient } from '../chunk-V2VEENJ2.js';
2
+ import '../chunk-HP6JTFNR.js';
3
3
  import '../chunk-CBZNP6RF.js';
4
4
  import '../chunk-XE4OXN2W.js';
5
5
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,6 @@
1
- import { security_exports } from './chunk-HF3EFD7G.js';
2
- import { LayerManager } from './chunk-UIJWXPOQ.js';
3
- import { DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG } from './chunk-ZA3IGCDJ.js';
1
+ import { security_exports } from './chunk-OJDXWHRJ.js';
2
+ import { LayerManager } from './chunk-GSEPF2B6.js';
3
+ import { DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG } from './chunk-HP6JTFNR.js';
4
4
  import { logger } from './chunk-CBZNP6RF.js';
5
5
  import { __export, __name } from './chunk-XE4OXN2W.js';
6
6
 
@@ -556,5 +556,5 @@ function createGatewayClientFromEnv() {
556
556
  __name(createGatewayClientFromEnv, "createGatewayClientFromEnv");
557
557
 
558
558
  export { CircuitState, GatewayClient, GatewayError, GatewayErrorType, createGatewayClient, createGatewayClientFromEnv, gateway_exports };
559
- //# sourceMappingURL=chunk-TXW7ZKA2.js.map
560
- //# sourceMappingURL=chunk-TXW7ZKA2.js.map
559
+ //# sourceMappingURL=chunk-3F4SLVRL.js.map
560
+ //# sourceMappingURL=chunk-3F4SLVRL.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/gateway/index.ts","../src/gateway/service-jwt.ts","../src/gateway/types.ts","../src/gateway/client.ts"],"names":["SIGNING_ENV_VAR","KEY_ID","DEFAULT_TTL_SECONDS","REFRESH_BEFORE_EXP_MS","joseModule","getJose","cache","Map","cacheKey","actorId","ttlSeconds","signServiceJwt","secret","process","env","key","cached","get","expiresAtMs","Date","now","token","joseLib","encoder","TextEncoder","keyBytes","encode","nowSec","Math","floor","expSec","SignJWT","actor_type","setProtectedHeader","alg","typ","kid","setSubject","setIssuer","setIssuedAt","setExpirationTime","sign","set","CircuitState","GatewayErrorType","GatewayError","Error","type","gatewayUrl","statusCode","graphqlErrors","cause","message","options","name","Object","setPrototypeOf","prototype","uuidv4","crypto","randomUUID","hasAuthorizationHeader","headers","keys","toLowerCase","resolveBypassPermissionValue","normalizedToken","trim","CircuitBreaker","state","CLOSED","failures","successes","consecutiveFailures","lastFailureTime","lastSuccessTime","openedAt","failureTimestamps","config","getState","checkStateTransition","recordSuccess","HALF_OPEN","logger","info","recordFailure","push","windowStart","failureWindow","filter","t","length","failureThreshold","OPEN","warn","threshold","allowRequest","forceOpen","forceClose","getStats","elapsed","resetTimeout","GatewayClient","layerManager","internalCircuitBreaker","crossLayerCircuitBreaker","retryConfig","defaultHeaders","timeout","enableLogging","LayerManager","layer","serviceName","serviceIdentity","internalGatewayUrl","crossLayerGatewayUrl","cbConfig","DEFAULT_CIRCUIT_BREAKER_CONFIG","circuitBreaker","DEFAULT_GATEWAY_RETRY_CONFIG","retry","getServiceIdentity","debug","internalUrl","getInternalUrl","crossLayerUrl","getCrossLayerUrl","getInternalGatewayUrl","getCrossLayerGatewayUrl","internalQuery","context","createRequestContext","executeWithRetry","bypassPermission","crossLayerQuery","query","getInternalCircuitBreaker","getCrossLayerCircuitBreaker","getHealthStatus","internal","url","circuitState","stats","crossLayer","updateDefaultHeaders","callType","requestId","workspaceId","startTime","shouldRetryError","error","GRAPHQL_ERROR","CIRCUIT_OPEN","calculateRetryDelay","attempt","min","initialDelay","pow","backoffMultiplier","maxDelay","logRetryAttempt","maxAttempts","delay","settings","skipCircuitBreaker","skipRetry","lastError","result","executeRequest","String","sleep","UNKNOWN_ERROR","buildRequestHeaders","value","entries","undefined","toString","handleGraphQLErrors","duration","errors","errorMessages","map","e","join","handleFetchError","TIMEOUT_ERROR","NETWORK_ERROR","serviceActorId","serviceJwt","body","JSON","stringify","variables","operationName","controller","AbortController","timeoutId","setTimeout","abort","response","fetch","method","signal","clearTimeout","ok","status","statusText","json","hasData","data","ms","Promise","resolve","createGatewayClient","createGatewayClientFromEnv"],"mappings":";;;;;;;AAAA,IAAA,eAAA,GAAA;;;;;;;;;;;;AC6BA,IAAMA,eAAAA,GAAkB,oBAAA;AACxB,IAAMC,MAAAA,GAAS,YAAA;AACf,IAAMC,mBAAAA,GAAsB,EAAA;AAC5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F,CAAA;AACF;AAnBgBqG,MAAAA,CAAAA,0BAAAA,EAAAA,4BAAAA,CAAAA","file":"chunk-TXW7ZKA2.js","sourcesContent":["/**\n * Gateway Module\n *\n * Provides unified gateway client for layer-aware M2M communication\n * with circuit breaker and retry logic.\n *\n * @module gateway\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient, createGatewayClientFromEnv } from '@burdenoff/be-sdk/gateway';\n *\n * // Create from environment variables\n * const client = createGatewayClientFromEnv();\n *\n * // Or create manually\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer, uses int-gateway with bypass)\n * const internalResult = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call (via public gateway)\n * const crossLayerResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\n// Client exports\nexport { GatewayClient, createGatewayClient, createGatewayClientFromEnv } from './client.js';\n\n// Type exports\nexport {\n CircuitState,\n GatewayErrorType,\n GatewayError,\n type GatewayClientConfig,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type GraphQLError,\n type IGatewayClient,\n type ICircuitBreaker,\n type CircuitBreakerStats,\n type GatewayClientHealth,\n type RequestContext,\n} from './types.js';\n\n// Gateway-side security plugin stack (for public gateways).\n// Imported by consumers as `@burdenoff/be-sdk/gateway/security` — this\n// re-export lets `@burdenoff/be-sdk/gateway` also resolve the namespace.\nexport * as Security from './security/index.js';\n","/**\n * Service JWT minting + caching for M2M cross-layer calls.\n *\n * The public gateways (global-public-gateway, wspace-public-gateway) validate\n * every incoming request's Authorization header and only propagate `x-actor-*`\n * context headers to subgraphs when the JWT is valid. Without a JWT, raw\n * actor headers are stripped as potential client spoofing. For service-to-\n * service cross-layer calls there is no user JWT to forward — we mint a short-\n * lived service JWT with `actor_type: 'service'` so the gateway admits the\n * call and the subgraph sees a trusted service context.\n *\n * Signing key: SERVICE_JWT_SECRET — a dedicated, separate secret from\n * GLOBAL_AUTH_SECRET (which signs user tokens). Keeping them distinct means a\n * service minter that leaks its env cannot forge user logins. The gateways\n * hold both secrets and pick between them by the JWT's `kid` header\n * (this minter stamps `kid: service-v1`).\n */\nimport type * as jose from 'jose';\n\n/**\n * Dedicated secret for service-minted JWTs.\n *\n * Deliberately separate from `GLOBAL_AUTH_SECRET` (which signs user tokens)\n * so that services that mint service JWTs do not also hold the ability to\n * forge user logins. Blast radius of a leaked secret stays scoped to 60s\n * service tokens with no PII.\n *\n * Gateways hold both secrets and select by the JWT's `kid` header.\n */\nconst SIGNING_ENV_VAR = 'SERVICE_JWT_SECRET';\nconst KEY_ID = 'service-v1';\nconst DEFAULT_TTL_SECONDS = 60;\nconst REFRESH_BEFORE_EXP_MS = 10_000;\n\nlet joseModule: typeof jose | null = null;\n\nasync function getJose(): Promise<typeof jose> {\n if (!joseModule) {\n joseModule = await import('jose');\n }\n return joseModule;\n}\n\ninterface CachedToken {\n token: string;\n expiresAtMs: number;\n}\n\nconst cache = new Map<string, CachedToken>();\n\nfunction cacheKey(actorId: string, ttlSeconds: number): string {\n return `${actorId}:${ttlSeconds}`;\n}\n\n/**\n * Sign a service-actor JWT.\n * Returns null when no signing secret is configured (opt-in).\n */\nexport async function signServiceJwt(\n actorId: string,\n ttlSeconds: number = DEFAULT_TTL_SECONDS\n): Promise<string | null> {\n const secret = process.env[SIGNING_ENV_VAR];\n if (!secret) {\n return null;\n }\n\n const key = cacheKey(actorId, ttlSeconds);\n const cached = cache.get(key);\n if (cached && cached.expiresAtMs - REFRESH_BEFORE_EXP_MS > Date.now()) {\n return cached.token;\n }\n\n const joseLib = await getJose();\n const encoder = new TextEncoder();\n const keyBytes = encoder.encode(secret);\n\n const nowSec = Math.floor(Date.now() / 1000);\n const expSec = nowSec + ttlSeconds;\n\n const token = await new joseLib.SignJWT({\n actor_type: 'service',\n })\n .setProtectedHeader({ alg: 'HS256', typ: 'JWT', kid: KEY_ID })\n .setSubject(actorId)\n // `iss` = the service identity that minted the token. Matches `sub`\n // because these are self-minted tokens (caller is asserting itself).\n // Gives the gateway room to enforce a minter allowlist later without\n // a token-format change.\n .setIssuer(actorId)\n .setIssuedAt(nowSec)\n .setExpirationTime(expSec)\n .sign(keyBytes);\n\n cache.set(key, { token, expiresAtMs: expSec * 1000 });\n return token;\n}\n\n/** Test hook to clear the cache between tests. */\nexport function __clearServiceJwtCache(): void {\n cache.clear();\n}\n","/**\n * Gateway Client Types\n *\n * Type definitions for the unified gateway client with\n * circuit breaker and retry logic.\n *\n * @module gateway/types\n * @category Gateway\n */\n\nimport type { ServiceLayer, CircuitBreakerConfig, GatewayRetryConfig, GatewayRequestHeaders } from '../types/layer.js';\n\n/**\n * Gateway client configuration\n */\nexport interface GatewayClientConfig {\n /**\n * Layer this client belongs to\n */\n layer: ServiceLayer;\n\n /**\n * Service name (for logging and headers)\n */\n serviceName: string;\n\n /**\n * Service identity for bypass headers\n * @default serviceName\n */\n serviceIdentity?: string;\n\n /**\n * Internal gateway URL (same layer M2M)\n * @default Resolved from layer defaults or environment\n */\n internalGatewayUrl?: string;\n\n /**\n * Cross-layer gateway URL (cross layer via public gateway)\n * @default Resolved from layer defaults or environment\n */\n crossLayerGatewayUrl?: string;\n\n /**\n * Request timeout in milliseconds\n * @default 30000 (30 seconds)\n */\n timeout?: number;\n\n /**\n * Circuit breaker configuration\n */\n circuitBreaker?: Partial<CircuitBreakerConfig>;\n\n /**\n * Retry configuration\n */\n retry?: Partial<GatewayRetryConfig>;\n\n /**\n * Enable request logging\n * @default true\n */\n enableLogging?: boolean;\n\n /**\n * Default headers to include in all requests\n */\n defaultHeaders?: GatewayRequestHeaders;\n}\n\n/**\n * Circuit breaker states\n */\nexport enum CircuitState {\n CLOSED = 'CLOSED',\n OPEN = 'OPEN',\n HALF_OPEN = 'HALF_OPEN',\n}\n\n/**\n * Circuit breaker instance interface\n */\nexport interface ICircuitBreaker {\n /**\n * Get current circuit state\n */\n getState(): CircuitState;\n\n /**\n * Record a successful call\n */\n recordSuccess(): void;\n\n /**\n * Record a failed call\n */\n recordFailure(): void;\n\n /**\n * Check if circuit allows calls\n */\n allowRequest(): boolean;\n\n /**\n * Force open the circuit\n */\n forceOpen(): void;\n\n /**\n * Force close the circuit\n */\n forceClose(): void;\n\n /**\n * Get circuit statistics\n */\n getStats(): CircuitBreakerStats;\n}\n\n/**\n * Circuit breaker statistics\n */\nexport interface CircuitBreakerStats {\n state: CircuitState;\n failures: number;\n successes: number;\n consecutiveFailures: number;\n lastFailureTime: number | null;\n lastSuccessTime: number | null;\n openedAt: number | null;\n}\n\n/**\n * GraphQL request options\n */\nexport interface GraphQLRequestOptions {\n /**\n * GraphQL query or mutation string\n */\n query: string;\n\n /**\n * GraphQL variables\n */\n variables?: Record<string, unknown>;\n\n /**\n * Operation name (for multi-operation documents)\n */\n operationName?: string;\n\n /**\n * Additional headers for this request\n */\n headers?: GatewayRequestHeaders;\n\n /**\n * Override timeout for this request\n */\n timeout?: number;\n\n /**\n * Skip circuit breaker for this request\n * @default false\n */\n skipCircuitBreaker?: boolean;\n\n /**\n * Skip retry logic for this request\n * @default false\n */\n skipRetry?: boolean;\n}\n\n/**\n * GraphQL response\n */\nexport interface GraphQLResponse<T = unknown> {\n /**\n * Response data\n */\n data?: T;\n\n /**\n * GraphQL errors\n */\n errors?: GraphQLError[];\n}\n\n/**\n * GraphQL error structure\n */\nexport interface GraphQLError {\n message: string;\n locations?: Array<{ line: number; column: number }>;\n path?: Array<string | number>;\n extensions?: Record<string, unknown>;\n}\n\n/**\n * Gateway client interface\n */\nexport interface IGatewayClient {\n /**\n * Execute internal (same layer) GraphQL query/mutation\n *\n * Uses internal gateway with bypass headers for M2M communication.\n *\n * @param options - Request options\n * @returns GraphQL response\n */\n internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n\n /**\n * Execute cross-layer GraphQL query/mutation\n *\n * Uses public gateway for cross-layer communication.\n *\n * @param options - Request options\n * @returns GraphQL response\n */\n crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n\n /**\n * Execute GraphQL query/mutation with explicit gateway URL\n *\n * @param gatewayUrl - Gateway URL to use\n * @param options - Request options\n * @returns GraphQL response\n */\n query<T = unknown>(gatewayUrl: string, options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n\n /**\n * Get internal gateway circuit breaker\n */\n getInternalCircuitBreaker(): ICircuitBreaker;\n\n /**\n * Get cross-layer gateway circuit breaker\n */\n getCrossLayerCircuitBreaker(): ICircuitBreaker;\n\n /**\n * Get client health status\n */\n getHealthStatus(): GatewayClientHealth;\n\n /**\n * Update default headers\n */\n updateDefaultHeaders(headers: Partial<GatewayRequestHeaders>): void;\n}\n\n/**\n * Gateway client health status\n */\nexport interface GatewayClientHealth {\n /**\n * Internal gateway status\n */\n internal: {\n url: string;\n circuitState: CircuitState;\n stats: CircuitBreakerStats;\n };\n\n /**\n * Cross-layer gateway status\n */\n crossLayer: {\n url: string;\n circuitState: CircuitState;\n stats: CircuitBreakerStats;\n };\n}\n\n/**\n * Gateway error types\n */\nexport enum GatewayErrorType {\n NETWORK_ERROR = 'NETWORK_ERROR',\n TIMEOUT_ERROR = 'TIMEOUT_ERROR',\n CIRCUIT_OPEN = 'CIRCUIT_OPEN',\n GRAPHQL_ERROR = 'GRAPHQL_ERROR',\n UNKNOWN_ERROR = 'UNKNOWN_ERROR',\n}\n\n/**\n * Gateway error class\n */\nexport class GatewayError extends Error {\n type: GatewayErrorType;\n gatewayUrl: string;\n statusCode?: number;\n graphqlErrors?: GraphQLError[];\n override cause?: Error;\n\n constructor(\n message: string,\n type: GatewayErrorType,\n gatewayUrl: string,\n options?: {\n statusCode?: number;\n graphqlErrors?: GraphQLError[];\n cause?: Error;\n }\n ) {\n super(message);\n this.name = 'GatewayError';\n this.type = type;\n this.gatewayUrl = gatewayUrl;\n this.statusCode = options?.statusCode;\n this.graphqlErrors = options?.graphqlErrors;\n this.cause = options?.cause;\n Object.setPrototypeOf(this, GatewayError.prototype);\n }\n}\n\n/**\n * Request context for logging and tracing\n */\nexport interface RequestContext {\n /**\n * Request ID for tracing\n */\n requestId: string;\n\n /**\n * Actor ID making the request\n */\n actorId?: string;\n\n /**\n * Workspace ID context\n */\n workspaceId?: string;\n\n /**\n * Timestamp when request started\n */\n startTime: number;\n\n /**\n * Call type\n */\n callType: 'internal' | 'cross-layer' | 'direct';\n}\n","/**\n * Unified Gateway Client\n *\n * Provides a layer-aware GraphQL client with circuit breaker,\n * retry logic, and automatic header management for M2M communication.\n *\n * @module gateway/client\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient } from '@burdenoff/be-sdk/gateway';\n *\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer)\n * const result = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call\n * const authResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\nimport { LayerManager } from '../layer/index.js';\nimport { logger } from '../logger/index.js';\nimport { signServiceJwt } from './service-jwt.js';\nimport {\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n type CircuitBreakerConfig,\n type GatewayRequestHeaders,\n type GatewayRetryConfig,\n type ServiceLayer,\n} from '../types/layer.js';\nimport {\n CircuitState,\n GatewayError,\n GatewayErrorType,\n type CircuitBreakerStats,\n type GatewayClientConfig,\n type GatewayClientHealth,\n type GraphQLError,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type ICircuitBreaker,\n type IGatewayClient,\n type RequestContext,\n} from './types.js';\n\nconst uuidv4 = (): string => crypto.randomUUID();\n\n/**\n * Case-insensitive presence check for the `Authorization` header. HTTP header\n * names are case-insensitive (RFC 7230), and while the outbound `fetch` will\n * preserve whatever casing the caller supplies, callers may legitimately set\n * `authorization` / `Authorization` / even `AUTHORIZATION` via defaultHeaders\n * or options.headers. We must not overwrite an already-supplied token.\n */\nfunction hasAuthorizationHeader(headers: Record<string, string>): boolean {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === 'authorization') return true;\n }\n return false;\n}\n\nexport function resolveBypassPermissionValue(\n token: string | undefined = process.env['INTERNAL_SERVICE_TOKEN']\n): string {\n const normalizedToken = token?.trim();\n\n if (!normalizedToken) {\n throw new Error('INTERNAL_SERVICE_TOKEN must be configured for bypass-enabled gateway calls');\n }\n\n return normalizedToken;\n}\n\n/**\n * Circuit Breaker Implementation\n */\nclass CircuitBreaker implements ICircuitBreaker {\n private state: CircuitState = CircuitState.CLOSED;\n private failures = 0;\n private successes = 0;\n private consecutiveFailures = 0;\n private lastFailureTime: number | null = null;\n private lastSuccessTime: number | null = null;\n private openedAt: number | null = null;\n private failureTimestamps: number[] = [];\n private config: CircuitBreakerConfig;\n\n constructor(config: CircuitBreakerConfig) {\n this.config = config;\n }\n\n getState(): CircuitState {\n this.checkStateTransition();\n return this.state;\n }\n\n recordSuccess(): void {\n this.successes++;\n this.consecutiveFailures = 0;\n this.lastSuccessTime = Date.now();\n\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit closed after successful test');\n }\n }\n\n recordFailure(): void {\n this.failures++;\n this.consecutiveFailures++;\n this.lastFailureTime = Date.now();\n this.failureTimestamps.push(Date.now());\n\n // Clean up old timestamps\n const windowStart = Date.now() - this.config.failureWindow;\n this.failureTimestamps = this.failureTimestamps.filter((t) => t > windowStart);\n\n // Check if we should open the circuit\n if (this.state === CircuitState.CLOSED && this.failureTimestamps.length >= this.config.failureThreshold) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit opened due to failures', {\n failures: this.failureTimestamps.length,\n threshold: this.config.failureThreshold,\n });\n }\n\n // If we're half-open and fail, go back to open\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit re-opened after failed test');\n }\n }\n\n allowRequest(): boolean {\n this.checkStateTransition();\n\n switch (this.state) {\n case CircuitState.CLOSED:\n return true;\n case CircuitState.OPEN:\n return false;\n case CircuitState.HALF_OPEN:\n // Allow one test request\n return true;\n default:\n return true;\n }\n }\n\n forceOpen(): void {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.info('[CircuitBreaker] Circuit force-opened');\n }\n\n forceClose(): void {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.consecutiveFailures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit force-closed');\n }\n\n getStats(): CircuitBreakerStats {\n return {\n state: this.state,\n failures: this.failures,\n successes: this.successes,\n consecutiveFailures: this.consecutiveFailures,\n lastFailureTime: this.lastFailureTime,\n lastSuccessTime: this.lastSuccessTime,\n openedAt: this.openedAt,\n };\n }\n\n private checkStateTransition(): void {\n if (this.state === CircuitState.OPEN && this.openedAt) {\n const elapsed = Date.now() - this.openedAt;\n if (elapsed >= this.config.resetTimeout) {\n this.state = CircuitState.HALF_OPEN;\n logger.info('[CircuitBreaker] Circuit transitioning to half-open');\n }\n }\n }\n}\n\n/**\n * Unified Gateway Client\n */\nexport class GatewayClient implements IGatewayClient {\n private config: GatewayClientConfig;\n private layerManager: LayerManager;\n private internalCircuitBreaker: CircuitBreaker;\n private crossLayerCircuitBreaker: CircuitBreaker;\n private retryConfig: GatewayRetryConfig;\n private defaultHeaders: GatewayRequestHeaders;\n\n constructor(config: GatewayClientConfig) {\n this.config = {\n timeout: 30000,\n enableLogging: true,\n ...config,\n };\n\n // Initialize layer manager\n this.layerManager = new LayerManager({\n layer: config.layer,\n serviceName: config.serviceName,\n serviceIdentity: config.serviceIdentity,\n });\n\n // Override URLs if provided\n if (config.internalGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n if (config.crossLayerGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n\n // Initialize circuit breakers\n const cbConfig: CircuitBreakerConfig = {\n ...DEFAULT_CIRCUIT_BREAKER_CONFIG,\n ...config.circuitBreaker,\n };\n this.internalCircuitBreaker = new CircuitBreaker(cbConfig);\n this.crossLayerCircuitBreaker = new CircuitBreaker(cbConfig);\n\n // Initialize retry config\n this.retryConfig = {\n ...DEFAULT_GATEWAY_RETRY_CONFIG,\n ...config.retry,\n };\n\n // Initialize default headers\n this.defaultHeaders = {\n 'x-service-identity': this.layerManager.getServiceIdentity(),\n 'x-actor-type': 'service',\n ...config.defaultHeaders,\n };\n\n logger.debug('[GatewayClient] Initialized', {\n layer: config.layer,\n serviceName: config.serviceName,\n internalUrl: this.getInternalUrl(),\n crossLayerUrl: this.getCrossLayerUrl(),\n });\n }\n\n private getInternalUrl(): string {\n return this.config.internalGatewayUrl || this.layerManager.getInternalGatewayUrl();\n }\n\n private getCrossLayerUrl(): string {\n return this.config.crossLayerGatewayUrl || this.layerManager.getCrossLayerGatewayUrl();\n }\n\n /**\n * Execute internal (same layer) GraphQL query/mutation\n */\n async internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('internal', options);\n\n return this.executeWithRetry(this.getInternalUrl(), options, this.internalCircuitBreaker, context, {\n bypassPermission: true,\n });\n }\n\n /**\n * Execute cross-layer GraphQL query/mutation\n */\n async crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('cross-layer', options);\n\n return this.executeWithRetry(\n this.getCrossLayerUrl(),\n options,\n this.crossLayerCircuitBreaker,\n context,\n { bypassPermission: false } // Cross-layer calls go through public gateway\n );\n }\n\n /**\n * Execute GraphQL query/mutation with explicit gateway URL\n */\n async query<T = unknown>(gatewayUrl: string, options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('direct', options);\n\n // Use internal circuit breaker for direct calls\n return this.executeWithRetry(gatewayUrl, options, this.internalCircuitBreaker, context, {\n bypassPermission: false,\n });\n }\n\n getInternalCircuitBreaker(): ICircuitBreaker {\n return this.internalCircuitBreaker;\n }\n\n getCrossLayerCircuitBreaker(): ICircuitBreaker {\n return this.crossLayerCircuitBreaker;\n }\n\n getHealthStatus(): GatewayClientHealth {\n return {\n internal: {\n url: this.getInternalUrl(),\n circuitState: this.internalCircuitBreaker.getState(),\n stats: this.internalCircuitBreaker.getStats(),\n },\n crossLayer: {\n url: this.getCrossLayerUrl(),\n circuitState: this.crossLayerCircuitBreaker.getState(),\n stats: this.crossLayerCircuitBreaker.getStats(),\n },\n };\n }\n\n updateDefaultHeaders(headers: Partial<GatewayRequestHeaders>): void {\n this.defaultHeaders = { ...this.defaultHeaders, ...headers };\n }\n\n private createRequestContext(\n callType: 'internal' | 'cross-layer' | 'direct',\n options: GraphQLRequestOptions\n ): RequestContext {\n return {\n requestId: uuidv4(),\n actorId: options.headers?.['x-actor-id'] || this.defaultHeaders['x-actor-id'],\n workspaceId: options.headers?.['x-workspace-id'] || this.defaultHeaders['x-workspace-id'],\n startTime: Date.now(),\n callType,\n };\n }\n\n /**\n * Check if an error should be retried\n */\n private shouldRetryError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) {\n return true;\n }\n // Don't retry GraphQL errors or circuit open errors\n return error.type !== GatewayErrorType.GRAPHQL_ERROR && error.type !== GatewayErrorType.CIRCUIT_OPEN;\n }\n\n /**\n * Calculate retry delay with exponential backoff\n */\n private calculateRetryDelay(attempt: number): number {\n return Math.min(\n this.retryConfig.initialDelay * Math.pow(this.retryConfig.backoffMultiplier, attempt - 1),\n this.retryConfig.maxDelay\n );\n }\n\n /**\n * Log retry attempt if logging is enabled\n */\n private logRetryAttempt(\n context: RequestContext,\n attempt: number,\n maxAttempts: number,\n delay: number,\n error: Error\n ): void {\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] Request failed, retrying', {\n requestId: context.requestId,\n attempt,\n maxAttempts,\n delay,\n error: error.message,\n });\n }\n }\n\n private async executeWithRetry<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n circuitBreaker: CircuitBreaker,\n context: RequestContext,\n settings: { bypassPermission: boolean }\n ): Promise<GraphQLResponse<T>> {\n // Check circuit breaker\n if (!options.skipCircuitBreaker && !circuitBreaker.allowRequest()) {\n throw new GatewayError(`Circuit breaker is open for ${gatewayUrl}`, GatewayErrorType.CIRCUIT_OPEN, gatewayUrl);\n }\n\n const maxAttempts = options.skipRetry ? 1 : this.retryConfig.maxAttempts;\n let lastError: Error | null = null;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const result = await this.executeRequest<T>(gatewayUrl, options, context, settings.bypassPermission);\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordSuccess();\n }\n return result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordFailure();\n }\n\n if (!this.shouldRetryError(error)) {\n throw error;\n }\n\n if (attempt < maxAttempts) {\n const delay = this.calculateRetryDelay(attempt);\n this.logRetryAttempt(context, attempt, maxAttempts, delay, lastError);\n await this.sleep(delay);\n }\n }\n }\n\n throw lastError || new GatewayError('Request failed after retries', GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n /**\n * Build headers for a request\n */\n private buildRequestHeaders(\n context: RequestContext,\n options: GraphQLRequestOptions,\n bypassPermission: boolean\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-request-id': context.requestId,\n 'x-call-type': context.callType,\n };\n\n // Add default headers\n for (const [key, value] of Object.entries(this.defaultHeaders)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n\n // Add request-specific headers\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n }\n\n // Add bypass headers for internal calls\n if (bypassPermission) {\n headers['x-bypass-permission'] = resolveBypassPermissionValue();\n headers['x-bypass-source'] = this.layerManager.getServiceIdentity();\n headers['x-bypass-timestamp'] = Date.now().toString();\n }\n\n return headers;\n }\n\n /**\n * Handle GraphQL errors in response\n */\n private handleGraphQLErrors<T>(\n result: GraphQLResponse<T>,\n context: RequestContext,\n gatewayUrl: string,\n duration: number\n ): void {\n if (!result.errors || result.errors.length === 0) {\n return;\n }\n\n const errorMessages = result.errors.map((e: GraphQLError) => e.message).join(', ');\n\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] GraphQL errors', {\n requestId: context.requestId,\n errors: result.errors,\n duration,\n });\n }\n\n throw new GatewayError(`GraphQL error: ${errorMessages}`, GatewayErrorType.GRAPHQL_ERROR, gatewayUrl, {\n graphqlErrors: result.errors,\n });\n }\n\n /**\n * Handle fetch errors\n */\n private handleFetchError(\n error: unknown,\n context: RequestContext,\n gatewayUrl: string,\n timeout: number,\n duration: number\n ): never {\n if (error instanceof GatewayError) {\n throw error;\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new GatewayError(`Request timed out after ${timeout}ms`, GatewayErrorType.TIMEOUT_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n if (this.config.enableLogging) {\n logger.error('[GatewayClient] Request failed', {\n requestId: context.requestId,\n error: error.message,\n duration,\n });\n }\n\n throw new GatewayError(error.message, GatewayErrorType.NETWORK_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n throw new GatewayError(String(error), GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n private async executeRequest<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n context: RequestContext,\n bypassPermission: boolean\n ): Promise<GraphQLResponse<T>> {\n const timeout = options.timeout || this.config.timeout || 30000;\n const headers = this.buildRequestHeaders(context, options, bypassPermission);\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which\n // requires JWT auth to propagate actor context. Mint a short-lived\n // service-actor JWT so the gateway admits the call and preserves\n // `x-actor-type: service` downstream. Skipped when the caller has\n // already supplied an Authorization header (e.g., user-originated\n // cross-layer flows) or when SERVICE_JWT_SECRET is unset.\n if (context.callType === 'cross-layer' && !hasAuthorizationHeader(headers)) {\n const serviceActorId = this.layerManager.getServiceIdentity();\n const serviceJwt = await signServiceJwt(serviceActorId);\n if (serviceJwt) {\n headers['Authorization'] = `Bearer ${serviceJwt}`;\n } else if (this.config.enableLogging) {\n // Subtle failure mode: without the JWT the public gateway strips\n // actor headers and the subgraph rejects with `authenticationRequired`.\n // Surface the root cause so operators rolling out a new caller don't\n // spend time debugging the downstream error.\n logger.debug(\n '[GatewayClient] SERVICE_JWT_SECRET not configured — cross-layer call will proceed without service JWT',\n { requestId: context.requestId, gatewayUrl }\n );\n }\n }\n\n const body = JSON.stringify({\n query: options.query,\n variables: options.variables || {},\n operationName: options.operationName,\n });\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Executing request', {\n requestId: context.requestId,\n gatewayUrl,\n operationName: options.operationName,\n callType: context.callType,\n bypassPermission,\n });\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n const duration = Date.now() - context.startTime;\n\n if (!response.ok) {\n throw new GatewayError(\n `HTTP ${response.status}: ${response.statusText}`,\n GatewayErrorType.NETWORK_ERROR,\n gatewayUrl,\n { statusCode: response.status }\n );\n }\n\n const result = (await response.json()) as GraphQLResponse<T>;\n this.handleGraphQLErrors(result, context, gatewayUrl, duration);\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Request completed', {\n requestId: context.requestId,\n duration,\n hasData: !!result.data,\n });\n }\n\n return result;\n } catch (error) {\n const duration = Date.now() - context.startTime;\n this.handleFetchError(error, context, gatewayUrl, timeout, duration);\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Create a gateway client for a specific layer\n */\nexport function createGatewayClient(config: GatewayClientConfig): GatewayClient {\n return new GatewayClient(config);\n}\n\n/**\n * Create a gateway client from environment variables\n *\n * Required environment variables:\n * - SERVICE_LAYER: 'wspace' | 'global'\n * - SERVICE_NAME: Service name\n *\n * Optional:\n * - SERVICE_IDENTITY: Service identity (defaults to SERVICE_NAME)\n * - {LAYER}_INT_GATEWAY_URL: Internal gateway URL\n * - {OPPOSITE_LAYER}_PUBLIC_GATEWAY_URL: Cross-layer gateway URL\n */\nexport function createGatewayClientFromEnv(): GatewayClient {\n const layer = process.env['SERVICE_LAYER'] as ServiceLayer;\n\n if (!layer || (layer !== 'wspace' && layer !== 'global')) {\n throw new Error(`[GatewayClient] Invalid or missing SERVICE_LAYER. Expected 'wspace' or 'global', got '${layer}'`);\n }\n\n const serviceName = process.env['SERVICE_NAME'];\n if (!serviceName) {\n throw new Error('[GatewayClient] SERVICE_NAME environment variable is required');\n }\n\n const serviceIdentity = process.env['SERVICE_IDENTITY'] || serviceName;\n\n return new GatewayClient({\n layer,\n serviceName,\n serviceIdentity,\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/gateway/index.ts","../src/gateway/service-jwt.ts","../src/gateway/types.ts","../src/gateway/client.ts"],"names":["SIGNING_ENV_VAR","KEY_ID","DEFAULT_TTL_SECONDS","REFRESH_BEFORE_EXP_MS","joseModule","getJose","cache","Map","cacheKey","actorId","ttlSeconds","signServiceJwt","secret","process","env","key","cached","get","expiresAtMs","Date","now","token","joseLib","encoder","TextEncoder","keyBytes","encode","nowSec","Math","floor","expSec","SignJWT","actor_type","setProtectedHeader","alg","typ","kid","setSubject","setIssuer","setIssuedAt","setExpirationTime","sign","set","CircuitState","GatewayErrorType","GatewayError","Error","type","gatewayUrl","statusCode","graphqlErrors","cause","message","options","name","Object","setPrototypeOf","prototype","uuidv4","crypto","randomUUID","hasAuthorizationHeader","headers","keys","toLowerCase","resolveBypassPermissionValue","normalizedToken","trim","CircuitBreaker","state","CLOSED","failures","successes","consecutiveFailures","lastFailureTime","lastSuccessTime","openedAt","failureTimestamps","config","getState","checkStateTransition","recordSuccess","HALF_OPEN","logger","info","recordFailure","push","windowStart","failureWindow","filter","t","length","failureThreshold","OPEN","warn","threshold","allowRequest","forceOpen","forceClose","getStats","elapsed","resetTimeout","GatewayClient","layerManager","internalCircuitBreaker","crossLayerCircuitBreaker","retryConfig","defaultHeaders","timeout","enableLogging","LayerManager","layer","serviceName","serviceIdentity","internalGatewayUrl","crossLayerGatewayUrl","cbConfig","DEFAULT_CIRCUIT_BREAKER_CONFIG","circuitBreaker","DEFAULT_GATEWAY_RETRY_CONFIG","retry","getServiceIdentity","debug","internalUrl","getInternalUrl","crossLayerUrl","getCrossLayerUrl","getInternalGatewayUrl","getCrossLayerGatewayUrl","internalQuery","context","createRequestContext","executeWithRetry","bypassPermission","crossLayerQuery","query","getInternalCircuitBreaker","getCrossLayerCircuitBreaker","getHealthStatus","internal","url","circuitState","stats","crossLayer","updateDefaultHeaders","callType","requestId","workspaceId","startTime","shouldRetryError","error","GRAPHQL_ERROR","CIRCUIT_OPEN","calculateRetryDelay","attempt","min","initialDelay","pow","backoffMultiplier","maxDelay","logRetryAttempt","maxAttempts","delay","settings","skipCircuitBreaker","skipRetry","lastError","result","executeRequest","String","sleep","UNKNOWN_ERROR","buildRequestHeaders","value","entries","undefined","toString","handleGraphQLErrors","duration","errors","errorMessages","map","e","join","handleFetchError","TIMEOUT_ERROR","NETWORK_ERROR","serviceActorId","serviceJwt","body","JSON","stringify","variables","operationName","controller","AbortController","timeoutId","setTimeout","abort","response","fetch","method","signal","clearTimeout","ok","status","statusText","json","hasData","data","ms","Promise","resolve","createGatewayClient","createGatewayClientFromEnv"],"mappings":";;;;;;;AAAA,IAAA,eAAA,GAAA;;;;;;;;;;;;AC6BA,IAAMA,eAAAA,GAAkB,oBAAA;AACxB,IAAMC,MAAAA,GAAS,YAAA;AACf,IAAMC,mBAAAA,GAAsB,EAAA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AA;GACF,CAAA;AACF;AAnBgBqG,MAAAA,CAAAA,0BAAAA,EAAAA,4BAAAA,CAAAA","file":"chunk-3F4SLVRL.js","sourcesContent":["/**\n * Gateway Module\n *\n * Provides unified gateway client for layer-aware M2M communication\n * with circuit breaker and retry logic.\n *\n * @module gateway\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient, createGatewayClientFromEnv } from '@burdenoff/be-sdk/gateway';\n *\n * // Create from environment variables\n * const client = createGatewayClientFromEnv();\n *\n * // Or create manually\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer, uses int-gateway with bypass)\n * const internalResult = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call (via public gateway)\n * const crossLayerResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\n// Client exports\nexport { GatewayClient, createGatewayClient, createGatewayClientFromEnv } from './client.js';\n\n// Type exports\nexport {\n CircuitState,\n GatewayErrorType,\n GatewayError,\n type GatewayClientConfig,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type GraphQLError,\n type IGatewayClient,\n type ICircuitBreaker,\n type CircuitBreakerStats,\n type GatewayClientHealth,\n type RequestContext,\n} from './types.js';\n\n// Gateway-side security plugin stack (for public gateways).\n// Imported by consumers as `@burdenoff/be-sdk/gateway/security` — this\n// re-export lets `@burdenoff/be-sdk/gateway` also resolve the namespace.\nexport * as Security from './security/index.js';\n","/**\n * Service JWT minting + caching for M2M cross-layer calls.\n *\n * The public gateways (global-public-gateway, wspace-public-gateway) validate\n * every incoming request's Authorization header and only propagate `x-actor-*`\n * context headers to subgraphs when the JWT is valid. Without a JWT, raw\n * actor headers are stripped as potential client spoofing. For service-to-\n * service cross-layer calls there is no user JWT to forward — we mint a short-\n * lived service JWT with `actor_type: 'service'` so the gateway admits the\n * call and the subgraph sees a trusted service context.\n *\n * Signing key: SERVICE_JWT_SECRET — a dedicated, separate secret from\n * GLOBAL_AUTH_SECRET (which signs user tokens). Keeping them distinct means a\n * service minter that leaks its env cannot forge user logins. The gateways\n * hold both secrets and pick between them by the JWT's `kid` header\n * (this minter stamps `kid: service-v1`).\n */\nimport type * as jose from 'jose';\n\n/**\n * Dedicated secret for service-minted JWTs.\n *\n * Deliberately separate from `GLOBAL_AUTH_SECRET` (which signs user tokens)\n * so that services that mint service JWTs do not also hold the ability to\n * forge user logins. Blast radius of a leaked secret stays scoped to 60s\n * service tokens with no PII.\n *\n * Gateways hold both secrets and select by the JWT's `kid` header.\n */\nconst SIGNING_ENV_VAR = 'SERVICE_JWT_SECRET';\nconst KEY_ID = 'service-v1';\nconst DEFAULT_TTL_SECONDS = 60;\nconst REFRESH_BEFORE_EXP_MS = 10_000;\n\nlet joseModule: typeof jose | null = null;\n\nasync function getJose(): Promise<typeof jose> {\n if (!joseModule) {\n joseModule = await import('jose');\n }\n return joseModule;\n}\n\ninterface CachedToken {\n token: string;\n expiresAtMs: number;\n}\n\nconst cache = new Map<string, CachedToken>();\n\nfunction cacheKey(actorId: string, ttlSeconds: number): string {\n return `${actorId}:${ttlSeconds}`;\n}\n\n/**\n * Sign a service-actor JWT.\n * Returns null when no signing secret is configured (opt-in).\n */\nexport async function signServiceJwt(\n actorId: string,\n ttlSeconds: number = DEFAULT_TTL_SECONDS\n): Promise<string | null> {\n const secret = process.env[SIGNING_ENV_VAR];\n if (!secret) {\n return null;\n }\n\n const key = cacheKey(actorId, ttlSeconds);\n const cached = cache.get(key);\n if (cached && cached.expiresAtMs - REFRESH_BEFORE_EXP_MS > Date.now()) {\n return cached.token;\n }\n\n const joseLib = await getJose();\n const encoder = new TextEncoder();\n const keyBytes = encoder.encode(secret);\n\n const nowSec = Math.floor(Date.now() / 1000);\n const expSec = nowSec + ttlSeconds;\n\n const token = await new joseLib.SignJWT({\n actor_type: 'service',\n })\n .setProtectedHeader({ alg: 'HS256', typ: 'JWT', kid: KEY_ID })\n .setSubject(actorId)\n // `iss` = the service identity that minted the token. Matches `sub`\n // because these are self-minted tokens (caller is asserting itself).\n // Gives the gateway room to enforce a minter allowlist later without\n // a token-format change.\n .setIssuer(actorId)\n .setIssuedAt(nowSec)\n .setExpirationTime(expSec)\n .sign(keyBytes);\n\n cache.set(key, { token, expiresAtMs: expSec * 1000 });\n return token;\n}\n\n/** Test hook to clear the cache between tests. */\nexport function __clearServiceJwtCache(): void {\n cache.clear();\n}\n","/**\n * Gateway Client Types\n *\n * Type definitions for the unified gateway client with\n * circuit breaker and retry logic.\n *\n * @module gateway/types\n * @category Gateway\n */\n\nimport type { ServiceLayer, CircuitBreakerConfig, GatewayRetryConfig, GatewayRequestHeaders } from '../types/layer.js';\n\n/**\n * Gateway client configuration\n */\nexport interface GatewayClientConfig {\n /**\n * Layer this client belongs to\n */\n layer: ServiceLayer;\n\n /**\n * Service name (for logging and headers)\n */\n serviceName: string;\n\n /**\n * Service identity for bypass headers\n * @default serviceName\n */\n serviceIdentity?: string;\n\n /**\n * Internal gateway URL (same layer M2M)\n * @default Resolved from layer defaults or environment\n */\n internalGatewayUrl?: string;\n\n /**\n * Cross-layer gateway URL (cross layer via public gateway)\n * @default Resolved from layer defaults or environment\n */\n crossLayerGatewayUrl?: string;\n\n /**\n * Request timeout in milliseconds\n * @default 30000 (30 seconds)\n */\n timeout?: number;\n\n /**\n * Circuit breaker configuration\n */\n circuitBreaker?: Partial<CircuitBreakerConfig>;\n\n /**\n * Retry configuration\n */\n retry?: Partial<GatewayRetryConfig>;\n\n /**\n * Enable request logging\n * @default true\n */\n enableLogging?: boolean;\n\n /**\n * Default headers to include in all requests\n */\n defaultHeaders?: GatewayRequestHeaders;\n}\n\n/**\n * Circuit breaker states\n */\nexport enum CircuitState {\n CLOSED = 'CLOSED',\n OPEN = 'OPEN',\n HALF_OPEN = 'HALF_OPEN',\n}\n\n/**\n * Circuit breaker instance interface\n */\nexport interface ICircuitBreaker {\n /**\n * Get current circuit state\n */\n getState(): CircuitState;\n\n /**\n * Record a successful call\n */\n recordSuccess(): void;\n\n /**\n * Record a failed call\n */\n recordFailure(): void;\n\n /**\n * Check if circuit allows calls\n */\n allowRequest(): boolean;\n\n /**\n * Force open the circuit\n */\n forceOpen(): void;\n\n /**\n * Force close the circuit\n */\n forceClose(): void;\n\n /**\n * Get circuit statistics\n */\n getStats(): CircuitBreakerStats;\n}\n\n/**\n * Circuit breaker statistics\n */\nexport interface CircuitBreakerStats {\n state: CircuitState;\n failures: number;\n successes: number;\n consecutiveFailures: number;\n lastFailureTime: number | null;\n lastSuccessTime: number | null;\n openedAt: number | null;\n}\n\n/**\n * GraphQL request options\n */\nexport interface GraphQLRequestOptions {\n /**\n * GraphQL query or mutation string\n */\n query: string;\n\n /**\n * GraphQL variables\n */\n variables?: Record<string, unknown>;\n\n /**\n * Operation name (for multi-operation documents)\n */\n operationName?: string;\n\n /**\n * Additional headers for this request\n */\n headers?: GatewayRequestHeaders;\n\n /**\n * Override timeout for this request\n */\n timeout?: number;\n\n /**\n * Skip circuit breaker for this request\n * @default false\n */\n skipCircuitBreaker?: boolean;\n\n /**\n * Skip retry logic for this request\n * @default false\n */\n skipRetry?: boolean;\n}\n\n/**\n * GraphQL response\n */\nexport interface GraphQLResponse<T = unknown> {\n /**\n * Response data\n */\n data?: T;\n\n /**\n * GraphQL errors\n */\n errors?: GraphQLError[];\n}\n\n/**\n * GraphQL error structure\n */\nexport interface GraphQLError {\n message: string;\n locations?: Array<{ line: number; column: number }>;\n path?: Array<string | number>;\n extensions?: Record<string, unknown>;\n}\n\n/**\n * Gateway client interface\n */\nexport interface IGatewayClient {\n /**\n * Execute internal (same layer) GraphQL query/mutation\n *\n * Uses internal gateway with bypass headers for M2M communication.\n *\n * @param options - Request options\n * @returns GraphQL response\n */\n internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n\n /**\n * Execute cross-layer GraphQL query/mutation\n *\n * Uses public gateway for cross-layer communication.\n *\n * @param options - Request options\n * @returns GraphQL response\n */\n crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n\n /**\n * Execute GraphQL query/mutation with explicit gateway URL\n *\n * @param gatewayUrl - Gateway URL to use\n * @param options - Request options\n * @returns GraphQL response\n */\n query<T = unknown>(gatewayUrl: string, options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n\n /**\n * Get internal gateway circuit breaker\n */\n getInternalCircuitBreaker(): ICircuitBreaker;\n\n /**\n * Get cross-layer gateway circuit breaker\n */\n getCrossLayerCircuitBreaker(): ICircuitBreaker;\n\n /**\n * Get client health status\n */\n getHealthStatus(): GatewayClientHealth;\n\n /**\n * Update default headers\n */\n updateDefaultHeaders(headers: Partial<GatewayRequestHeaders>): void;\n}\n\n/**\n * Gateway client health status\n */\nexport interface GatewayClientHealth {\n /**\n * Internal gateway status\n */\n internal: {\n url: string;\n circuitState: CircuitState;\n stats: CircuitBreakerStats;\n };\n\n /**\n * Cross-layer gateway status\n */\n crossLayer: {\n url: string;\n circuitState: CircuitState;\n stats: CircuitBreakerStats;\n };\n}\n\n/**\n * Gateway error types\n */\nexport enum GatewayErrorType {\n NETWORK_ERROR = 'NETWORK_ERROR',\n TIMEOUT_ERROR = 'TIMEOUT_ERROR',\n CIRCUIT_OPEN = 'CIRCUIT_OPEN',\n GRAPHQL_ERROR = 'GRAPHQL_ERROR',\n UNKNOWN_ERROR = 'UNKNOWN_ERROR',\n}\n\n/**\n * Gateway error class\n */\nexport class GatewayError extends Error {\n type: GatewayErrorType;\n gatewayUrl: string;\n statusCode?: number;\n graphqlErrors?: GraphQLError[];\n override cause?: Error;\n\n constructor(\n message: string,\n type: GatewayErrorType,\n gatewayUrl: string,\n options?: {\n statusCode?: number;\n graphqlErrors?: GraphQLError[];\n cause?: Error;\n }\n ) {\n super(message);\n this.name = 'GatewayError';\n this.type = type;\n this.gatewayUrl = gatewayUrl;\n this.statusCode = options?.statusCode;\n this.graphqlErrors = options?.graphqlErrors;\n this.cause = options?.cause;\n Object.setPrototypeOf(this, GatewayError.prototype);\n }\n}\n\n/**\n * Request context for logging and tracing\n */\nexport interface RequestContext {\n /**\n * Request ID for tracing\n */\n requestId: string;\n\n /**\n * Actor ID making the request\n */\n actorId?: string;\n\n /**\n * Workspace ID context\n */\n workspaceId?: string;\n\n /**\n * Timestamp when request started\n */\n startTime: number;\n\n /**\n * Call type\n */\n callType: 'internal' | 'cross-layer' | 'direct';\n}\n","/**\n * Unified Gateway Client\n *\n * Provides a layer-aware GraphQL client with circuit breaker,\n * retry logic, and automatic header management for M2M communication.\n *\n * @module gateway/client\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient } from '@burdenoff/be-sdk/gateway';\n *\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer)\n * const result = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call\n * const authResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\nimport { LayerManager } from '../layer/index.js';\nimport { logger } from '../logger/index.js';\nimport { signServiceJwt } from './service-jwt.js';\nimport {\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n type CircuitBreakerConfig,\n type GatewayRequestHeaders,\n type GatewayRetryConfig,\n type ServiceLayer,\n} from '../types/layer.js';\nimport {\n CircuitState,\n GatewayError,\n GatewayErrorType,\n type CircuitBreakerStats,\n type GatewayClientConfig,\n type GatewayClientHealth,\n type GraphQLError,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type ICircuitBreaker,\n type IGatewayClient,\n type RequestContext,\n} from './types.js';\n\nconst uuidv4 = (): string => crypto.randomUUID();\n\n/**\n * Case-insensitive presence check for the `Authorization` header. HTTP header\n * names are case-insensitive (RFC 7230), and while the outbound `fetch` will\n * preserve whatever casing the caller supplies, callers may legitimately set\n * `authorization` / `Authorization` / even `AUTHORIZATION` via defaultHeaders\n * or options.headers. We must not overwrite an already-supplied token.\n */\nfunction hasAuthorizationHeader(headers: Record<string, string>): boolean {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === 'authorization') return true;\n }\n return false;\n}\n\nexport function resolveBypassPermissionValue(\n token: string | undefined = process.env['INTERNAL_SERVICE_TOKEN']\n): string {\n const normalizedToken = token?.trim();\n\n if (!normalizedToken) {\n throw new Error('INTERNAL_SERVICE_TOKEN must be configured for bypass-enabled gateway calls');\n }\n\n return normalizedToken;\n}\n\n/**\n * Circuit Breaker Implementation\n */\nclass CircuitBreaker implements ICircuitBreaker {\n private state: CircuitState = CircuitState.CLOSED;\n private failures = 0;\n private successes = 0;\n private consecutiveFailures = 0;\n private lastFailureTime: number | null = null;\n private lastSuccessTime: number | null = null;\n private openedAt: number | null = null;\n private failureTimestamps: number[] = [];\n private config: CircuitBreakerConfig;\n\n constructor(config: CircuitBreakerConfig) {\n this.config = config;\n }\n\n getState(): CircuitState {\n this.checkStateTransition();\n return this.state;\n }\n\n recordSuccess(): void {\n this.successes++;\n this.consecutiveFailures = 0;\n this.lastSuccessTime = Date.now();\n\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit closed after successful test');\n }\n }\n\n recordFailure(): void {\n this.failures++;\n this.consecutiveFailures++;\n this.lastFailureTime = Date.now();\n this.failureTimestamps.push(Date.now());\n\n // Clean up old timestamps\n const windowStart = Date.now() - this.config.failureWindow;\n this.failureTimestamps = this.failureTimestamps.filter((t) => t > windowStart);\n\n // Check if we should open the circuit\n if (this.state === CircuitState.CLOSED && this.failureTimestamps.length >= this.config.failureThreshold) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit opened due to failures', {\n failures: this.failureTimestamps.length,\n threshold: this.config.failureThreshold,\n });\n }\n\n // If we're half-open and fail, go back to open\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit re-opened after failed test');\n }\n }\n\n allowRequest(): boolean {\n this.checkStateTransition();\n\n switch (this.state) {\n case CircuitState.CLOSED:\n return true;\n case CircuitState.OPEN:\n return false;\n case CircuitState.HALF_OPEN:\n // Allow one test request\n return true;\n default:\n return true;\n }\n }\n\n forceOpen(): void {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.info('[CircuitBreaker] Circuit force-opened');\n }\n\n forceClose(): void {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.consecutiveFailures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit force-closed');\n }\n\n getStats(): CircuitBreakerStats {\n return {\n state: this.state,\n failures: this.failures,\n successes: this.successes,\n consecutiveFailures: this.consecutiveFailures,\n lastFailureTime: this.lastFailureTime,\n lastSuccessTime: this.lastSuccessTime,\n openedAt: this.openedAt,\n };\n }\n\n private checkStateTransition(): void {\n if (this.state === CircuitState.OPEN && this.openedAt) {\n const elapsed = Date.now() - this.openedAt;\n if (elapsed >= this.config.resetTimeout) {\n this.state = CircuitState.HALF_OPEN;\n logger.info('[CircuitBreaker] Circuit transitioning to half-open');\n }\n }\n }\n}\n\n/**\n * Unified Gateway Client\n */\nexport class GatewayClient implements IGatewayClient {\n private config: GatewayClientConfig;\n private layerManager: LayerManager;\n private internalCircuitBreaker: CircuitBreaker;\n private crossLayerCircuitBreaker: CircuitBreaker;\n private retryConfig: GatewayRetryConfig;\n private defaultHeaders: GatewayRequestHeaders;\n\n constructor(config: GatewayClientConfig) {\n this.config = {\n timeout: 30000,\n enableLogging: true,\n ...config,\n };\n\n // Initialize layer manager\n this.layerManager = new LayerManager({\n layer: config.layer,\n serviceName: config.serviceName,\n serviceIdentity: config.serviceIdentity,\n });\n\n // Override URLs if provided\n if (config.internalGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n if (config.crossLayerGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n\n // Initialize circuit breakers\n const cbConfig: CircuitBreakerConfig = {\n ...DEFAULT_CIRCUIT_BREAKER_CONFIG,\n ...config.circuitBreaker,\n };\n this.internalCircuitBreaker = new CircuitBreaker(cbConfig);\n this.crossLayerCircuitBreaker = new CircuitBreaker(cbConfig);\n\n // Initialize retry config\n this.retryConfig = {\n ...DEFAULT_GATEWAY_RETRY_CONFIG,\n ...config.retry,\n };\n\n // Initialize default headers\n this.defaultHeaders = {\n 'x-service-identity': this.layerManager.getServiceIdentity(),\n 'x-actor-type': 'service',\n ...config.defaultHeaders,\n };\n\n logger.debug('[GatewayClient] Initialized', {\n layer: config.layer,\n serviceName: config.serviceName,\n internalUrl: this.getInternalUrl(),\n crossLayerUrl: this.getCrossLayerUrl(),\n });\n }\n\n private getInternalUrl(): string {\n return this.config.internalGatewayUrl || this.layerManager.getInternalGatewayUrl();\n }\n\n private getCrossLayerUrl(): string {\n return this.config.crossLayerGatewayUrl || this.layerManager.getCrossLayerGatewayUrl();\n }\n\n /**\n * Execute internal (same layer) GraphQL query/mutation\n */\n async internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('internal', options);\n\n return this.executeWithRetry(this.getInternalUrl(), options, this.internalCircuitBreaker, context, {\n bypassPermission: true,\n });\n }\n\n /**\n * Execute cross-layer GraphQL query/mutation\n */\n async crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('cross-layer', options);\n\n return this.executeWithRetry(\n this.getCrossLayerUrl(),\n options,\n this.crossLayerCircuitBreaker,\n context,\n { bypassPermission: false } // Cross-layer calls go through public gateway\n );\n }\n\n /**\n * Execute GraphQL query/mutation with explicit gateway URL\n */\n async query<T = unknown>(gatewayUrl: string, options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('direct', options);\n\n // Use internal circuit breaker for direct calls\n return this.executeWithRetry(gatewayUrl, options, this.internalCircuitBreaker, context, {\n bypassPermission: false,\n });\n }\n\n getInternalCircuitBreaker(): ICircuitBreaker {\n return this.internalCircuitBreaker;\n }\n\n getCrossLayerCircuitBreaker(): ICircuitBreaker {\n return this.crossLayerCircuitBreaker;\n }\n\n getHealthStatus(): GatewayClientHealth {\n return {\n internal: {\n url: this.getInternalUrl(),\n circuitState: this.internalCircuitBreaker.getState(),\n stats: this.internalCircuitBreaker.getStats(),\n },\n crossLayer: {\n url: this.getCrossLayerUrl(),\n circuitState: this.crossLayerCircuitBreaker.getState(),\n stats: this.crossLayerCircuitBreaker.getStats(),\n },\n };\n }\n\n updateDefaultHeaders(headers: Partial<GatewayRequestHeaders>): void {\n this.defaultHeaders = { ...this.defaultHeaders, ...headers };\n }\n\n private createRequestContext(\n callType: 'internal' | 'cross-layer' | 'direct',\n options: GraphQLRequestOptions\n ): RequestContext {\n return {\n requestId: uuidv4(),\n actorId: options.headers?.['x-actor-id'] || this.defaultHeaders['x-actor-id'],\n workspaceId: options.headers?.['x-workspace-id'] || this.defaultHeaders['x-workspace-id'],\n startTime: Date.now(),\n callType,\n };\n }\n\n /**\n * Check if an error should be retried\n */\n private shouldRetryError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) {\n return true;\n }\n // Don't retry GraphQL errors or circuit open errors\n return error.type !== GatewayErrorType.GRAPHQL_ERROR && error.type !== GatewayErrorType.CIRCUIT_OPEN;\n }\n\n /**\n * Calculate retry delay with exponential backoff\n */\n private calculateRetryDelay(attempt: number): number {\n return Math.min(\n this.retryConfig.initialDelay * Math.pow(this.retryConfig.backoffMultiplier, attempt - 1),\n this.retryConfig.maxDelay\n );\n }\n\n /**\n * Log retry attempt if logging is enabled\n */\n private logRetryAttempt(\n context: RequestContext,\n attempt: number,\n maxAttempts: number,\n delay: number,\n error: Error\n ): void {\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] Request failed, retrying', {\n requestId: context.requestId,\n attempt,\n maxAttempts,\n delay,\n error: error.message,\n });\n }\n }\n\n private async executeWithRetry<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n circuitBreaker: CircuitBreaker,\n context: RequestContext,\n settings: { bypassPermission: boolean }\n ): Promise<GraphQLResponse<T>> {\n // Check circuit breaker\n if (!options.skipCircuitBreaker && !circuitBreaker.allowRequest()) {\n throw new GatewayError(`Circuit breaker is open for ${gatewayUrl}`, GatewayErrorType.CIRCUIT_OPEN, gatewayUrl);\n }\n\n const maxAttempts = options.skipRetry ? 1 : this.retryConfig.maxAttempts;\n let lastError: Error | null = null;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const result = await this.executeRequest<T>(gatewayUrl, options, context, settings.bypassPermission);\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordSuccess();\n }\n return result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordFailure();\n }\n\n if (!this.shouldRetryError(error)) {\n throw error;\n }\n\n if (attempt < maxAttempts) {\n const delay = this.calculateRetryDelay(attempt);\n this.logRetryAttempt(context, attempt, maxAttempts, delay, lastError);\n await this.sleep(delay);\n }\n }\n }\n\n throw lastError || new GatewayError('Request failed after retries', GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n /**\n * Build headers for a request\n */\n private buildRequestHeaders(\n context: RequestContext,\n options: GraphQLRequestOptions,\n bypassPermission: boolean\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-request-id': context.requestId,\n 'x-call-type': context.callType,\n };\n\n // Add default headers\n for (const [key, value] of Object.entries(this.defaultHeaders)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n\n // Add request-specific headers\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n }\n\n // Add bypass headers for internal calls\n if (bypassPermission) {\n headers['x-bypass-permission'] = resolveBypassPermissionValue();\n headers['x-bypass-source'] = this.layerManager.getServiceIdentity();\n headers['x-bypass-timestamp'] = Date.now().toString();\n }\n\n return headers;\n }\n\n /**\n * Handle GraphQL errors in response\n */\n private handleGraphQLErrors<T>(\n result: GraphQLResponse<T>,\n context: RequestContext,\n gatewayUrl: string,\n duration: number\n ): void {\n if (!result.errors || result.errors.length === 0) {\n return;\n }\n\n const errorMessages = result.errors.map((e: GraphQLError) => e.message).join(', ');\n\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] GraphQL errors', {\n requestId: context.requestId,\n errors: result.errors,\n duration,\n });\n }\n\n throw new GatewayError(`GraphQL error: ${errorMessages}`, GatewayErrorType.GRAPHQL_ERROR, gatewayUrl, {\n graphqlErrors: result.errors,\n });\n }\n\n /**\n * Handle fetch errors\n */\n private handleFetchError(\n error: unknown,\n context: RequestContext,\n gatewayUrl: string,\n timeout: number,\n duration: number\n ): never {\n if (error instanceof GatewayError) {\n throw error;\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new GatewayError(`Request timed out after ${timeout}ms`, GatewayErrorType.TIMEOUT_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n if (this.config.enableLogging) {\n logger.error('[GatewayClient] Request failed', {\n requestId: context.requestId,\n error: error.message,\n duration,\n });\n }\n\n throw new GatewayError(error.message, GatewayErrorType.NETWORK_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n throw new GatewayError(String(error), GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n private async executeRequest<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n context: RequestContext,\n bypassPermission: boolean\n ): Promise<GraphQLResponse<T>> {\n const timeout = options.timeout || this.config.timeout || 30000;\n const headers = this.buildRequestHeaders(context, options, bypassPermission);\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which\n // requires JWT auth to propagate actor context. Mint a short-lived\n // service-actor JWT so the gateway admits the call and preserves\n // `x-actor-type: service` downstream. Skipped when the caller has\n // already supplied an Authorization header (e.g., user-originated\n // cross-layer flows) or when SERVICE_JWT_SECRET is unset.\n if (context.callType === 'cross-layer' && !hasAuthorizationHeader(headers)) {\n const serviceActorId = this.layerManager.getServiceIdentity();\n const serviceJwt = await signServiceJwt(serviceActorId);\n if (serviceJwt) {\n headers['Authorization'] = `Bearer ${serviceJwt}`;\n } else if (this.config.enableLogging) {\n // Subtle failure mode: without the JWT the public gateway strips\n // actor headers and the subgraph rejects with `authenticationRequired`.\n // Surface the root cause so operators rolling out a new caller don't\n // spend time debugging the downstream error.\n logger.debug(\n '[GatewayClient] SERVICE_JWT_SECRET not configured — cross-layer call will proceed without service JWT',\n { requestId: context.requestId, gatewayUrl }\n );\n }\n }\n\n const body = JSON.stringify({\n query: options.query,\n variables: options.variables || {},\n operationName: options.operationName,\n });\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Executing request', {\n requestId: context.requestId,\n gatewayUrl,\n operationName: options.operationName,\n callType: context.callType,\n bypassPermission,\n });\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n const duration = Date.now() - context.startTime;\n\n if (!response.ok) {\n throw new GatewayError(\n `HTTP ${response.status}: ${response.statusText}`,\n GatewayErrorType.NETWORK_ERROR,\n gatewayUrl,\n { statusCode: response.status }\n );\n }\n\n const result = (await response.json()) as GraphQLResponse<T>;\n this.handleGraphQLErrors(result, context, gatewayUrl, duration);\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Request completed', {\n requestId: context.requestId,\n duration,\n hasData: !!result.data,\n });\n }\n\n return result;\n } catch (error) {\n const duration = Date.now() - context.startTime;\n this.handleFetchError(error, context, gatewayUrl, timeout, duration);\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Create a gateway client for a specific layer\n */\nexport function createGatewayClient(config: GatewayClientConfig): GatewayClient {\n return new GatewayClient(config);\n}\n\n/**\n * Create a gateway client from environment variables\n *\n * Required environment variables:\n * - SERVICE_LAYER: 'wspace' | 'global'\n * - SERVICE_NAME: Service name\n *\n * Optional:\n * - SERVICE_IDENTITY: Service identity (defaults to SERVICE_NAME)\n * - {LAYER}_INT_GATEWAY_URL: Internal gateway URL\n * - {OPPOSITE_LAYER}_PUBLIC_GATEWAY_URL: Cross-layer gateway URL\n */\nexport function createGatewayClientFromEnv(): GatewayClient {\n const layer = process.env['SERVICE_LAYER'] as ServiceLayer;\n\n if (!layer || (layer !== 'wspace' && layer !== 'global')) {\n throw new Error(`[GatewayClient] Invalid or missing SERVICE_LAYER. Expected 'wspace' or 'global', got '${layer}'`);\n }\n\n const serviceName = process.env['SERVICE_NAME'];\n if (!serviceName) {\n throw new Error('[GatewayClient] SERVICE_NAME environment variable is required');\n }\n\n const serviceIdentity = process.env['SERVICE_IDENTITY'] || serviceName;\n\n return new GatewayClient({\n layer,\n serviceName,\n serviceIdentity,\n });\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { DEFAULT_LAYER_RESOURCES } from './chunk-ZA3IGCDJ.js';
1
+ import { DEFAULT_LAYER_RESOURCES } from './chunk-HP6JTFNR.js';
2
2
  import { logger } from './chunk-CBZNP6RF.js';
3
3
  import { __name } from './chunk-XE4OXN2W.js';
4
4
 
@@ -754,5 +754,5 @@ var TemporalModule = class _TemporalModule {
754
754
  };
755
755
 
756
756
  export { TemporalClient, TemporalClientFactory, TemporalModule, TemporalWorker, TemporalWorkerFactory, TemporalWorkerManager };
757
- //# sourceMappingURL=chunk-R3XPCYHM.js.map
758
- //# sourceMappingURL=chunk-R3XPCYHM.js.map
757
+ //# sourceMappingURL=chunk-5SD7DU3L.js.map
758
+ //# sourceMappingURL=chunk-5SD7DU3L.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/temporal/client.ts","../src/temporal/worker.ts","../src/temporal/module.ts"],"names":["temporalClientModule","getTemporalClientModule","TemporalClient","client","connection","config","isConnected","connectionTimeout","tls","connect","logger","info","address","namespace","Connection","Client","tlsOptions","undefined","error","Error","message","String","disconnect","close","getClient","startWorkflow","workflowType","options","debug","workflowId","taskQueue","handle","workflow","start","args","workflowExecutionTimeout","workflowRunTimeout","workflowTaskTimeout","cronSchedule","memo","searchAttributes","executeWorkflow","result","execute","getWorkflowHandle","runId","getHandle","signalWorkflow","signalName","signal","queryWorkflow","queryName","query","cancelWorkflow","cancel","terminateWorkflow","reason","terminate","describeWorkflow","description","describe","status","name","getWorkflowResult","isClientConnected","getConfig","TemporalClientFactory","createWorkspaceClient","process","env","createTenantClient","createFromEnv","moduleType","createClientForLayer","layer","serviceName","envPrefix","toUpperCase","defaults","DEFAULT_LAYER_RESOURCES","temporalAddress","layerPrefix","derivedNamespace","replace","createFromLayerEnv","startsWith","temporalWorkerModule","getTemporalWorkerModule","TemporalWorker","worker","isRunning","maxConcurrentWorkflowTaskExecutions","maxConcurrentActivityTaskExecutions","debugMode","warn","Worker","NativeConnection","create","workflowsPath","activities","run","stop","shutdown","isWorkerRunning","TemporalWorkerFactory","createWorkspaceWorker","createTenantWorker","TemporalWorkerManager","workers","Map","registerWorker","has","set","startAll","count","size","startPromises","Array","from","entries","map","Promise","all","stopAll","stopPromises","getWorker","get","removeWorker","delete","getWorkerNames","keys","TemporalModule","workerManager","autoConnect","initialize","catch","getWorkerManager","createWorker","startWorkers","stopWorkers","fromEnv"],"mappings":";;;;;AAmBA,IAAIA,oBAAAA,GAAmE,IAAA;AAKvE,eAAeC,uBAAAA,GAAAA;AACb,EAAA,IAAI,CAACD,oBAAAA,EAAsB;AACzBA,IAAAA,oBAAAA,GAAuB,MAAM,OAAO,oBAAA,CAAA;AACtC,EAAA;AACA,EAAA,OAAOA,oBAAAA;AACT;AALeC,MAAAA,CAAAA,uBAAAA,EAAAA,yBAAAA,CAAAA;AAmER,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EAAA,MAAMiD,YAAAA,GAA8B;AAClC,IAAA,MAAM,IAAA,CAAKN,cAAcnB,QAAAA,EAAQ;AACnC,EAAA;;;;AAKA,EAAA,MAAM0B,WAAAA,GAA6B;AACjC,IAAA,MAAM,IAAA,CAAKP,cAAcT,OAAAA,EAAO;AAClC,EAAA;;;;AAKA,EAAA,MAAMrG,UAAAA,GAA4B;AAChC,IAAA,MAAM,IAAA,CAAKnB,OAAOmB,UAAAA,EAAU;AAC9B,EAAA;;;;EAKA2C,SAAAA,GAAkC;AAChC,IAAA,OAAO;AAAE,MAAA,GAAG,IAAA,CAAK5D;AAAO,KAAA;AAC1B,EAAA;;;;AAKA,EAAA,OAAOuI,OAAAA,GAA0B;AAC/B,IAAA,MAAMpE,UAAAA,GAAcJ,OAAAA,CAAQC,GAAAA,CAAI,sBAAA,CAAA,IAA2B,WAAA;AAC3D,IAAA,MAAMzD,OAAAA,GACJ4D,UAAAA,KAAe,QAAA,GACXJ,OAAAA,CAAQC,GAAAA,CAAI,qBAAA,CAAA,IAA0B,gBAAA,GACtCD,OAAAA,CAAQC,GAAAA,CAAI,wBAAA,CAAA,IAA6B,gBAAA;AAC/C,IAAA,MAAMxD,SAAAA,GAAYuD,OAAAA,CAAQC,GAAAA,CAAI,oBAAA,CAAA;AAC9B,IAAA,MAAMvC,SAAAA,GAAYsC,OAAAA,CAAQC,GAAAA,CAAI,qBAAA,CAAA;AAE9B,IAAA,OAAO,IAAI8D,eAAAA,CAAe;AACxB3D,MAAAA,UAAAA;AACA5D,MAAAA,OAAAA;AACAC,MAAAA,SAAAA;AACAiB,MAAAA;KACF,CAAA;AACF,EAAA;AACF","file":"chunk-R3XPCYHM.js","sourcesContent":["/**\n * Temporal Client Module\n * Provides unified Temporal client for workspace and tenant microservices\n *\n * NOTE: Uses dynamic imports to avoid requiring @temporalio/client at bundle time.\n * This allows services that don't use Temporal to avoid installing the dependency.\n */\n\nimport type {\n Client as TemporalClientType,\n Connection as TemporalConnectionType,\n WorkflowHandle,\n} from '@temporalio/client';\nimport type { Duration } from '@temporalio/common';\nimport { logger } from '../logger/index.js';\nimport type { ServiceLayer } from '../types/layer.js';\nimport { DEFAULT_LAYER_RESOURCES } from '../types/layer.js';\n\n// Lazy-loaded Temporal client module\nlet temporalClientModule: typeof import('@temporalio/client') | null = null;\n\n/**\n * Lazily load the @temporalio/client module\n */\nasync function getTemporalClientModule(): Promise<typeof import('@temporalio/client')> {\n if (!temporalClientModule) {\n temporalClientModule = await import('@temporalio/client');\n }\n return temporalClientModule;\n}\n\n/**\n * Workflow search attributes type for visibility queries\n * Uses a generic Record type to avoid importing deprecated SearchAttributes\n * Search attributes are key-value pairs used for workflow visibility and querying\n * We use unknown for maximum compatibility with the SDK's internal types\n */\ntype WorkflowSearchAttributes = Record<string, unknown>;\n\n/**\n * Temporal client configuration\n */\nexport interface TemporalClientConfig {\n /** Temporal server address (e.g., localhost:7233 or K8s service DNS) */\n address: string;\n /** Temporal namespace (e.g., workspace-tags, tenant-auth) */\n namespace: string;\n /** Default task queue for workflows */\n taskQueue?: string;\n /** Connection timeout in milliseconds */\n connectionTimeout?: number;\n /** Enable TLS for connection */\n tls?: boolean;\n /** TLS certificate options */\n tlsOptions?: {\n serverNameOverride?: string;\n serverRootCACertificate?: Buffer;\n clientCertPair?: {\n crt: Buffer;\n key: Buffer;\n };\n };\n}\n\n/**\n * Workflow execution options\n */\nexport interface WorkflowStartOptions<T extends unknown[] = unknown[]> {\n /** Workflow ID (must be unique) */\n workflowId: string;\n /** Task queue name */\n taskQueue: string;\n /** Workflow arguments */\n args?: T;\n /** Workflow execution timeout (duration string like '1m', '1h', milliseconds, or Duration object) */\n workflowExecutionTimeout?: Duration;\n /** Workflow run timeout (duration string like '1m', '1h', milliseconds, or Duration object) */\n workflowRunTimeout?: Duration;\n /** Workflow task timeout (duration string like '1m', '1h', milliseconds, or Duration object) */\n workflowTaskTimeout?: Duration;\n /** Cron schedule (for scheduled workflows) */\n cronSchedule?: string;\n /** Memo (indexed metadata) */\n memo?: Record<string, unknown>;\n /** Search attributes for workflow visibility (extracted from SDK to avoid deprecated type import) */\n searchAttributes?: WorkflowSearchAttributes;\n}\n\n/**\n * Temporal Client wrapper for Burdenoff microservices\n */\nexport class TemporalClient {\n private client: TemporalClientType | null = null;\n private connection: TemporalConnectionType | null = null;\n private config: TemporalClientConfig;\n private isConnected = false;\n\n constructor(config: TemporalClientConfig) {\n this.config = {\n connectionTimeout: 10000,\n tls: false,\n ...config,\n };\n }\n\n /**\n * Connect to Temporal server\n */\n async connect(): Promise<TemporalClientType> {\n if (this.client && this.isConnected) {\n return this.client;\n }\n\n try {\n logger.info('Connecting to Temporal server', {\n address: this.config.address,\n namespace: this.config.namespace,\n });\n\n // Dynamically import Temporal client module\n const { Connection, Client } = await getTemporalClientModule();\n\n this.connection = await Connection.connect({\n address: this.config.address,\n tls: this.config.tls ? this.config.tlsOptions : undefined,\n });\n\n this.client = new Client({\n connection: this.connection,\n namespace: this.config.namespace,\n });\n\n this.isConnected = true;\n\n logger.info('Successfully connected to Temporal', {\n address: this.config.address,\n namespace: this.config.namespace,\n });\n\n return this.client;\n } catch (error) {\n logger.error('Failed to connect to Temporal', {\n error: error instanceof Error ? error.message : String(error),\n address: this.config.address,\n });\n throw error;\n }\n }\n\n /**\n * Disconnect from Temporal server\n */\n async disconnect(): Promise<void> {\n if (this.connection) {\n await this.connection.close();\n this.connection = null;\n this.client = null;\n this.isConnected = false;\n\n logger.info('Disconnected from Temporal', {\n address: this.config.address,\n });\n }\n }\n\n /**\n * Get the underlying Temporal client\n */\n async getClient(): Promise<TemporalClientType> {\n return this.connect();\n }\n\n /**\n * Start a workflow execution using string workflow name\n * Note: Since workflow is specified as string (not function reference),\n * return type is WorkflowHandle without type parameter\n */\n async startWorkflow<T extends unknown[] = unknown[]>(\n workflowType: string,\n options: WorkflowStartOptions<T>\n ): Promise<WorkflowHandle> {\n const client = await this.connect();\n\n try {\n logger.debug('Starting workflow', {\n workflowType,\n workflowId: options.workflowId,\n taskQueue: options.taskQueue,\n });\n\n const handle = await client.workflow.start(workflowType, {\n workflowId: options.workflowId,\n taskQueue: options.taskQueue,\n args: options.args ?? [],\n workflowExecutionTimeout: options.workflowExecutionTimeout,\n workflowRunTimeout: options.workflowRunTimeout,\n workflowTaskTimeout: options.workflowTaskTimeout,\n cronSchedule: options.cronSchedule,\n memo: options.memo,\n searchAttributes: options.searchAttributes as Record<string, never>,\n });\n\n logger.info('Workflow started successfully', {\n workflowType,\n workflowId: options.workflowId,\n });\n\n return handle;\n } catch (error) {\n logger.error('Failed to start workflow', {\n workflowType,\n workflowId: options.workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Execute a workflow and wait for result using string workflow name\n * Note: Since workflow is specified as string (not function reference),\n * return type is unknown (caller must assert type if needed)\n */\n async executeWorkflow<T extends unknown[] = unknown[]>(\n workflowType: string,\n options: WorkflowStartOptions<T>\n ): Promise<unknown> {\n const client = await this.connect();\n\n try {\n logger.debug('Executing workflow', {\n workflowType,\n workflowId: options.workflowId,\n taskQueue: options.taskQueue,\n });\n\n const result = await client.workflow.execute(workflowType, {\n workflowId: options.workflowId,\n taskQueue: options.taskQueue,\n args: options.args ?? [],\n workflowExecutionTimeout: options.workflowExecutionTimeout,\n workflowRunTimeout: options.workflowRunTimeout,\n workflowTaskTimeout: options.workflowTaskTimeout,\n memo: options.memo,\n searchAttributes: options.searchAttributes as Record<string, never>,\n });\n\n logger.info('Workflow executed successfully', {\n workflowType,\n workflowId: options.workflowId,\n });\n\n return result;\n } catch (error) {\n logger.error('Failed to execute workflow', {\n workflowType,\n workflowId: options.workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Get workflow handle by ID\n */\n async getWorkflowHandle(workflowId: string, runId?: string): Promise<WorkflowHandle> {\n const client = await this.connect();\n return client.workflow.getHandle(workflowId, runId);\n }\n\n /**\n * Signal a running workflow\n */\n async signalWorkflow(workflowId: string, signalName: string, args?: unknown[]): Promise<void> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n await handle.signal(signalName, args);\n\n logger.info('Workflow signal sent', {\n workflowId,\n signalName,\n });\n } catch (error) {\n logger.error('Failed to signal workflow', {\n workflowId,\n signalName,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Query a running workflow\n */\n async queryWorkflow(workflowId: string, queryName: string, args?: unknown[]): Promise<unknown> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n const result = await handle.query(queryName, args);\n\n logger.debug('Workflow query executed', {\n workflowId,\n queryName,\n });\n\n return result;\n } catch (error) {\n logger.error('Failed to query workflow', {\n workflowId,\n queryName,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Cancel a running workflow\n */\n async cancelWorkflow(workflowId: string): Promise<void> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n await handle.cancel();\n\n logger.info('Workflow cancelled', {\n workflowId,\n });\n } catch (error) {\n logger.error('Failed to cancel workflow', {\n workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Terminate a running workflow\n */\n async terminateWorkflow(workflowId: string, reason?: string): Promise<void> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n await handle.terminate(reason);\n\n logger.info('Workflow terminated', {\n workflowId,\n reason,\n });\n } catch (error) {\n logger.error('Failed to terminate workflow', {\n workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Describe a workflow execution\n */\n async describeWorkflow(workflowId: string): Promise<unknown> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n const description = await handle.describe();\n\n logger.debug('Workflow described', {\n workflowId,\n status: description.status.name,\n });\n\n return description;\n } catch (error) {\n logger.error('Failed to describe workflow', {\n workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Get workflow result\n */\n async getWorkflowResult(workflowId: string): Promise<unknown> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n const result = await handle.result();\n\n logger.info('Workflow result retrieved', {\n workflowId,\n });\n\n return result;\n } catch (error) {\n logger.error('Failed to get workflow result', {\n workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Check if client is connected\n */\n isClientConnected(): boolean {\n return this.isConnected;\n }\n\n /**\n * Get configuration\n */\n getConfig(): TemporalClientConfig {\n return { ...this.config };\n }\n}\n\n/**\n * Factory for creating Temporal clients based on module type\n */\nexport class TemporalClientFactory {\n /**\n * Create a Temporal client for workspace modules\n */\n static createWorkspaceClient(config?: Partial<TemporalClientConfig>): TemporalClient {\n const address = config?.address || process.env['TEMPORAL_WORKSPACE_URL'] || 'localhost:7233';\n const namespace = config?.namespace || process.env['TEMPORAL_NAMESPACE'] || 'workspace-default';\n const taskQueue = config?.taskQueue || process.env['TEMPORAL_TASK_QUEUE'];\n\n return new TemporalClient({\n address,\n namespace,\n taskQueue,\n ...config,\n });\n }\n\n /**\n * Create a Temporal client for tenant modules\n */\n static createTenantClient(config?: Partial<TemporalClientConfig>): TemporalClient {\n const address = config?.address || process.env['TEMPORAL_TENANT_URL'] || 'localhost:7233';\n const namespace = config?.namespace || process.env['TEMPORAL_NAMESPACE'] || 'tenant-default';\n const taskQueue = config?.taskQueue || process.env['TEMPORAL_TASK_QUEUE'];\n\n return new TemporalClient({\n address,\n namespace,\n taskQueue,\n ...config,\n });\n }\n\n /**\n * Create a Temporal client from environment variables\n * Automatically detects workspace vs tenant based on TEMPORAL_MODULE_TYPE\n */\n static createFromEnv(): TemporalClient {\n const moduleType = process.env['TEMPORAL_MODULE_TYPE'] || 'workspace';\n\n if (moduleType === 'tenant') {\n return this.createTenantClient();\n }\n\n return this.createWorkspaceClient();\n }\n\n // ========================================================================\n // Layer-Aware Factory Methods\n // ========================================================================\n\n /**\n * Create a Temporal client for a specific layer\n *\n * @param layer - Service layer ('wspace' or 'global')\n * @param serviceName - Service name for identification\n * @param config - Optional configuration overrides\n * @returns Temporal client configured for the layer\n *\n * @example\n * ```typescript\n * const client = TemporalClientFactory.createClientForLayer('wspace', 'wspace-tags-svc');\n * await client.connect();\n * await client.startWorkflow('processTagUpdate', {\n * workflowId: 'tag-update-123',\n * taskQueue: 'wspace-tags-queue',\n * });\n * ```\n */\n static createClientForLayer(\n layer: ServiceLayer,\n serviceName: string,\n config?: Partial<TemporalClientConfig>\n ): TemporalClient {\n const envPrefix = layer.toUpperCase();\n const defaults = DEFAULT_LAYER_RESOURCES[layer];\n\n // Resolve Temporal address from layer-specific or generic env vars\n const address =\n config?.address ||\n process.env[`${envPrefix}_TEMPORAL_ADDRESS`] ||\n process.env['TEMPORAL_ADDRESS'] ||\n defaults.temporalAddress;\n\n // Derive namespace from layer and service name\n const layerPrefix = `${layer}-`;\n const derivedNamespace = `${layer}-${serviceName.replace(layerPrefix, '').replace('-svc', '')}`;\n const namespace =\n config?.namespace ||\n process.env[`${envPrefix}_TEMPORAL_NAMESPACE`] ||\n process.env['TEMPORAL_NAMESPACE'] ||\n derivedNamespace;\n\n const taskQueue =\n config?.taskQueue ||\n process.env[`${envPrefix}_TEMPORAL_TASK_QUEUE`] ||\n process.env['TEMPORAL_TASK_QUEUE'] ||\n `${serviceName}-queue`;\n\n logger.info('[TemporalClientFactory] Creating layer client', {\n layer,\n serviceName,\n address,\n namespace,\n taskQueue,\n });\n\n return new TemporalClient({\n address,\n namespace,\n taskQueue,\n ...config,\n });\n }\n\n /**\n * Create a Temporal client from layer environment detection\n *\n * @param serviceName - Service name for identification\n * @returns Temporal client configured based on detected layer\n */\n static createFromLayerEnv(serviceName: string): TemporalClient {\n // Detect layer from service name or environment\n const layer =\n (process.env['SERVICE_LAYER'] as ServiceLayer) || (serviceName.startsWith('global-') ? 'global' : 'wspace');\n\n return this.createClientForLayer(layer, serviceName);\n }\n}\n","/**\n * Temporal Worker Module\n * Provides utilities for creating and managing Temporal workers\n *\n * NOTE: Uses dynamic imports to avoid requiring @temporalio/worker at bundle time.\n * This allows services that don't use Temporal to avoid installing the dependency.\n */\n\nimport type {\n Worker as TemporalWorkerType,\n NativeConnection as TemporalNativeConnectionType,\n} from '@temporalio/worker';\nimport { logger } from '../logger/index.js';\n\n// Lazy-loaded Temporal worker module\nlet temporalWorkerModule: typeof import('@temporalio/worker') | null = null;\n\n/**\n * Lazily load the @temporalio/worker module\n */\nasync function getTemporalWorkerModule(): Promise<typeof import('@temporalio/worker')> {\n if (!temporalWorkerModule) {\n temporalWorkerModule = await import('@temporalio/worker');\n }\n return temporalWorkerModule;\n}\n\n/**\n * Worker configuration\n */\nexport interface TemporalWorkerConfig {\n /** Temporal server address */\n address: string;\n /** Temporal namespace */\n namespace: string;\n /** Task queue to poll */\n taskQueue: string;\n /** Path to workflow files */\n workflowsPath: string;\n /** Activities object */\n activities?: Record<string, (...args: unknown[]) => Promise<unknown>>;\n /** Maximum concurrent workflow task executions */\n maxConcurrentWorkflowTaskExecutions?: number;\n /** Maximum concurrent activity task executions */\n maxConcurrentActivityTaskExecutions?: number;\n /** Enable debug logging */\n debugMode?: boolean;\n /** TLS options */\n tls?: {\n serverNameOverride?: string;\n serverRootCACertificate?: Buffer;\n clientCertPair?: {\n crt: Buffer;\n key: Buffer;\n };\n };\n}\n\n/**\n * Temporal Worker wrapper for Burdenoff microservices\n */\nexport class TemporalWorker {\n private worker: TemporalWorkerType | null = null;\n private connection: TemporalNativeConnectionType | null = null;\n private config: TemporalWorkerConfig;\n private isRunning = false;\n\n constructor(config: TemporalWorkerConfig) {\n this.config = {\n maxConcurrentWorkflowTaskExecutions: 100,\n maxConcurrentActivityTaskExecutions: 100,\n debugMode: false,\n ...config,\n };\n }\n\n /**\n * Start the worker\n */\n async start(): Promise<void> {\n if (this.isRunning) {\n logger.warn('Worker already running', {\n taskQueue: this.config.taskQueue,\n });\n return;\n }\n\n try {\n logger.info('Starting Temporal worker', {\n address: this.config.address,\n namespace: this.config.namespace,\n taskQueue: this.config.taskQueue,\n });\n\n // Dynamically import Temporal worker module\n const { Worker, NativeConnection } = await getTemporalWorkerModule();\n\n // Create native connection\n this.connection = await NativeConnection.connect({\n address: this.config.address,\n tls: this.config.tls,\n });\n\n // Create worker\n this.worker = await Worker.create({\n connection: this.connection,\n namespace: this.config.namespace,\n taskQueue: this.config.taskQueue,\n workflowsPath: this.config.workflowsPath,\n activities: this.config.activities,\n maxConcurrentWorkflowTaskExecutions: this.config.maxConcurrentWorkflowTaskExecutions,\n maxConcurrentActivityTaskExecutions: this.config.maxConcurrentActivityTaskExecutions,\n });\n\n this.isRunning = true;\n\n logger.info('Temporal worker started successfully', {\n taskQueue: this.config.taskQueue,\n workflowsPath: this.config.workflowsPath,\n });\n\n // Run worker (this blocks)\n await this.worker.run();\n } catch (error) {\n logger.error('Failed to start Temporal worker', {\n error: error instanceof Error ? error.message : String(error),\n taskQueue: this.config.taskQueue,\n });\n throw error;\n }\n }\n\n /**\n * Stop the worker\n */\n async stop(): Promise<void> {\n if (!this.isRunning || !this.worker) {\n logger.warn('Worker not running', {\n taskQueue: this.config.taskQueue,\n });\n return;\n }\n\n try {\n logger.info('Stopping Temporal worker', {\n taskQueue: this.config.taskQueue,\n });\n\n this.worker.shutdown();\n this.isRunning = false;\n\n if (this.connection) {\n await this.connection.close();\n this.connection = null;\n }\n\n this.worker = null;\n\n logger.info('Temporal worker stopped successfully', {\n taskQueue: this.config.taskQueue,\n });\n } catch (error) {\n logger.error('Failed to stop Temporal worker', {\n error: error instanceof Error ? error.message : String(error),\n taskQueue: this.config.taskQueue,\n });\n throw error;\n }\n }\n\n /**\n * Check if worker is running\n */\n isWorkerRunning(): boolean {\n return this.isRunning;\n }\n\n /**\n * Get worker configuration\n */\n getConfig(): TemporalWorkerConfig {\n return { ...this.config };\n }\n}\n\n/**\n * Factory for creating Temporal workers based on module type\n */\nexport class TemporalWorkerFactory {\n /**\n * Create a Temporal worker for workspace modules\n */\n static createWorkspaceWorker(config: {\n workflowsPath: string;\n activities?: Record<string, (...args: unknown[]) => Promise<unknown>>;\n taskQueue?: string;\n namespace?: string;\n address?: string;\n }): TemporalWorker {\n const address = config.address || process.env['TEMPORAL_WORKSPACE_URL'] || 'localhost:7233';\n const namespace = config.namespace || process.env['TEMPORAL_NAMESPACE'] || 'workspace-default';\n const taskQueue = config.taskQueue || process.env['TEMPORAL_TASK_QUEUE'] || 'workspace-default-tasks';\n\n return new TemporalWorker({\n address,\n namespace,\n taskQueue,\n workflowsPath: config.workflowsPath,\n activities: config.activities,\n });\n }\n\n /**\n * Create a Temporal worker for tenant modules\n */\n static createTenantWorker(config: {\n workflowsPath: string;\n activities?: Record<string, (...args: unknown[]) => Promise<unknown>>;\n taskQueue?: string;\n namespace?: string;\n address?: string;\n }): TemporalWorker {\n const address = config.address || process.env['TEMPORAL_TENANT_URL'] || 'localhost:7233';\n const namespace = config.namespace || process.env['TEMPORAL_NAMESPACE'] || 'tenant-default';\n const taskQueue = config.taskQueue || process.env['TEMPORAL_TASK_QUEUE'] || 'tenant-default-tasks';\n\n return new TemporalWorker({\n address,\n namespace,\n taskQueue,\n workflowsPath: config.workflowsPath,\n activities: config.activities,\n });\n }\n\n /**\n * Create a Temporal worker from environment variables\n * Automatically detects workspace vs tenant based on TEMPORAL_MODULE_TYPE\n */\n static createFromEnv(config: {\n workflowsPath: string;\n activities?: Record<string, (...args: unknown[]) => Promise<unknown>>;\n }): TemporalWorker {\n const moduleType = process.env['TEMPORAL_MODULE_TYPE'] || 'workspace';\n\n if (moduleType === 'tenant') {\n return this.createTenantWorker(config);\n }\n\n return this.createWorkspaceWorker(config);\n }\n}\n\n/**\n * Worker manager for handling worker lifecycle\n */\nexport class TemporalWorkerManager {\n private workers: Map<string, TemporalWorker> = new Map();\n\n /**\n * Register a worker\n */\n registerWorker(name: string, worker: TemporalWorker): void {\n if (this.workers.has(name)) {\n logger.warn('Worker already registered, replacing', { name });\n }\n this.workers.set(name, worker);\n }\n\n /**\n * Start all registered workers\n */\n async startAll(): Promise<void> {\n logger.info('Starting all Temporal workers', {\n count: this.workers.size,\n });\n\n const startPromises = Array.from(this.workers.entries()).map(async ([name, worker]) => {\n try {\n await worker.start();\n logger.info('Worker started', { name });\n } catch (error) {\n logger.error('Failed to start worker', {\n name,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n });\n\n await Promise.all(startPromises);\n }\n\n /**\n * Stop all registered workers\n */\n async stopAll(): Promise<void> {\n logger.info('Stopping all Temporal workers', {\n count: this.workers.size,\n });\n\n const stopPromises = Array.from(this.workers.entries()).map(async ([name, worker]) => {\n try {\n await worker.stop();\n logger.info('Worker stopped', { name });\n } catch (error) {\n logger.error('Failed to stop worker', {\n name,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n });\n\n await Promise.all(stopPromises);\n }\n\n /**\n * Get a worker by name\n */\n getWorker(name: string): TemporalWorker | undefined {\n return this.workers.get(name);\n }\n\n /**\n * Remove a worker\n */\n removeWorker(name: string): boolean {\n return this.workers.delete(name);\n }\n\n /**\n * Get all registered worker names\n */\n getWorkerNames(): string[] {\n return Array.from(this.workers.keys());\n }\n}\n","/**\n * Temporal Module for Burdenoff SDK\n * Integrates Temporal workflow orchestration into the SDK\n */\n\nimport type { TemporalClient } from './client.js';\nimport { TemporalClientFactory } from './client.js';\nimport type { TemporalWorker } from './worker.js';\nimport { TemporalWorkerFactory, TemporalWorkerManager } from './worker.js';\nimport { logger } from '../logger/index.js';\n\n/**\n * Temporal module configuration\n */\nexport interface TemporalModuleConfig {\n /** Module type (workspace or tenant) */\n moduleType: 'workspace' | 'tenant';\n /** Temporal server address */\n address?: string;\n /** Temporal namespace */\n namespace?: string;\n /** Default task queue */\n taskQueue?: string;\n /** Auto-connect on initialization */\n autoConnect?: boolean;\n}\n\n/**\n * Temporal Module\n * Main entry point for Temporal functionality in the SDK\n */\nexport class TemporalModule {\n private client: TemporalClient;\n private workerManager: TemporalWorkerManager;\n private config: TemporalModuleConfig;\n\n constructor(config: TemporalModuleConfig) {\n this.config = {\n autoConnect: true,\n ...config,\n };\n\n // Create client based on module type\n if (config.moduleType === 'tenant') {\n this.client = TemporalClientFactory.createTenantClient({\n address: config.address,\n namespace: config.namespace,\n taskQueue: config.taskQueue,\n });\n } else {\n this.client = TemporalClientFactory.createWorkspaceClient({\n address: config.address,\n namespace: config.namespace,\n taskQueue: config.taskQueue,\n });\n }\n\n this.workerManager = new TemporalWorkerManager();\n\n // Trigger autoConnect if enabled (non-blocking)\n if (this.config.autoConnect) {\n this.initialize();\n }\n }\n\n /**\n * Initialize the Temporal module (connect client)\n * This is called automatically if autoConnect is true\n */\n private initialize(): void {\n // Connect in background\n this.client.connect().catch((error) => {\n logger.error('Failed to auto-connect to Temporal', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n }\n\n /**\n * Get the Temporal client\n */\n getClient(): TemporalClient {\n return this.client;\n }\n\n /**\n * Get the worker manager\n */\n getWorkerManager(): TemporalWorkerManager {\n return this.workerManager;\n }\n\n /**\n * Create and register a worker\n */\n createWorker(config: {\n name: string;\n workflowsPath: string;\n activities?: Record<string, (...args: unknown[]) => Promise<unknown>>;\n taskQueue?: string;\n }): TemporalWorker {\n const worker =\n this.config.moduleType === 'tenant'\n ? TemporalWorkerFactory.createTenantWorker({\n workflowsPath: config.workflowsPath,\n activities: config.activities,\n taskQueue: config.taskQueue,\n namespace: this.config.namespace,\n address: this.config.address,\n })\n : TemporalWorkerFactory.createWorkspaceWorker({\n workflowsPath: config.workflowsPath,\n activities: config.activities,\n taskQueue: config.taskQueue,\n namespace: this.config.namespace,\n address: this.config.address,\n });\n\n this.workerManager.registerWorker(config.name, worker);\n return worker;\n }\n\n /**\n * Start all registered workers\n */\n async startWorkers(): Promise<void> {\n await this.workerManager.startAll();\n }\n\n /**\n * Stop all registered workers\n */\n async stopWorkers(): Promise<void> {\n await this.workerManager.stopAll();\n }\n\n /**\n * Disconnect from Temporal\n */\n async disconnect(): Promise<void> {\n await this.client.disconnect();\n }\n\n /**\n * Get module configuration\n */\n getConfig(): TemporalModuleConfig {\n return { ...this.config };\n }\n\n /**\n * Create a Temporal module from environment variables\n */\n static fromEnv(): TemporalModule {\n const moduleType = (process.env['TEMPORAL_MODULE_TYPE'] || 'workspace') as 'workspace' | 'tenant';\n const address =\n moduleType === 'tenant'\n ? process.env['TEMPORAL_TENANT_URL'] || 'localhost:7233'\n : process.env['TEMPORAL_WORKSPACE_URL'] || 'localhost:7233';\n const namespace = process.env['TEMPORAL_NAMESPACE'];\n const taskQueue = process.env['TEMPORAL_TASK_QUEUE'];\n\n return new TemporalModule({\n moduleType,\n address,\n namespace,\n taskQueue,\n });\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/temporal/client.ts","../src/temporal/worker.ts","../src/temporal/module.ts"],"names":["temporalClientModule","getTemporalClientModule","TemporalClient","client","connection","config","isConnected","connectionTimeout","tls","connect","logger","info","address","namespace","Connection","Client","tlsOptions","undefined","error","Error","message","String","disconnect","close","getClient","startWorkflow","workflowType","options","debug","workflowId","taskQueue","handle","workflow","start","args","workflowExecutionTimeout","workflowRunTimeout","workflowTaskTimeout","cronSchedule","memo","searchAttributes","executeWorkflow","result","execute","getWorkflowHandle","runId","getHandle","signalWorkflow","signalName","signal","queryWorkflow","queryName","query","cancelWorkflow","cancel","terminateWorkflow","reason","terminate","describeWorkflow","description","describe","status","name","getWorkflowResult","isClientConnected","getConfig","TemporalClientFactory","createWorkspaceClient","process","env","createTenantClient","createFromEnv","moduleType","createClientForLayer","layer","serviceName","envPrefix","toUpperCase","defaults","DEFAULT_LAYER_RESOURCES","temporalAddress","layerPrefix","derivedNamespace","replace","createFromLayerEnv","startsWith","temporalWorkerModule","getTemporalWorkerModule","TemporalWorker","worker","isRunning","maxConcurrentWorkflowTaskExecutions","maxConcurrentActivityTaskExecutions","debugMode","warn","Worker","NativeConnection","create","workflowsPath","activities","run","stop","shutdown","isWorkerRunning","TemporalWorkerFactory","createWorkspaceWorker","createTenantWorker","TemporalWorkerManager","workers","Map","registerWorker","has","set","startAll","count","size","startPromises","Array","from","entries","map","Promise","all","stopAll","stopPromises","getWorker","get","removeWorker","delete","getWorkerNames","keys","TemporalModule","workerManager","autoConnect","initialize","catch","getWorkerManager","createWorker","startWorkers","stopWorkers","fromEnv"],"mappings":";;;;;AAmBA,IAAIA,oBAAAA,GAAmE,IAAA;AAKvE,eAAeC,uBAAAA,GAAAA;AACb,EAAA,IAAI,CAACD,oBAAAA,EAAsB;AACzBA,IAAAA,oBAAAA,GAAuB,MAAM,OAAO,oBAAA,CAAA;AACtC,EAAA;AACA,EAAA,OAAOA,oBAAAA;AACT;AALeC,MAAAA,CAAAA,uBAAAA,EAAAA,yBAAAA,CAAAA;AAmER,IAAMC,iBAAN,MAAMA;EA3Fb;;;EA4FUC,MAAAA,GAAoC,IAAA;EACpCC,UAAAA,GAA4C,IAAA;AAC5CC,EAAAA,MAAAA;EACAC,WAAAA,GAAc,KAAA;AAEtB,EAAA,WAAA,CAAYD,MAAAA,EAA8B;AACxC,IAAA,IAAA,CAAKA,MAAAA,GAAS;MACZE,iBAAAA,EAAmB,GAAA;MACnBC,GAAAA,EAAK,KAAA;MACL,GAAGH;AACL,KAAA;AACF,EAAA;;;;AAKA,EAAA,MAAMI,OAAAA,GAAuC;AAC3C,IAAA,IAAI,IAAA,CAAKN,MAAAA,IAAU,IAAA,CAAKG,WAAAA,EAAa;AACnC,MAAA,OAAO,IAAA,CAAKH,MAAAA;AACd,IAAA;AAEA,IAAA,IAAI;AACFO,MAAAA,MAAAA,CAAOC,KAAK,+BAAA,EAAiC;AAC3CC,QAAAA,OAAAA,EAAS,KAAKP,MAAAA,CAAOO,OAAAA;AACrBC,QAAAA,SAAAA,EAAW,KAAKR,MAAAA,CAAOQ;OACzB,CAAA;AAGA,MAAA,MAAM,EAAEC,UAAAA,EAAYC,MAAAA,EAAM,GAAK,MAAMd,uBAAAA,EAAAA;AAErC,MAAA,IAAA,CAAKG,UAAAA,GAAa,MAAMU,UAAAA,CAAWL,OAAAA,CAAQ;AACzCG,QAAAA,O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A,GAAYsC,OAAAA,CAAQC,GAAAA,CAAI,qBAAA,CAAA;AAE9B,IAAA,OAAO,IAAI8D,eAAAA,CAAe;AACxB3D,MAAAA,UAAAA;AACA5D,MAAAA,OAAAA;AACAC,MAAAA,SAAAA;AACAiB,MAAAA;KACF,CAAA;AACF,EAAA;AACF","file":"chunk-5SD7DU3L.js","sourcesContent":["/**\n * Temporal Client Module\n * Provides unified Temporal client for workspace and tenant microservices\n *\n * NOTE: Uses dynamic imports to avoid requiring @temporalio/client at bundle time.\n * This allows services that don't use Temporal to avoid installing the dependency.\n */\n\nimport type {\n Client as TemporalClientType,\n Connection as TemporalConnectionType,\n WorkflowHandle,\n} from '@temporalio/client';\nimport type { Duration } from '@temporalio/common';\nimport { logger } from '../logger/index.js';\nimport type { ServiceLayer } from '../types/layer.js';\nimport { DEFAULT_LAYER_RESOURCES } from '../types/layer.js';\n\n// Lazy-loaded Temporal client module\nlet temporalClientModule: typeof import('@temporalio/client') | null = null;\n\n/**\n * Lazily load the @temporalio/client module\n */\nasync function getTemporalClientModule(): Promise<typeof import('@temporalio/client')> {\n if (!temporalClientModule) {\n temporalClientModule = await import('@temporalio/client');\n }\n return temporalClientModule;\n}\n\n/**\n * Workflow search attributes type for visibility queries\n * Uses a generic Record type to avoid importing deprecated SearchAttributes\n * Search attributes are key-value pairs used for workflow visibility and querying\n * We use unknown for maximum compatibility with the SDK's internal types\n */\ntype WorkflowSearchAttributes = Record<string, unknown>;\n\n/**\n * Temporal client configuration\n */\nexport interface TemporalClientConfig {\n /** Temporal server address (e.g., localhost:7233 or K8s service DNS) */\n address: string;\n /** Temporal namespace (e.g., workspace-tags, tenant-auth) */\n namespace: string;\n /** Default task queue for workflows */\n taskQueue?: string;\n /** Connection timeout in milliseconds */\n connectionTimeout?: number;\n /** Enable TLS for connection */\n tls?: boolean;\n /** TLS certificate options */\n tlsOptions?: {\n serverNameOverride?: string;\n serverRootCACertificate?: Buffer;\n clientCertPair?: {\n crt: Buffer;\n key: Buffer;\n };\n };\n}\n\n/**\n * Workflow execution options\n */\nexport interface WorkflowStartOptions<T extends unknown[] = unknown[]> {\n /** Workflow ID (must be unique) */\n workflowId: string;\n /** Task queue name */\n taskQueue: string;\n /** Workflow arguments */\n args?: T;\n /** Workflow execution timeout (duration string like '1m', '1h', milliseconds, or Duration object) */\n workflowExecutionTimeout?: Duration;\n /** Workflow run timeout (duration string like '1m', '1h', milliseconds, or Duration object) */\n workflowRunTimeout?: Duration;\n /** Workflow task timeout (duration string like '1m', '1h', milliseconds, or Duration object) */\n workflowTaskTimeout?: Duration;\n /** Cron schedule (for scheduled workflows) */\n cronSchedule?: string;\n /** Memo (indexed metadata) */\n memo?: Record<string, unknown>;\n /** Search attributes for workflow visibility (extracted from SDK to avoid deprecated type import) */\n searchAttributes?: WorkflowSearchAttributes;\n}\n\n/**\n * Temporal Client wrapper for Burdenoff microservices\n */\nexport class TemporalClient {\n private client: TemporalClientType | null = null;\n private connection: TemporalConnectionType | null = null;\n private config: TemporalClientConfig;\n private isConnected = false;\n\n constructor(config: TemporalClientConfig) {\n this.config = {\n connectionTimeout: 10000,\n tls: false,\n ...config,\n };\n }\n\n /**\n * Connect to Temporal server\n */\n async connect(): Promise<TemporalClientType> {\n if (this.client && this.isConnected) {\n return this.client;\n }\n\n try {\n logger.info('Connecting to Temporal server', {\n address: this.config.address,\n namespace: this.config.namespace,\n });\n\n // Dynamically import Temporal client module\n const { Connection, Client } = await getTemporalClientModule();\n\n this.connection = await Connection.connect({\n address: this.config.address,\n tls: this.config.tls ? this.config.tlsOptions : undefined,\n });\n\n this.client = new Client({\n connection: this.connection,\n namespace: this.config.namespace,\n });\n\n this.isConnected = true;\n\n logger.info('Successfully connected to Temporal', {\n address: this.config.address,\n namespace: this.config.namespace,\n });\n\n return this.client;\n } catch (error) {\n logger.error('Failed to connect to Temporal', {\n error: error instanceof Error ? error.message : String(error),\n address: this.config.address,\n });\n throw error;\n }\n }\n\n /**\n * Disconnect from Temporal server\n */\n async disconnect(): Promise<void> {\n if (this.connection) {\n await this.connection.close();\n this.connection = null;\n this.client = null;\n this.isConnected = false;\n\n logger.info('Disconnected from Temporal', {\n address: this.config.address,\n });\n }\n }\n\n /**\n * Get the underlying Temporal client\n */\n async getClient(): Promise<TemporalClientType> {\n return this.connect();\n }\n\n /**\n * Start a workflow execution using string workflow name\n * Note: Since workflow is specified as string (not function reference),\n * return type is WorkflowHandle without type parameter\n */\n async startWorkflow<T extends unknown[] = unknown[]>(\n workflowType: string,\n options: WorkflowStartOptions<T>\n ): Promise<WorkflowHandle> {\n const client = await this.connect();\n\n try {\n logger.debug('Starting workflow', {\n workflowType,\n workflowId: options.workflowId,\n taskQueue: options.taskQueue,\n });\n\n const handle = await client.workflow.start(workflowType, {\n workflowId: options.workflowId,\n taskQueue: options.taskQueue,\n args: options.args ?? [],\n workflowExecutionTimeout: options.workflowExecutionTimeout,\n workflowRunTimeout: options.workflowRunTimeout,\n workflowTaskTimeout: options.workflowTaskTimeout,\n cronSchedule: options.cronSchedule,\n memo: options.memo,\n searchAttributes: options.searchAttributes as Record<string, never>,\n });\n\n logger.info('Workflow started successfully', {\n workflowType,\n workflowId: options.workflowId,\n });\n\n return handle;\n } catch (error) {\n logger.error('Failed to start workflow', {\n workflowType,\n workflowId: options.workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Execute a workflow and wait for result using string workflow name\n * Note: Since workflow is specified as string (not function reference),\n * return type is unknown (caller must assert type if needed)\n */\n async executeWorkflow<T extends unknown[] = unknown[]>(\n workflowType: string,\n options: WorkflowStartOptions<T>\n ): Promise<unknown> {\n const client = await this.connect();\n\n try {\n logger.debug('Executing workflow', {\n workflowType,\n workflowId: options.workflowId,\n taskQueue: options.taskQueue,\n });\n\n const result = await client.workflow.execute(workflowType, {\n workflowId: options.workflowId,\n taskQueue: options.taskQueue,\n args: options.args ?? [],\n workflowExecutionTimeout: options.workflowExecutionTimeout,\n workflowRunTimeout: options.workflowRunTimeout,\n workflowTaskTimeout: options.workflowTaskTimeout,\n memo: options.memo,\n searchAttributes: options.searchAttributes as Record<string, never>,\n });\n\n logger.info('Workflow executed successfully', {\n workflowType,\n workflowId: options.workflowId,\n });\n\n return result;\n } catch (error) {\n logger.error('Failed to execute workflow', {\n workflowType,\n workflowId: options.workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Get workflow handle by ID\n */\n async getWorkflowHandle(workflowId: string, runId?: string): Promise<WorkflowHandle> {\n const client = await this.connect();\n return client.workflow.getHandle(workflowId, runId);\n }\n\n /**\n * Signal a running workflow\n */\n async signalWorkflow(workflowId: string, signalName: string, args?: unknown[]): Promise<void> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n await handle.signal(signalName, args);\n\n logger.info('Workflow signal sent', {\n workflowId,\n signalName,\n });\n } catch (error) {\n logger.error('Failed to signal workflow', {\n workflowId,\n signalName,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Query a running workflow\n */\n async queryWorkflow(workflowId: string, queryName: string, args?: unknown[]): Promise<unknown> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n const result = await handle.query(queryName, args);\n\n logger.debug('Workflow query executed', {\n workflowId,\n queryName,\n });\n\n return result;\n } catch (error) {\n logger.error('Failed to query workflow', {\n workflowId,\n queryName,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Cancel a running workflow\n */\n async cancelWorkflow(workflowId: string): Promise<void> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n await handle.cancel();\n\n logger.info('Workflow cancelled', {\n workflowId,\n });\n } catch (error) {\n logger.error('Failed to cancel workflow', {\n workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Terminate a running workflow\n */\n async terminateWorkflow(workflowId: string, reason?: string): Promise<void> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n await handle.terminate(reason);\n\n logger.info('Workflow terminated', {\n workflowId,\n reason,\n });\n } catch (error) {\n logger.error('Failed to terminate workflow', {\n workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Describe a workflow execution\n */\n async describeWorkflow(workflowId: string): Promise<unknown> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n const description = await handle.describe();\n\n logger.debug('Workflow described', {\n workflowId,\n status: description.status.name,\n });\n\n return description;\n } catch (error) {\n logger.error('Failed to describe workflow', {\n workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Get workflow result\n */\n async getWorkflowResult(workflowId: string): Promise<unknown> {\n const handle = await this.getWorkflowHandle(workflowId);\n\n try {\n const result = await handle.result();\n\n logger.info('Workflow result retrieved', {\n workflowId,\n });\n\n return result;\n } catch (error) {\n logger.error('Failed to get workflow result', {\n workflowId,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Check if client is connected\n */\n isClientConnected(): boolean {\n return this.isConnected;\n }\n\n /**\n * Get configuration\n */\n getConfig(): TemporalClientConfig {\n return { ...this.config };\n }\n}\n\n/**\n * Factory for creating Temporal clients based on module type\n */\nexport class TemporalClientFactory {\n /**\n * Create a Temporal client for workspace modules\n */\n static createWorkspaceClient(config?: Partial<TemporalClientConfig>): TemporalClient {\n const address = config?.address || process.env['TEMPORAL_WORKSPACE_URL'] || 'localhost:7233';\n const namespace = config?.namespace || process.env['TEMPORAL_NAMESPACE'] || 'workspace-default';\n const taskQueue = config?.taskQueue || process.env['TEMPORAL_TASK_QUEUE'];\n\n return new TemporalClient({\n address,\n namespace,\n taskQueue,\n ...config,\n });\n }\n\n /**\n * Create a Temporal client for tenant modules\n */\n static createTenantClient(config?: Partial<TemporalClientConfig>): TemporalClient {\n const address = config?.address || process.env['TEMPORAL_TENANT_URL'] || 'localhost:7233';\n const namespace = config?.namespace || process.env['TEMPORAL_NAMESPACE'] || 'tenant-default';\n const taskQueue = config?.taskQueue || process.env['TEMPORAL_TASK_QUEUE'];\n\n return new TemporalClient({\n address,\n namespace,\n taskQueue,\n ...config,\n });\n }\n\n /**\n * Create a Temporal client from environment variables\n * Automatically detects workspace vs tenant based on TEMPORAL_MODULE_TYPE\n */\n static createFromEnv(): TemporalClient {\n const moduleType = process.env['TEMPORAL_MODULE_TYPE'] || 'workspace';\n\n if (moduleType === 'tenant') {\n return this.createTenantClient();\n }\n\n return this.createWorkspaceClient();\n }\n\n // ========================================================================\n // Layer-Aware Factory Methods\n // ========================================================================\n\n /**\n * Create a Temporal client for a specific layer\n *\n * @param layer - Service layer ('wspace' or 'global')\n * @param serviceName - Service name for identification\n * @param config - Optional configuration overrides\n * @returns Temporal client configured for the layer\n *\n * @example\n * ```typescript\n * const client = TemporalClientFactory.createClientForLayer('wspace', 'wspace-tags-svc');\n * await client.connect();\n * await client.startWorkflow('processTagUpdate', {\n * workflowId: 'tag-update-123',\n * taskQueue: 'wspace-tags-queue',\n * });\n * ```\n */\n static createClientForLayer(\n layer: ServiceLayer,\n serviceName: string,\n config?: Partial<TemporalClientConfig>\n ): TemporalClient {\n const envPrefix = layer.toUpperCase();\n const defaults = DEFAULT_LAYER_RESOURCES[layer];\n\n // Resolve Temporal address from layer-specific or generic env vars\n const address =\n config?.address ||\n process.env[`${envPrefix}_TEMPORAL_ADDRESS`] ||\n process.env['TEMPORAL_ADDRESS'] ||\n defaults.temporalAddress;\n\n // Derive namespace from layer and service name\n const layerPrefix = `${layer}-`;\n const derivedNamespace = `${layer}-${serviceName.replace(layerPrefix, '').replace('-svc', '')}`;\n const namespace =\n config?.namespace ||\n process.env[`${envPrefix}_TEMPORAL_NAMESPACE`] ||\n process.env['TEMPORAL_NAMESPACE'] ||\n derivedNamespace;\n\n const taskQueue =\n config?.taskQueue ||\n process.env[`${envPrefix}_TEMPORAL_TASK_QUEUE`] ||\n process.env['TEMPORAL_TASK_QUEUE'] ||\n `${serviceName}-queue`;\n\n logger.info('[TemporalClientFactory] Creating layer client', {\n layer,\n serviceName,\n address,\n namespace,\n taskQueue,\n });\n\n return new TemporalClient({\n address,\n namespace,\n taskQueue,\n ...config,\n });\n }\n\n /**\n * Create a Temporal client from layer environment detection\n *\n * @param serviceName - Service name for identification\n * @returns Temporal client configured based on detected layer\n */\n static createFromLayerEnv(serviceName: string): TemporalClient {\n // Detect layer from service name or environment\n const layer =\n (process.env['SERVICE_LAYER'] as ServiceLayer) || (serviceName.startsWith('global-') ? 'global' : 'wspace');\n\n return this.createClientForLayer(layer, serviceName);\n }\n}\n","/**\n * Temporal Worker Module\n * Provides utilities for creating and managing Temporal workers\n *\n * NOTE: Uses dynamic imports to avoid requiring @temporalio/worker at bundle time.\n * This allows services that don't use Temporal to avoid installing the dependency.\n */\n\nimport type {\n Worker as TemporalWorkerType,\n NativeConnection as TemporalNativeConnectionType,\n} from '@temporalio/worker';\nimport { logger } from '../logger/index.js';\n\n// Lazy-loaded Temporal worker module\nlet temporalWorkerModule: typeof import('@temporalio/worker') | null = null;\n\n/**\n * Lazily load the @temporalio/worker module\n */\nasync function getTemporalWorkerModule(): Promise<typeof import('@temporalio/worker')> {\n if (!temporalWorkerModule) {\n temporalWorkerModule = await import('@temporalio/worker');\n }\n return temporalWorkerModule;\n}\n\n/**\n * Worker configuration\n */\nexport interface TemporalWorkerConfig {\n /** Temporal server address */\n address: string;\n /** Temporal namespace */\n namespace: string;\n /** Task queue to poll */\n taskQueue: string;\n /** Path to workflow files */\n workflowsPath: string;\n /** Activities object */\n activities?: Record<string, (...args: unknown[]) => Promise<unknown>>;\n /** Maximum concurrent workflow task executions */\n maxConcurrentWorkflowTaskExecutions?: number;\n /** Maximum concurrent activity task executions */\n maxConcurrentActivityTaskExecutions?: number;\n /** Enable debug logging */\n debugMode?: boolean;\n /** TLS options */\n tls?: {\n serverNameOverride?: string;\n serverRootCACertificate?: Buffer;\n clientCertPair?: {\n crt: Buffer;\n key: Buffer;\n };\n };\n}\n\n/**\n * Temporal Worker wrapper for Burdenoff microservices\n */\nexport class TemporalWorker {\n private worker: TemporalWorkerType | null = null;\n private connection: TemporalNativeConnectionType | null = null;\n private config: TemporalWorkerConfig;\n private isRunning = false;\n\n constructor(config: TemporalWorkerConfig) {\n this.config = {\n maxConcurrentWorkflowTaskExecutions: 100,\n maxConcurrentActivityTaskExecutions: 100,\n debugMode: false,\n ...config,\n };\n }\n\n /**\n * Start the worker\n */\n async start(): Promise<void> {\n if (this.isRunning) {\n logger.warn('Worker already running', {\n taskQueue: this.config.taskQueue,\n });\n return;\n }\n\n try {\n logger.info('Starting Temporal worker', {\n address: this.config.address,\n namespace: this.config.namespace,\n taskQueue: this.config.taskQueue,\n });\n\n // Dynamically import Temporal worker module\n const { Worker, NativeConnection } = await getTemporalWorkerModule();\n\n // Create native connection\n this.connection = await NativeConnection.connect({\n address: this.config.address,\n tls: this.config.tls,\n });\n\n // Create worker\n this.worker = await Worker.create({\n connection: this.connection,\n namespace: this.config.namespace,\n taskQueue: this.config.taskQueue,\n workflowsPath: this.config.workflowsPath,\n activities: this.config.activities,\n maxConcurrentWorkflowTaskExecutions: this.config.maxConcurrentWorkflowTaskExecutions,\n maxConcurrentActivityTaskExecutions: this.config.maxConcurrentActivityTaskExecutions,\n });\n\n this.isRunning = true;\n\n logger.info('Temporal worker started successfully', {\n taskQueue: this.config.taskQueue,\n workflowsPath: this.config.workflowsPath,\n });\n\n // Run worker (this blocks)\n await this.worker.run();\n } catch (error) {\n logger.error('Failed to start Temporal worker', {\n error: error instanceof Error ? error.message : String(error),\n taskQueue: this.config.taskQueue,\n });\n throw error;\n }\n }\n\n /**\n * Stop the worker\n */\n async stop(): Promise<void> {\n if (!this.isRunning || !this.worker) {\n logger.warn('Worker not running', {\n taskQueue: this.config.taskQueue,\n });\n return;\n }\n\n try {\n logger.info('Stopping Temporal worker', {\n taskQueue: this.config.taskQueue,\n });\n\n this.worker.shutdown();\n this.isRunning = false;\n\n if (this.connection) {\n await this.connection.close();\n this.connection = null;\n }\n\n this.worker = null;\n\n logger.info('Temporal worker stopped successfully', {\n taskQueue: this.config.taskQueue,\n });\n } catch (error) {\n logger.error('Failed to stop Temporal worker', {\n error: error instanceof Error ? error.message : String(error),\n taskQueue: this.config.taskQueue,\n });\n throw error;\n }\n }\n\n /**\n * Check if worker is running\n */\n isWorkerRunning(): boolean {\n return this.isRunning;\n }\n\n /**\n * Get worker configuration\n */\n getConfig(): TemporalWorkerConfig {\n return { ...this.config };\n }\n}\n\n/**\n * Factory for creating Temporal workers based on module type\n */\nexport class TemporalWorkerFactory {\n /**\n * Create a Temporal worker for workspace modules\n */\n static createWorkspaceWorker(config: {\n workflowsPath: string;\n activities?: Record<string, (...args: unknown[]) => Promise<unknown>>;\n taskQueue?: string;\n namespace?: string;\n address?: string;\n }): TemporalWorker {\n const address = config.address || process.env['TEMPORAL_WORKSPACE_URL'] || 'localhost:7233';\n const namespace = config.namespace || process.env['TEMPORAL_NAMESPACE'] || 'workspace-default';\n const taskQueue = config.taskQueue || process.env['TEMPORAL_TASK_QUEUE'] || 'workspace-default-tasks';\n\n return new TemporalWorker({\n address,\n namespace,\n taskQueue,\n workflowsPath: config.workflowsPath,\n activities: config.activities,\n });\n }\n\n /**\n * Create a Temporal worker for tenant modules\n */\n static createTenantWorker(config: {\n workflowsPath: string;\n activities?: Record<string, (...args: unknown[]) => Promise<unknown>>;\n taskQueue?: string;\n namespace?: string;\n address?: string;\n }): TemporalWorker {\n const address = config.address || process.env['TEMPORAL_TENANT_URL'] || 'localhost:7233';\n const namespace = config.namespace || process.env['TEMPORAL_NAMESPACE'] || 'tenant-default';\n const taskQueue = config.taskQueue || process.env['TEMPORAL_TASK_QUEUE'] || 'tenant-default-tasks';\n\n return new TemporalWorker({\n address,\n namespace,\n taskQueue,\n workflowsPath: config.workflowsPath,\n activities: config.activities,\n });\n }\n\n /**\n * Create a Temporal worker from environment variables\n * Automatically detects workspace vs tenant based on TEMPORAL_MODULE_TYPE\n */\n static createFromEnv(config: {\n workflowsPath: string;\n activities?: Record<string, (...args: unknown[]) => Promise<unknown>>;\n }): TemporalWorker {\n const moduleType = process.env['TEMPORAL_MODULE_TYPE'] || 'workspace';\n\n if (moduleType === 'tenant') {\n return this.createTenantWorker(config);\n }\n\n return this.createWorkspaceWorker(config);\n }\n}\n\n/**\n * Worker manager for handling worker lifecycle\n */\nexport class TemporalWorkerManager {\n private workers: Map<string, TemporalWorker> = new Map();\n\n /**\n * Register a worker\n */\n registerWorker(name: string, worker: TemporalWorker): void {\n if (this.workers.has(name)) {\n logger.warn('Worker already registered, replacing', { name });\n }\n this.workers.set(name, worker);\n }\n\n /**\n * Start all registered workers\n */\n async startAll(): Promise<void> {\n logger.info('Starting all Temporal workers', {\n count: this.workers.size,\n });\n\n const startPromises = Array.from(this.workers.entries()).map(async ([name, worker]) => {\n try {\n await worker.start();\n logger.info('Worker started', { name });\n } catch (error) {\n logger.error('Failed to start worker', {\n name,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n });\n\n await Promise.all(startPromises);\n }\n\n /**\n * Stop all registered workers\n */\n async stopAll(): Promise<void> {\n logger.info('Stopping all Temporal workers', {\n count: this.workers.size,\n });\n\n const stopPromises = Array.from(this.workers.entries()).map(async ([name, worker]) => {\n try {\n await worker.stop();\n logger.info('Worker stopped', { name });\n } catch (error) {\n logger.error('Failed to stop worker', {\n name,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n });\n\n await Promise.all(stopPromises);\n }\n\n /**\n * Get a worker by name\n */\n getWorker(name: string): TemporalWorker | undefined {\n return this.workers.get(name);\n }\n\n /**\n * Remove a worker\n */\n removeWorker(name: string): boolean {\n return this.workers.delete(name);\n }\n\n /**\n * Get all registered worker names\n */\n getWorkerNames(): string[] {\n return Array.from(this.workers.keys());\n }\n}\n","/**\n * Temporal Module for Burdenoff SDK\n * Integrates Temporal workflow orchestration into the SDK\n */\n\nimport type { TemporalClient } from './client.js';\nimport { TemporalClientFactory } from './client.js';\nimport type { TemporalWorker } from './worker.js';\nimport { TemporalWorkerFactory, TemporalWorkerManager } from './worker.js';\nimport { logger } from '../logger/index.js';\n\n/**\n * Temporal module configuration\n */\nexport interface TemporalModuleConfig {\n /** Module type (workspace or tenant) */\n moduleType: 'workspace' | 'tenant';\n /** Temporal server address */\n address?: string;\n /** Temporal namespace */\n namespace?: string;\n /** Default task queue */\n taskQueue?: string;\n /** Auto-connect on initialization */\n autoConnect?: boolean;\n}\n\n/**\n * Temporal Module\n * Main entry point for Temporal functionality in the SDK\n */\nexport class TemporalModule {\n private client: TemporalClient;\n private workerManager: TemporalWorkerManager;\n private config: TemporalModuleConfig;\n\n constructor(config: TemporalModuleConfig) {\n this.config = {\n autoConnect: true,\n ...config,\n };\n\n // Create client based on module type\n if (config.moduleType === 'tenant') {\n this.client = TemporalClientFactory.createTenantClient({\n address: config.address,\n namespace: config.namespace,\n taskQueue: config.taskQueue,\n });\n } else {\n this.client = TemporalClientFactory.createWorkspaceClient({\n address: config.address,\n namespace: config.namespace,\n taskQueue: config.taskQueue,\n });\n }\n\n this.workerManager = new TemporalWorkerManager();\n\n // Trigger autoConnect if enabled (non-blocking)\n if (this.config.autoConnect) {\n this.initialize();\n }\n }\n\n /**\n * Initialize the Temporal module (connect client)\n * This is called automatically if autoConnect is true\n */\n private initialize(): void {\n // Connect in background\n this.client.connect().catch((error) => {\n logger.error('Failed to auto-connect to Temporal', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n }\n\n /**\n * Get the Temporal client\n */\n getClient(): TemporalClient {\n return this.client;\n }\n\n /**\n * Get the worker manager\n */\n getWorkerManager(): TemporalWorkerManager {\n return this.workerManager;\n }\n\n /**\n * Create and register a worker\n */\n createWorker(config: {\n name: string;\n workflowsPath: string;\n activities?: Record<string, (...args: unknown[]) => Promise<unknown>>;\n taskQueue?: string;\n }): TemporalWorker {\n const worker =\n this.config.moduleType === 'tenant'\n ? TemporalWorkerFactory.createTenantWorker({\n workflowsPath: config.workflowsPath,\n activities: config.activities,\n taskQueue: config.taskQueue,\n namespace: this.config.namespace,\n address: this.config.address,\n })\n : TemporalWorkerFactory.createWorkspaceWorker({\n workflowsPath: config.workflowsPath,\n activities: config.activities,\n taskQueue: config.taskQueue,\n namespace: this.config.namespace,\n address: this.config.address,\n });\n\n this.workerManager.registerWorker(config.name, worker);\n return worker;\n }\n\n /**\n * Start all registered workers\n */\n async startWorkers(): Promise<void> {\n await this.workerManager.startAll();\n }\n\n /**\n * Stop all registered workers\n */\n async stopWorkers(): Promise<void> {\n await this.workerManager.stopAll();\n }\n\n /**\n * Disconnect from Temporal\n */\n async disconnect(): Promise<void> {\n await this.client.disconnect();\n }\n\n /**\n * Get module configuration\n */\n getConfig(): TemporalModuleConfig {\n return { ...this.config };\n }\n\n /**\n * Create a Temporal module from environment variables\n */\n static fromEnv(): TemporalModule {\n const moduleType = (process.env['TEMPORAL_MODULE_TYPE'] || 'workspace') as 'workspace' | 'tenant';\n const address =\n moduleType === 'tenant'\n ? process.env['TEMPORAL_TENANT_URL'] || 'localhost:7233'\n : process.env['TEMPORAL_WORKSPACE_URL'] || 'localhost:7233';\n const namespace = process.env['TEMPORAL_NAMESPACE'];\n const taskQueue = process.env['TEMPORAL_TASK_QUEUE'];\n\n return new TemporalModule({\n moduleType,\n address,\n namespace,\n taskQueue,\n });\n }\n}\n"]}